Compare commits

...
23 Commits
Author SHA1 Message Date
Radosław SmolińskiandClaude Opus 5.5 39309c5c1c CHANGELOG 1.16.4: the verify limit counts every try; lockout from a sibling subdomain
CI / check (push) Failing after 5m29s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 09:36:54 +01:00
Radosław SmolińskiandClaude Opus 5.5 d722157e20 1.16.4 upgrade notes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 09:35:08 +01:00
Radosław SmolińskiandClaude Opus 5.5 03443fd7ee 1.16.4
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 09:35:08 +01:00
Radosław SmolińskiandClaude Opus 5.5 f0f26393a3 Merge claude/security-fix-staff-check-2fa: staff checks only for staff collections; 2FA covers everything
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 02:26:56 +01:00
Radosław SmolińskiandClaude Fable 5.2 dc5326ea1c Review round 3: job-queue rules keep Payload's own defaults; a failed 2FA lookup fails closed
Job queue (R3-1): only a rule that exists is wrapped. At config time that
is what the project wrote; Payload fills in the rest when it builds the
config (3.94.1: run, queue and cancel are all defaultAccess, a logged-in
user) and the sweep of the running config wraps those. No default is
invented, so a request without a user gets what Payload itself answers.

hasTotp false while the account's record carries a TOTP secret (the 2FA
package's own lookup failed, R3-4): the account owes its code, not
'not set up yet'.

Docs: the two-configs-in-one-process case for calls without a source, and
that a half-logged-in editor's browser is refused media files.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 02:22:04 +01:00
Radosław SmolińskiandClaude Fable 5.2 c56f0d41b8 Security review round 2: no exception by name, staff list fails closed, verify limit
R2-1: the sweep skipped every collection whose slug starts with payload-,
so a plugin's payload-... collection added after ipalKit was never guarded.
There is no exception by name or prefix now: every collection and global
is guarded, Payload's own included, and the job queue's run / queue /
cancel rules too.

R2-2: role predicates called without a source fail closed where the staff
collections are not known (browser bundle, middleware, edge): nobody is
staff. They accept req.payload, a config (also the client config) or
{ staffCollections } as the source.

R2-3: the staff list is filed per config / Payload instance; a call without
a source gets only what every config in the process calls staff.

R2-4: payload.config is watched on the instance, so a config swapped in by
a dev reload is guarded before any request or Local API call.

R2-5: verify attempts are limited per account (default 5 in 10 minutes,
twoFactor.verifyLimit), counted in memory, never skipped.

R2-6: a user object without collection owes the second factor; endpoints
the 2FA package may add on collections or globals are guarded too; a
warning names staff collections that 2FA does not cover; docs state what
is not covered, fix the one-argument examples and the doctor example.

HTTP tests for each on payload-2fa beta.7, run on SQLite, Postgres and
MongoDB (test adapter added).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 01:46:25 +01:00
Radosław SmolińskiandClaude Fable 5.2 32faaa5e30 Security review fixes: staff collection first everywhere, 2FA package endpoints guarded, per-entity opt-out, hot reload
F1: roles count only for accounts of a staff collection, in every exported
predicate and access builder (isAdmin, isEditor, hasMinimumRole, adminOnly,
adminOrEditor, requireRole, adminOrSelf, adminOrSelfIn, the Field variants,
the roles field) and first in userMeetsRole. An account of another auth
collection with its own roles: ['admin'] gets nothing. Staff collections:
admin.user, access.authCollection, access.staffCollections. Predicates take
req.payload as an optional last argument and otherwise use the staff
collections of the config ipalKit built in this process.

F2: every endpoint @clocklimited/payload-2fa registers answers accounts of
the 2FA collection only (setup-totp wrote the secret into the 2FA collection
under the caller's id, whatever collection the caller came from); remove and
the admin reset/remove endpoints also need the second factor.

F3: per-entity opt-out honoured, operation by operation: the package's
custom.totp.disableAccessWrapper and ipal-kit's custom.ipal.secondFactor
(passed on to the package); the package's global disableAccessWrapper too.

F4: a no-user auth strategy on the 2FA collection guards the live config at
the start of each request, so entities from plugins listed after ipalKit
stay guarded after a dev hot reload and with disableOnInit.

Tests through HTTP for all four; the 2FA tests now run on payload-2fa
3.0.0-beta.7 (what client sites use), a second file on beta.1 (alias), and
the HTTP files can run against Postgres (IPAL_TEST_POSTGRES_URI). Docs,
agent guide, skills and changelog updated; the not-yet-enrolled limitation
is stated plainly.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 01:02:34 +01:00
Radosław SmolińskiandClaude Fable 5.2 97ee1289aa Reference smoke test: send the site origin so the login cookie counts; test typing
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 00:38:01 +01:00
Radosław SmolińskiandClaude Fable 5.2 0c61ac231b Security: staff checks only for staff collections; 2FA covers what the plugin adds
Staff check (userMeetsRole): the 'no roles field = every account passes'
rule applied to the account's own collection, so an account of a second
auth collection (customers) passed every staff check. It now applies only
to staff collections: the panel's login collection plus the new
access.staffCollections. The injected auth collection uses the new
adminOrSelfIn(slug), so an account of another collection with the same
numeric id is not 'self'.

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

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

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 00:31:55 +01:00
Radosław SmolińskiandClaude Opus 5.5 bc1045a5b7 Merge claude/drift-decisions-1163: PAYLOAD_SECRET minimum in production, doctor seen in CI, create --external
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:09:26 +01:00
Radosław SmolińskiandClaude Opus 5.5 71fea221f1 Merge claude/docs-drift-1163: docs brought in line with the 1.16.3 code
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:09:26 +01:00
Radosław SmolińskiandClaude Opus 5.5 0d8d906653 Comments: tab name Search engines, credit text, generateStaticParams scope
Comments and the ipal-kit usage line only (adds ipal-doctor); no behaviour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:19 +01:00
Radosław SmolińskiandClaude Opus 5.5 b5df59691c ipal-kit create: a bare --external installs every external skill
Matches the help text and docs/project-starter.md; a list stays as given,
no flag leaves it to the answers. resolveExternal() + test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:19 +01:00
Radosław SmolińskiandClaude Opus 5.5 5cd0224ebd ipal-doctor: never write first-seen dates when CI is set
The CLI ignored CI (writeSeen was only !sites && !json); docs and comments
already said "not in CI". shouldWriteSeen() + test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 36f8f69f82 ipalEnvRules: PAYLOAD_SECRET at least 32 characters in production
New option secretMinLength (default 32, 0 turns it off); checked only with
NODE_ENV=production. Docs: env table, deployment (what changing the secret
does, checked in Payload 3.94.1 and payload-2fa), AGENT.md, ipal-reference,
ipal-setup. Tests: short secret fails in production, passes in dev, 0 and a
custom minimum.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 40fed78da2 Docs: forms reject text over 5000 characters; Site settings update is editor+
(a) The code rejects an over-long value (kind 'too_long', validation text at
the field, answers kept); the limit is fixed. (c) Site settings update needs
the editor role; overridable with globalOverrides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 37592764b5 Docs: fix doc/code drift found against 1.16.3 (docs only)
Verified the IAWL summary's "Doc/code" notes against the code and swept
CLI flags, option names/defaults and env vars. Fixed in the docs:
admin groups (consent-records, cookie-review → Privacy; Form messages
global → Forms), tab labels (More, Spam protection, E-mail sending,
Search engines; Sending method), construction field labels, {field} =
label, globalOverrides instead of "a plugin after ipalKit", enabled:false
keeps globals, pages role labels en+pl, switchLocalePath prefix,
accessibility cookie (necessary), seeding summary() shape, prepublishOnly
chain, doctor --strict --offline in the starter, package files list,
ipal-skills --external in PROGRAMISTA, DATABASE_URI (not _URL),
uploadsCollection exists, SiteProviders nonce, buildLinksField labels,
MCP list_pages limit wording, IPAL_DOCTOR_TOKEN in the env table; shipped
seo-check message "Search engines". Reference skills copy refreshed.

Open questions (not changed): forms over-long text, PAYLOAD_SECRET
length, Site settings update access, doctor seen in CI, bare
`ipal-kit create --external`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 23:47:35 +01:00
Radosław SmolińskiandClaude Opus 5.5 e603561de4 1.16.3: renumber the prepared release (was 1.17.0)
CI / check (push) Failing after 6m22s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:53:57 +01:00
Radosław SmolińskiandClaude Opus 5.5 e29f882aa6 1.17.0 upgrade notes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:46:47 +01:00
Radosław SmolińskiandClaude Opus 5.5 195ca3ab11 1.17.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:46:40 +01:00
Radosław SmolińskiandClaude Opus 5.5 b9df570e84 Merge claude/deps-payload-3-94: Payload 3.94.1, dependency updates, overrides re-checked
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:43:23 +01:00
Radosław SmolińskiandClaude Opus 5.5 a0c576e54c Dev audit: @swc/cli 0.8.2, vite 7.3.8; Node 22.23.5 check in Coolify
@swc/cli 0.8.0 still resolved piscina 4.9.3 and @xhmikosr/decompress 10.2.1
(the two criticals). 0.8.2 with refreshed transitive deps and vite 7.3.8 as a
direct dev dependency take the dev-tree audit from 31 to 4 (0 high, 0 critical).
Docs: Payload 3.94 needs Node 22.23.5+ also in Coolify; how to check it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:43:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 ab51027617 Payload 3.94.1, dependency updates, overrides re-checked
- payload and every @payloadcms/* 3.94.1 in the plugin's dev dependencies, the
  reference site and the starter (peer range unchanged: ^3.90.2); react/react-dom
  19.3.1; reference engines node >=22.23.5 <23 (Payload 3.94's minimum).
- Overrides re-checked: dompurify and happy-dom still needed; mongoose (3.90–3.93)
  and undici (3.90–3.91) only on an older Payload; graphql-scalars no longer needed
  (GHSA-x8rm-f576-gq67 covers 1.24.1–2.0.0; Payload pins 1.22.2). Reference keeps
  dompurify + happy-dom; plugin root drops graphql-scalars.
- ipal-doctor transitive-min: the mongoose fix names the Payload upgrade first.
- nodemailer 10.6.1; dev: playwright 1.65.1, vitest 5.1.1, prettier 3.10.1,
  @swc/cli 0.8, rimraf 6 (clean uses --glob), cross-env 10, open 11,
  sort-package-json 4, @swc-node/register 1.12.1, vite-tsconfig-paths 6.1.1;
  reference tailwind 4.3.5, postcss 8.5.33.
- Kept back: typescript 7, eslint 10, graphql 17, @types/node 26, lucide-react 1.x.
- AGENT.md §4 item 12, ipal-setup, ipal-upgrade, README, PROGRAMISTA §1, forms.md,
  doctor.md; reference skills copy; CHANGELOG Unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 15:18:58 +01:00
104 changed files with 5284 additions and 1773 deletions
+12 -10
View File
@@ -77,10 +77,12 @@ site with every team convention, installs it from a shipped lockfile and makes t
`nodemailer`, `lucide-react`, `slugify` and `server-only` are regular
`dependencies` of the plugin — they install with it; don't add them yourself.
The plugin's `nodemailer` 10 needs **Node.js 20 or later**.
The plugin's `nodemailer` 10 needs **Node.js 20 or later**; Payload 3.94 itself needs **Node.js 22.23.5 or later**
on the 22 line.
What you provide are the **peer dependencies** — packages the plugin shares with
your project — in a version matching your Payload:
your project — in a version matching your Payload. The plugin accepts Payload `^3.90.2`; the reference site and the starter use
**3.94.1** (with `react` / `react-dom` 19.3.1, which Payload 3.94 requires):
| Peer | Range | Notes |
|---|---|---|
@@ -91,17 +93,17 @@ your project — in a version matching your Payload:
| `@payloadcms/storage-s3` | `^3.90.2` | optional — only when media go to Cloudflare R2 ([docs/storage.md](./docs/storage.md)) |
```bash
pnpm add @payloadcms/[email protected]0.2 @payloadcms/[email protected]0.2 \
pnpm add @payloadcms/[email protected]4.1 @payloadcms/[email protected]4.1 \
@clocklimited/payload-2fa
pnpm add @payloadcms/[email protected]0.2 # only with R2 media
pnpm add @payloadcms/[email protected]4.1 # only with R2 media
```
Keep every `@payloadcms/*` at exactly the same version as `payload`
(`pnpm.overrides` — see PROGRAMISTA.md §1). Then run `pnpm audit --prod`: with
`payload` 3.90.x, Payload's own tree pins a vulnerable `undici`, `dompurify`,
`graphql-scalars`, `mongoose` (MongoDB adapter) and `happy-dom` (the last three even in the latest Payload) — add the
five overrides from [AGENT.md §4 item 12](./docs/agent/AGENT.md) (recommended, not
required by the plugin). Upload optimization and image
(`pnpm.overrides` — see PROGRAMISTA.md §1). Then run `pnpm audit --prod`: even
Payload 3.94.1 brings a vulnerable `happy-dom` (via Lexical) and `dompurify` — add
the two overrides from [AGENT.md §4 item 12](./docs/agent/AGENT.md); an older Payload
also needs the `mongoose` (MongoDB adapter, up to 3.93) and `undici` (up to 3.91)
ones listed there (recommended, not required by the plugin). Upload optimization and image
placeholders also use the `sharp` you pass to `buildConfig({ sharp })`
(standard in a `create-payload-app` project).
@@ -162,7 +164,7 @@ clean working tree):
```bash
npm version patch # 1.0.0 → 1.0.1 (commit + tag)
npm publish # prepublishOnly runs: pnpm clean && pnpm build && pnpm test:int
npm publish # prepublishOnly runs: pnpm clean && pnpm build && pnpm build:starter && pnpm test:int && pnpm starter:gate
git push && git push --tags
```
+2 -2
View File
@@ -3,7 +3,7 @@
// pnpm dlx @intecion/ipal-kit@<version> create intecion.com → a new client site (docs/project-starter.md)
// pnpm exec ipal-kit create intecion.com --dir ../intecioncom-web --answers answers.json
// `pnpm dlx <package>` runs the bin named after the package, so every subcommand lives here.
// The other tools keep their own bins: ipal-skills, ipal-blocks, ipal-tokens.
// The other tools keep their own bins: ipal-skills, ipal-blocks, ipal-tokens, ipal-doctor.
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
@@ -11,7 +11,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'
const USAGE = `Usage: ipal-kit <command> [options]
create <domain> a new client site from the reference site (ipal-kit create --help)
Other tools: ipal-skills, ipal-blocks, ipal-tokens`
Other tools: ipal-skills, ipal-blocks, ipal-tokens, ipal-doctor`
const [command, ...args] = process.argv.slice(2)
if (command !== 'create') {
+6 -6
View File
@@ -1,11 +1,11 @@
#!/usr/bin/env node
// ipal-skills — copies the ipal-kit agent skills into the project.
// pnpm ipal-skills → ./.agents/skills/ipal-*
// pnpm ipal-skills --dry-run → show what would change
// pnpm ipal-skills --dest .claude/skills
// pnpm ipal-skills --no-pointer → skills only, leave AGENTS.md / CLAUDE.md alone
// pnpm ipal-skills --external → also the vendored third-party skills (ext-*, pinned, text only)
// pnpm ipal-skills --external ext-accessibility,ext-payload → only those
// pnpm exec ipal-skills → ./.agents/skills/ipal-*
// pnpm exec ipal-skills --dry-run → show what would change
// pnpm exec ipal-skills --dest .claude/skills
// pnpm exec ipal-skills --no-pointer → skills only, leave AGENTS.md / CLAUDE.md alone
// pnpm exec ipal-skills --external → also the vendored third-party skills (ext-*, pinned, text only)
// pnpm exec ipal-skills --external ext-accessibility,ext-payload → only those
// Only folders named ipal-* are touched; the project's own skills stay as they are.
// ipal-* folders that no longer exist in the package are removed (renamed/retired skills).
// ext-* folders are touched only with --external, and only those carrying ipal-kit's SOURCE.md.
+180
View File
@@ -8,6 +8,186 @@ 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.4
### Security
- **2FA now covers what the plugin adds.** The 2FA package wraps the collections and globals that exist when it
runs; the plugin's own globals and collections were added afterwards and were not wrapped. With 2FA on, an
account that had typed its **password but not the code** could read and change them over the API (REST and
GraphQL): Site settings, Site integrations (including the SMTP password and the Turnstile secret), Cookie banner,
Notifications, forms, form submissions, consent records, cookie review, stats, and the plugin's staff endpoints.
The project's own collections and the user accounts were protected. **Affects every site with 2FA on, in every
earlier version.** It needed a valid staff password. Now ipal-kit runs its own second-factor check on every
collection and global — whichever plugin added it and in whatever order — and on its endpoints
([security.md](./security.md) "What the second factor covers").
- **Accounts of a second auth collection are no longer staff.** Roles, and the rule "no `roles` field = every
account passes", counted for an account of any auth collection. In a project with a visitor account collection
(`customers`, a client zone) such an account passed the plugin's staff checks, with the same reach as above —
every check when its collection had no `roles` field, and `isAdmin` / `adminOnly` / `requireRole` and the others
when it had a `roles` field of its own. With open sign-up, anyone could make one. In the injected auth
collection, "only my own record" also matched an account of another collection with the same numeric id
(Postgres, SQLite). **Affects only projects with more than one auth collection.** Now the staff-collection check
comes first in every predicate and access function: only accounts of the panel's login collection,
`access.authCollection` and `access.staffCollections` count, and the injected collection uses `adminOrSelfIn`
([access.md](./access.md#who-is-staff)).
- **The 2FA package's endpoints accept accounts of the 2FA collection only.** `@clocklimited/payload-2fa` (checked
in 3.0.0-beta.1 and beta.7) takes the logged-in account from any auth collection and writes the TOTP secret into
the 2FA collection under that account's id. With numeric ids (Postgres, SQLite) an account of another auth
collection could set the secret of the staff account with the same id; whoever knew that staff password then
passed 2FA, and the owner's authenticator stopped working. **Affects only projects with more than one auth
collection on Postgres or SQLite** (MongoDB ids do not repeat across collections). ipalKit now guards every
endpoint the package registers; reset and remove also need the second factor
([security.md](./security.md) "The 2FA package's endpoints").
- **Guessing the 2FA code is now limited.** The package never counted verify attempts. Now at most 5 tries
per account in 10 minutes, right or wrong (`twoFactor.verifyLimit`); further tries get `429`. The counter lives in each server
instance's memory and resets when the app restarts or redeploys.
- **Every collection and global is covered, whatever its name** — Payload's own (`payload-preferences`,
`payload-jobs`, …), a plugin's `payload-…` collection, the job queue's `run / queue / cancel` rules.
- **Not changed, and important:** an account that has **not set TOTP up yet** is an ordinary logged-in account —
its password alone opens everything its role allows. Set 2FA up right after an account is created;
`ipal-doctor --url` reports accounts without it.
- **Who was affected, in short.** Every site with 2FA on: a staff password without the code opened the plugin's
settings, integrations (SMTP password, Turnstile secret), forms, submissions and consent records. Sites with a
second auth collection: also visitor accounts. Neither leaves a trace in the data.
### Changed
- **`ipalEnvRules()` checks the `PAYLOAD_SECRET` length in production.** A new option, `secretMinLength`, defaults
to 32; `0` turns the check off. It is checked only with `NODE_ENV=production`, and it uses the `secretVar` you
set. The error gives the length only, never the value.
- **ipal-doctor** never writes first-seen dates (`seen` in `ipal-doctor.json`) when `CI` is set. A normal local run
still writes them, and `until` silences do not depend on them.
- **`ipal-kit create <domain> --external`** with no list installs every vendored `ext-*` skill. A list is used as
given; without the flag the answers decide.
- **Docs brought in line with the code** (38 files): forms reject text over 5000 characters instead of cutting it;
Site settings `update` needs editor or higher; tab and group names (Search engines, More, Privacy, Image viewer,
Form messages); `prepublishOnly`, CLI usage, seeding `summary()`, `switchLocalePath`. Source comments and the
`ipal-kit` usage line name the current labels.
- **Visible with 2FA on:**
- A session that typed the password but not the code gets `403` from the API on everything, including public
globals, pages and media files. Anonymous visitors are unaffected. An editor who leaves the panel at the code
screen and opens the public site in the same browser may see missing images until they enter the code or
log out.
- Accounts of other auth collections get `403` from the 2FA endpoints (`/api/setup-totp`, `/api/verify-totp`, …).
### Added
- `access.staffCollections`: name further auth collections whose accounts are staff.
- `adminOrSelfIn(slug)`, `staffCollectionSlugs(payload)`, `secondFactorPassed(req)`, `requireSecondFactor(access)`
for the project's own access functions and endpoints. `isAdmin`, `isEditor` and `hasMinimumRole` take an optional
last argument that says which collections are staff: `req.payload`, a config, or `{ staffCollections: [...] }`.
- `twoFactor.verifyLimit: false | { max, windowMinutes }`.
- Per-entity opt-out from the second factor: `custom.ipal.secondFactor: false | { read: false }` on a collection
or global; the package's `custom.totp.disableAccessWrapper` is honoured as before.
- `twoFactor.guard: false`: ipal-kit's second-factor check off everywhere, the package's wrapper only (not recommended).
### Requires project changes
- **Every site: upgrade and redeploy.** No config change for a site with one auth collection and
`@clocklimited/payload-2fa` 3.0.0-beta.7 (tested: beta.1 and beta.7). `pnpm ipal:skills` afterwards.
- **`PAYLOAD_SECRET` at least 32 characters in production.**
- **Check before you deploy 1.16.4:** Coolify app → Terminal →
`node -e 'console.log(process.env.PAYLOAD_SECRET.length)'`. 32 or more: nothing to do.
- **Shorter:** either set a random value of 32+ characters (`openssl rand -base64 48`) in Coolify → Environment
Variables and redeploy, or for now add `secretMinLength: 0` (or a lower number) to `ipalEnvRules({ … })` in
`src/instrumentation.ts`.
- **Changing the secret on a live site** (Payload derives its signing key from it): everyone is logged out;
every user enters the 2FA code again (authenticator apps keep working); stored API keys (`useAPIKey`) stop
working; uploads in progress fail. Do it with the owner's OK at a quiet time. If you rotate it as part of the
security steps below, do both in one deploy ([deployment.md](./deployment.md) "`PAYLOAD_SECRET` — length and
changing it").
- **Every site: no account without 2FA.** `pnpm exec ipal-doctor --url <site>` → accounts without 2FA must be 0;
have each such account set TOTP up now, or remove it.
- **Because the earlier behaviour left no trace** (there is no audit log), decide per site with the owner:
- change the **SMTP password** and the **Turnstile secret** stored in Site integrations when a staff password
may have been known to someone else (a reused or shared password, a former employee, a phishing report) — or
simply do it once, it is cheap;
- look through **Site settings and Site integrations** for values nobody on the team set (analytics and tag
manager IDs, sender address, construction mode), and through each **form's Emails tab** for unknown
recipients or BCC addresses;
- form submissions and consent records could have been read; whether that needs a data-protection assessment
is the client's decision.
- **A site with a second auth collection:** treat the points above as required, not optional. Set
`admin: { user: '<staff collection>' }` in `buildConfig`, use `adminOrSelfIn('<slug>')` in your own auth
collections, and if the second collection really is staff, name it in `access.staffCollections`. Roles no
longer count for accounts of other collections: a rule that used `isAdmin` / `adminOnly` for them needs its own
check of `req.user.collection`. On Postgres or SQLite also ask every staff member to confirm their
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.
- **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
role does not count without `collection`. Own
endpoints: add `secondFactorPassed(req)` or `userMeetsRole(req, role)`.
- **Startup stops with `[ipal] twoFactor: the injected 2FA plugin did not add …`:** the installed 2FA package is
not one the check recognises. Install a supported version; `twoFactor.guard: false` only as a stop-gap.
- **Check after deploy:** security.md → "What the second factor covers" → Check (three `403`), then log in fully
and open Site integrations and a form submission in the panel.
### Known limitations
- **An account that has not set up 2FA yet** is an ordinary logged-in account: its password alone opens what its
role allows, SMTP credentials included. A later release addresses this. Until then: set 2FA up right after
creating an account, and check the `ipal-doctor --url` count.
- **The verify limit** is per server instance and in memory. A restart or redeploy resets it. Whoever already holds
a staff password can keep trying slowly (about 720 tries a day), or lock the owner out of entering the code for
10 minutes at a time. A hostile page on a sibling subdomain of the site can cause that lockout without the
password, while the owner is logged in to the panel.
- **Accounts of an extra staff collection** (`access.staffCollections`) are not covered by 2FA. The log warns at
start.
- **Dashboard alert widgets** (Integration alerts, Cookie crawl alert) show integration error text to every panel
role. This is older than this release.
## 1.16.3
### Changed
- **Payload 3.94.1** in the reference site and the project starter (was 3.90.2), with `react` / `react-dom` 19.3.1 and
Node.js `>=22.23.5 <23` in the reference `engines`. The plugin is built and tested against 3.94.1; its peer range is
unchanged (`^3.90.2`), so a project on 3.90.x is not forced to move. What Payload 3.91–3.94 change that a project
notices: Node.js 22.23.5 or later (24.22.3 / 26.13.1 on newer lines), `react` ^19.3.1, Next.js 16.4.5 or later,
`@payloadcms/db-mongodb` ships `mongoose` 8.24.7 (3.94.0), the `deepmerge` dependency is gone (3.94.1), field access
now receives the document id, draft read access and block child read access are checked more strictly, and the slug
field no longer fails required validation on create (a 3.90.2 bug). Nothing in the plugin needed a code change; the
generated types and the import map of the reference site are unchanged.
- **Overrides re-checked against Payload 3.94.1** (AGENT.md §4 item 12): `dompurify` and `happy-dom` are still needed
(Lexical still brings `happy-dom` ^20.9.0: two highs). `mongoose` (MongoDB, Payload 3.90–3.93) and `undici` (Payload
3.90–3.91) are needed only on an older Payload. **`graphql-scalars` needs no override any more**: GHSA-x8rm-f576-gq67
now covers 1.24.1–2.0.0 only, and `@payloadcms/graphql` pins 1.22.2. The reference site and the starter keep only the
`dompurify` and `happy-dom` lines.
- **ipal-doctor `transitive-min`:** the `mongoose` finding names the Payload upgrade (3.94.1) as the first fix; the
thresholds are unchanged.
- Dependencies: `nodemailer` 10.6.1 (runtime). Dev tooling: Playwright 1.65.1 (run `pnpm exec playwright install
chromium` once), Vitest 5.1.1, Prettier 3.10.1, `@swc/cli` 0.8.2 (with `piscina` 4.9.4 and `@xhmikosr/decompress` 11: clears the two critical dev
advisories), `vite` 7.3.8 as a direct dev dependency (Vitest's peer; clears the vite high), `rimraf` 6,
`cross-env` 10 (also in the reference site), `open` 11, `sort-package-json` 4, `@swc-node/register` 1.12.1,
`vite-tsconfig-paths` 6.1.1, Tailwind 4.3.5 and PostCSS 8.5.33 in the reference site. `pnpm audit` of the plugin's
dev tree: 31 → 4 (0 critical, 0 high; what is left sits under `drizzle-kit` and the ESLint toolchain). `--prod` stays
at 0, and the reference site at 0.
- Kept back, with the reason: TypeScript 7 (typescript-eslint supports TypeScript below 6.1 only), ESLint 10
(`eslint-config-next` 16.4.6 plugins do not support it — the lint run crashes), `graphql` 17 (Payload requires
^16.8.1), `@types/node` 26 (projects stay on Node 22), `lucide-react` 1.x (a runtime dependency: projects are told to
keep their own lucide on 0.400.x; moving needs its own change and icon-map checks).
### What projects must update
- **Nothing is required.** The plugin still works with Payload 3.90.2 and later.
- **Recommended — move to Payload 3.94.1** (the `ipal-upgrade` skill, "Every upgrade — Payload"): every `payload` /
`@payloadcms/*` to 3.94.1 (in `dependencies` and `pnpm.overrides`), `react` and `react-dom` 19.3.1, Node.js 22.23.5
or later (`"engines": { "node": ">=22.23.5 <23" }`, `.nvmrc` stays `22`), `pnpm install`, `pnpm payload generate:types`,
`pnpm payload generate:importmap`, `rm -rf .next`, build, redeploy on Coolify. Postgres/SQLite: run
`pnpm payload migrate:create` and commit it if it is not empty (Payload 3.94.1 changes how long index and foreign
key names are built). MongoDB: no migration.
- **Node.js 22.23.5 or later everywhere the site runs — before you move to Payload 3.94.** Payload 3.94 refuses older
Node (`engines`: `^22.23.5 || ^24.22.3 || >=26.13.1`). Locally: `node -v`. **Coolify:** Nixpacks picks the Node major
from `engines` / `.nvmrc`, and the patch version comes from the Nixpacks release on the server — so after the first
deploy open the app → Terminal and run `node -v` (the build log shows it too). If it is below 22.23.5, update Coolify
(newer Nixpacks) before you deploy Payload 3.94; until then, stay on 3.90.x. CI images (`node:22` / `setup-node`
with `22`) must resolve to 22.23.5 or later as well.
- **Overrides** (`pnpm.overrides`): on 3.94.x keep `"dompurify@<3.4.17": "^3.4.17"` and
`"happy-dom@<21.0.4": "^21.0.4"`; the `mongoose` and `undici` lines do nothing there — remove them. Remove
`"graphql-scalars@<2.0.1": "^2.0.1"` if you have it (optional). Sites that stay on 3.90–3.93 keep the 1.16.2 lines.
- **Verify:** `pnpm ls payload` → 3.94.1; `pnpm audit --prod` → no high or critical; `pnpm exec ipal-doctor` → no
`versions` finding; the panel opens and a document saves; a form submission arrives.
- `pnpm ipal:skills` for the updated `ipal-setup` / `ipal-upgrade` skills.
## 1.16.2
### Security
+89 -19
View File
@@ -13,6 +13,7 @@ ipalKit({
// defaultRole: 'user', // role of new accounts
// firstUserAdmin: true, // the account from "Create first user" → admin
// authAccess: { … }, // access of the injected auth collection (your keys win)
// staffCollections: ['partners'], // more auth collections whose accounts are staff
},
// globalOverrides: { … }, // access / admin / hooks / fields of the plugin's globals
})
@@ -24,6 +25,7 @@ ipalKit({
| `access.defaultRole` | `'user'` | role of a new account when an admin did not set one |
| `access.firstUserAdmin` | `true` | the account from the "Create first user" screen (`…/first-register` on an empty collection) gets `['admin']`, even when the form picked `user`; `false` = it gets what was submitted |
| `access.authAccess` | see the table below | `access` of the **injected** auth collection, merged over the default (your keys win) |
| `access.staffCollections` | `[]` | more auth collections whose accounts count as **staff**, besides the one the panel logs in with (`admin.user`); see "Who is staff" |
| `globalOverrides` | — | changes to the plugin's globals: an object merges `access` / `admin` key by key (your keys win) and appends `hooks` (yours run after the plugin's), other keys (label, fields, …) replace; a function `(global) => global` takes over the whole global |
The `roles` field (select hasMany, required, `saveToJWT`): readable without limits; only an admin
@@ -40,7 +42,7 @@ only checks that someone is logged in.
| Resource | Read | Write | How to change |
|---|---|---|---|
| auth collection **injected** by the plugin, with roles | admin: everyone; others: only themselves | `create` / `delete` / `unlock`: admin; `update`: admin or self | `access.authAccess`, or your own collection |
| auth collection **injected** by the plugin, with roles | admin: everyone; other accounts **of that collection**: only themselves (`adminOrSelfIn`) | `create` / `delete` / `unlock`: admin; `update`: admin or self | `access.authAccess`, or your own collection |
| Site settings, Cookie banner, Notifications | public | `editor+` | `globalOverrides` |
| Site integrations | admin | admin | `globalOverrides` |
| Forms | public (Emails tab only `editor+`) | `editor+` | `forms.formOverrides.access`, the Emails field in `formOverrides.fields` |
@@ -58,37 +60,101 @@ ipalKit({
```
The project's own auth collection keeps its own `access` — the plugin only adds the
`roles` field. Give it at least `update: adminOrSelf`, `delete: adminOnly`, `create: adminOnly`,
`roles` field. Give it at least `update: adminOrSelfIn('users')`, `delete: adminOnly`, `create: adminOnly`,
`unlock: adminOnly`: Payload's default lets any logged-in account change the email and password
of another account and unlock any account. A collection injected **without** `access` (no roles)
keeps Payload's default rules — without roles all accounts are equal.
> **Without `access` there is no `roles` field**, so `isAdmin` always returns `false`. The plugin's own
> staff features therefore check with `userMeetsRole(req, minimum)`: when the user's auth collection has no
> `roles` field, every logged-in account passes (as in Payload's default — without roles all accounts are
> equal). That keeps Site integrations, the settings globals, `/api/ipal/test-email`, stats, consent records
> and form submissions reachable. To narrow them without roles: `globalOverrides` for the globals,
> `forms.formSubmissionOverrides` for submissions, or add `access` to get roles.
## Who is staff
**Staff collections** are the auth collections whose accounts work in the panel:
- the one the admin panel logs in with (`admin.user`; Payload's default is the **first** auth collection in the
list — set `admin: { user: 'users' }` yourself as soon as the project has two);
- the one that carries the plugin's roles (`access.authCollection`);
- the ones named in `access.staffCollections`.
An account of **any other auth collection** — `customers`, `members`, a client zone — is a visitor to the
plugin. **Nothing in the plugin counts a role for it**, also when its own collection has a `roles` field with
the value `admin`: not `userMeetsRole`, not `isAdmin` / `isEditor` / `hasMinimumRole`, not `adminOnly`,
`adminOrEditor`, `requireRole`, `adminOrSelf`, `adminOrSelfIn` or the `…Field` variants, not the `roles` field
itself. The staff-collection check always comes first.
The plugin's own staff features — Site integrations, the settings globals, form submissions, consent records,
stats, the cookie scanner, `/api/ipal/test-email` — check with `userMeetsRole(req, minimum)`, in this order:
1. the account belongs to a staff collection;
2. with 2FA on: an account that has TOTP set up has entered the code in this session
([security.md](./security.md) → "What the second factor covers");
3. it holds at least the role `minimum` — **or** its collection has no `roles` field at all. Then every account
of that staff collection passes, as in Payload's default (without roles all accounts are equal).
What follows:
- **Without `access`** there is no `roles` field, so `isAdmin` always returns `false` and rule 3 keeps the
staff features reachable: every account of the panel collection is admin to the plugin. To narrow that
without roles: `globalOverrides` for the globals, `forms.formSubmissionOverrides` for submissions, or add
`access` to get roles.
- **A second staff collection** (e.g. `partners` who edit content): name it in
`access.staffCollections`. That is the one switch that makes its roles count. Without a `roles` field every
partner passes every staff check, admin ones included; to tell them apart add the field:
`fields: [buildRolesField('editor')]` in that collection. **2FA covers one collection** (`twoFactor.collectionSlug`,
by default the panel's): accounts of a further staff collection are staff with a password alone. ipalKit says
so in the log at start (`[ipal] 2FA covers "users" only…`); name such a collection only when that is acceptable.
- **Payload's own default** for a collection or global without `access` is "any logged-in account" — an account
of a visitor collection included. In a project with a second auth collection give every collection and global
explicit `access` (`adminOrEditor`, `requireRole(…)`, …).
- **A visitor collection that should reach one thing** (e.g. customers read their own form submissions):
do not make it staff. Write that one rule yourself — `forms.formSubmissionOverrides.access.read`,
`globalOverrides`, `collectionOverrides` of the module — and check `req.user.collection` in it.
- **A user object you build yourself** (Local API with `overrideAccess: false`, a custom auth strategy) must
carry `collection`: `{ ...doc, collection: 'users' }`. Payload's own strategies and `payload.auth()` set it. An
account without it is not staff.
> **Changed in 1.16.4.** Before, a role or the "no roles field" rule counted for an account
> of any auth collection: an account of a second auth collection passed staff checks — every one when its
> collection had no `roles` field, and the matching ones when it had its own `roles` field. A project with one
> auth collection sees no difference. A project that relied on a second collection being staff sets
> `access.staffCollections`.
## Predicates (front end / hooks / access)
```ts
import { isAdmin, isEditor, hasMinimumRole, userMeetsRole } from '@intecion/ipal-kit'
import { isAdmin, isEditor, hasMinimumRole, staffCollectionSlugs, userMeetsRole } from '@intecion/ipal-kit'
isAdmin(user) // admin?
isEditor(user) // editor or admin (hierarchy)
hasMinimumRole(user, 'editor') // at least editor
userMeetsRole(req, 'admin') // admin — or any logged-in user when the auth collection has no roles field
isAdmin(req.user, req.payload) // a staff account with the admin role
isEditor(req.user, req.payload) // editor or admin (hierarchy)
hasMinimumRole(req.user, 'editor', req.payload) // at least editor
userMeetsRole(req, 'admin') // the plugin's staff check: staff collection, second factor, role ("Who is staff")
staffCollectionSlugs(req.payload) // ['users', …]
```
They take a loosely typed user (like `req.user`) and read `roles` defensively.
They take a loosely typed user (like `req.user`) and read `roles` defensively. The last argument tells them
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 |
| 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 */ }
```
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.
## Ready access functions
### Collection-level (return boolean | Where)
```ts
import { adminOnly, adminOrEditor, adminOrSelf, requireRole, authenticated } from '@intecion/ipal-kit'
import { adminOnly, adminOrEditor, adminOrSelf, adminOrSelfIn, requireRole, authenticated } from '@intecion/ipal-kit'
export const Articles = {
slug: 'articles',
@@ -101,8 +167,12 @@ export const Articles = {
// ...
}
// Users: everyone sees themselves, an admin sees everyone
access: { read: adminOrSelf }
// Users: everyone sees themselves, an admin sees everyone.
// adminOrSelfIn(slug): "self" = an account of THAT collection. Use it for an auth collection whenever
// the project has more than one: adminOrSelf only compares ids, and with numeric ids (Postgres, SQLite)
// customer no. 5 would match staff account no. 5.
access: { read: adminOrSelfIn('users') }
access: { read: adminOrSelf } // fine with a single auth collection
// any minimum threshold
access: { update: requireRole('editor') }
@@ -143,10 +213,10 @@ Types: `AccessOption`, `Role`, `GlobalOverride`, `GlobalOverrides`, `IpalGlobalS
- **Turn off:** leave out `access` — no `roles` field, the auth collection keeps Payload's rules
(or yours). `access.firstUserAdmin: false` stops giving admin to the first account.
- **Override:** `access.authAccess` (injected collection), your own auth collection (wins whole),
- **Override:** `access.staffCollections` (who is staff), `access.authAccess` (injected collection), your own auth collection (wins whole),
`globalOverrides` (globals), `forms.formOverrides` / `formSubmissionOverrides` (forms),
`defaultRole`. The role hierarchy (`ROLE_HIERARCHY`) is fixed.
- **Extend:** `requireRole` / `requireRoleField`, predicates, `buildRolesField`, `injectRoles`,
- **Extend:** `requireRole` / `requireRoleField`, `adminOrSelfIn`, predicates (`userMeetsRole`, `staffCollectionSlugs`), `buildRolesField`, `injectRoles`,
`applyGlobalOverrides` in your own collections and globals.
- **Check:** log in with a `user` account → `PATCH /api/globals/site-settings` = 403,
`DELETE /api/users/<admin id>` = 403; the account from "Create first user" has the `admin` role.
+3
View File
@@ -172,6 +172,9 @@ The provider re-applies and syncs on the client anyway. This only removes the fl
### State and attributes (`A11yState`)
Cookie `a11y-prefs` (`A11Y_COOKIE`, JSON, `path=/`, `max-age` 1 year, `samesite=lax`).
It is written only when the visitor changes a setting, with no consent check: a preference the visitor
chose, no tracking (the same reasoning as the theme choice, theme.md). List it as **necessary** in the
cookie list — the scanner does not declare it, add it with `declarations` (cookie-scanner.md).
Widget texts: `texts` prop wins, otherwise `A11Y_DEFAULT_TEXTS[locale]` (`en`, `pl`; prop `locale`,
incl. `texts.on` / `texts.off` for the switches).
The helpers `A11Y_COOKIE`, `A11Y_DEFAULT`, `parseA11y`, `serializeA11y`, `a11yAttributes`
+61 -32
View File
@@ -49,6 +49,10 @@ Write new rules, AGENTS.md entries and plugin-gap reports in English.
`postgres://…@db:5432/intecioncom_prod`. You derive the names from the domain and confirm them with the owner (ipal-setup
stage 0). `ipalEnvRules({ databaseName: true })` warns when they do not match (deployment.md §4.2a).
**`PAYLOAD_SECRET`:** at least 32 random characters, different per environment (`ipal-kit create` writes 64). In
production `ipalEnvRules` refuses a shorter one (`secretMinLength`, default 32, `0` = off). Never change it on a live
site without the owner's OK: every login session and every stored API key depends on it (deployment.md §1).
**Seeding on production** (details: `node_modules/@intecion/ipal-kit/docs/seeding.md`). Write seeds with
`createSeeder` from `@intecion/ipal-kit/seed` (the templates do) — it enforces every rule below:
- Call `guardSeedExit()` first in every seed script (before `getPayload`): a run that ends early exits 1 with the reason
@@ -199,7 +203,7 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2.
| 10 | **Forms** | every form from a **seed** (`scripts/seed-form-*.ts`: fields, confirmation, mail to the company **and** confirmation to the customer, every language); a block with `<RenderForm>` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P |
| 11 | **Turnstile** | `<SiteProviders>` in `[locale]/layout.tsx` (wires `TurnstileProvider` with the key from the panel); `RenderForm` renders the widget; keys in Site integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P |
| 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`<SiteProviders analytics={{ consentMode: 'basic' }}>` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (`cookieScanner: true` → *Cookie review* → **Scan cookies** → *Approve cookies* → **Approve and add**; or cookie-scan → import) — feeds `<CookieTable>` on the policy page **and** the lists in the `detailed` window; Cookies → Settings window → Cookie list headings in every language | consent.md, analytics.md | A, `ipal-consent-check` |
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withPayload(withSecurityConfig(nextConfig))` (no `X-Powered-By`); CSP: `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } })` + `buildAdminCspHeaders` on `/admin/:path*` + `src/app/api/csp-report/route.ts` (`createCspReportRoute`) → read the reports → `mode: 'enforce'`; `twoFactor: { issuer, plugin: payloadTotp }` + `generate:importmap` (`TotpRedirectProvider`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading); `IPAL_IP_HEADER` in production | security.md, forms.md | A |
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withPayload(withSecurityConfig(nextConfig))` (no `X-Powered-By`); CSP: `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } })` + `buildAdminCspHeaders` on `/admin/:path*` + `src/app/api/csp-report/route.ts` (`createCspReportRoute`) → read the reports → `mode: 'enforce'`; `twoFactor: { issuer, plugin: payloadTotp }` + `generate:importmap` (`TotpRedirectProvider`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading; a login with the password only gets `403` from `/api/globals/site-integrations` and `/api/form-submissions` — security.md "What the second factor covers"); own endpoints: `secondFactorPassed(req)` / `userMeetsRole(req, role)`; **set 2FA up right after creating an account** — until then its password alone opens everything its role allows; `ipal-doctor --url` must report 0 accounts without 2FA; `IPAL_IP_HEADER` in production | security.md, forms.md | A |
| 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging with `IPAL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A |
| 15 | System pages | Site settings → System pages: homepage, 404, privacy policy, cookies; legal links in the footer by role (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P |
| 16 | **Nothing hardcoded** | every text, link, image, file, company data from the panel; domains and keys from `.env` (§2) | — | A, P |
@@ -514,41 +518,43 @@ No abbreviations (`HeroSection`, not `HeroSec`). Do not create `lib/pages.ts`,
(`pnpm why sharp`). The plugin's peer range stays open (`next >=15`) — the minimum is yours to keep.
**Check:** `pnpm ls next sharp` → next ≥ 16.4.5, sharp ≥ 0.35.5; `pnpm exec ipal-doctor` → no `next-min`
finding; `pnpm dev` prints no security-upgrade warning.
12. **No open production advisories.** Node.js 20 or later (the plugin's `nodemailer` 10 requires it). Run
12. **No open production advisories.** Node.js 20 or later for the plugin itself (its `nodemailer` 10 requires it);
**Payload 3.94 needs Node.js 22.23.5 or later** on the 22 line (`engines`: `">=22.23.5 <23"`, `.nvmrc` `22`), locally,
in CI and in Coolify (Nixpacks takes the major from `engines` / `.nvmrc` and the patch from its own release: check
`node -v` in the app's Terminal; below 22.23.5, update Coolify before moving to Payload 3.94). Run
`pnpm audit --prod`. The plugin's own dependencies are clean; what remains comes from Payload's tree, which only
the project's lockfile can fix. With `payload` 3.90.x five packages are pinned below a fix and need `pnpm.overrides`
next to the `@payloadcms/*` ones:
the project's lockfile can fix. With `payload` **3.94.x** two packages are still pinned below a fix and need
`pnpm.overrides` next to the `@payloadcms/*` ones:
```json
"dompurify@<3.4.17": "^3.4.17",
"graphql-scalars@<2.0.1": "^2.0.1",
"happy-dom@<21.0.4": "^21.0.4",
"happy-dom@<21.0.4": "^21.0.4"
```
`happy-dom` comes from `@payloadcms/richtext-lexical` → `@lexical/headless` 0.50 (`^20.9.0`, still so in 3.94.1);
every 20.x has GHSA-c8p4-j97h-3vg8 (high, SSRF when parsing untrusted HTML, fixed in 21.0.0) and
GHSA-834v-8h66-3h79 (high, host code execution, fixed in 21.0.4). 21 is a major, but only
`@lexical/headless/dom` (`withDOM`) loads it — Payload never imports that entry, and Lexical 0.53 itself moved to
`^21.0.4`. `dompurify` comes from the admin code editor (`@payloadcms/ui` → `monaco-editor`; low advisories).
**On an older Payload** add these too, until you upgrade (upgrading to 3.94.1 is the better fix):
```json
"mongoose@>=8 <8.24.7": "~8.24.10",
"undici@>=7 <7.30.1": "^7.30.1"
```
`mongoose` (MongoDB sites — every site that uses `@payloadcms/db-mongodb`): the adapter pins 8.24.1 exactly, up
to the latest Payload (3.93.0). 8.x below 8.24.7 has five advisories: GHSA-pcrw-h46h-c93h (critical,
`sanitizeFilter` not applied on `countDocuments`, fixed in 8.24.3), GHSA-gg4r-jv3p-qx3c and GHSA-8332-j7wj-wjw4
(high), GHSA-wr5m-5jph-8m96 and GHSA-6972-9mcm-vhwj (moderate), all fixed in 8.24.7. The override stays on the
8.24 patch line (`~8.24.10`), the line Payload itself tests; the reference site seeds, builds and passes its smoke
tests on it. `happy-dom` comes from `@payloadcms/richtext-lexical` → `@lexical/headless` 0.50 (`^20.9.0`); every
20.x has GHSA-c8p4-j97h-3vg8 (high, SSRF when parsing untrusted HTML, fixed in 21.0.0) and GHSA-834v-8h66-3h79
(high, host code execution, fixed in 21.0.4). 21 is a major, but only `@lexical/headless/dom` (`withDOM`) loads
it — Payload 3.90 never imports that entry, and Lexical 0.53 itself moved to `^21.0.4`; `withDOM` HTML parsing and
export are checked on 21.0.4. Both overrides stop matching once Payload ships a fixed version — remove them then.
`undici` comes from `payload` (3.92.1 and later already ship 7.30.1), `dompurify` from the admin code editor
(`@payloadcms/ui` → `monaco-editor`, which pins 3.2.7). `graphql-scalars` comes from `@payloadcms/graphql`, which
pins 1.22.2 up to the latest Payload (3.92.1); every version up to 2.0.0 has a high ReDoS advisory in the
`PhoneNumber` scalar (GHSA-x8rm-f576-gq67). 2.x is a major (graphql-js 16+, Node.js 22 recommended), but Payload
only uses `DateTimeResolver` and `EmailAddressResolver`, which work unchanged — keep the override until Payload
ships 2.0.1 or later. `deepmerge` (low, from `payload`) has no fixed version yet; it stays in the report. Everything else in the report (`fast-uri`, `js-yaml`,
`browserslist`, `source-map-js`, `fast-copy`, `baseline-browser-mapping`) is a range: `pnpm update` or a fresh
lockfile picks up the fix; add an override like the ones above only if it does not. These are recommendations —
the plugin forces none of them. Never add a project dependency on `nodemailer` or `@types/nodemailer`.
**Check:** `pnpm audit --prod` → no high or critical (only the `deepmerge` low may remain);
`pnpm why undici dompurify graphql-scalars mongoose happy-dom` → only the fixed versions (mongoose 8.24.7 or
later, happy-dom 21.0.4 or later); `pnpm exec ipal-doctor` → no `transitive-min` finding; after the mongoose
override run `pnpm build`, open the panel and save a document; with GraphQL in use, a query that reads a
`createdAt` (DateTime) and filters on `email` (EmailAddress) returns data.
`mongoose` (MongoDB sites on Payload 3.90–3.93): `@payloadcms/db-mongodb` pins 8.24.1, which has five advisories —
GHSA-pcrw-h46h-c93h (critical, `sanitizeFilter` not applied on `countDocuments`, fixed in 8.24.3),
GHSA-gg4r-jv3p-qx3c and GHSA-8332-j7wj-wjw4 (high), GHSA-wr5m-5jph-8m96 and GHSA-6972-9mcm-vhwj (moderate), all
fixed in 8.24.7; Payload 3.94.0 and later ship 8.24.7. `undici` (Payload 3.90–3.91): 3.92.0 and later ship 7.30.1.
Both selectors match only the vulnerable versions, so they do nothing once Payload ships the fix — remove them then.
**`graphql-scalars` needs no override any more:** GHSA-x8rm-f576-gq67 now covers 1.24.1–2.0.0 only, and
`@payloadcms/graphql` pins 1.22.2. A `"graphql-scalars@<2.0.1": "^2.0.1"` line added earlier may be removed (it
also works if kept: Payload's GraphQL runs unchanged on 2.x). The `deepmerge` low is gone from Payload 3.94.1.
Everything else in the report (`fast-uri`, `js-yaml`, `browserslist`, `source-map-js`, `fast-copy`,
`baseline-browser-mapping`) is a range: `pnpm update` or a fresh lockfile picks up the fix; add an override like
the ones above only if it does not. These are recommendations — the plugin forces none of them. Never add a
project dependency on `nodemailer` or `@types/nodemailer`.
**Check:** `pnpm audit --prod` → no high or critical; `pnpm why dompurify happy-dom mongoose undici` → only the
fixed versions (dompurify 3.4.17 or later, happy-dom 21.0.4 or later, mongoose 8.24.7 or later, undici 7.30.1 or
later); `pnpm exec ipal-doctor` → no `transitive-min` finding; after a Payload or mongoose change run
`pnpm build`, open the panel and save a document.
---
@@ -574,6 +580,25 @@ By default: `pages`, `media` + the plugin's globals (`site-settings`,
you need extra fields (then your own `Users.ts` with the slug from `access.authCollection`;
the plugin adds roles and 2FA to it).
**A second auth collection** (`customers`, `members`, a client zone) — only when the client requires accounts
for visitors. Then, all four:
1. `admin: { user: 'users' }` in `buildConfig` — Payload otherwise logs the panel in with the FIRST auth
collection in the list, and 2FA and the staff checks follow the panel collection.
2. Its accounts are visitors to the plugin: no role counts for them (also a `roles` field of their own with
the value `admin`) and they pass none of its checks — `userMeetsRole`, `isAdmin`, `adminOnly`,
`adminOrEditor`, `requireRole`, the settings globals, Site integrations, form submissions, consent records,
stats, cookie scanner. Give them exactly what they need with your own `access` rules that check
`req.user.collection`; never add the collection to `access.staffCollections` to "make something work".
`access.staffCollections` is for a second collection of STAFF (access.md → "Who is staff").
3. In every auth collection use `adminOrSelfIn('<its slug>')`, not `adminOrSelf`, for "only my own record".
4. Payload's default for a collection or global without `access` is "any logged-in account" — a customer too.
Give every collection and global explicit `access`. 2FA covers the panel's collection only.
5. Never let a sign-up write a field that grants rights (`roles`, `isAdmin`, …): give such a field
`access: { create: adminOnlyField, update: adminOnlyField }`.
6. Check: log in as such an account (`POST /api/customers/login`), then `GET /api/globals/site-integrations`,
`GET /api/form-submissions` and `GET /api/users` with its token must answer `403`, and so must
`POST /api/setup-totp`.
**NEVER:** a second `media`, `daneFirmy`/`settings`/
`navigation`/`footer` as collections (they are globals), FAQ/hero/features as collections
(they are blocks), a collection for a single thing (that is a page or a global).
@@ -1034,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`, `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); injected `users`: `access.authAccess`, first user = admin (`access.firstUserAdmin`) | access.md |
| Roles and access | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `adminOrSelfIn(slug)` (several auth collections), `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); staff checks: `userMeetsRole(req, role)`, `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 |
| Data from globals | `getGlobal`, `getSiteSettings`, `getSiteIntegrations` | payload-helpers.md |
**Links and navigation**
@@ -1128,7 +1153,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Plugin globals: write editor+ (Site integrations: admin) | — | `ipalKit({ globalOverrides: { <slug>: { access, admin, hooks } } })`; a function `(global) => global` takes over (`applyGlobalOverrides`) |
| Global saves revalidate the layout (with `ipalKit({ revalidatePath })`) | omit `revalidatePath`; once: `context: { disableRevalidate: true }` | `buildGlobalRevalidateHook` on your own globals |
| Form files (`forms.attachments`): off; when on — 10 MB, PDF/DOC/DOCX ticked, programs/macros/archives refused, no antivirus, Graph sends files of 3 MB and more through a draft it deletes | omit `attachments`; `forms.fields.file: false`; `mailAdapter({ graph: { largeAttachments: false } })` | `maxSizeMB` / `maxTotalMB` / `maxFiles` / `fileTypes` / `allowRisky` / `scan` / `strictPdf` / `notice` / `submit`; `buildFileBlock`; `formSubmissionOverrides.fields` for the file fields of a submission |
| Staff features without `access` (no roles field): every logged-in account passes (`userMeetsRole`) | add `access` (roles decide) | `globalOverrides`, `forms.formSubmissionOverrides`, `consentLog.collectionOverrides`, `stats.collectionOverrides` |
| Staff features without `access` (no roles field): every account of the panel's login collection passes (`userMeetsRole`); accounts of other auth collections never do | add `access` (roles decide) | `access.staffCollections` (more staff collections), `globalOverrides`, `forms.formSubmissionOverrides`, `consentLog.collectionOverrides`, `stats.collectionOverrides` |
| Cookie check (`crawl`): start editor+ or the token, results token-only for the running job, latest result only, dashboard warning on, e-mail off until recipients are set | omit `crawl`; `crawl.dashboard: false` | `crawl.serviceUrl` / `token` / `siteUrl` / `maxPages` / `acceptSelector` / `consentMode` / `trackerHosts` / `globalOverride`; *Cookie check → Warning e-mails to*; building blocks `ingestCrawlResult`, `findCrawlViolations`, `parseCrawlResult` |
| Cookie admin: one *Cookies* entry — review list and site check as tabs, their own entries out of the navigation (pages and API kept) | `cookieScanner.adminLayout: 'separate'` | `addCookieScannerTabs`, `CookieReviewTab`, `CookieSiteCheckTab`; `collectionOverrides` / `crawl.globalOverride` win |
| Theme choice in localStorage under `theme` (next-themes' key); old `ipal-theme` moved before paint; declared to the cookie scanner as necessary local storage | — | `ipalKit({ theme: { storageKey } })`; `<ThemeSwitcher storageKey>` / `useTheme({ storageKey })` |
@@ -1140,6 +1165,10 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Injected `users`: admin manages everyone, others only themselves | — | `access.authAccess` (your keys win); your own `users` collection wins whole |
| First registered account = admin | `access.firstUserAdmin: false` | `buildRolesField(defaultRole, { firstUserAdmin })` |
| 2FA on the panel's login collection, mismatch = startup error; redirect to the 2FA screens by `TotpRedirectProvider` | `twoFactor: false` (discouraged) | `twoFactor.collectionSlug`, `allowCollectionMismatch: true`, `twoFactor.provider` (own component, or `false` for the package's) |
| The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints |
| At most 5 verify attempts per account in 10 minutes (`POST /api/verify-totp` → `429`) | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes }` |
| The 2FA package's endpoints (`/api/setup-totp`, `verify-totp`, `remove-totp`, `admin/*`) answer accounts of the 2FA collection only; reset and remove need the second factor | — (always on with 2FA) | `adminManageAccess` through the wrapped factory (security.md "Resetting 2FA") |
| Roles count only for accounts of a staff collection, in every predicate and access function | — | `access.staffCollections` |
| `enabled: false` keeps the schema | — | — (no endpoints, `onInit` or admin components; no DROP TABLE in `migrate:create`) |
| No client IP = one shared `unknown-ip` bucket at 20× the limit | `setUnknownIpFactor(0)` (only with a limiter in front) | `setUnknownIpFactor(n)`; `UNKNOWN_IP_FACTOR` |
| Turnstile token domain not checked | (default) | `createSubmitAction({ turnstileHostnames })`, `verifyTurnstile({ hostnames })` — leave empty in dev |
+1 -1
View File
@@ -2,7 +2,7 @@
<!-- Generated by scripts/reference-index.mjs from reference/ — do not edit by hand (pnpm reference:index). -->
The reference site is one complete client site on ipal-kit 1.16.2 ("Example Studio", made up) that uses
The reference site is one complete client site on ipal-kit 1.16.4 ("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:
@@ -4,7 +4,7 @@
// Reads the syntax tree (the project's TypeScript), so comments never count and multi-line forms work.
// Not reported: the panel's own labels (AGENT.md §6.5a), only in a schema file — a .ts file under
// collections/, globals/, fields/ or blocks/, or one importing Payload's schema types; never a .tsx file:
// - adminText('Title', 'Tytuł') from @intecion/ipal-kit
// - adminText('Title', 'Tytuł') from @intecion/ipal-kit/blocks
// - { en: 'Title', pl: 'Tytuł' } as the value of label, singular, plural, description, placeholder or group
// - rowLabel('title', { en: 'Item', pl: 'Pozycja' }) from @intecion/ipal-kit
// - const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' }
+7 -2
View File
@@ -48,8 +48,13 @@ Ask only when the brief leaves a business question open (e.g. "do posts have aut
generateStaticParams, hreflang.
3. Entry list = a block (EntriesList) with `getEntries`; the entry page uses
`resolveRoute` (type `entry`); JSON-LD per seo.md (e.g. Article).
4. `pnpm generate:types`, `pnpm payload generate:importmap`.
5. Postgres with migrations → `pnpm payload migrate:create`.
4. **An auth collection for visitors** (`auth: true`: customers, members) only when the client requires it
(AGENT.md §5 "A second auth collection"): `admin: { user: 'users' }` in `buildConfig`, `access` with
`adminOrSelfIn('<slug>')` for read / update and an explicit `create`, never in `access.staffCollections`.
Its accounts pass none of the plugin's staff checks. Check: its token → `403` from
`/api/globals/site-integrations` and `/api/form-submissions`.
5. `pnpm generate:types`, `pnpm payload generate:importmap`.
6. Postgres with migrations → `pnpm payload migrate:create`.
## 4. Check
The **ipal-audit** skill. By hand: an entry in the panel → visible at `/<locale>/<archive>/<slug>`,
+6
View File
@@ -34,6 +34,12 @@ through this procedure. Ask only when you are missing something you cannot get y
### Build / TypeScript
| Symptom | Cause | Fix |
|---|---|---|
| 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'] })` |
| startup: `[ipal] twoFactor: the injected 2FA plugin did not add the totpSecret field / hasTotp field / totp auth strategy` | the installed `@clocklimited/payload-2fa` is not a version ipal-kit's second-factor check recognises (tested: 3.0.0-beta.1 and beta.7), or a custom factory was injected | install a supported version; stop-gap only: `twoFactor.guard: false` (the plugin's own data is then not covered by 2FA — security.md) |
| own route or script gets `403` / "not allowed" on `form-submissions`, `forms`, a settings global with `overrideAccess: false`, although the user is an admin | the `user` was fetched by id and passed by hand: it does not carry how the account logged in, so the second-factor check refuses it | take the user from `payload.auth({ headers })` (it sets `collection` and how the account logged in), or (server-only code that needs no access check) leave `overrideAccess` at its default; a hand-built user needs at least `collection: 'users'` for its role to count |
| an account of a second auth collection (`customers`) gets `403` from a settings global, submissions, `/api/ipal/*`, `/api/setup-totp`, or `isAdmin` / `adminOnly` say no although it has `roles: ['admin']`, after an upgrade | by design since 1.16.4: roles and staff checks count only for accounts of a staff collection | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") |
| `TS2307 next/navigation` in the plugin's `dist` | import without `.js` in the plugin client (NodeNext) | **ipal-kit bug** → plugin gap; the plugin imports `'next/navigation.js'` |
| `TS2307 @payloadcms/storage-s3` | package missing when using `buildR2Storage` | `pnpm add @payloadcms/storage-s3` + `buildR2Storage(['media'], { s3Storage })` |
| `does not provide an export named X` / `X is not a function` | symbol not exported from the entry point, or wrong subpath (`/client` vs root vs `/server` vs `/rsc`) | `docs/README.md` → the right import; missing from every entry → **ipal-kit bug** (export) |
+1 -1
View File
@@ -175,7 +175,7 @@ Details the seed already covers, which you check after every manual change in th
- [ ] unticked consent → a message from Notifications (not the English fallback);
- [ ] 6 quick submissions → `rate_limited`;
- [ ] Turnstile with keys → widget visible; submitting without solving the widget → `turnstile`;
wrong secret → the form goes through, and the panel (dashboard + Site integrations → Turnstile) shows a red alert;
wrong secret → the form goes through, and the panel (dashboard + Site integrations → Spam protection) shows a red alert;
- [ ] Turnstile without keys → no widget, the form goes through;
- [ ] second language → labels and messages in that language;
- [ ] GTM Preview → an event with the name from the panel after success;
+13 -11
View File
@@ -14,7 +14,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
- **The plugin helps, never limits:** every module can be turned off, every default can be overridden,
the project config wins, the building blocks (`build*`, `create*`) are exported — compose your own version from them.
- Missing option / behaviour that does not match the docs → skill **ipal-plugin-gap** (report). Never patch `node_modules`.
- Described per the 1.12.x code. "currently always" = no option to turn it off today (gap → ipal-plugin-gap).
- Described per the current code (checked against 1.16.3). "currently always" = no option to turn it off today (gap → ipal-plugin-gap).
## 1. `ipalKit({...})` options (`IpalOptions`, `dist/types.d.ts`)
@@ -25,11 +25,12 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `i18n.fallback` | `true` | `localization.fallback` | `false` |
| `i18n.locales[]` `{ code, label, rtl? }` | — | list of languages (min. 1); `rtl: true` → `rtl` in Payload | adding a language: skill **ipal-locale-add** |
| admin languages (no option) | English + Polish | `i18n.supportedLanguages` set to `{ en, pl }` when the project has none; plugin component texts in `i18n.translations.<lang>.ipal` (`adminTexts`); every plugin label is `{ en, pl }` (rules: `docs/dev/admin-ux.md`) | your own `i18n.supportedLanguages` wins; override a component text with `i18n.translations.<lang>.ipal.<key>`; field/global labels via `globalOverrides` / `collectionOverrides` — see i18n.md "Admin panel languages and texts" |
| `access` | none | `roles` field (`user` < `editor` < `admin`, `saveToJWT`) in the auth collection | omit → **no roles**: every logged-in account passes the plugin's admin/editor checks (`userMeetsRole`): Site integrations, the e-mail test, stats, consent-records, settings globals, `form-submissions`. Narrow them with `globalOverrides` / collection overrides |
| `access` | none | `roles` field (`user` < `editor` < `admin`, `saveToJWT`) in the auth collection | omit → **no roles**: every account of the panel's login collection passes the plugin's admin/editor checks (`userMeetsRole`; accounts of other auth collections never pass): Site integrations, the e-mail test, stats, consent-records, settings globals, `form-submissions`. Narrow them with `globalOverrides` / collection overrides |
| `access.authCollection` | — (required in `access`) | collection that gets `roles`; also the slug of the injected auth collection | your own collection with that slug wins |
| `access.defaultRole` | `'user'` | `defaultValue` of the `roles` field | `'editor'` / `'admin'` |
| `access.authAccess` | `{ create: adminOnly, delete: adminOnly, read: adminOrSelf, unlock: adminOnly, update: adminOrSelf }` | access of the auth collection the plugin **injects** (Payload's default lets any logged-in account edit or delete every other account) | your keys win, e.g. `{ read: authenticated }`; your own collection with that slug wins whole (give it `adminOrSelf` / `adminOnly` yourself) |
| `access.authAccess` | `{ create: adminOnly, delete: adminOnly, read: adminOrSelfIn(slug), unlock: adminOnly, update: adminOrSelfIn(slug) }` | access of the auth collection the plugin **injects** (Payload's default lets any logged-in account edit or delete every other account) | your keys win, e.g. `{ read: authenticated }`; your own collection with that slug wins whole (give it `adminOrSelf` / `adminOnly` yourself) |
| `access.firstUserAdmin` | `true` | the account made on Payload's "Create first user" screen (`/first-register` on an empty collection) gets `roles: ['admin']`; an open sign-up still gets `defaultRole` | `false` = that account gets what was submitted |
| `access.staffCollections` | `[]` | more auth collections whose accounts are staff, 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 |
| `adminRoute` | `'/admin'` | `config.routes.admin`; stats link and views, `IntegrationAlerts` | the project moves `app/(payload)/<route>/` itself and adds the route to the proxy matcher (security.md) |
| `twoFactor` | **none = error** | `@clocklimited/payload-2fa` with `forceSetup: true` (TOTP enforced, also checked in the API) | `twoFactor: false` (discouraged); omitting the option throws `[ipal] twoFactor.issuer is required` |
| `twoFactor.issuer` | — (required) | name in the authenticator app | — |
@@ -37,6 +38,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `twoFactor.collectionSlug` | the panel's login collection (`admin.user`, else the first auth collection) | collection with 2FA; startup fails with `[ipal] twoFactor…` when it is not an auth collection or differs from `admin.user` | point it at the login collection |
| `twoFactor.provider` | `'@intecion/ipal-kit/admin#TotpRedirectProvider'` | admin provider that sends users to `setup-totp` / `verify-totp` (path read in the browser); replaces the package's header-based one | own component path / `{ path, clientProps, serverProps }` (gets clientProps `forceSetup`); `false` keeps the package's (needs `x-pathname` on `/admin`, else `setup-totp?back=null` loops) |
| `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations.<lang>.totpPlugin.<key>` (security.md) |
| `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | 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.allowCollectionMismatch` | `false` | allows `collectionSlug` ≠ `admin.user` (panel users of the other collection then skip 2FA) | `true` only when you protect a second auth collection on purpose |
| `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site settings + vendor credit | omit / `false`; `true` = defaults |
| `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — |
@@ -59,7 +62,6 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `seo.generateTitle` / `generateDescription` | plugin-seo | preview / generation in the panel | your own function `({ doc }) => string` |
| `seo.searchSettings` | tab on (the tab exists with or without `seo`) | Site settings → **Search engines** tab: `searchVerification.google/bing/yandex` (→ `<meta>` via `generatePageMetadata`), `aiCrawlers.policy` + `aiCrawlers.rules[]` (→ robots.txt via `getRobots`), localized `llmsIntro` (→ top of `/llms.txt`); empty fields change nothing. Postgres: `migrate:create` after upgrading | `false` = no tab, but this key exists only inside `seo` (which needs `collections`); without `seo` use the top-level `searchSettings: false`. When both are set, the top-level `searchSettings` wins; `(fields) => fields` = your own set (keep the names `searchVerification`, `aiCrawlers`, `llmsIntro` or read your own fields in your routes) |
| `searchSettings` | tab on | same tab and values as `seo.searchSettings`, but a top-level option: works **with or without `seo`**; read as `searchSettings ?? seo.searchSettings`, so it wins when both are set | `false` = no tab; `(fields) => fields` = your own set |
| — (no option) | `uploadsCollection: 'media'` | meta image from the `media` collection | currently always `media` (gap) |
| `forms` | none | `@payloadcms/plugin-form-builder`: `forms`, `form-submissions` collections | omit |
| `forms.adminGroup` | `'Forms'` | sidebar group | `false` = Payload default; `admin.group` in overrides wins |
| `forms.fields.*` | on: `checkbox`, `checkboxGroup`, `country`, `date`, `email`, `message`, `number`, `radio`, `select`, `state`, `step`, `text`, `textarea`, `time`; off: `payment` | block types in the builder (all with "Show only when") | `<type>: false`; a block object replaces it; `payment: true` **does nothing** (filtered out) — pass a block object |
@@ -89,8 +91,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `stats.retentionDays` / `timeZone` / `dashboard` | 90 / `'Europe/Warsaw'` / `true` | retention, day boundary, `StatsWidget` | `dashboard: false` hides the chart |
| `indexNow` | `false` | `afterChange` hook (publish → IndexNow, production + https only) in the `pages.slug ?? 'pages'` collection and each one from `content` | `true` + `indexnow-key.txt` route |
| `lightbox` | `false` | **Image viewer** group in the Form messages global (`notifications`) (image viewer labels: open, dialog, previous, next, close, counter — localized); read by `getNotificationTexts(...).lightbox` / `getSiteShell().lightboxTexts`. Postgres: `migrate:create` | omit = English fallbacks + the `texts` prop; `lightboxNotificationFields` for your own global; `globalOverrides.notifications` |
| `siteSettingsFields` | none | **Custom** tab in Site settings | `Field[]` |
| `integrationsFields` | none | **Custom** tab in Site integrations | `Field[]` |
| `siteSettingsFields` | none | **More** tab in Site settings | `Field[]` |
| `integrationsFields` | none | **More** tab in Site integrations | `Field[]` |
| `globalOverrides` | none | changes the plugin's globals (`site-settings`, `site-integrations`, `cookie-settings`, `notifications`): an object merges `access` / `admin` / `hooks` key by key (your keys win, your hooks run after the plugin's), other keys replace; a function `(global) => global` takes over | e.g. `{ notifications: { access: { update: authenticated } } }`; the way to change the plugin globals' access or hooks |
| `revalidatePath` | none | `revalidatePath` from `next/cache` (injected): saving any plugin global revalidates the whole layout (`buildGlobalRevalidateHook`) | omit = globals change after the ISR window; once: `context: { disableRevalidate: true }` |
| `enabled` | `true` | `false` → collections, globals and fields stay (schema and migrations unchanged), but no plugin endpoints (`/api/ipal/*`), no `onInit` work and no admin components; `i18n` is validated anyway | `false`; check: `payload migrate:create` after switching produces no DROP TABLE |
@@ -139,7 +141,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `IntegrationAlerts` | `beforeDashboard` | **currently always** (renders nothing when everything works) |
| `IntegrationStatusBanner` | UI field in the Site integrations tabs | always (with the global) |
| `MaskedField` | SMTP / Turnstile secrets | always |
| `TestEmailButton` | Site integrations → SMTP | always |
| `TestEmailButton` | Site integrations → E-mail sending | always |
| `MetaDescriptionCheck` | below `meta.description` | `seo` and `descriptionCheck !== false` |
| `FaviconCheck` | below Site settings → Site icon (`afterInput`) | always (with the global); remove with a `globalOverrides['site-settings']` function |
| `RowLabel` | array row labels (Cookie banner categories and cookie list; your own `rowLabel(...)`) | always |
@@ -178,11 +180,11 @@ Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ip
| image lightbox (optional) | layout + blocks | `lightbox: true` in `ipalKit`; `<SiteProviders shell lightbox>`; `<LightboxTrigger group image={lightboxImage(media, { size: 'hero' })}>` around the thumbnail (`/client`); `<RenderRichText lightbox>` | keyboard: Tab to a thumbnail, Enter → dialog with focus on Close, ←/→, Esc → focus back; Network: a resized file on a phone | lightbox.md |
| image on the frontend | `Media` primitive | `<Image {...mediaImageProps(media, { sizes })} />`, video `videoProps` | blur before load | media.md |
| storage | `payload.config.ts` | `buildR2Storage(['media'], { s3Storage })` — always (without `R2_*` = local disk) | upload → URL from `R2_PUBLIC_URL` | storage.md |
| e-mail | `payload.config.ts` | `email: mailAdapter()` (SMTP from the panel / Graph from env; also `panelSmtpAdapter`, `graphAdapter`, `sendEmail` from `/server`) | Site integrations → SMTP → **Send test** | email.md |
| e-mail | `payload.config.ts` | `email: mailAdapter()` (SMTP from the panel / Graph from env; also `panelSmtpAdapter`, `graphAdapter`, `sendEmail` from `/server`) | Site integrations → E-mail sending → **Send test** | email.md |
| forms — action | `app/(frontend)/[locale]/actions.ts` | `'use server'`; `export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`/server`) | submit → document in Form Submissions + e-mails | forms.md, skill **ipal-form** |
| forms — files | config + panel | `forms: { attachments: true }`; a **File** field on the form; an e-mail with fixed recipients in Forms → E-mails; `mailAdapter({ graph: { largeAttachments } })` when Graph must stay under 3 MB; Azure: `Mail.ReadWrite` limited to the forms mailbox for files of 3 MB and more over Graph | Test e-mail with "Attach a 10 MB test file" arrives; a submission with a PDF arrives with the attachment; nothing in Media | forms.md "Files", email.md "Attachments" |
| forms — render | form block | `<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />` (`/rsc`) | form from the panel, Turnstile, message from Notifications | forms.md |
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site integrations → Turnstile or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site integrations → Spam protection or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
| consent | layout + policy page | banner via `SiteProviders`; table `<CookieTable rows={…} labels={…} />` (`/rsc`) from `getCookieTable` | `ipal-consent-check`; delete the consent cookie → the banner comes back | consent.md |
| cookie crawl | config + env + service | `cookieScanner: { crawl: true }`, `IPAL_COOKIE_SCAN_URL` / `IPAL_COOKIE_SCAN_TOKEN`, site in the service's `IPAL_CRAWLER_SITES`; optional Coolify scheduled task `curl -X POST -H "Authorization: Bearer $IPAL_COOKIE_SCAN_TOKEN" $U/api/ipal/cookie-crawl` | **Check site** → "Last crawl …: N pages, N violations"; *Privacy → Cookie check* | cookie-scanner.md → Browser crawl |
| cookie list | config | `cookieScanner: true` (+ `declarations` for embeds/chat), `generate:importmap`, `migrate:create` | *Cookie review* → **Scan cookies** → **Review and approve** → **Approve and add** → Cookies → Cookie list; `<CookieBanner settings="detailed">` and `<CookieTable>` list it | cookie-scanner.md |
@@ -232,13 +234,13 @@ and what throws without `i18n`: frontend.md. `SiteProviders` props: `shell`, `ba
| variable | required when | effect when missing | where to set |
|---|---|---|---|
| `DATABASE_URI` | always (Payload; `ipalEnvRules` always) | no database, startup fails | env (name: `databaseVar`); the database is named `<domain without dots>_prod` / `_dev` (`intecioncom_prod`), checked by `databaseName: true` |
| `PAYLOAD_SECRET` | always | Payload does not start; `assertEnv` throws | env, ≥32 characters, different in prod (`secretVar`) |
| `PAYLOAD_SECRET` | always; ≥ 32 characters in production (`ipalEnvRules({ secretMinLength })`, default 32, `0` = off) | Payload does not start; `assertEnv` throws (also for a too-short secret in production) | env, different in prod (`secretVar`) |
| `NEXT_PUBLIC_SERVER_URL` | always (`kind: 'url'`) | sitemap/robots/canonical/JSON-LD/llms with origin `''` (relative), IndexNow does not send, R2 relative URL without a prefix | env (`serverUrlVar`) |
| `NODE_ENV` | no (`development`/`production`/`test`) | `production` is stricter: R2 and `IPAL_IP_HEADER` required, IndexNow works, IP warning, `buildImagesConfig` prod | set by Next / hosting |
| `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` | `storage: true` + production, or when at least one is set (all or none) | local disk (in prod files disappear on redeploy); incomplete set → warning | env |
| `R2_PUBLIC_URL` | optional; required only with `ipalEnvRules({ storage: { requirePublicUrl: true } })` (then like the other `R2_*`); absolute URL in prod when set | empty (default) → media served by the app at `/api/media/file/…` (Media needs `access.read: () => true`); set it only for a media domain on Cloudflare (storage.md); `R2_PUBLIC_URL` alone in dev = media read-only; `/media` allowed outside prod; also used by `buildImagesConfig`, `MediaPreconnect`, CSP | env |
| `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER` | `emailGraph: true` / Graph transport in the panel | `mailAdapter` falls back to SMTP from the panel (logged) | env (agency Exchange) |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | `turnstile: true` (names: `siteKeyVar`/`secretVar`) | fallback for keys from Site integrations → Turnstile; neither set → Turnstile off | panel (takes precedence) or env |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | `turnstile: true` (names: `siteKeyVar`/`secretVar`) | fallback for keys from Site integrations → Spam protection; neither set → Turnstile off | panel (takes precedence) or env |
| `INDEXNOW_KEY` | no | key from Site integrations → IndexNow (generated) | env or panel |
| `IPAL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) |
| `IPAL_COOKIE_SCAN_URL`, `IPAL_COOKIE_SCAN_TOKEN` | `cookieScanner.crawl` (`ipalEnvRules({ cookieCrawl: true })` requires both in production; token ≥ 16 chars) | **Check site** disabled, the box names the missing variable | env; the token also goes into the scanner service's `IPAL_CRAWLER_SITES` as `host=token` |
@@ -53,20 +53,22 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `adminOnly` | `@intecion/ipal-kit` | Collection `Access`: `admin` role only. In `access.read/create/update/delete`. |
| `adminOrEditor` | `@intecion/ipal-kit` | Collection `Access`: `editor` or `admin`. Typical for content edited in the panel. |
| `adminOrSelf` | `@intecion/ipal-kit` | Collection `Access`: admin sees everything, a logged-in user only their own document (`Where` `id = user.id`), anonymous nothing. E.g. `users.read`. |
| `adminOrSelfIn(slug)` | `@intecion/ipal-kit` | `adminOrSelf` for the auth collection `slug`: only an account **of that collection** is "self"; an account of another auth collection gets nothing. Use it whenever the project has more than one auth collection (with numeric ids `adminOrSelf` would match customer no. 5 with staff account no. 5). The injected auth collection uses it. |
| `authenticated` | `@intecion/ipal-kit` | Collection `Access`: any logged-in user. |
| `requireRole(minimum)` | `@intecion/ipal-kit` | Collection `Access` factory: at least the given role (`'user' \| 'editor' \| 'admin'`). |
| `adminOnlyField` | `@intecion/ipal-kit` | `FieldAccess` (boolean only): field for admin only. In `field.access.read/update`. |
| `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)` | `@intecion/ipal-kit` | Predicate → `boolean`: whether the user has a role ≥ `minimum` (reads `user.roles` safely). For your own access logic/hooks. |
| `isAdmin(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `admin` role. |
| `isEditor(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `editor` or higher. |
| `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`): role ≥ `minimum`, **or** any logged-in user when the user's auth collection has no `roles` field (the project omitted `access`). The plugin's staff features use it (Site integrations, settings globals, test e-mail, stats, consent records, form submissions). Use it in your own access when the project may run without roles. |
| `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. |
| `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:** `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`).
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `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`
@@ -288,7 +290,7 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection,
| Export | Import from | What it does / when |
|---|---|---|
| `assertEnv(rules, { env?, label? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | validates `process.env` against the rules at startup; collects every missing item and throws one error |
| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, databaseVar?, databaseName? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | ready rule set (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` depending on the features used) for `assertEnv`; `R2_PUBLIC_URL` optional unless `storage: { requirePublicUrl: true }`; `databaseName: true \| { domain?, warn? }` only warns when the `DATABASE_URI` database is not `<domain without dots>_prod` / `_dev` |
| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, secretMinLength?, databaseVar?, databaseName? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | ready rule set (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` depending on the features used) for `assertEnv`; `R2_PUBLIC_URL` optional unless `storage: { requirePublicUrl: true }`; `secretMinLength` (default 32, `0` = off) is the minimum `PAYLOAD_SECRET` length in production; `databaseName: true \| { domain?, warn? }` only warns when the `DATABASE_URI` database is not `<domain without dots>_prod` / `_dev` |
| `databaseNamesFor(domainOrUrl)` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | the two database names for a site: `intecion.com` → `{ prod: 'intecioncom_prod', dev: 'intecioncom_dev' }` (`www.` dropped, dots removed) |
| `databaseNameFromUri(uri)` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | the database name (URI path) of a Mongo / Postgres `DATABASE_URI`; null for SQLite files or no name |
| `checkDatabaseName({ databaseUri, domain })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | warning text when the name breaks the rule, else null (skips localhost / no domain) — what `databaseName` uses |
@@ -567,7 +569,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). A required field (layout) with references is written complete in the first write; a link to a page later in the same call waits for it; required cycles and unknown targets are an error with nothing written; the dry run reports the same. |
| `upsertBy(collection, key, data)` | (method) | Matches by other keys, e.g. a form by `{ title }`. |
| `fillGlobal(slug, data)` | (method) | Fills only empty fields of a global — a choice (select, radio, checkbox, number, date) still at its `defaultValue` counts as empty, text never does; a field already holding the seeded value is skipped (all seeded fields with `update` when untouched). |
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, notListed, errors }`; exit 1 when `errors`. |
| `guardSeedExit({ label?, log?, process? })`, `activeSeedExitGuard()` | `@intecion/ipal-kit/seed` | Call first in a seed script: a run that ends before Payload initializes or before `summary()` (Node exiting through an empty event loop under `payload run`) prints `[seed] ended before …` and exits 1 instead of a silent 0. `createSeeder` / `summary()` report to it; `dispose()` stops it. |
| `isLocalDatabase(url, { localHosts? })` | `@intecion/ipal-kit/seed` | `true` for SQLite files, Unix sockets, localhost / 127.0.0.1 / ::1 (+ `SEED_LOCAL_HOSTS`). |
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field, or a whole array per locale) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids (shared rows of non-localized arrays and blocks; a `localized: true` field keeps rows per locale). |
@@ -583,6 +585,8 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|---|---|---|
| `buildSecurityHeaders({ hsts?, csp?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. `csp` = `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`); off by default. `additional` overrides by key. |
| `withSecurityConfig(nextConfig, { hidePoweredBy? })` | `@intecion/ipal-kit` | Next config wrapper: `poweredByHeader: false` + drops `X-Powered-By` from `headers()` (Next's "Next.js" and withPayload's "Next.js, Payload"). `withPayload(withSecurityConfig(nextConfig))`; `hidePoweredBy: false` = no change. |
| `secondFactorPassed(req)` | `@intecion/ipal-kit` | `boolean` with `req` (`{ payload, user }`): `false` only for an account of the 2FA collection that has TOTP set up and has not entered the code in this session (password only). `true` for a full login, an API key, an account that has not set TOTP up yet, accounts of other auth collections, no user, and with `twoFactor: false`. Guard your own endpoints with it: `if (!req.user \|\| !secondFactorPassed(req)) return 403`. |
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
| `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` |
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
| `buildCspHeaders(args)` | `@intecion/ipal-kit` | `[csp, Reporting-Endpoints]` (the second only with `reportUri`). |
+1 -1
View File
@@ -31,7 +31,7 @@ Checks the **running** app, not the code — exactly what Googlebot gets.
| no JSON-LD structured data | no `<SiteProviders>` / `<JsonLdGraph>` in `[locale]/layout.tsx`, or an empty name in Site settings |
| `/llms.txt` / `/llms-full.txt` → 404 | no route (`export { llmsRoute as GET }` / `llmsFullRoute` from `lib/content`) |
| Markdown version `/md/…` → 404 | no `src/app/md/[locale]/[[...slug]]/route.ts`; the page is noindex/draft |
| `sitemap.xml → 503` | database unreachable while building the sitemap (`sitemapRoute` returns 503 + Retry-After instead of an empty one) — check `DATABASE_URL` / database health |
| `sitemap.xml → 503` | database unreachable while building the sitemap (`sitemapRoute` returns 503 + Retry-After instead of an empty one) — check `DATABASE_URI` / database health |
| sitemap index parts not 200 | site > `maxUrls` (10 000) → `/sitemap.xml` is an index; the `?part=N` parts must answer 200 — your own route without `part` handling, or a CDN cache with an old part count |
| MCP not answering initialize | no `src/app/api/mcp/route.ts`, or Cloudflare Access without a Bypass (mcp.md) |
@@ -228,7 +228,7 @@ if (issues.noLinks.length) report('WARNING', 'pages without internal links', 'li
if (!skipped('jsonld') && issues.jsonLd.length) report('ERROR', 'no JSON-LD structured data', '<JsonLdGraph> WebSite + Organization in [locale]/layout.tsx (AGENT.md §0b.4)', issues.jsonLd.slice(0, 5))
if (!skipped('markdown') && issues.mdAlt.length) report('WARNING', 'no text/markdown alternate link in head', 'createContentHelpers({ markdownAlternate: true }) (AGENT.md §0b.6)', issues.mdAlt.slice(0, 3))
// --- 4b. Search Console / Bing verification tags (Site Settings → Search & AI) ----
// --- 4b. Search Console / Bing verification tags (Site Settings → Search engines) ----
// INFO only: domain (DNS) verification — the recommended route — leaves the tags empty.
if (!skipped('verification') && sample.length) {
const page = await get(sample[0]).catch(() => null)
@@ -236,7 +236,7 @@ if (!skipped('verification') && sample.length) {
const missing = [['google-site-verification', 'Google Search Console'], ['msvalidate.01', 'Bing Webmaster Tools']]
.filter(([name]) => !new RegExp(`<meta[^>]+name="${name}"`, 'i').test(head))
.map(([, label]) => label)
if (missing.length) report('INFO', 'no verification meta tag (fine with DNS / domain verification)', 'only for URL-prefix verification: paste the code in Site Settings → Search & AI', missing)
if (missing.length) report('INFO', 'no verification meta tag (fine with DNS / domain verification)', 'only for URL-prefix verification: paste the code in Site Settings → Search engines', missing)
}
// --- 5. 404 ---------------------------------------------------------------
+23 -11
View File
@@ -74,7 +74,7 @@ pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create <
```
It generates the site from the reference site, writes `.env` (fresh `PAYLOAD_SECRET`), installs from the shipped
lockfile, runs `ipal-skills`, `ipal-tokens`, `generate:types`, `generate:importmap`, `typecheck` (and `ipal-doctor
--strict` when shipped), checks for secrets and makes the first commit. **Check:** `git log --oneline` = 1 commit,
--strict --offline` when shipped), checks for secrets and makes the first commit. **Check:** `git log --oneline` = 1 commit,
`git status` clean, `AGENTS.md` → "Project decisions" holds every answer, `pnpm typecheck` passes. Then go to stage 11.
**Turn off / override:** it stops (nothing written) for **single-language sites** and **a default language other than
`pl`** (not supported yet), sites without `en`, URLs without a prefix and
@@ -96,11 +96,13 @@ pnpm add @intecion/ipal-kit @payloadcms/plugin-seo @payloadcms/plugin-form-build
**Next.js 16.4.5 or later** (minimum safe version: 16.0.0–16.4.0 have critical advisories, 16.3.0–16.4.4 have
GHSA-mfr8-8qww-v76h — AGENT.md §4 item 11): `pnpm add [email protected] [email protected] sharp@^0.35.5` when
create-payload-app gave you an older one.
**Node.js 20 or later** (the plugin's `nodemailer` 10 requires it). After the install, `pnpm audit --prod` → no high or
critical; with `payload` 3.90.x add the `dompurify`, `graphql-scalars`, `happy-dom`, `mongoose` and `undici` overrides
from AGENT.md §4 item 12 (`"mongoose@>=8 <8.24.7": "~8.24.10"` lifts the 8.24.1 that `@payloadcms/db-mongodb` pins —
one critical and two high advisories; `"happy-dom@<21.0.4": "^21.0.4"` fixes two high ones). `pnpm exec ipal-doctor`
→ no `transitive-min` finding.
**Payload 3.94.1** (what the reference site and the starter use; the plugin accepts `^3.90.2`): every `payload` /
`@payloadcms/*` on the same exact version, `react` and `react-dom` 19.3.1 (Payload 3.94 requires `^19.3.1`), and
**Node.js 22.23.5 or later** on the 22 line (`"engines": { "node": ">=22.23.5 <23" }`, `.nvmrc` `22`) — Payload 3.94's
minimum, also in Coolify (Nixpacks picks the patch: check `node -v` in the app's Terminal after the first deploy). After the install, `pnpm audit --prod` → no high or critical; add the `dompurify` and `happy-dom` overrides
from AGENT.md §4 item 12 (`"happy-dom@<21.0.4": "^21.0.4"` fixes two high advisories Lexical still brings in). On an
older Payload also the `mongoose` (MongoDB) and `undici` ones listed there. `pnpm exec ipal-doctor` → no
`transitive-min` finding.
`nodemailer`, `lucide-react`, `slugify`, `server-only` come with the plugin — do not add them (your own
`lucide-react` only `~0.400.0`). In `package.json`: pin every `@payloadcms/*` (ui, next, db-*, richtext-lexical,
plugin-seo, plugin-form-builder, storage-s3) in `pnpm.overrides` **to the exact `payload` version**, then
@@ -197,12 +199,12 @@ export default buildConfig({
`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`,
`GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER`. Local `.env` with `PAYLOAD_SECRET` ≥ 32 characters.
`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).
**Check.** `pnpm payload generate:importmap` (whiteLabel adds admin components) and `pnpm generate:types` without
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading);
the panel shows Site settings, Site integrations, Cookie banner, Notifications, the Forms group, Consent records.
the panel shows Site settings, Site integrations, Cookies, Form messages, the Forms group, Consent records.
`curl -s -o /dev/null -w '%{http_code}' -X POST localhost:3000/api/ipal/consent -H 'content-type: application/json'
-d '{"id":"0123456789abcdef","version":1,"state":{"necessary":true,"functional":false,"analytics":false,"marketing":false}}'` → `201`.
@@ -215,11 +217,21 @@ the panel shows Site settings, Site integrations, Cookie banner, Notifications,
(discouraged); without an injected `plugin: payloadTotp` it also throws. `forceSetup` currently always `true`.
- `users`: the injected collection lets admins manage everyone and others only themselves — loosen with
`access: { authCollection: 'users', authAccess: { read: authenticated } }` (your keys win); your own collection with
that slug wins whole (the plugin only adds `roles` — give it `adminOrSelf` / `adminOnly`). The first account
that slug wins whole (the plugin only adds `roles` — give it `adminOrSelfIn('users')` / `adminOnly`). The first account
(Create first user) gets `admin` — `access.firstUserAdmin: false` turns that off. `localization` currently always
overridden from `i18n`.
- 2FA wraps the panel's login collection (`admin.user`); a different `twoFactor.collectionSlug` stops startup with
`[ipal] twoFactor…` unless `allowCollectionMismatch: true`.
`[ipal] twoFactor…` unless `allowCollectionMismatch: true`. The second factor covers every collection and global
(the plugin's own, and those of plugins listed after `ipalKit`) and the plugin's endpoints; guard your own
endpoints with `secondFactorPassed(req)` or `userMeetsRole(req, role)` (security.md "What the second factor covers").
Verify attempts: 5 per account in 10 minutes (`twoFactor.verifyLimit`).
**Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone
opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`.
- 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
collection of STAFF goes in `access.staffCollections` (access.md "Who is staff"). Check: that account's token
gets `403` from `/api/globals/site-integrations` and `/api/form-submissions`.
- The `site-settings`, `site-integrations`, `cookie-settings`, `notifications` globals (write: editor+; Site
Integrations: admin), the `/api/ipal/test-email` endpoint and dashboard alerts — currently always present; extend
`siteSettingsFields` / `integrationsFields`; change access, admin or hooks with
@@ -509,7 +521,7 @@ Cookies → Cookie list; on the cookie policy page a block with `<CookieTable>`
the same list appears in the `settings="detailed"` dialog (labels: Cookies → Settings window → Cookie list headings, every language).
**Check.** Panel → Forms: the seeded form; a submission on `/pl` → an entry in Form Submissions + 2 emails (SMTP:
Site integrations → SMTP → Send test); with Turnstile test keys the widget is visible, without a token the submission is rejected;
Site integrations → E-mail sending → Send test); with Turnstile test keys the widget is visible, without a token the submission is rejected;
`node .agents/skills/ipal-consent-check/scripts/consent-check.mjs http://localhost:3000/pl` = 0 errors;
after a choice in the banner a new record in Consent records.
+76 -9
View File
@@ -87,18 +87,33 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
(a new image ships the fixed next and sharp). **Check:** `pnpm exec ipal-doctor` → no `next-min` finding; `pnpm dev`
prints no security-upgrade warning.
**Every upgrade — dependency advisories** (AGENT.md §4 item 12): `pnpm audit --prod`; with `payload` 3.90.x add the
`dompurify`, `graphql-scalars`, `happy-dom`, `mongoose` and `undici` overrides to `pnpm.overrides`, `pnpm install`, audit
again. MongoDB sites need the `mongoose` one now: `@payloadcms/db-mongodb` pins 8.24.1 (up to Payload 3.93.0), which has
a critical advisory (GHSA-pcrw-h46h-c93h) and four more, all fixed in 8.24.7:
**Every upgrade — Payload** (AGENT.md §4 items 11–12): the reference site and the starter run Payload **3.94.1**; the
plugin still accepts `^3.90.2`, so moving is recommended, not forced. To move: every `payload` / `@payloadcms/*` (in
`dependencies` and in `pnpm.overrides`) to the same exact version, `react` and `react-dom` to 19.3.1 (Payload 3.94
requires `^19.3.1`), Node.js 22.23.5 or later (`"engines": { "node": ">=22.23.5 <23" }`, `.nvmrc` `22`) on every machine and
in Coolify — Payload 3.94 refuses older Node. Nixpacks takes only the major from `engines` / `.nvmrc`; the patch comes
from the Nixpacks release on the Coolify server, so check `node -v` in the app's Terminal (or the build log) and update
Coolify first if it is below 22.23.5 (until then, stay on 3.90.x). Then `pnpm install`, `pnpm payload generate:types`, `pnpm payload generate:importmap`, `rm -rf .next`,
build, redeploy. Payload 3.91–3.94 change no schema the plugin defines: no migration from the plugin; on
Postgres/SQLite run `pnpm payload migrate:create` anyway and commit it if it is not empty.
**Check:** `pnpm ls payload @payloadcms/ui @payloadcms/db-mongodb` → one version, 3.94.1; the panel opens and a document
saves; `pnpm exec ipal-doctor` → no `versions` finding; Coolify app → Terminal → `node -v` → 22.23.5 or later.
**Every upgrade — dependency advisories** (AGENT.md §4 item 12): `pnpm audit --prod`; on Payload 3.94.x add the
`dompurify` and `happy-dom` overrides to `pnpm.overrides`; on an older Payload also `mongoose` (MongoDB sites; 3.90–3.93
pin 8.24.1, which has a critical advisory, GHSA-pcrw-h46h-c93h, and four more) and `undici` (3.90–3.91):
```json
"dompurify@<3.4.17": "^3.4.17",
"happy-dom@<21.0.4": "^21.0.4",
"mongoose@>=8 <8.24.7": "~8.24.10"
"mongoose@>=8 <8.24.7": "~8.24.10",
"undici@>=7 <7.30.1": "^7.30.1"
```
Then `pnpm install`, `pnpm build`, commit `package.json` and the lockfile, redeploy on Coolify (the new image ships the
fixed packages; no data or schema change, no migration). **Check:** `pnpm audit --prod` → no high or critical (the
`deepmerge` low has no fix yet); `pnpm why mongoose happy-dom` → 8.24.7 or later, 21.0.4 or later;
`pnpm exec ipal-doctor` → no `transitive-min` finding; the panel opens and a document saves.
The selectors match only vulnerable versions, so on 3.94.x the last two do nothing — remove them. A
`"graphql-scalars@<2.0.1": "^2.0.1"` line is no longer needed (the advisory no longer covers Payload's 1.22.2); remove
it or keep it. Then `pnpm install`, `pnpm build`, commit `package.json` and the lockfile, redeploy on Coolify (no data or
schema change, no migration). **Check:** `pnpm audit --prod` → no high or critical; `pnpm why dompurify happy-dom
mongoose undici` → 3.4.17, 21.0.4, 8.24.7, 7.30.1 or later; `pnpm exec ipal-doctor` → no `transitive-min` finding; the
panel opens and a document saves.
**→ 1.14.0 (PROGRAMISTA §6, items 48–49; CHANGELOG "What projects must update" — do all 8, in order):**
1. `pnpm payload generate:importmap` — `@intecion/ipal-kit/admin#FaviconCheck` (hint under Site settings → Site icon)
@@ -295,6 +310,58 @@ every site:**
**Check:** `pnpm why mongoose happy-dom` → mongoose 8.24.10, happy-dom 21.0.4; `pnpm audit --prod` → no high or critical;
`pnpm exec ipal-doctor` → no `transitive-min` finding; open the panel and save a document.
**→ 1.16.3 (PROGRAMISTA §6, item 64; Payload 3.94.1 in the reference site and the starter; AGENT.md §4 items 11–12) —
recommended, not required (the plugin's peer range stays `^3.90.2`):**
1. **Node.js 22.23.5 or later first — everywhere the site runs.** Payload 3.94 refuses older Node. Locally: `node -v`.
Coolify: Nixpacks takes only the major from `engines` / `.nvmrc`; the patch comes from the Nixpacks release on the
server, so open the app → Terminal → `node -v` (or read the build log). Below 22.23.5: update Coolify first, and
stay on Payload 3.90.x until then. CI images must resolve to 22.23.5 or later as well.
2. Every `payload` / `@payloadcms/*` to 3.94.1 (in `dependencies` and `pnpm.overrides`), `react` and `react-dom` 19.3.1,
`"engines": { "node": ">=22.23.5 <23" }` (`.nvmrc` stays `22`). Overrides: keep `"dompurify@<3.4.17": "^3.4.17"`
and `"happy-dom@<21.0.4": "^21.0.4"`; remove the `mongoose`, `undici` and `graphql-scalars` lines (they do nothing
on 3.94.x). Then `pnpm install`, `pnpm payload generate:types`, `pnpm payload generate:importmap`, `rm -rf .next`,
`pnpm build`; commit `package.json` and the lockfile, redeploy on Coolify.
3. Postgres/SQLite: `pnpm payload migrate:create`, commit it if it is not empty (3.94.1 changes long index and foreign
key names). MongoDB: no migration.
4. `pnpm ipal:skills` (updated `ipal-setup` / `ipal-upgrade`).
**Check:** `pnpm ls payload @payloadcms/ui @payloadcms/db-mongodb` → 3.94.1; `pnpm why dompurify happy-dom` → 3.4.17,
21.0.4; `pnpm audit --prod` → no high or critical; `pnpm exec ipal-doctor` → no `versions` finding; Coolify Terminal
`node -v` → 22.23.5 or later; the panel opens, a document saves, a form submission arrives.
**→ 1.16.4 (PROGRAMISTA §6, items 65–66; security fixes: 2FA coverage and staff checks) — required
for every site:**
0. **Before deploying:** check the production `PAYLOAD_SECRET` length (Coolify app → Terminal →
`node -e 'console.log(process.env.PAYLOAD_SECRET.length)'`). Shorter than 32: set a new random secret (with the
owner's OK: logs everyone out, 2FA code again, API keys regenerate; deployment.md "`PAYLOAD_SECRET` — length and
changing it"), or add `secretMinLength: 0` to `ipalEnvRules({ … })` for now and note it under "Project
decisions" in AGENTS.md.
1. Update the package, `pnpm install`, `pnpm ipal:skills`, build, redeploy on Coolify. No migration, no config
change for a site with one auth collection. `pnpm ls @clocklimited/payload-2fa` should show 3.0.0-beta.7 (tested: beta.1 and beta.7);
another version may stop startup with `[ipal] twoFactor: the injected 2FA plugin did not add …`.
2. `grep -rn "auth:" src/collections` — more than one auth collection? Then: `admin: { user: '<staff slug>' }` in
`buildConfig`; `adminOrSelfIn('<slug>')` instead of `adminOrSelf` in each; `access.staffCollections` only when
the second collection is staff (access.md "Who is staff"). Never list a visitor collection there. Roles now
count only for accounts of a staff collection: code that relied on `isAdmin` / `adminOnly` for accounts of
another collection needs its own rule (`req.user.collection === '…'`).
3. `grep -rn "overrideAccess: false" src` — a call on a plugin collection or global (`form-submissions`, `forms`,
`consent-records`, `stats-visits`, `cookie-review`, the settings globals) must pass the `user` from
`payload.auth({ headers })`; a user object built by hand needs `collection: '<staff slug>'` for its role to
count. Own endpoints that check `req.user`: add `secondFactorPassed(req)` or use `userMeetsRole(req, role)`.
`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'] })`.
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
password and Turnstile secret, a look through Site settings, Site integrations and each form's Emails tab.
Do not change those values yourself without that decision.
**Check:** with 2FA on, log in over the API with the password only (security.md → "What the second factor covers" →
Check) → `403` from `/api/globals/site-integrations`, `/api/form-submissions`, `/api/users`; log in fully in the
panel → Site integrations and a form submission open, a setting saves. With a second auth collection: its token
gets `403` from the same addresses and from `POST /api/setup-totp`. The Coolify log has no
`PAYLOAD_SECRET must be at least`; `pnpm exec ipal-doctor` has no `env` finding.
## 2. Inventory (no code changes)
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
+1 -1
View File
@@ -233,7 +233,7 @@ Container ID and keep GA4 alone, to rule out the container as a variable.
- **Extend:** other scripts → `ConsentScript` ([consent.md](./consent.md)); low-level
`loadMetaPixel` / `loadClarity` / `loadLinkedIn` / `loadTikTok`, `pushDataLayer` from `/client`;
`setDefaultConsent` / `updateConsent` from the root; your own fields in Site integrations via
`ipalKit({ integrationsFields })` (*Custom* tab).
`ipalKit({ integrationsFields })` (*More* tab).
## Meta Pixel via GTM
+1 -1
View File
@@ -414,7 +414,7 @@ to add the hook to a config. Nothing to migrate.
| Option | `consentLog?: boolean \| { retentionDays?: number; collectionOverrides?: CollectionOverride }` (type `ConsentLogOptions`) |
| `retentionDays` | default `1095` (3 years) |
| `collectionOverrides` | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), other keys replace; a function `(collection) => collection` takes over (keep the slug — the endpoint writes to it) |
| Collection | `consent-records` (`CONSENT_LOG_SLUG`), group *Settings*; fields `consentId` (index), `version`, `choices.{necessary,functional,analytics,marketing}`, `createdAt` |
| Collection | `consent-records` (`CONSENT_LOG_SLUG`), group *Privacy*; fields `consentId` (index), `version`, `choices.{necessary,functional,analytics,marketing}`, `createdAt` |
| Collection access | `read` / `delete` — admin (without `access`, i.e. no roles: any logged-in account — narrow it with `collectionOverrides`); `create` / `update` — nobody through the API (written only by the endpoint, `overrideAccess`) |
| Endpoint | `POST /api/ipal/consent`, public (no login) |
| Body | `{ id: string (hex 16–64), version: int ≥ 1, state: { necessary, functional, analytics, marketing: boolean } }` |
+2 -2
View File
@@ -9,8 +9,8 @@ subpages (e.g. a brief), and everything else is blocked — no code changes, one
| Field | Meaning |
|---|---|
| Site under construction | turns the mode on |
| Pages still available | pages that still open; **the home page is always available** |
| Maintenance mode | turns the mode on |
| Available pages | pages that still open; **the home page is always available** |
| Notice title / text / Close button label | popup content (per language); empty button → `×` with a screen-reader name in the page language ("Close" / "Zamknij") |
Fields in the SiteSettings global: group `construction` → `enabled`, `allowedPages` (relationship to the pages
+1 -1
View File
@@ -237,7 +237,7 @@ API route; the admin view is at `COOKIE_APPROVAL_VIEW_PATH` (`/cookie-approval`)
## Collection `cookie-review`
`COOKIE_REVIEW_SLUG`, group *Settings*. Fields: `name`, `storage` (`cookie` / `localStorage` /
`COOKIE_REVIEW_SLUG`, group *Privacy* (with the default `adminLayout: 'combined'` it is out of the navigation and shown as the *Review and approve* tab of *Cookies*). Fields: `name`, `storage` (`cookie` / `localStorage` /
`sessionStorage`), `category`, `vendor`, `domain`, `purpose` (localized), `retention` (localized),
`setBeforeConsent`, `status` (`draft` / `accepted` / `rejected`), `needsDescription` (set when an
unknown cookie is approved without a purpose; cleared when a purpose is written), and read-only
+15 -1
View File
@@ -24,12 +24,25 @@ DATABASE_URI=mongodb://user:pass@mongo:27017/intecioncom_prod?authSource=admin
# dev: …/intecioncom_dev, or file:./dev.db
# Payload secret (signs sessions/tokens) — random, long
PAYLOAD_SECRET=<random-string-min-32-chars>
PAYLOAD_SECRET=<random-string-min-32-chars> # ipalEnvRules: ≥ 32 characters in production (secretMinLength)
# Public site URL (canonical, hreflang, OG, manifest)
NEXT_PUBLIC_SERVER_URL=https://klient.pl # dev: http://localhost:3000
```
**`PAYLOAD_SECRET` — length and changing it.** `ipalEnvRules` refuses a secret shorter than 32 characters in
production (`secretMinLength`; `0` turns the check off, outside production nothing is checked). Payload (3.94)
derives its signing key from it (`sha256(secret)`, first 32 hex characters). Changing it on a live site therefore:
- **logs everyone out** — every login token (the `payload-token` cookie, JWTs from login / refresh / password reset)
is signed with it and stops being valid;
- **asks every user for the 2FA code again** — `@clocklimited/payload-2fa` signs its own 2FA cookie with it; the TOTP
keys themselves are stored as they are, so the authenticator apps keep working;
- **breaks stored API keys** (only in collections with `useAPIKey`) — Payload stores them encrypted with the secret
and finds them by an HMAC of it: they no longer authenticate and cannot be revealed — generate new ones;
- fails uploads that are in progress (client upload receipts are signed with it).
ipal-kit itself derives nothing from it. Change it only with the owner's OK, at a quiet time, and tell the editors
they will have to log in again.
### Email — Graph (OPTIONAL, agency-level, when transport = Graph)
```bash
@@ -77,6 +90,7 @@ URLs point at that domain. Outside production, `R2_PUBLIC_URL` alone → read-on
| `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`) |
| `IPAL_DOCTOR_TOKEN` | ⬜ | ops | ≥ 32 characters turns on the `ipal-doctor` status endpoint `GET /api/ipal/doctor` (404 without it) — [doctor.md](./doctor.md) |
"✅ prod" = required by `ipalEnvRules({ storage: true })` / `({ ipHeader: true })` with
`NODE_ENV=production` — as long as the project runs the validation (env.md). The plugin itself does not stop
+21 -17
View File
@@ -57,14 +57,14 @@ tab, a missing Forms collection or a crash. In `package.json`:
```json
"pnpm": {
"overrides": {
"payload": "3.90.2",
"@payloadcms/ui": "3.90.2",
"@payloadcms/next": "3.90.2",
"@payloadcms/db-postgres": "3.90.2",
"@payloadcms/richtext-lexical": "3.90.2",
"@payloadcms/plugin-seo": "3.90.2",
"@payloadcms/plugin-form-builder": "3.90.2",
"@payloadcms/storage-s3": "3.90.2"
"payload": "3.94.1",
"@payloadcms/ui": "3.94.1",
"@payloadcms/next": "3.94.1",
"@payloadcms/db-postgres": "3.94.1",
"@payloadcms/richtext-lexical": "3.94.1",
"@payloadcms/plugin-seo": "3.94.1",
"@payloadcms/plugin-form-builder": "3.94.1",
"@payloadcms/storage-s3": "3.94.1"
}
}
```
@@ -119,7 +119,7 @@ layout under `[locale]` (because `<html lang>` must know the language).
```
Run `pnpm ipal:skills` after install and after every ipal-kit update; commit `.agents/skills/`.
(`ipal-skills` is the package `bin` — without the script: `pnpm exec ipal-skills`; options
`--dest <dir>`, `--dry-run`, `--no-pointer`.)
`--dest <dir>`, `--dry-run`, `--no-pointer`, `--external [ext-a,ext-b]`.)
The command also adds to `AGENTS.md` a `<!-- ipal-kit:start -->…<!-- ipal-kit:end -->` block
with a pointer to AGENT.md and the `ipal-reference` / `ipal-setup` skills, and creates a missing
`CLAUDE.md` with the line `@AGENTS.md`. On later runs it replaces only the text between the
@@ -460,7 +460,7 @@ pnpm dev
| Variable | Required | Description |
|---|---|---|
| `DATABASE_URI` | ✅ | Postgres / Mongo (dev can use SQLite) |
| `PAYLOAD_SECRET` | ✅ | random, ≥32 characters, different in production |
| `PAYLOAD_SECRET` | ✅ | random, ≥32 characters, different in production — `ipalEnvRules` checks the length in production (`secretMinLength`, default 32, `0` = off) |
| `NEXT_PUBLIC_SERVER_URL` | ✅ | public URL (canonical, hreflang, OG); without it links are relative |
| `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER` | ⬜ | email through Microsoft Graph |
| `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` | ✅ prod | media in Cloudflare R2 — always in production (missing → container disk, files vanish on redeploy without a volume); in dev they can be empty (storage.md) |
@@ -555,7 +555,7 @@ Test without a database: `DATABASE_URI=mongodb://invalid-host:27017/x pnpm build
### 4.6 Email — SMTP or Graph
Client on M365/Exchange → Graph (SMTP AUTH is often turned off). Own SMTP/Gmail →
SMTP. The switch is in the admin panel (Site integrations → SMTP → Email Transport).
SMTP. The switch is in the admin panel (Site integrations → E-mail sending → Sending method).
Graph, one-time: App registration in Azure, the `Mail.Send` application permission
+ **Grant admin consent**, the `GRAPH_*` variables. `from.address` always =
`GRAPH_SENDER` (otherwise `ErrorSendAsDenied`); sender name from the admin panel; the
@@ -620,8 +620,8 @@ Do one item at a time, build, check. Order by importance:
| 15j | the form front end sends `fetch('/api/form-submissions')` (from this version REST returns 403 for anonymous users) | rewrite as a server action + `submitForm` (skill `ipal-form`) | forms.md |
| 15k | Turnstile secret saved by code (`updateGlobal` in `onInit` / an action) or own `verify` without `remoteip` | delete the workaround: secret in the admin panel or env `TURNSTILE_SECRET_KEY`; the plugin does not send `remoteip` and logs the rejection reason | turnstile.md |
| 15l | a Turnstile outage blocked forms | nothing in the project: on an error on our side the plugin accepts the submission and shows an alert in the admin panel; `generate:importmap`, Postgres: `migrate:create` | turnstile.md |
| 15m | own plugin moving Notifications into a group; `formOverrides`/`formSubmissionOverrides` only for labels and the admin group | delete — the plugin itself puts Form messages → Settings, and forms → the "Forms" group with labels (`forms.adminGroup`) | forms.md |
| 15n | mail errors visible only in logs | nothing in the project: `mailAdapter()` shows the send error on the dashboard and in Site integrations → SMTP; `generate:importmap`, Postgres: `migrate:create` | email.md |
| 15m | own plugin moving Notifications into a group; `formOverrides`/`formSubmissionOverrides` only for labels and the admin group | delete — the plugin itself puts Form messages in the "Forms" group, and forms → the "Forms" group with labels (`forms.adminGroup`) | forms.md |
| 15n | mail errors visible only in logs | nothing in the project: `mailAdapter()` shows the send error on the dashboard and in Site integrations → E-mail sending; `generate:importmap`, Postgres: `migrate:create` | email.md |
| 16 | Hard-coded 404 | 404 role in System pages + `getNotFoundPage` | pages.md |
| 16a | `privacyPolicy: { label: 'Polityka prywatności', … }` in the layout | delete the whole parameter; enter the text in Cookies → Privacy link label | consent.md |
| 17 | **AI/GEO (mandatory since 1.9.0)** | llms.txt + llms-full.txt, the `/md/…` route, `markdownAlternate: true`, `prefersMarkdown` in the proxy, `/api/mcp`, `buildSummaryField`, AI bots allowed — AGENT.md §0b | content.md, seo.md, mcp.md |
@@ -671,6 +671,9 @@ Do one item at a time, build, check. Order by importance:
| 61 | **1.16.0 — files on forms** — a CV / drawing field built by hand (own upload collection, bucket, `<input type="file">` posting to an own route), or "send the file by e-mail" asked for and refused | `forms: { attachments: true }` + a **File** field (panel or seed) + one e-mail with a fixed recipient; Postgres/SQLite `migrate:create`; `generate:types`; `formClasses` keys `file`, `help`, `fileList`, `fileItem`, `fileRemove`; proxy body limit (nginx `client_max_body_size 12m`); Graph: `Mail.ReadWrite` limited to the forms mailbox, or SMTP settings, or ~2.8 MB; test e-mail with the 10 MB file; delete the hand-built upload path; `pnpm ipal:skills` | CHANGELOG 1.16.0, forms.md "Files", email.md "Attachments", deployment.md "Form files" |
| 62 | **1.16.1** — `pnpm dev` warns "Next.js 16.4.3 is affected by a known security vulnerability"; ipal-doctor `next-min` error below 16.4.5 (GHSA-mfr8-8qww-v76h) | `pnpm add [email protected] [email protected]`, `rm -rf .next`, build, commit the lockfile, redeploy on Coolify; `pnpm ipal:skills`; no option, migration or import map change | CHANGELOG 1.16.1, AGENT.md §4 item 11 |
| 63 | **1.16.2** — `pnpm audit --prod` shows `mongoose` (critical, via `@payloadcms/db-mongodb`) or `happy-dom` (high, via `@payloadcms/richtext-lexical`); ipal-doctor `transitive-min` | `pnpm.overrides`: `"mongoose@>=8 <8.24.7": "~8.24.10"` (MongoDB sites) and `"happy-dom@<21.0.4": "^21.0.4"`; `pnpm install`, build, commit the lockfile, redeploy on Coolify; `pnpm ipal:skills`; no migration | CHANGELOG 1.16.2, AGENT.md §4 item 12 |
| 64 | **1.16.3** — the reference site and the starter run Payload 3.94.1; the site is still on 3.90–3.93, or `node -v` (locally or in the Coolify app's Terminal) is below 22.23.5 | Recommended, not required (the plugin still accepts `^3.90.2`). First make sure Node is 22.23.5 or later everywhere, Coolify included (Nixpacks picks the patch: check `node -v`, update Coolify if lower). Then every `payload` / `@payloadcms/*` 3.94.1 (in `dependencies` and `pnpm.overrides`), `react` / `react-dom` 19.3.1, `"engines": { "node": ">=22.23.5 <23" }`; overrides: keep `dompurify` and `happy-dom`, drop `mongoose`, `undici` and `graphql-scalars`; `pnpm install`, `generate:types`, `generate:importmap`, `rm -rf .next`, build, redeploy; Postgres/SQLite: `migrate:create`; `pnpm ipal:skills` | CHANGELOG 1.16.3, AGENT.md §4 items 11–12, ipal-upgrade "Every upgrade — Payload" |
| 65 | **1.16.4 — security** — with 2FA on, a login with the password only gets `200` from `/api/globals/site-integrations` or `/api/form-submissions`; or the project has a second auth collection (`customers`) | Upgrade and redeploy (no config change with one auth collection). With the owner: change the SMTP password and the Turnstile secret, review Site settings / Site integrations / each form's Emails tab for values nobody set. Second auth collection: `admin: { user }` in `buildConfig`, `adminOrSelfIn('<slug>')`, `access.staffCollections` only for a second STAFF collection. Every account must have 2FA set up (`ipal-doctor --url` → 0 without). Own endpoints: `secondFactorPassed(req)`; own `overrideAccess: false` calls: `user` from `payload.auth()`. `pnpm ipal:skills`; no migration | CHANGELOG 1.16.4, security.md "What the second factor covers", access.md "Who is staff" |
| 66 | **1.16.4** — production `PAYLOAD_SECRET` shorter than 32 characters (the site would stop at `assertEnv`) | Before deploying 1.16.4, check the length in Coolify (`node -e 'console.log(process.env.PAYLOAD_SECRET.length)'`). Shorter: a random 32+ character secret (logs everyone out, asks for 2FA again, breaks stored API keys), or `ipalEnvRules({ secretMinLength: 0 })` for now | CHANGELOG 1.16.4, deployment.md "PAYLOAD_SECRET — length and changing it" |
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`.
@@ -744,9 +747,9 @@ a missing export in `src/index.ts` (`is not a function` in the project), `pnpm a
dev is running.
`dist/` **is not in git** (`.gitignore`). `prepublishOnly` runs `pnpm clean && pnpm build &&
pnpm test:int` before every `npm publish`, so you cannot release a stale dist or a
version with red tests (`pnpm clean && pnpm build` above is only a grep check before the
commit). `prepare` (`pnpm build`) builds the package on install from git and on `pnpm install` in the repo.
pnpm build:starter && pnpm test:int && pnpm starter:gate` before every `npm publish`, so you cannot release a stale
dist, a version with red tests or a starter that does not produce a working site
(docs/project-starter.md; `pnpm clean && pnpm build` above is only a grep check before the commit). `prepare` (`pnpm build`) builds the package on install from git and on `pnpm install` in the repo.
`typecheck` and `lint` are **not** in `prepublishOnly` — before a commit: `pnpm typecheck && pnpm lint &&
pnpm test:int` (CI in `.gitea/workflows/ci.yml` runs typecheck, lint, test:int and build on push and PR).
@@ -793,7 +796,8 @@ an empty project (only errors) and a complete one (0 errors). CI (`.gitea/workfl
typecheck, lint, tests and build on every push.
### 8.2 Plugin package.json
- `"files": ["dist", "docs", "bin"]` — **the docs and the `ipal-skills` command ship in the package**; agents in projects
- `"files": ["dist", "docs", "bin", "src/modules/block-library"]` — **the docs and the `ipal-skills` command ship in the package**
(the block-library source is what `ipal-blocks eject` copies); agents in projects
read `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`. Without `docs` they have nothing.
- One `exports` block, all paths to `./dist/` (not `./src/`).
- `payload`, `@payloadcms/*`, `next`, `react` → **`peerDependencies`**
+2 -2
View File
@@ -69,7 +69,7 @@ returns counts only — never names, e-mails or values:
{ "node": "v22.20.0", "pendingCookies": 0, "plugin": "1.15.0", "usersWithout2fa": 0 }
```
Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'MY_TOKEN', access: ({ req }) => … } })`
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)
(`access` lets a logged-in admin read it without the token). Building blocks: `buildDoctorEndpoint`,
`collectDoctorStatus` from `@intecion/ipal-kit/doctor`.
@@ -81,7 +81,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
| | `plugin-latest` | warning; error two or more minors behind | the installed plugin is the newest on the team registry (registry) |
| | `next-min` | error | `next` ≥ 16.4.5 (below 16.4.1: RCE/DoS advisories; 16.3.0–16.4.4: GHSA-mfr8-8qww-v76h); `eslint-config-next` on the same minor (warning) |
| | `sharp-min` | error | `sharp` ≥ 0.35.5 |
| | `transitive-min` | error (`mongoose`), warning (`happy-dom`) | packages Payload pins below a security fix, in any depth of the tree (read from `pnpm-lock.yaml`, else `node_modules/.pnpm`): `mongoose` 8.x ≥ 8.24.7 (GHSA-pcrw-h46h-c93h and four more), `happy-dom` ≥ 21.0.4 (GHSA-c8p4-j97h-3vg8, GHSA-834v-8h66-3h79). The fix it prints is the `pnpm.overrides` line from AGENT.md §4 item 12 |
| | `transitive-min` | error (`mongoose`), warning (`happy-dom`) | packages Payload pins below a security fix, in any depth of the tree (read from `pnpm-lock.yaml`, else `node_modules/.pnpm`): `mongoose` 8.x ≥ 8.24.7 (GHSA-pcrw-h46h-c93h and four more; Payload 3.90–3.93 pin 8.24.1, 3.94.0+ ship 8.24.7 — the fix it prints names the Payload upgrade first), `happy-dom` ≥ 21.0.4 (GHSA-c8p4-j97h-3vg8, GHSA-834v-8h66-3h79). The fix it prints is the `pnpm.overrides` line from AGENT.md §4 item 12 |
| | `node-22` | warning | `engines.node` only 22 (`">=22 <23"`), `.nvmrc` / `.node-version` = 22; with `--deep`, the running Node |
| | `pnpm-pinned` | info | `packageManager` is set |
| | `deps-audit` | error on critical/high, info on moderate/low | `pnpm audit --prod` (registry) |
+2 -2
View File
@@ -276,7 +276,7 @@ import { mailAdapter } from '@intecion/ipal-kit'
email: mailAdapter()
```
Panel → Site integrations → SMTP → **Email Transport** (SMTP / Microsoft Graph).
Panel → Site integrations → E-mail sending → **Sending method** (SMTP / Microsoft Graph).
The dispatcher reads this choice per send. Guard: if Graph is selected but the
secrets are missing in .env → log + fallback to SMTP (no silent failure).
@@ -299,7 +299,7 @@ Save your changes before the test — the endpoint reads from the database, not
`mailAdapter()` stores the send result in Site integrations (at most once per 10 min
while an error persists, immediately when the state changes). When sending fails:
- **Dashboard** — a red alert with the cause and a link to Site integrations,
- **Site integrations → SMTP** — a banner with the error (e.g. `SMTP: connect ECONNREFUSED …`,
- **Site integrations → E-mail sending** — a banner with the error (e.g. `SMTP: connect ECONNREFUSED …`,
`SMTP: SMTP is not configured…`, `SMTP: Invalid login: 535 …`,
`Microsoft Graph: Graph sendMail failed (403).`) and the time.
+2 -1
View File
@@ -66,13 +66,14 @@ ipalEnvRules({
turnstile?: boolean | { siteKeyVar?: string; secretVar?: string }, // NEXT_PUBLIC_TURNSTILE_SITE_KEY, TURNSTILE_SECRET_KEY
serverUrlVar?: string, // default 'NEXT_PUBLIC_SERVER_URL'
secretVar?: string, // default 'PAYLOAD_SECRET'
secretMinLength?: number, // default 32 — minimum PAYLOAD_SECRET length, checked in production only; 0 = off
databaseVar?: string, // default 'DATABASE_URI'
databaseName?: boolean | { domain?: string; warn?: (message: string) => void },
// WARN (never fail) when the DATABASE_URI database is not <domain without dots>_prod / _dev
})
```
Always (core): `DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` (URL),
Always (core): `DATABASE_URI`, `PAYLOAD_SECRET` (in production at least `secretMinLength` = 32 characters), `NEXT_PUBLIC_SERVER_URL` (URL),
`NODE_ENV` (optional, oneOf `development`/`production`/`test`). The names `R2_*` / `GRAPH_*` /
`NEXT_PUBLIC_SERVER_URL` / `IPAL_IP_HEADER` / Turnstile match what the plugin modules
read; DB/secret are Payload variables — their names can be overridden.
+6 -3
View File
@@ -33,7 +33,7 @@ configuration (see below) or extend the plugin. Do NOT hard-code your own form.
## Dependency
```json
"dependencies": { "@payloadcms/plugin-form-builder": "3.90.2" } // same version as payload
"dependencies": { "@payloadcms/plugin-form-builder": "3.94.1" } // same version as payload
```
(the plugin's peer dependency: `^3.90.2`)
@@ -535,7 +535,10 @@ form), but `create`/`update`/`delete` and reading the Emails tab (recipients, BC
Validation matters, because a server action is a public endpoint — it can be called
without the form. The plugin loads the form definition and: rejects unknown
keys, enforces `required` fields, truncates length (5000 characters). Only what the
keys, enforces `required` fields and **rejects** a text value longer than 5000 characters — nothing is cut
or stored. The limit is fixed (no option today). The result is `{ success: false, reason: 'validation',
kind: 'too_long', field, label }`, and the visitor sees the **validation** text at that field ("Check the field
"{field}"." — Form messages → Form, `{field}` = the field's label) with every answer kept. Only what the
form defines reaches the database.
Rate limit: 5/min/IP by default (60 s window, the `form` counter is separate from search and MCP),
@@ -578,7 +581,7 @@ type SubmitFormResult =
| { success: true; submissionId: string | number }
| { success: false; reason: 'rate_limited' }
| { success: false; reason: 'turnstile' }
| { success: false; reason: 'validation'; field?: string; kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields' | 'file_too_large' | 'file_type' | 'file_refused' | 'file_count'; file?: string; max?: number; types?: string; optional?: boolean }
| { success: false; reason: 'validation'; field?: string; kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields' | 'file_too_large' | 'file_type' | 'file_refused' | 'file_count'; label?: string; file?: string; max?: number; types?: string; optional?: boolean }
| { success: false; reason: 'delivery'; field?: string; file?: string; optional?: boolean; submissionId?: string | number } // the file could not be e-mailed
| { success: false; reason: 'not_found' }
| { success: false; reason: 'consent'; field?: string }
+1
View File
@@ -161,6 +161,7 @@ It does not mount `AlternateLinksProvider` (i18n.md) — add it yourself if you
| `cookieMap` | — | extra cookies per category to clean up after consent is withdrawn |
| `jsonLd` | `[]` | extra JSON-LD nodes |
| `lightbox` | off | `true` / `{ texts, classNames, icons, loop, unstyled }` → one `<LightboxProvider>` for the site; texts from `shell.lightboxTexts` (Form messages → Image viewer) — lightbox.md |
| `nonce` | — | CSP nonce (`(await headers()).get('x-nonce')` with `createProxy({ csp })`) for the theme script and the analytics tags — security.md |
| `preconnect` | `true` | `<link rel=preconnect>` to the media origin |
| `stats` | off | `true`/props → `<PageStats>` (stats.md) |
| `theme` | `false` | `<ThemeScript>` before the first paint (theme.md) |
+4 -1
View File
@@ -101,7 +101,8 @@ archive (when you pass `prefix`, e.g. `/en/articles`), otherwise `/{locale}` (ro
instead of a dead end on 404. Both functions take `homeSlug` (default `'home'`,
a string or a per-language map) and `prefix` (the archive page slugs per language →
`/en/articles/my-post`). `buildLocalizedPath` returns `undefined` when the slug
(or prefix) is missing in a language.
(or prefix) is missing in a language. The fallback paths (archive, `/{locale}`) always carry the
locale prefix, also on a single-language site — a switcher is only for two or more languages.
Others: `getDefaultLocale(config)`, `getLocaleDefinition(code, config)`,
`negotiateLocale({ config, cookieLocale, acceptLanguage })`,
@@ -288,6 +289,8 @@ export const dynamic = 'force-dynamic'
```
Links (`resolveLink`, `resolveNav`, `getSystemLinks`), sitemap, canonical, llms.txt and MCP produce URLs
without `/pl` by themselves — the number of languages in `i18n.config.ts` decides, not the folder structure.
Exception: links to content-collection entries (`buildEntryPath`, `buildArchivePath`) always get `/{locale}`
(content.md, links.md).
(The `md/[locale]/[[...slug]]` route on a single-language site also serves subpages, but not `/md` —
hence `md/[[...slug]]` here.)
+7 -6
View File
@@ -13,10 +13,10 @@ Currently always added by the plugin. Tabs (unnamed — flat data, e.g. `ga4Meas
| Tab | Fields |
|---|---|
| Analytics | `ga4MeasurementId`, `gtmContainerId`, `metaPixelId`, `clarityProjectId`, `linkedInPartnerId`, `tiktokPixelId` |
| Turnstile | `turnstileSiteKey`, `turnstileSecretKey`, hidden `turnstileStatus` + banner |
| SMTP | `emailTransport` (`smtp` / `graph`), `smtpHost`, `smtpPort`, `smtpUser`, `smtpPassword`, `smtpFromAddress`, `smtpFromName`, test button, hidden `emailStatus` + banner |
| Spam protection | `turnstileSiteKey`, `turnstileSecretKey`, hidden `turnstileStatus` + banner |
| E-mail sending | `emailTransport` (`smtp` / `graph`), `smtpHost`, `smtpPort`, `smtpUser`, `smtpPassword`, `smtpFromAddress`, `smtpFromName`, test button, hidden `emailStatus` + banner |
| IndexNow | `indexNowKey` (generated on first save) |
| Custom | fields from the `integrationsFields` option — only when given |
| More | fields from the `integrationsFields` option — only when given |
Access: read and write only for the `admin` role (secrets) — anonymous users and editors get nothing
over REST/GraphQL. On the server, read through the Local API:
@@ -26,7 +26,7 @@ import { getSiteIntegrations } from '@intecion/ipal-kit'
const integrations = await getSiteIntegrations<SiteIntegration>(payload) // overrideAccess — do not send the whole thing to the browser
```
The "Send test" button (SMTP) calls `POST /api/ipal/test-email` (endpoint currently always added).
The "Send test" button (E-mail sending tab) calls `POST /api/ipal/test-email` (endpoint currently always added).
## Integration status — dashboard alert and tab banner
@@ -79,5 +79,6 @@ The dashboard `IntegrationAlerts` checks only `emailStatus` and `turnstileStatus
are **currently always added** — there is no option to turn them off. Workaround: a project plugin
wired after `ipalKit()` that removes / replaces the entry in `config.globals`, `config.endpoints` or
`admin.components.beforeDashboard`.
- Extension: `integrationsFields` (the *More* tab). The plugin's tabs, access and labels cannot
currently be overridden with an option.
- Extension: `integrationsFields` (the *More* tab). Access, hooks, labels and tabs: override with
`ipalKit({ globalOverrides: { 'site-integrations': … } })` (an object merges `access` / `admin` / `hooks`,
a function gets the whole global — hooks.md).
+1 -1
View File
@@ -53,7 +53,7 @@ The provider renders nothing until an image is opened.
ipalKit({ …, lightbox: true })
```
Adds the **Lightbox** group to **Settings → Notifications**: trigger name ("Enlarge image"), dialog
Adds the **Image viewer** group (`lightbox`) to **Forms → Form messages** (`notifications`): trigger name ("Enlarge image"), dialog
name ("Image viewer"), Previous, Next, Close and the counter (`{current} / {total}`) — localized per
language. `getNotificationTexts(...).lightbox` reads them; an empty field falls back to English
(`LIGHTBOX_FALLBACK`). On Postgres this adds columns: run `pnpm payload migrate:create` and commit the
+1 -1
View File
@@ -27,7 +27,7 @@ fields: [
| `required` | `false` | target and label fields are required |
| `interfaceName` | `CmsLink` / `CmsLinkPlain` / `CmsLinkNoLabel` / `CmsLinkPlainNoLabel` | type name in `payload-types.ts` |
| `maxRows` | `2` | `buildLinksField` only |
| `labels` | `{ singular: 'Button', plural: 'Buttons' }` | `buildLinksField` only — admin panel: "Add Button"; a list of links: `{ singular: 'Link', plural: 'Links' }` |
| `labels` | `{ singular: { en: 'Button', pl: 'Przycisk' }, plural: { en: 'Buttons', pl: 'Przyciski' } }` | `buildLinksField` only — admin panel: "Add Button"; a list of links: `{ singular: 'Link', plural: 'Links' }` (a string or `{ en, pl }`) |
`buildLinksField` has a built-in `rowLabel`: a collapsed row shows the button
label ("Contact us"), not "Button 01". It needs an importMap entry —
+1 -1
View File
@@ -21,7 +21,7 @@ no `next/server` import.
| Tool | Arguments | Returns |
|-----------|-----------|--------|
| `get_site_info` | `locale?` | site name and description (Site settings), languages, home page and sitemap URLs |
| `list_pages` | `locale?`, `limit?` (default 50, max 200) | published pages **and archive-collection entries** (e.g. blog): title, URL, description (a table of contents). The source is the same index as llms.txt (`collectSiteIndex`), which reads at most 1000 documents per collection |
| `list_pages` | `locale?`, `limit?` (default 50, max 200) | published pages **and archive-collection entries** (e.g. blog): title, URL, description (a table of contents). The source is the same index as llms.txt (`collectSiteIndex`); `list_pages` reads it with `limit: 1000` (at most 1000 documents per collection; llms.txt reads them all) |
| `search_content` | `query` (required), `locale?`, `limit?` (default 10, max 50) | list of pages (only the `collection` collection): title, URL, description (or `summaryField`) |
| `get_page` | `path` (e.g. `/pl/o-nas`; without a language prefix → default language) | the page as clean Markdown |
+6 -5
View File
@@ -13,8 +13,8 @@ This way no message is hardcoded — everything goes through the panel.
## Config
No options — the **Notifications** global (slug `notifications`, panel group *Settings*) is always built. The editor manages
the texts in the panel (Notifications tab), grouped per context. Group `form`:
No options — the **Notifications** global (slug `notifications`, shown in the panel as **Form messages**, group *Forms*) is always built. The editor manages
the texts in the panel (Form messages), grouped per context. Group `form`:
`success`, `error`, `rateLimited`, `turnstile`, `validation`, `consent`,
`notFound` and the multi-step form buttons: `next` ("Next"), `back` ("Back"),
`stepOf` ("Step {current} of {total}"). Every empty field → the built-in default in the page language
@@ -80,12 +80,13 @@ these keys falls back to `validation` / `error`. The result carries `field`, so
## {field} interpolation
The `validation` text may contain `{field}` — it is replaced with the **technical name** of the field with
the error (`name`, not the label), only the first `{field}` occurrence; no name → empty string:
The `validation` text may contain `{field}` — it is replaced with the **label** of the field with
the error in the page language (the technical `name` only when the field has no label), only the first `{field}` occurrence;
no field at fault → the generic `error` text instead:
```
Panel: "Sprawdź pole {field} i spróbuj ponownie."
Result: "Sprawdź pole email i spróbuj ponownie."
Result: "Sprawdź pole E-mail i spróbuj ponownie."
```
## Adding new contexts
+2 -2
View File
@@ -303,7 +303,7 @@ else skip it — otherwise you lose SSG and SEO.
## Turn off, override, extend
- Turn off: omit the `pages` option — the System pages and Maintenance tabs disappear (and `content` stops working).
- `roles` limits the set of role fields; field labels and descriptions are currently fixed (in English).
- You cannot add your own roles with the `pages` option — add extra SiteSettings fields with `siteSettingsFields` (the "Custom" tab, payload-helpers.md), but then call the helpers (`getSystemPagePath`, `getSystemLinks`) by hand: `getSystemPagePath({ page: settings.myRole, … })`, `getSystemLinks(locale, ['myRole'])`.
- `roles` limits the set of role fields; field labels and descriptions are fixed (English and Polish, set by the plugin); to change them, override the field through `globalOverrides` (hooks.md).
- You cannot add your own roles with the `pages` option — add extra SiteSettings fields with `siteSettingsFields` (the "More" tab, payload-helpers.md), but then call the helpers (`getSystemPagePath`, `getSystemLinks`) by hand: `getSystemPagePath({ page: settings.myRole, … })`, `getSystemLinks(locale, ['myRole'])`.
- 404: `createNotFoundPage` (`load` / `blocks` / `fallback` / `blockProps`) or a fully custom `not-found.tsx` (above).
- Catch-all page: `createPageRoute` with `render`, `onMissing`, `homeAlias: false` — or your own page on `resolveRoute`.
+12 -11
View File
@@ -7,25 +7,26 @@ the plugin never calls `getPayload` itself.
## Config
The `site-settings` (`SITE_SETTINGS_SLUG`), `site-integrations` (`SITE_INTEGRATIONS_SLUG`),
`cookie-settings` and `notifications` globals are **currently always added** by the plugin (when
`enabled !== false`) — there is no option to skip them or change their slug.
`cookie-settings` and `notifications` globals are **currently always added** by the plugin (also with
`enabled: false`, which keeps the schema) — there is no option to skip them or change their slug.
| `ipalKit()` option | What it does |
|---|---|
| `siteSettingsFields?: Field[]` | extra SiteSettings fields in a separate **"Custom"** tab (flat data: `settings.myField`) |
| `integrationsFields?: Field[]` | extra SiteIntegrations fields in the "Custom" tab |
| `siteSettingsFields?: Field[]` | extra SiteSettings fields in a separate **"More"** tab (flat data: `settings.myField`) |
| `integrationsFields?: Field[]` | extra SiteIntegrations fields in the "More" tab |
SiteSettings tabs (unnamed — flat data): **General** (`siteName`, `siteDescription`,
`titleOrder`, `titleSeparator`, `logo`, `defaultShareImage`, `sameAs`, `favicon`, …),
**Theme** (`defaultTheme`, `allowThemeToggle`, `themeToggleLabel`), **System pages**
(from `pages` / `content`), **E-mails** (from `forms.emailLayout`), **Maintenance**
(from `pages`), **Custom** (from `siteSettingsFields`).
(from `pages` / `content`), **Search engines** (on by default; `searchSettings: false` removes it, seo.md), **E-mails** (from `forms.emailLayout`),
**Maintenance** (from `pages`), **More** (from `siteSettingsFields`).
**Access:** SiteSettings has `read: () => true` — **the whole global, including fields from
`siteSettingsFields`, is public** over REST/GraphQL (`/api/globals/site-settings`).
Keep nothing confidential there (use SiteIntegrations for that, `read`/`update` admin only).
SiteSettings does not set `update` — Payload's default applies (any logged-in
user of an auth collection).
SiteSettings `update` requires the **editor** role or higher (a plain `user` account must not change the brand,
the homepage or the under-construction mode; without a `roles` field every logged-in account passes). Change it with
`ipalKit({ globalOverrides: { 'site-settings': { access: { update } } } })` (hooks.md).
## Front end — reading globals
@@ -78,7 +79,7 @@ const data = await getGlobal<MyType>(payload, 'my-global', { locale: 'pl', depth
## Turn off, override, extend
- The plugin's globals are currently always added (no option to turn them off / change slugs); `enabled: false` removes the whole plugin, including them.
- Extension: `siteSettingsFields` / `integrationsFields` (the "Custom" tab); the shape of the existing tabs is fixed.
- You can change a global's access, hooks and fields only by overriding it in the config after `ipalKit` (your own plugin mapping `config.globals`, example in hooks.md).
- The plugin's globals are currently always added (no option to turn them off / change slugs); `enabled: false` keeps them (schema unchanged) and only drops the plugin's endpoints, `onInit` work and admin components.
- Extension: `siteSettingsFields` / `integrationsFields` (the "More" tab).
- Change a global's access, hooks, labels or fields with `ipalKit({ globalOverrides: { 'site-settings': … } })` — an object merges `access` / `admin` / `hooks` key by key, a function gets the whole global (hooks.md "Turn off, override, extend").
- `getGlobal(payload, slug, { locale, depth })` works with any project global.
+1 -1
View File
@@ -180,7 +180,7 @@ compiled code with source maps, docs — is ~340 KB unpacked (~4 % of 7.96 MB) a
`_dev` database (MongoDB in its own Docker container) → `pnpm generate:types && pnpm build` →
`SEED_ONLY="pages:kontakt" [SEED_DRY_RUN=1] pnpm seed` in production mode → a full seed in production refused (the guard's
"full seed refused" message is required; a run where Payload never initialized is inconclusive and retried, up to 3) →
`pnpm start` with `/api/health`, `/pl`, report-only CSP, no `X-Powered-By`, `/llms.txt` → `ipal-doctor --strict`
`pnpm start` with `/api/health`, `/pl`, report-only CSP, no `X-Powered-By`, `/llms.txt` → `ipal-doctor --strict --offline`
(when shipped) → with the `nixpacks` CLI on PATH, the same seed inside the Nixpacks image. Each run packs to a new
file name and calls `dlx` with `--config.dlx-cache-max-age=0` (pnpm's dlx cache is keyed by the spec, so a reused path
would run the previous build), then checks the new site's `.ipal/starter.json` → `source` (the bundle's sha256 and the
+151 -4
View File
@@ -344,8 +344,9 @@ addition to real safeguards, not a replacement for them.
The plugin enforces two-factor authentication (TOTP) for ALL panel users —
with no way to turn it off per user. Every project gets it automatically.
It uses the proven `@clocklimited/payload-2fa` (it wraps access control — TOTP is
checked before access to DATA, not only the panel UI).
It uses `@clocklimited/payload-2fa`, which wraps access control: TOTP is checked before access to DATA
(REST, GraphQL), not only in the panel UI. On top of the package ipal-kit runs its own check, so the second
factor also covers what the package cannot see — see "What the second factor covers" below.
### Dependency
@@ -368,6 +369,7 @@ ipalKit({
plugin: payloadTotp, // ← INJECT — see below why
// collectionSlug: 'users', // default: the panel login collection (admin.user, else the first auth collection)
// allowCollectionMismatch: true, // deliberate only: 2FA on a collection other than admin.user
// guard: false, // NOT recommended: ipal-kit's own check off, the package's wrapper only
},
})
```
@@ -390,6 +392,131 @@ gets the injected plugin.
The plugin sets `forceSetup: true` — every user MUST set up TOTP after
logging in. There is no per-user "on/off" option.
### What the second factor covers
The package wraps the `access` functions of the collections and globals that are in the config **at the moment
it runs**. ipalKit runs it early, so the plugin's own globals and collections (Site settings, Site integrations,
Cookie banner, Notifications, forms, form submissions, consent records, cookie review, stats) and anything a
plugin listed after `ipalKit` adds were not wrapped. **Up to 1.16.3 a staff password without the TOTP code
therefore read and changed them over the API.** Since 1.16.4 ipal-kit closes that itself:
| Where | How |
|---|---|
| every collection and global in the config when ipalKit finishes | `access` wrapped with `requireSecondFactor` |
| collections and globals added by plugins listed **after** ipalKit | wrapped in ipalKit's `onInit`; the log line `[ipal] 2FA also enforced on entities added after ipalKit: …` names them |
| the same after a dev hot reload, or when Payload runs with `disableOnInit` | the instance's `config` is watched, so a swapped config is guarded the moment Payload assigns it (before any request or Local API call); as a second line an auth strategy that authenticates nobody (`ipal-second-factor-guard` on the 2FA collection) does the same at the start of every request |
| the plugin's endpoints (`/api/ipal/test-email`, `cookie-scan`, `cookie-approval`, `cookie-crawl`, the `access` option of `/api/ipal/doctor`) | `userMeetsRole` and `secondFactorPassed` |
| the 2FA package's own endpoints (`/api/setup-totp`, `/api/verify-totp`, `/api/remove-totp`, `/api/admin/reset-user-totp`, `/api/admin/remove-user-totp`, any a later version adds) | accounts of the 2FA collection only; everything except setup and verify also needs the second factor ("The 2FA package's endpoints" below) |
The order of the project's `plugins` array does not matter, and **there is no exception by name**: Payload's own
collections (in 3.94.1: `payload-preferences`, `payload-locked-documents`, `payload-migrations`,
`payload-query-presets`, `payload-folders`, `payload-jobs`, `payload-kv`, the global `payload-jobs-stats`) are
guarded like every other, and so is whatever a later Payload version or a plugin adds under any slug
(`payload-mcp-api-keys`, …). The job queue's own rules (`jobs.access.run / queue / cancel`) are guarded too:
Payload's defaults stay exactly as Payload sets them (in 3.94.1 a logged-in user for all three); a session that
owes its code is refused.
Only `access.admin` (may this account open the panel) is left alone: the code is entered inside the panel, and
the verify and setup screens are rendered from the session, not from any collection.
A session that still owes its code is refused **everything**, also what anonymous visitors may read (Site
settings, Notifications, the Cookie banner, forms): for that account the answer is `403` until the code is
entered. The public site is not affected — it reads on the server; only files the browser fetches itself with
that session's cookie (images from `media`) are refused, so an editor who typed the password and not yet the code
sees broken images on the site until the code is entered or they log out.
An account of the 2FA collection passes when it logged in with **password and code**, or uses an **API key**
(`auth.useAPIKey`), or has **not set TOTP up yet** (the setup screen needs that; the package behaves the same).
Everything else is refused, including a user object the check does not recognise. Accounts of other auth
collections, anonymous visitors, bearer-token routes (`/api/ipal/doctor`, the cookie-crawl callback, MCP) and
the Local API with `overrideAccess: true` (the default) are not affected.
> **Until an account has set TOTP up, its password alone opens everything its role allows** — Site
> integrations with the SMTP password included. Enforced setup is a redirect in the panel; over the API such an
> account is an ordinary logged-in account (it has to be, or it could not set TOTP up). So: **set 2FA up right
> after an account is created** — create the account, log in as it, scan the code, in one sitting — and never
> leave an invited account waiting. `ipal-doctor --url` reports the number of accounts without 2FA
> (`2fa`, deep check); it must be 0.
**Verify attempts are limited** (`twoFactor.verifyLimit`). The package checks the code and never counts tries;
a six-digit code has about three right answers in a million, so whoever held the password could guess. ipalKit
counts attempts per account on `POST /api/verify-totp`: by default the **sixth attempt within 10 minutes** —
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).
**What is NOT covered — the complete list.** (1) Anonymous requests: the access function decides. (2) Accounts
of other auth collections: 2FA is about one collection; such an account is not staff unless its collection is in
`access.staffCollections`, and then it is staff **without** a second factor (warning in the log at start).
(3) API keys. (4) An account that has not set TOTP up yet. (5) Entities the project opted out (below).
(6) `access.admin`. (7) Endpoints that are not the plugin's or the 2FA package's: your own endpoints and other
plugins' endpoints check whatever they check — add `secondFactorPassed(req)` to yours. (8) Server code using the
Local API with `overrideAccess: true`. Nothing is skipped by slug, name or prefix, and a user object the check
cannot read is refused.
**Per-entity opt-out.** A collection or global that may be reached with the password alone (a project decision,
e.g. a health record the panel reads before the code is entered), operation by operation:
```ts
// the 2FA package's own key — it leaves the operation unwrapped, and so does ipal-kit
{ slug: 'notices', custom: { totp: { disableAccessWrapper: { read: true } } }, … }
// ipal-kit's key — the same, and it also works for entities the package never sees
{ slug: 'notices', custom: { ipal: { secondFactor: { read: false } } }, … } // or secondFactor: false = every operation
```
Operations: `create`, `delete`, `read`, `readVersions`, `unlock`, `update` (collections); `read`, `readDrafts`,
`readVersions`, `update` (globals). For one of the plugin's own globals set it through `globalOverrides`
(`{ notifications: { custom: { ipal: { secondFactor: { read: false } } } } }`) — and note that the plugin's
staff rules (`userMeetsRole`) ask for the second factor themselves, so also give that operation your own
`access` function there. `disableAccessWrapper: true` passed to the package's factory turns all access
wrapping off, ipal-kit's included; the endpoints stay guarded.
**The 2FA package's endpoints.** The package takes `req.user` from whatever auth collection it comes and then
acts on the 2FA collection by id: `/api/setup-totp` writes the TOTP secret under the **caller's** id. With
numeric ids (Postgres, SQLite) an account of another auth collection could therefore set the secret of the
staff account that has the same id, and whoever knew that staff password then passed 2FA. ipalKit wraps every
endpoint the package registers: a logged-in account of another collection gets `403`; remove and the admin
reset / remove endpoints also need the second factor, so a password alone cannot reset TOTP and enrol again.
This guard is on whenever 2FA is on, also with `twoFactor.guard: false`.
Two things follow for project code:
- `payload.find({ …, user, overrideAccess: false })` on a plugin collection needs a `user` that came from
`payload.auth({ headers })` (it carries how the account logged in). A user fetched with `findByID` and passed
by hand is refused when it has TOTP set up.
- Your own endpoints do not go through `access`. Guard them:
```ts
import { requireSecondFactor, secondFactorPassed, userMeetsRole } from '@intecion/ipal-kit'
// an endpoint
handler: async (req) => {
if (!req.user || !secondFactorPassed(req)) return Response.json({ ok: false }, { status: 403 })
// or: if (!userMeetsRole(req, 'editor')) … — it includes the second-factor check
}
// an access function (collections and globals in the config are wrapped for you; this is for the rest)
access: { read: requireSecondFactor(({ req }) => isAdmin(req.user, req.payload)) }
```
**Fails closed.** At startup ipalKit checks that the injected 2FA plugin added what the check reads (the
`totpSecret` and `hasTotp` fields and the `totp` auth strategy on the 2FA collection). When it did not — a
package version with another shape — startup stops with `[ipal] twoFactor: the injected 2FA plugin did not
add …`. Tested with `@clocklimited/payload-2fa` 3.0.0-beta.1 and 3.0.0-beta.7 (the versions in between are not run in the plugin's tests). `twoFactor.guard: false` switches
ipal-kit's check off and leaves the package's wrapper alone; the plugin's own data is then open to a password
without the code again, so use it only to get a site started while the package is being sorted out.
**Check** (replace the address and the account):
```bash
# password only, no code → 403 on all three
TOKEN=$(curl -s https://example.com/api/users/login -H 'content-type: application/json' \
-d '{"email":"admin@example.com","password":"…"}' | node -pe 'JSON.parse(require("fs").readFileSync(0)).token')
for p in globals/site-integrations form-submissions users; do
curl -s -o /dev/null -w "$p %{http_code}\n" -H "Authorization: JWT $TOKEN" https://example.com/api/$p
done
```
### Import map (required)
The 2FA screens and the redirect to them are admin components. After adding `twoFactor`, and after every
@@ -462,14 +589,18 @@ show the QR code. `back=null` or a page that keeps reloading means the import ma
An admin can reset another user's 2FA (when they lose their phone) — through
`adminManageAccess` in the @clocklimited configuration. ipalKit passes it only `collection`,
`forceSetup` and `issuer`; pass other options by wrapping the injected factory:
`plugin: (opts) => payloadTotp({ ...opts, adminManageAccess: ({ req }) => isAdmin(req.user) })`.
`plugin: (opts) => payloadTotp({ ...opts, adminManageAccess: ({ req }) => isAdmin(req.user, req.payload) })`.
ipal-kit's guard on those endpoints adds the rest: the caller must be an account of the 2FA collection that has
passed the second factor itself. After a reset the account is "not set up" again — have its owner set TOTP up
at once (see the note above).
### Why @clocklimited and not another one
Chosen because it wraps ACCESS CONTROL (TOTP before data access) + forceSetup
(enforced for everyone). Other 2FA plugins for Payload only gate /admin
navigation — a user with a password can bypass them through REST/GraphQL/Bearer. @clocklimited protects
data access, not just the UI.
data access, not just the UI — for what is in the config when it runs; ipal-kit's own check covers the rest
("What the second factor covers").
## 1.9.1 — security review results
@@ -483,6 +614,18 @@ data access, not just the UI.
- Uploads: `buildUploadSecurityHeaders()` in `next.config.ts` (an SVG cannot run a script on the site's domain).
- `users`: the plugin injects an auth collection when the project has none (roles and 2FA always attach).
## 1.16.4 — two access fixes
- **Staff checks and a second auth collection.** Roles and the "no roles field" rule counted for an account of
any auth collection — a `customers` account passed the plugin's staff checks, and with its own `roles` field
also `isAdmin`, `adminOnly` and the rest. Now the staff-collection check comes first everywhere: the panel's
login collection, `access.authCollection` and `access.staffCollections`
([access.md](./access.md#who-is-staff)). The injected auth collection uses `adminOrSelfIn(slug)`, so an
account of another collection with the same numeric id no longer counts as "self".
- **2FA and the plugin's own data.** See "What the second factor covers" above.
- **The 2FA package's endpoints** accept accounts of the 2FA collection only ("The 2FA package's endpoints").
- After upgrading: [PROGRAMISTA.md](./dev/PROGRAMISTA.md) upgrade table, and the CHANGELOG entry of that release.
## Form files (`forms.attachments`)
Files attached to a form are **never stored and cannot be downloaded**: they are checked in memory, attached to
@@ -517,6 +660,10 @@ size while reading, content signature, container and macro checks, an optional `
## Turn off, override, extend
- **Verify limit:** `twoFactor.verifyLimit: { max, windowMinutes }`, or `false`.
- **2FA check:** per entity `custom.ipal.secondFactor` / `custom.totp.disableAccessWrapper` (one operation or
all); `twoFactor.guard: false` turns ipal-kit's own second-factor check off everywhere (not recommended);
`requireSecondFactor` / `secondFactorPassed` are exported for your own access functions and endpoints.
- **Turn off:** headers — do not call `buildSecurityHeaders`, or `null` / `false` per header (`frameOptions`,
`referrerPolicy`, `permissionsPolicy`, `coop`), `hsts: false`; CSP — leave out `csp` (the default);
X-Powered-By hiding — `withSecurityConfig(config, { hidePoweredBy: false })` or do not call it;
+1 -1
View File
@@ -223,7 +223,7 @@ links to a page or form) passes validation:
| `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (references to existing records resolved, links to pages later in the call filled in pass 2; a required one waits for its page), then every record gets its full content, so pages can link to each other in any order. Unknown targets and required cycles: error, nothing written |
| `upsertBy(collection, key, data)` | matches by other natural keys, e.g. `{ title: 'Contact form' }` (all keys must match, default locale) |
| `fillGlobal(slug, data)` | fills only the global's empty fields (the default locale decides). A choice — select, radio, checkbox, number, date — still at the field's `defaultValue` counts as empty (Payload stores defaults on the first save, so `defaultTheme: 'system'` can be seeded over `light`); text is never treated so, even when it equals a default. A field that already holds exactly the seeded value is not written (`skip (exists)`), so re-running a seed of defaults changes nothing. With `update` and an untouched global: every seeded field |
| `summary()` | prints the summary and returns `{ created, skipped, updated, skippedEdited, errors }` |
| `summary()` | prints the summary and returns `{ created, skipped, updated, skippedEdited, notListed, errors }` |
Each method prints one line per record (see [Running a seed](#running-a-seed)) and returns
`{ status, label, id, note }`. A failed write is reported as `error` and the run goes on; exit
+1 -1
View File
@@ -317,7 +317,7 @@ What the sitemap contains:
Skips: drafts (`_status !== 'published'`) and documents with `meta.noindex`. When
**Site settings → Maintenance** is on — everything except the pages that
stay open (home page + "Pages still available"), because the rest redirects to the
stay open (home page + "Available pages"), because the rest redirects to the
notice and a crawler would index that instead of the content. `llms.txt` does the same.
Large collections (1.13): documents are read in batches of 500 (`SITEMAP_BATCH_SIZE`), only
+1 -1
View File
@@ -119,4 +119,4 @@ redraws the widget (the token must be obtained again). A fixed theme: `turnstile
- **Extend:** your own switcher on `useTheme()`; `themeScript()` as script text for your own
tag; `themeConfigFrom(settings)` to read the settings.
Your own fields in Site settings (e.g. extra tokens) — `ipalKit({ siteSettingsFields })`, they go to the
*Custom* tab.
*More* tab.
+1 -1
View File
@@ -97,7 +97,7 @@ and for `degraded` (a problem on our side, see below) — depending on
On `degraded` the panel shows the problem:
- **Dashboard** — a red "Integration problem…" alert with a link to Site integrations
(`admin.components.beforeDashboard`, wired by the plugin automatically),
- **Site integrations → Turnstile** — a banner with the cause, code and time.
- **Site integrations → Spam protection** — a banner with the cause, code and time.
The server saves the status when it verifies a form (no cron), at most once per 10 min
while the error lasts, and at once when the state changes. Saving new keys in the panel
+32 -29
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.16.2",
"version": "1.16.4",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
@@ -108,7 +108,7 @@
"build:starter": "node scripts/build-starter.mjs",
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
"build:types": "tsc --outDir dist --rootDir ./src",
"clean": "rimraf {dist,*.tsbuildinfo}",
"clean": "rimraf --glob dist \"*.tsbuildinfo\"",
"cookie-db:refresh": "node scripts/refresh-cookie-database.mjs",
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
"dev": "next dev dev --turbo",
@@ -132,7 +132,7 @@
"dependencies": {
"busboy": "1.6.0",
"lucide-react": "0.400.0",
"nodemailer": "10.3.1",
"nodemailer": "10.6.1",
"server-only": "0.0.1",
"slugify": "1.6.9"
},
@@ -149,40 +149,44 @@
"react": "^19.0.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@payloadcms/db-postgres": "3.90.2",
"@payloadcms/db-sqlite": "3.90.2",
"@clocklimited/payload-2fa": "3.0.0-beta.7",
"@eslint/eslintrc": "^3.3.7",
"@payloadcms/db-mongodb": "3.94.1",
"@payloadcms/db-postgres": "3.94.1",
"@payloadcms/db-sqlite": "3.94.1",
"@payloadcms/eslint-config": "3.28.0",
"@payloadcms/next": "3.90.2",
"@payloadcms/plugin-form-builder": "3.90.2",
"@payloadcms/plugin-seo": "3.90.2",
"@payloadcms/richtext-lexical": "3.90.2",
"@payloadcms/ui": "3.90.2",
"@playwright/test": "1.64.0",
"@swc-node/register": "1.10.9",
"@swc/cli": "0.6.0",
"@types/busboy": "1.5.4",
"@payloadcms/next": "3.94.1",
"@payloadcms/plugin-form-builder": "3.94.1",
"@payloadcms/plugin-seo": "3.94.1",
"@payloadcms/richtext-lexical": "3.94.1",
"@payloadcms/ui": "3.94.1",
"@playwright/test": "1.65.1",
"@swc-node/register": "1.12.1",
"@swc/cli": "0.8.2",
"@types/busboy": "1.5.5",
"@types/node": "22.20.5",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"copyfiles": "2.4.1",
"cross-env": "^7.0.3",
"cross-env": "^10.1.0",
"eslint": "^9.23.0",
"eslint-config-next": "16.4.6",
"graphql": "^16.8.1",
"next": "16.4.6",
"open": "^10.1.0",
"payload": "3.90.2",
"prettier": "^3.4.2",
"qs-esm": "8.0.1",
"react": "19.3.0",
"react-dom": "19.3.0",
"rimraf": "3.0.2",
"open": "^11.0.4",
"payload": "3.94.1",
"payload-2fa-beta1": "npm:@clocklimited/[email protected]",
"prettier": "^3.10.1",
"qs-esm": "8.0.2",
"react": "19.3.1",
"react-dom": "19.3.1",
"rimraf": "6.1.4",
"sharp": "0.35.5",
"sort-package-json": "^2.10.0",
"sort-package-json": "^4.1.0",
"typescript": "5.9.3",
"vite-tsconfig-paths": "6.0.5",
"vitest": "5.0.4"
"vite": "7.3.8",
"vite-tsconfig-paths": "6.1.1",
"vitest": "5.1.1"
},
"engines": {
"node": ">=20.9.0",
@@ -203,7 +207,6 @@
"dompurify@<3.4.17": "^3.4.17",
"fast-copy@<3.1.0": "^3.1.0",
"fast-uri@<3.1.9": "^3.1.9",
"graphql-scalars@<2.0.1": "^2.0.1",
"happy-dom@<21.0.4": "^21.0.4",
"js-yaml@>=4 <4.3.2": "^4.3.2",
"source-map-js@<1.2.2": "^1.2.2",
+1775 -953
View File
File diff suppressed because it is too large Load Diff
@@ -4,7 +4,7 @@
// Reads the syntax tree (the project's TypeScript), so comments never count and multi-line forms work.
// Not reported: the panel's own labels (AGENT.md §6.5a), only in a schema file — a .ts file under
// collections/, globals/, fields/ or blocks/, or one importing Payload's schema types; never a .tsx file:
// - adminText('Title', 'Tytuł') from @intecion/ipal-kit
// - adminText('Title', 'Tytuł') from @intecion/ipal-kit/blocks
// - { en: 'Title', pl: 'Tytuł' } as the value of label, singular, plural, description, placeholder or group
// - rowLabel('title', { en: 'Item', pl: 'Pozycja' }) from @intecion/ipal-kit
// - const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' }
@@ -48,8 +48,13 @@ Ask only when the brief leaves a business question open (e.g. "do posts have aut
generateStaticParams, hreflang.
3. Entry list = a block (EntriesList) with `getEntries`; the entry page uses
`resolveRoute` (type `entry`); JSON-LD per seo.md (e.g. Article).
4. `pnpm generate:types`, `pnpm payload generate:importmap`.
5. Postgres with migrations → `pnpm payload migrate:create`.
4. **An auth collection for visitors** (`auth: true`: customers, members) only when the client requires it
(AGENT.md §5 "A second auth collection"): `admin: { user: 'users' }` in `buildConfig`, `access` with
`adminOrSelfIn('<slug>')` for read / update and an explicit `create`, never in `access.staffCollections`.
Its accounts pass none of the plugin's staff checks. Check: its token → `403` from
`/api/globals/site-integrations` and `/api/form-submissions`.
5. `pnpm generate:types`, `pnpm payload generate:importmap`.
6. Postgres with migrations → `pnpm payload migrate:create`.
## 4. Check
The **ipal-audit** skill. By hand: an entry in the panel → visible at `/<locale>/<archive>/<slug>`,
@@ -34,6 +34,12 @@ through this procedure. Ask only when you are missing something you cannot get y
### Build / TypeScript
| Symptom | Cause | Fix |
|---|---|---|
| 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'] })` |
| startup: `[ipal] twoFactor: the injected 2FA plugin did not add the totpSecret field / hasTotp field / totp auth strategy` | the installed `@clocklimited/payload-2fa` is not a version ipal-kit's second-factor check recognises (tested: 3.0.0-beta.1 and beta.7), or a custom factory was injected | install a supported version; stop-gap only: `twoFactor.guard: false` (the plugin's own data is then not covered by 2FA — security.md) |
| own route or script gets `403` / "not allowed" on `form-submissions`, `forms`, a settings global with `overrideAccess: false`, although the user is an admin | the `user` was fetched by id and passed by hand: it does not carry how the account logged in, so the second-factor check refuses it | take the user from `payload.auth({ headers })` (it sets `collection` and how the account logged in), or (server-only code that needs no access check) leave `overrideAccess` at its default; a hand-built user needs at least `collection: 'users'` for its role to count |
| an account of a second auth collection (`customers`) gets `403` from a settings global, submissions, `/api/ipal/*`, `/api/setup-totp`, or `isAdmin` / `adminOnly` say no although it has `roles: ['admin']`, after an upgrade | by design since 1.16.4: roles and staff checks count only for accounts of a staff collection | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") |
| `TS2307 next/navigation` in the plugin's `dist` | import without `.js` in the plugin client (NodeNext) | **ipal-kit bug** → plugin gap; the plugin imports `'next/navigation.js'` |
| `TS2307 @payloadcms/storage-s3` | package missing when using `buildR2Storage` | `pnpm add @payloadcms/storage-s3` + `buildR2Storage(['media'], { s3Storage })` |
| `does not provide an export named X` / `X is not a function` | symbol not exported from the entry point, or wrong subpath (`/client` vs root vs `/server` vs `/rsc`) | `docs/README.md` → the right import; missing from every entry → **ipal-kit bug** (export) |
+1 -1
View File
@@ -175,7 +175,7 @@ Details the seed already covers, which you check after every manual change in th
- [ ] unticked consent → a message from Notifications (not the English fallback);
- [ ] 6 quick submissions → `rate_limited`;
- [ ] Turnstile with keys → widget visible; submitting without solving the widget → `turnstile`;
wrong secret → the form goes through, and the panel (dashboard + Site integrations → Turnstile) shows a red alert;
wrong secret → the form goes through, and the panel (dashboard + Site integrations → Spam protection) shows a red alert;
- [ ] Turnstile without keys → no widget, the form goes through;
- [ ] second language → labels and messages in that language;
- [ ] GTM Preview → an event with the name from the panel after success;
@@ -14,7 +14,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
- **The plugin helps, never limits:** every module can be turned off, every default can be overridden,
the project config wins, the building blocks (`build*`, `create*`) are exported — compose your own version from them.
- Missing option / behaviour that does not match the docs → skill **ipal-plugin-gap** (report). Never patch `node_modules`.
- Described per the 1.12.x code. "currently always" = no option to turn it off today (gap → ipal-plugin-gap).
- Described per the current code (checked against 1.16.3). "currently always" = no option to turn it off today (gap → ipal-plugin-gap).
## 1. `ipalKit({...})` options (`IpalOptions`, `dist/types.d.ts`)
@@ -25,11 +25,12 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `i18n.fallback` | `true` | `localization.fallback` | `false` |
| `i18n.locales[]` `{ code, label, rtl? }` | — | list of languages (min. 1); `rtl: true` → `rtl` in Payload | adding a language: skill **ipal-locale-add** |
| admin languages (no option) | English + Polish | `i18n.supportedLanguages` set to `{ en, pl }` when the project has none; plugin component texts in `i18n.translations.<lang>.ipal` (`adminTexts`); every plugin label is `{ en, pl }` (rules: `docs/dev/admin-ux.md`) | your own `i18n.supportedLanguages` wins; override a component text with `i18n.translations.<lang>.ipal.<key>`; field/global labels via `globalOverrides` / `collectionOverrides` — see i18n.md "Admin panel languages and texts" |
| `access` | none | `roles` field (`user` < `editor` < `admin`, `saveToJWT`) in the auth collection | omit → **no roles**: every logged-in account passes the plugin's admin/editor checks (`userMeetsRole`): Site integrations, the e-mail test, stats, consent-records, settings globals, `form-submissions`. Narrow them with `globalOverrides` / collection overrides |
| `access` | none | `roles` field (`user` < `editor` < `admin`, `saveToJWT`) in the auth collection | omit → **no roles**: every account of the panel's login collection passes the plugin's admin/editor checks (`userMeetsRole`; accounts of other auth collections never pass): Site integrations, the e-mail test, stats, consent-records, settings globals, `form-submissions`. Narrow them with `globalOverrides` / collection overrides |
| `access.authCollection` | — (required in `access`) | collection that gets `roles`; also the slug of the injected auth collection | your own collection with that slug wins |
| `access.defaultRole` | `'user'` | `defaultValue` of the `roles` field | `'editor'` / `'admin'` |
| `access.authAccess` | `{ create: adminOnly, delete: adminOnly, read: adminOrSelf, unlock: adminOnly, update: adminOrSelf }` | access of the auth collection the plugin **injects** (Payload's default lets any logged-in account edit or delete every other account) | your keys win, e.g. `{ read: authenticated }`; your own collection with that slug wins whole (give it `adminOrSelf` / `adminOnly` yourself) |
| `access.authAccess` | `{ create: adminOnly, delete: adminOnly, read: adminOrSelfIn(slug), unlock: adminOnly, update: adminOrSelfIn(slug) }` | access of the auth collection the plugin **injects** (Payload's default lets any logged-in account edit or delete every other account) | your keys win, e.g. `{ read: authenticated }`; your own collection with that slug wins whole (give it `adminOrSelf` / `adminOnly` yourself) |
| `access.firstUserAdmin` | `true` | the account made on Payload's "Create first user" screen (`/first-register` on an empty collection) gets `roles: ['admin']`; an open sign-up still gets `defaultRole` | `false` = that account gets what was submitted |
| `access.staffCollections` | `[]` | more auth collections whose accounts are staff, 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 |
| `adminRoute` | `'/admin'` | `config.routes.admin`; stats link and views, `IntegrationAlerts` | the project moves `app/(payload)/<route>/` itself and adds the route to the proxy matcher (security.md) |
| `twoFactor` | **none = error** | `@clocklimited/payload-2fa` with `forceSetup: true` (TOTP enforced, also checked in the API) | `twoFactor: false` (discouraged); omitting the option throws `[ipal] twoFactor.issuer is required` |
| `twoFactor.issuer` | — (required) | name in the authenticator app | — |
@@ -37,6 +38,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `twoFactor.collectionSlug` | the panel's login collection (`admin.user`, else the first auth collection) | collection with 2FA; startup fails with `[ipal] twoFactor…` when it is not an auth collection or differs from `admin.user` | point it at the login collection |
| `twoFactor.provider` | `'@intecion/ipal-kit/admin#TotpRedirectProvider'` | admin provider that sends users to `setup-totp` / `verify-totp` (path read in the browser); replaces the package's header-based one | own component path / `{ path, clientProps, serverProps }` (gets clientProps `forceSetup`); `false` keeps the package's (needs `x-pathname` on `/admin`, else `setup-totp?back=null` loops) |
| `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations.<lang>.totpPlugin.<key>` (security.md) |
| `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | 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.allowCollectionMismatch` | `false` | allows `collectionSlug` ≠ `admin.user` (panel users of the other collection then skip 2FA) | `true` only when you protect a second auth collection on purpose |
| `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site settings + vendor credit | omit / `false`; `true` = defaults |
| `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — |
@@ -59,7 +62,6 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `seo.generateTitle` / `generateDescription` | plugin-seo | preview / generation in the panel | your own function `({ doc }) => string` |
| `seo.searchSettings` | tab on (the tab exists with or without `seo`) | Site settings → **Search engines** tab: `searchVerification.google/bing/yandex` (→ `<meta>` via `generatePageMetadata`), `aiCrawlers.policy` + `aiCrawlers.rules[]` (→ robots.txt via `getRobots`), localized `llmsIntro` (→ top of `/llms.txt`); empty fields change nothing. Postgres: `migrate:create` after upgrading | `false` = no tab, but this key exists only inside `seo` (which needs `collections`); without `seo` use the top-level `searchSettings: false`. When both are set, the top-level `searchSettings` wins; `(fields) => fields` = your own set (keep the names `searchVerification`, `aiCrawlers`, `llmsIntro` or read your own fields in your routes) |
| `searchSettings` | tab on | same tab and values as `seo.searchSettings`, but a top-level option: works **with or without `seo`**; read as `searchSettings ?? seo.searchSettings`, so it wins when both are set | `false` = no tab; `(fields) => fields` = your own set |
| — (no option) | `uploadsCollection: 'media'` | meta image from the `media` collection | currently always `media` (gap) |
| `forms` | none | `@payloadcms/plugin-form-builder`: `forms`, `form-submissions` collections | omit |
| `forms.adminGroup` | `'Forms'` | sidebar group | `false` = Payload default; `admin.group` in overrides wins |
| `forms.fields.*` | on: `checkbox`, `checkboxGroup`, `country`, `date`, `email`, `message`, `number`, `radio`, `select`, `state`, `step`, `text`, `textarea`, `time`; off: `payment` | block types in the builder (all with "Show only when") | `<type>: false`; a block object replaces it; `payment: true` **does nothing** (filtered out) — pass a block object |
@@ -89,8 +91,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `stats.retentionDays` / `timeZone` / `dashboard` | 90 / `'Europe/Warsaw'` / `true` | retention, day boundary, `StatsWidget` | `dashboard: false` hides the chart |
| `indexNow` | `false` | `afterChange` hook (publish → IndexNow, production + https only) in the `pages.slug ?? 'pages'` collection and each one from `content` | `true` + `indexnow-key.txt` route |
| `lightbox` | `false` | **Image viewer** group in the Form messages global (`notifications`) (image viewer labels: open, dialog, previous, next, close, counter — localized); read by `getNotificationTexts(...).lightbox` / `getSiteShell().lightboxTexts`. Postgres: `migrate:create` | omit = English fallbacks + the `texts` prop; `lightboxNotificationFields` for your own global; `globalOverrides.notifications` |
| `siteSettingsFields` | none | **Custom** tab in Site settings | `Field[]` |
| `integrationsFields` | none | **Custom** tab in Site integrations | `Field[]` |
| `siteSettingsFields` | none | **More** tab in Site settings | `Field[]` |
| `integrationsFields` | none | **More** tab in Site integrations | `Field[]` |
| `globalOverrides` | none | changes the plugin's globals (`site-settings`, `site-integrations`, `cookie-settings`, `notifications`): an object merges `access` / `admin` / `hooks` key by key (your keys win, your hooks run after the plugin's), other keys replace; a function `(global) => global` takes over | e.g. `{ notifications: { access: { update: authenticated } } }`; the way to change the plugin globals' access or hooks |
| `revalidatePath` | none | `revalidatePath` from `next/cache` (injected): saving any plugin global revalidates the whole layout (`buildGlobalRevalidateHook`) | omit = globals change after the ISR window; once: `context: { disableRevalidate: true }` |
| `enabled` | `true` | `false` → collections, globals and fields stay (schema and migrations unchanged), but no plugin endpoints (`/api/ipal/*`), no `onInit` work and no admin components; `i18n` is validated anyway | `false`; check: `payload migrate:create` after switching produces no DROP TABLE |
@@ -139,7 +141,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `IntegrationAlerts` | `beforeDashboard` | **currently always** (renders nothing when everything works) |
| `IntegrationStatusBanner` | UI field in the Site integrations tabs | always (with the global) |
| `MaskedField` | SMTP / Turnstile secrets | always |
| `TestEmailButton` | Site integrations → SMTP | always |
| `TestEmailButton` | Site integrations → E-mail sending | always |
| `MetaDescriptionCheck` | below `meta.description` | `seo` and `descriptionCheck !== false` |
| `FaviconCheck` | below Site settings → Site icon (`afterInput`) | always (with the global); remove with a `globalOverrides['site-settings']` function |
| `RowLabel` | array row labels (Cookie banner categories and cookie list; your own `rowLabel(...)`) | always |
@@ -178,11 +180,11 @@ Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ip
| image lightbox (optional) | layout + blocks | `lightbox: true` in `ipalKit`; `<SiteProviders shell lightbox>`; `<LightboxTrigger group image={lightboxImage(media, { size: 'hero' })}>` around the thumbnail (`/client`); `<RenderRichText lightbox>` | keyboard: Tab to a thumbnail, Enter → dialog with focus on Close, ←/→, Esc → focus back; Network: a resized file on a phone | lightbox.md |
| image on the frontend | `Media` primitive | `<Image {...mediaImageProps(media, { sizes })} />`, video `videoProps` | blur before load | media.md |
| storage | `payload.config.ts` | `buildR2Storage(['media'], { s3Storage })` — always (without `R2_*` = local disk) | upload → URL from `R2_PUBLIC_URL` | storage.md |
| e-mail | `payload.config.ts` | `email: mailAdapter()` (SMTP from the panel / Graph from env; also `panelSmtpAdapter`, `graphAdapter`, `sendEmail` from `/server`) | Site integrations → SMTP → **Send test** | email.md |
| e-mail | `payload.config.ts` | `email: mailAdapter()` (SMTP from the panel / Graph from env; also `panelSmtpAdapter`, `graphAdapter`, `sendEmail` from `/server`) | Site integrations → E-mail sending → **Send test** | email.md |
| forms — action | `app/(frontend)/[locale]/actions.ts` | `'use server'`; `export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`/server`) | submit → document in Form Submissions + e-mails | forms.md, skill **ipal-form** |
| forms — files | config + panel | `forms: { attachments: true }`; a **File** field on the form; an e-mail with fixed recipients in Forms → E-mails; `mailAdapter({ graph: { largeAttachments } })` when Graph must stay under 3 MB; Azure: `Mail.ReadWrite` limited to the forms mailbox for files of 3 MB and more over Graph | Test e-mail with "Attach a 10 MB test file" arrives; a submission with a PDF arrives with the attachment; nothing in Media | forms.md "Files", email.md "Attachments" |
| forms — render | form block | `<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />` (`/rsc`) | form from the panel, Turnstile, message from Notifications | forms.md |
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site integrations → Turnstile or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site integrations → Spam protection or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
| consent | layout + policy page | banner via `SiteProviders`; table `<CookieTable rows={…} labels={…} />` (`/rsc`) from `getCookieTable` | `ipal-consent-check`; delete the consent cookie → the banner comes back | consent.md |
| cookie crawl | config + env + service | `cookieScanner: { crawl: true }`, `IPAL_COOKIE_SCAN_URL` / `IPAL_COOKIE_SCAN_TOKEN`, site in the service's `IPAL_CRAWLER_SITES`; optional Coolify scheduled task `curl -X POST -H "Authorization: Bearer $IPAL_COOKIE_SCAN_TOKEN" $U/api/ipal/cookie-crawl` | **Check site** → "Last crawl …: N pages, N violations"; *Privacy → Cookie check* | cookie-scanner.md → Browser crawl |
| cookie list | config | `cookieScanner: true` (+ `declarations` for embeds/chat), `generate:importmap`, `migrate:create` | *Cookie review* → **Scan cookies** → **Review and approve** → **Approve and add** → Cookies → Cookie list; `<CookieBanner settings="detailed">` and `<CookieTable>` list it | cookie-scanner.md |
@@ -232,13 +234,13 @@ and what throws without `i18n`: frontend.md. `SiteProviders` props: `shell`, `ba
| variable | required when | effect when missing | where to set |
|---|---|---|---|
| `DATABASE_URI` | always (Payload; `ipalEnvRules` always) | no database, startup fails | env (name: `databaseVar`); the database is named `<domain without dots>_prod` / `_dev` (`intecioncom_prod`), checked by `databaseName: true` |
| `PAYLOAD_SECRET` | always | Payload does not start; `assertEnv` throws | env, ≥32 characters, different in prod (`secretVar`) |
| `PAYLOAD_SECRET` | always; ≥ 32 characters in production (`ipalEnvRules({ secretMinLength })`, default 32, `0` = off) | Payload does not start; `assertEnv` throws (also for a too-short secret in production) | env, different in prod (`secretVar`) |
| `NEXT_PUBLIC_SERVER_URL` | always (`kind: 'url'`) | sitemap/robots/canonical/JSON-LD/llms with origin `''` (relative), IndexNow does not send, R2 relative URL without a prefix | env (`serverUrlVar`) |
| `NODE_ENV` | no (`development`/`production`/`test`) | `production` is stricter: R2 and `IPAL_IP_HEADER` required, IndexNow works, IP warning, `buildImagesConfig` prod | set by Next / hosting |
| `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` | `storage: true` + production, or when at least one is set (all or none) | local disk (in prod files disappear on redeploy); incomplete set → warning | env |
| `R2_PUBLIC_URL` | optional; required only with `ipalEnvRules({ storage: { requirePublicUrl: true } })` (then like the other `R2_*`); absolute URL in prod when set | empty (default) → media served by the app at `/api/media/file/…` (Media needs `access.read: () => true`); set it only for a media domain on Cloudflare (storage.md); `R2_PUBLIC_URL` alone in dev = media read-only; `/media` allowed outside prod; also used by `buildImagesConfig`, `MediaPreconnect`, CSP | env |
| `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER` | `emailGraph: true` / Graph transport in the panel | `mailAdapter` falls back to SMTP from the panel (logged) | env (agency Exchange) |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | `turnstile: true` (names: `siteKeyVar`/`secretVar`) | fallback for keys from Site integrations → Turnstile; neither set → Turnstile off | panel (takes precedence) or env |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | `turnstile: true` (names: `siteKeyVar`/`secretVar`) | fallback for keys from Site integrations → Spam protection; neither set → Turnstile off | panel (takes precedence) or env |
| `INDEXNOW_KEY` | no | key from Site integrations → IndexNow (generated) | env or panel |
| `IPAL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) |
| `IPAL_COOKIE_SCAN_URL`, `IPAL_COOKIE_SCAN_TOKEN` | `cookieScanner.crawl` (`ipalEnvRules({ cookieCrawl: true })` requires both in production; token ≥ 16 chars) | **Check site** disabled, the box names the missing variable | env; the token also goes into the scanner service's `IPAL_CRAWLER_SITES` as `host=token` |
@@ -53,20 +53,22 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `adminOnly` | `@intecion/ipal-kit` | Collection `Access`: `admin` role only. In `access.read/create/update/delete`. |
| `adminOrEditor` | `@intecion/ipal-kit` | Collection `Access`: `editor` or `admin`. Typical for content edited in the panel. |
| `adminOrSelf` | `@intecion/ipal-kit` | Collection `Access`: admin sees everything, a logged-in user only their own document (`Where` `id = user.id`), anonymous nothing. E.g. `users.read`. |
| `adminOrSelfIn(slug)` | `@intecion/ipal-kit` | `adminOrSelf` for the auth collection `slug`: only an account **of that collection** is "self"; an account of another auth collection gets nothing. Use it whenever the project has more than one auth collection (with numeric ids `adminOrSelf` would match customer no. 5 with staff account no. 5). The injected auth collection uses it. |
| `authenticated` | `@intecion/ipal-kit` | Collection `Access`: any logged-in user. |
| `requireRole(minimum)` | `@intecion/ipal-kit` | Collection `Access` factory: at least the given role (`'user' \| 'editor' \| 'admin'`). |
| `adminOnlyField` | `@intecion/ipal-kit` | `FieldAccess` (boolean only): field for admin only. In `field.access.read/update`. |
| `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)` | `@intecion/ipal-kit` | Predicate → `boolean`: whether the user has a role ≥ `minimum` (reads `user.roles` safely). For your own access logic/hooks. |
| `isAdmin(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `admin` role. |
| `isEditor(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `editor` or higher. |
| `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`): role ≥ `minimum`, **or** any logged-in user when the user's auth collection has no `roles` field (the project omitted `access`). The plugin's staff features use it (Site integrations, settings globals, test e-mail, stats, consent records, form submissions). Use it in your own access when the project may run without roles. |
| `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. |
| `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:** `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`).
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `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`
@@ -288,7 +290,7 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection,
| Export | Import from | What it does / when |
|---|---|---|
| `assertEnv(rules, { env?, label? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | validates `process.env` against the rules at startup; collects every missing item and throws one error |
| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, databaseVar?, databaseName? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | ready rule set (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` depending on the features used) for `assertEnv`; `R2_PUBLIC_URL` optional unless `storage: { requirePublicUrl: true }`; `databaseName: true \| { domain?, warn? }` only warns when the `DATABASE_URI` database is not `<domain without dots>_prod` / `_dev` |
| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, secretMinLength?, databaseVar?, databaseName? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | ready rule set (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` depending on the features used) for `assertEnv`; `R2_PUBLIC_URL` optional unless `storage: { requirePublicUrl: true }`; `secretMinLength` (default 32, `0` = off) is the minimum `PAYLOAD_SECRET` length in production; `databaseName: true \| { domain?, warn? }` only warns when the `DATABASE_URI` database is not `<domain without dots>_prod` / `_dev` |
| `databaseNamesFor(domainOrUrl)` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | the two database names for a site: `intecion.com` → `{ prod: 'intecioncom_prod', dev: 'intecioncom_dev' }` (`www.` dropped, dots removed) |
| `databaseNameFromUri(uri)` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | the database name (URI path) of a Mongo / Postgres `DATABASE_URI`; null for SQLite files or no name |
| `checkDatabaseName({ databaseUri, domain })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | warning text when the name breaks the rule, else null (skips localhost / no domain) — what `databaseName` uses |
@@ -567,7 +569,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). A required field (layout) with references is written complete in the first write; a link to a page later in the same call waits for it; required cycles and unknown targets are an error with nothing written; the dry run reports the same. |
| `upsertBy(collection, key, data)` | (method) | Matches by other keys, e.g. a form by `{ title }`. |
| `fillGlobal(slug, data)` | (method) | Fills only empty fields of a global — a choice (select, radio, checkbox, number, date) still at its `defaultValue` counts as empty, text never does; a field already holding the seeded value is skipped (all seeded fields with `update` when untouched). |
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, notListed, errors }`; exit 1 when `errors`. |
| `guardSeedExit({ label?, log?, process? })`, `activeSeedExitGuard()` | `@intecion/ipal-kit/seed` | Call first in a seed script: a run that ends before Payload initializes or before `summary()` (Node exiting through an empty event loop under `payload run`) prints `[seed] ended before …` and exits 1 instead of a silent 0. `createSeeder` / `summary()` report to it; `dispose()` stops it. |
| `isLocalDatabase(url, { localHosts? })` | `@intecion/ipal-kit/seed` | `true` for SQLite files, Unix sockets, localhost / 127.0.0.1 / ::1 (+ `SEED_LOCAL_HOSTS`). |
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field, or a whole array per locale) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids (shared rows of non-localized arrays and blocks; a `localized: true` field keeps rows per locale). |
@@ -583,6 +585,8 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|---|---|---|
| `buildSecurityHeaders({ hsts?, csp?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. `csp` = `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`); off by default. `additional` overrides by key. |
| `withSecurityConfig(nextConfig, { hidePoweredBy? })` | `@intecion/ipal-kit` | Next config wrapper: `poweredByHeader: false` + drops `X-Powered-By` from `headers()` (Next's "Next.js" and withPayload's "Next.js, Payload"). `withPayload(withSecurityConfig(nextConfig))`; `hidePoweredBy: false` = no change. |
| `secondFactorPassed(req)` | `@intecion/ipal-kit` | `boolean` with `req` (`{ payload, user }`): `false` only for an account of the 2FA collection that has TOTP set up and has not entered the code in this session (password only). `true` for a full login, an API key, an account that has not set TOTP up yet, accounts of other auth collections, no user, and with `twoFactor: false`. Guard your own endpoints with it: `if (!req.user \|\| !secondFactorPassed(req)) return 403`. |
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
| `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` |
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
| `buildCspHeaders(args)` | `@intecion/ipal-kit` | `[csp, Reporting-Endpoints]` (the second only with `reportUri`). |
@@ -31,7 +31,7 @@ Checks the **running** app, not the code — exactly what Googlebot gets.
| no JSON-LD structured data | no `<SiteProviders>` / `<JsonLdGraph>` in `[locale]/layout.tsx`, or an empty name in Site settings |
| `/llms.txt` / `/llms-full.txt` → 404 | no route (`export { llmsRoute as GET }` / `llmsFullRoute` from `lib/content`) |
| Markdown version `/md/…` → 404 | no `src/app/md/[locale]/[[...slug]]/route.ts`; the page is noindex/draft |
| `sitemap.xml → 503` | database unreachable while building the sitemap (`sitemapRoute` returns 503 + Retry-After instead of an empty one) — check `DATABASE_URL` / database health |
| `sitemap.xml → 503` | database unreachable while building the sitemap (`sitemapRoute` returns 503 + Retry-After instead of an empty one) — check `DATABASE_URI` / database health |
| sitemap index parts not 200 | site > `maxUrls` (10 000) → `/sitemap.xml` is an index; the `?part=N` parts must answer 200 — your own route without `part` handling, or a CDN cache with an old part count |
| MCP not answering initialize | no `src/app/api/mcp/route.ts`, or Cloudflare Access without a Bypass (mcp.md) |
@@ -228,7 +228,7 @@ if (issues.noLinks.length) report('WARNING', 'pages without internal links', 'li
if (!skipped('jsonld') && issues.jsonLd.length) report('ERROR', 'no JSON-LD structured data', '<JsonLdGraph> WebSite + Organization in [locale]/layout.tsx (AGENT.md §0b.4)', issues.jsonLd.slice(0, 5))
if (!skipped('markdown') && issues.mdAlt.length) report('WARNING', 'no text/markdown alternate link in head', 'createContentHelpers({ markdownAlternate: true }) (AGENT.md §0b.6)', issues.mdAlt.slice(0, 3))
// --- 4b. Search Console / Bing verification tags (Site Settings → Search & AI) ----
// --- 4b. Search Console / Bing verification tags (Site Settings → Search engines) ----
// INFO only: domain (DNS) verification — the recommended route — leaves the tags empty.
if (!skipped('verification') && sample.length) {
const page = await get(sample[0]).catch(() => null)
@@ -236,7 +236,7 @@ if (!skipped('verification') && sample.length) {
const missing = [['google-site-verification', 'Google Search Console'], ['msvalidate.01', 'Bing Webmaster Tools']]
.filter(([name]) => !new RegExp(`<meta[^>]+name="${name}"`, 'i').test(head))
.map(([, label]) => label)
if (missing.length) report('INFO', 'no verification meta tag (fine with DNS / domain verification)', 'only for URL-prefix verification: paste the code in Site Settings → Search & AI', missing)
if (missing.length) report('INFO', 'no verification meta tag (fine with DNS / domain verification)', 'only for URL-prefix verification: paste the code in Site Settings → Search engines', missing)
}
// --- 5. 404 ---------------------------------------------------------------
+23 -11
View File
@@ -74,7 +74,7 @@ pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create <
```
It generates the site from the reference site, writes `.env` (fresh `PAYLOAD_SECRET`), installs from the shipped
lockfile, runs `ipal-skills`, `ipal-tokens`, `generate:types`, `generate:importmap`, `typecheck` (and `ipal-doctor
--strict` when shipped), checks for secrets and makes the first commit. **Check:** `git log --oneline` = 1 commit,
--strict --offline` when shipped), checks for secrets and makes the first commit. **Check:** `git log --oneline` = 1 commit,
`git status` clean, `AGENTS.md` → "Project decisions" holds every answer, `pnpm typecheck` passes. Then go to stage 11.
**Turn off / override:** it stops (nothing written) for **single-language sites** and **a default language other than
`pl`** (not supported yet), sites without `en`, URLs without a prefix and
@@ -96,11 +96,13 @@ pnpm add @intecion/ipal-kit @payloadcms/plugin-seo @payloadcms/plugin-form-build
**Next.js 16.4.5 or later** (minimum safe version: 16.0.0–16.4.0 have critical advisories, 16.3.0–16.4.4 have
GHSA-mfr8-8qww-v76h — AGENT.md §4 item 11): `pnpm add [email protected] [email protected] sharp@^0.35.5` when
create-payload-app gave you an older one.
**Node.js 20 or later** (the plugin's `nodemailer` 10 requires it). After the install, `pnpm audit --prod` → no high or
critical; with `payload` 3.90.x add the `dompurify`, `graphql-scalars`, `happy-dom`, `mongoose` and `undici` overrides
from AGENT.md §4 item 12 (`"mongoose@>=8 <8.24.7": "~8.24.10"` lifts the 8.24.1 that `@payloadcms/db-mongodb` pins —
one critical and two high advisories; `"happy-dom@<21.0.4": "^21.0.4"` fixes two high ones). `pnpm exec ipal-doctor`
→ no `transitive-min` finding.
**Payload 3.94.1** (what the reference site and the starter use; the plugin accepts `^3.90.2`): every `payload` /
`@payloadcms/*` on the same exact version, `react` and `react-dom` 19.3.1 (Payload 3.94 requires `^19.3.1`), and
**Node.js 22.23.5 or later** on the 22 line (`"engines": { "node": ">=22.23.5 <23" }`, `.nvmrc` `22`) — Payload 3.94's
minimum, also in Coolify (Nixpacks picks the patch: check `node -v` in the app's Terminal after the first deploy). After the install, `pnpm audit --prod` → no high or critical; add the `dompurify` and `happy-dom` overrides
from AGENT.md §4 item 12 (`"happy-dom@<21.0.4": "^21.0.4"` fixes two high advisories Lexical still brings in). On an
older Payload also the `mongoose` (MongoDB) and `undici` ones listed there. `pnpm exec ipal-doctor` → no
`transitive-min` finding.
`nodemailer`, `lucide-react`, `slugify`, `server-only` come with the plugin — do not add them (your own
`lucide-react` only `~0.400.0`). In `package.json`: pin every `@payloadcms/*` (ui, next, db-*, richtext-lexical,
plugin-seo, plugin-form-builder, storage-s3) in `pnpm.overrides` **to the exact `payload` version**, then
@@ -197,12 +199,12 @@ export default buildConfig({
`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`,
`GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER`. Local `.env` with `PAYLOAD_SECRET` ≥ 32 characters.
`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).
**Check.** `pnpm payload generate:importmap` (whiteLabel adds admin components) and `pnpm generate:types` without
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading);
the panel shows Site settings, Site integrations, Cookie banner, Notifications, the Forms group, Consent records.
the panel shows Site settings, Site integrations, Cookies, Form messages, the Forms group, Consent records.
`curl -s -o /dev/null -w '%{http_code}' -X POST localhost:3000/api/ipal/consent -H 'content-type: application/json'
-d '{"id":"0123456789abcdef","version":1,"state":{"necessary":true,"functional":false,"analytics":false,"marketing":false}}'` → `201`.
@@ -215,11 +217,21 @@ the panel shows Site settings, Site integrations, Cookie banner, Notifications,
(discouraged); without an injected `plugin: payloadTotp` it also throws. `forceSetup` currently always `true`.
- `users`: the injected collection lets admins manage everyone and others only themselves — loosen with
`access: { authCollection: 'users', authAccess: { read: authenticated } }` (your keys win); your own collection with
that slug wins whole (the plugin only adds `roles` — give it `adminOrSelf` / `adminOnly`). The first account
that slug wins whole (the plugin only adds `roles` — give it `adminOrSelfIn('users')` / `adminOnly`). The first account
(Create first user) gets `admin` — `access.firstUserAdmin: false` turns that off. `localization` currently always
overridden from `i18n`.
- 2FA wraps the panel's login collection (`admin.user`); a different `twoFactor.collectionSlug` stops startup with
`[ipal] twoFactor…` unless `allowCollectionMismatch: true`.
`[ipal] twoFactor…` unless `allowCollectionMismatch: true`. The second factor covers every collection and global
(the plugin's own, and those of plugins listed after `ipalKit`) and the plugin's endpoints; guard your own
endpoints with `secondFactorPassed(req)` or `userMeetsRole(req, role)` (security.md "What the second factor covers").
Verify attempts: 5 per account in 10 minutes (`twoFactor.verifyLimit`).
**Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone
opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`.
- 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
collection of STAFF goes in `access.staffCollections` (access.md "Who is staff"). Check: that account's token
gets `403` from `/api/globals/site-integrations` and `/api/form-submissions`.
- The `site-settings`, `site-integrations`, `cookie-settings`, `notifications` globals (write: editor+; Site
Integrations: admin), the `/api/ipal/test-email` endpoint and dashboard alerts — currently always present; extend
`siteSettingsFields` / `integrationsFields`; change access, admin or hooks with
@@ -509,7 +521,7 @@ Cookies → Cookie list; on the cookie policy page a block with `<CookieTable>`
the same list appears in the `settings="detailed"` dialog (labels: Cookies → Settings window → Cookie list headings, every language).
**Check.** Panel → Forms: the seeded form; a submission on `/pl` → an entry in Form Submissions + 2 emails (SMTP:
Site integrations → SMTP → Send test); with Turnstile test keys the widget is visible, without a token the submission is rejected;
Site integrations → E-mail sending → Send test); with Turnstile test keys the widget is visible, without a token the submission is rejected;
`node .agents/skills/ipal-consent-check/scripts/consent-check.mjs http://localhost:3000/pl` = 0 errors;
after a choice in the banner a new record in Consent records.
+76 -9
View File
@@ -87,18 +87,33 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
(a new image ships the fixed next and sharp). **Check:** `pnpm exec ipal-doctor` → no `next-min` finding; `pnpm dev`
prints no security-upgrade warning.
**Every upgrade — dependency advisories** (AGENT.md §4 item 12): `pnpm audit --prod`; with `payload` 3.90.x add the
`dompurify`, `graphql-scalars`, `happy-dom`, `mongoose` and `undici` overrides to `pnpm.overrides`, `pnpm install`, audit
again. MongoDB sites need the `mongoose` one now: `@payloadcms/db-mongodb` pins 8.24.1 (up to Payload 3.93.0), which has
a critical advisory (GHSA-pcrw-h46h-c93h) and four more, all fixed in 8.24.7:
**Every upgrade — Payload** (AGENT.md §4 items 11–12): the reference site and the starter run Payload **3.94.1**; the
plugin still accepts `^3.90.2`, so moving is recommended, not forced. To move: every `payload` / `@payloadcms/*` (in
`dependencies` and in `pnpm.overrides`) to the same exact version, `react` and `react-dom` to 19.3.1 (Payload 3.94
requires `^19.3.1`), Node.js 22.23.5 or later (`"engines": { "node": ">=22.23.5 <23" }`, `.nvmrc` `22`) on every machine and
in Coolify — Payload 3.94 refuses older Node. Nixpacks takes only the major from `engines` / `.nvmrc`; the patch comes
from the Nixpacks release on the Coolify server, so check `node -v` in the app's Terminal (or the build log) and update
Coolify first if it is below 22.23.5 (until then, stay on 3.90.x). Then `pnpm install`, `pnpm payload generate:types`, `pnpm payload generate:importmap`, `rm -rf .next`,
build, redeploy. Payload 3.91–3.94 change no schema the plugin defines: no migration from the plugin; on
Postgres/SQLite run `pnpm payload migrate:create` anyway and commit it if it is not empty.
**Check:** `pnpm ls payload @payloadcms/ui @payloadcms/db-mongodb` → one version, 3.94.1; the panel opens and a document
saves; `pnpm exec ipal-doctor` → no `versions` finding; Coolify app → Terminal → `node -v` → 22.23.5 or later.
**Every upgrade — dependency advisories** (AGENT.md §4 item 12): `pnpm audit --prod`; on Payload 3.94.x add the
`dompurify` and `happy-dom` overrides to `pnpm.overrides`; on an older Payload also `mongoose` (MongoDB sites; 3.90–3.93
pin 8.24.1, which has a critical advisory, GHSA-pcrw-h46h-c93h, and four more) and `undici` (3.90–3.91):
```json
"dompurify@<3.4.17": "^3.4.17",
"happy-dom@<21.0.4": "^21.0.4",
"mongoose@>=8 <8.24.7": "~8.24.10"
"mongoose@>=8 <8.24.7": "~8.24.10",
"undici@>=7 <7.30.1": "^7.30.1"
```
Then `pnpm install`, `pnpm build`, commit `package.json` and the lockfile, redeploy on Coolify (the new image ships the
fixed packages; no data or schema change, no migration). **Check:** `pnpm audit --prod` → no high or critical (the
`deepmerge` low has no fix yet); `pnpm why mongoose happy-dom` → 8.24.7 or later, 21.0.4 or later;
`pnpm exec ipal-doctor` → no `transitive-min` finding; the panel opens and a document saves.
The selectors match only vulnerable versions, so on 3.94.x the last two do nothing — remove them. A
`"graphql-scalars@<2.0.1": "^2.0.1"` line is no longer needed (the advisory no longer covers Payload's 1.22.2); remove
it or keep it. Then `pnpm install`, `pnpm build`, commit `package.json` and the lockfile, redeploy on Coolify (no data or
schema change, no migration). **Check:** `pnpm audit --prod` → no high or critical; `pnpm why dompurify happy-dom
mongoose undici` → 3.4.17, 21.0.4, 8.24.7, 7.30.1 or later; `pnpm exec ipal-doctor` → no `transitive-min` finding; the
panel opens and a document saves.
**→ 1.14.0 (PROGRAMISTA §6, items 48–49; CHANGELOG "What projects must update" — do all 8, in order):**
1. `pnpm payload generate:importmap` — `@intecion/ipal-kit/admin#FaviconCheck` (hint under Site settings → Site icon)
@@ -295,6 +310,58 @@ every site:**
**Check:** `pnpm why mongoose happy-dom` → mongoose 8.24.10, happy-dom 21.0.4; `pnpm audit --prod` → no high or critical;
`pnpm exec ipal-doctor` → no `transitive-min` finding; open the panel and save a document.
**→ 1.16.3 (PROGRAMISTA §6, item 64; Payload 3.94.1 in the reference site and the starter; AGENT.md §4 items 11–12) —
recommended, not required (the plugin's peer range stays `^3.90.2`):**
1. **Node.js 22.23.5 or later first — everywhere the site runs.** Payload 3.94 refuses older Node. Locally: `node -v`.
Coolify: Nixpacks takes only the major from `engines` / `.nvmrc`; the patch comes from the Nixpacks release on the
server, so open the app → Terminal → `node -v` (or read the build log). Below 22.23.5: update Coolify first, and
stay on Payload 3.90.x until then. CI images must resolve to 22.23.5 or later as well.
2. Every `payload` / `@payloadcms/*` to 3.94.1 (in `dependencies` and `pnpm.overrides`), `react` and `react-dom` 19.3.1,
`"engines": { "node": ">=22.23.5 <23" }` (`.nvmrc` stays `22`). Overrides: keep `"dompurify@<3.4.17": "^3.4.17"`
and `"happy-dom@<21.0.4": "^21.0.4"`; remove the `mongoose`, `undici` and `graphql-scalars` lines (they do nothing
on 3.94.x). Then `pnpm install`, `pnpm payload generate:types`, `pnpm payload generate:importmap`, `rm -rf .next`,
`pnpm build`; commit `package.json` and the lockfile, redeploy on Coolify.
3. Postgres/SQLite: `pnpm payload migrate:create`, commit it if it is not empty (3.94.1 changes long index and foreign
key names). MongoDB: no migration.
4. `pnpm ipal:skills` (updated `ipal-setup` / `ipal-upgrade`).
**Check:** `pnpm ls payload @payloadcms/ui @payloadcms/db-mongodb` → 3.94.1; `pnpm why dompurify happy-dom` → 3.4.17,
21.0.4; `pnpm audit --prod` → no high or critical; `pnpm exec ipal-doctor` → no `versions` finding; Coolify Terminal
`node -v` → 22.23.5 or later; the panel opens, a document saves, a form submission arrives.
**→ 1.16.4 (PROGRAMISTA §6, items 65–66; security fixes: 2FA coverage and staff checks) — required
for every site:**
0. **Before deploying:** check the production `PAYLOAD_SECRET` length (Coolify app → Terminal →
`node -e 'console.log(process.env.PAYLOAD_SECRET.length)'`). Shorter than 32: set a new random secret (with the
owner's OK: logs everyone out, 2FA code again, API keys regenerate; deployment.md "`PAYLOAD_SECRET` — length and
changing it"), or add `secretMinLength: 0` to `ipalEnvRules({ … })` for now and note it under "Project
decisions" in AGENTS.md.
1. Update the package, `pnpm install`, `pnpm ipal:skills`, build, redeploy on Coolify. No migration, no config
change for a site with one auth collection. `pnpm ls @clocklimited/payload-2fa` should show 3.0.0-beta.7 (tested: beta.1 and beta.7);
another version may stop startup with `[ipal] twoFactor: the injected 2FA plugin did not add …`.
2. `grep -rn "auth:" src/collections` — more than one auth collection? Then: `admin: { user: '<staff slug>' }` in
`buildConfig`; `adminOrSelfIn('<slug>')` instead of `adminOrSelf` in each; `access.staffCollections` only when
the second collection is staff (access.md "Who is staff"). Never list a visitor collection there. Roles now
count only for accounts of a staff collection: code that relied on `isAdmin` / `adminOnly` for accounts of
another collection needs its own rule (`req.user.collection === '…'`).
3. `grep -rn "overrideAccess: false" src` — a call on a plugin collection or global (`form-submissions`, `forms`,
`consent-records`, `stats-visits`, `cookie-review`, the settings globals) must pass the `user` from
`payload.auth({ headers })`; a user object built by hand needs `collection: '<staff slug>'` for its role to
count. Own endpoints that check `req.user`: add `secondFactorPassed(req)` or use `userMeetsRole(req, role)`.
`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'] })`.
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
password and Turnstile secret, a look through Site settings, Site integrations and each form's Emails tab.
Do not change those values yourself without that decision.
**Check:** with 2FA on, log in over the API with the password only (security.md → "What the second factor covers" →
Check) → `403` from `/api/globals/site-integrations`, `/api/form-submissions`, `/api/users`; log in fully in the
panel → Site integrations and a form submission open, a setting saves. With a second auth collection: its token
gets `403` from the same addresses and from `POST /api/setup-totp`. The Coolify log has no
`PAYLOAD_SECRET must be at least`; `pnpm exec ipal-doctor` has no `env` finding.
## 2. Inventory (no code changes)
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
+1 -1
View File
@@ -47,7 +47,7 @@ Write everything in this file in English.
<!-- /starter:decisions -->
<!-- ipal-kit:start -->
## ipal-kit 1.16.2 — agent guide
## ipal-kit 1.16.4 — 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:
+33
View File
@@ -219,3 +219,36 @@ test('admin: sign in through 2FA, agency credit, panel link preview', async ({ p
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
await expect(page.getByText(/Intecion/).first()).toBeVisible()
})
// 2FA covers what the plugin adds, over the API too (REST and GraphQL): a correct password without the code
// from the authenticator app opens neither the settings nor visitors' data; the code does.
test('API: a staff password without the 2FA code opens nothing; with the code it does', async ({ playwright, baseURL }) => {
const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = process.env
test.skip(!email || !password || !secret, 'E2E_* test admin not configured')
// Its own cookie jar. Payload takes the login cookie only from the site's own origin (csrf), so say where we are:
// without `Origin` these requests would count as anonymous and prove nothing.
const api = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } })
const login = await api.post('/api/users/login', { data: { email, password } })
expect(login.status()).toBe(200)
const guarded = ['/api/globals/site-integrations', '/api/form-submissions', '/api/consent-records', '/api/users', '/api/globals/site-settings', '/api/forms']
for (const path of guarded) {
const res = await api.get(path)
expect(res.status(), `${path} without the code`).toBe(403)
expect(await res.text()).not.toContain('e2e-sink') // the SMTP password create-test-admin.ts stored
}
expect((await api.post('/api/globals/site-settings', { data: {} })).status()).toBe(403)
expect((await api.post('/api/ipal/test-email', { data: { to: '[email protected]' } })).status()).toBe(403)
const query = '{ SiteIntegration { smtpPassword } FormSubmissions { totalDocs } }'
const before = await (await api.post('/api/graphql', { data: { query } })).json()
expect(before.errors?.length).toBeGreaterThan(0)
expect(JSON.stringify(before)).not.toContain('e2e-sink')
const verify = await api.post('/api/verify-totp', { data: { token: totp(secret!) } })
expect((await verify.json()).ok).toBe(true)
for (const path of guarded) {expect((await api.get(path)).status(), `${path} with the code`).toBe(200)}
const after = await (await api.post('/api/graphql', { data: { query } })).json()
expect(after.errors).toBeUndefined()
expect(after.data.SiteIntegration.smtpPassword).toBe('e2e-sink')
await api.dispose()
})
+27 -30
View File
@@ -5,7 +5,7 @@
"description": "Reference site for @intecion/ipal-kit: Example Studio (made-up architecture studio), Payload CMS 3 + Next 16",
"type": "module",
"engines": {
"node": ">=22 <23"
"node": ">=22.23.5 <23"
},
"packageManager": "[email protected]",
"scripts": {
@@ -25,29 +25,29 @@
"dependencies": {
"@clocklimited/payload-2fa": "3.0.0-beta.7",
"@intecion/ipal-kit": "file:..",
"@payloadcms/db-mongodb": "3.90.2",
"@payloadcms/next": "3.90.2",
"@payloadcms/plugin-form-builder": "3.90.2",
"@payloadcms/plugin-seo": "3.90.2",
"@payloadcms/richtext-lexical": "3.90.2",
"@payloadcms/storage-s3": "3.90.2",
"@payloadcms/ui": "3.90.2",
"cross-env": "^7.0.3",
"@payloadcms/db-mongodb": "3.94.1",
"@payloadcms/next": "3.94.1",
"@payloadcms/plugin-form-builder": "3.94.1",
"@payloadcms/plugin-seo": "3.94.1",
"@payloadcms/richtext-lexical": "3.94.1",
"@payloadcms/storage-s3": "3.94.1",
"@payloadcms/ui": "3.94.1",
"cross-env": "^10.1.0",
"graphql": "^16.8.1",
"next": "16.4.6",
"payload": "3.90.2",
"react": "19.3.0",
"react-dom": "19.3.0",
"payload": "3.94.1",
"react": "19.3.1",
"react-dom": "19.3.1",
"sharp": "0.35.5"
},
"devDependencies": {
"@playwright/test": "1.64.0",
"@tailwindcss/postcss": "^4.1.0",
"@playwright/test": "1.65.1",
"@tailwindcss/postcss": "^4.3.5",
"@types/node": "22.20.5",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"postcss": "^8.5.0",
"tailwindcss": "^4.1.0",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"postcss": "^8.5.33",
"tailwindcss": "^4.3.5",
"typescript": "5.9.3"
},
"pnpm": {
@@ -57,19 +57,16 @@
"unrs-resolver"
],
"overrides": {
"payload": "3.90.2",
"@payloadcms/db-mongodb": "3.90.2",
"@payloadcms/next": "3.90.2",
"@payloadcms/plugin-form-builder": "3.90.2",
"@payloadcms/plugin-seo": "3.90.2",
"@payloadcms/richtext-lexical": "3.90.2",
"@payloadcms/storage-s3": "3.90.2",
"@payloadcms/ui": "3.90.2",
"payload": "3.94.1",
"@payloadcms/db-mongodb": "3.94.1",
"@payloadcms/next": "3.94.1",
"@payloadcms/plugin-form-builder": "3.94.1",
"@payloadcms/plugin-seo": "3.94.1",
"@payloadcms/richtext-lexical": "3.94.1",
"@payloadcms/storage-s3": "3.94.1",
"@payloadcms/ui": "3.94.1",
"dompurify@<3.4.17": "^3.4.17",
"graphql-scalars@<2.0.1": "^2.0.1",
"happy-dom@<21.0.4": "^21.0.4",
"mongoose@>=8 <8.24.7": "~8.24.10",
"undici@>=7 <7.30.1": "^7.30.1"
"happy-dom@<21.0.4": "^21.0.4"
}
},
"dependenciesMeta": {
+444 -446
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -120,7 +120,7 @@ const lightboxText = (
})
/**
* The "Lightbox" group — labels of the image viewer (<LightboxProvider texts>).
* The "Image viewer" group (`lightbox`) — labels of the image viewer (<LightboxProvider texts>).
* Added by ipalKit `lightbox: true`; exported so a project can place it in its
* own global instead.
*/
+5 -1
View File
@@ -8,6 +8,7 @@ export {
adminOrEditor,
adminOrEditorField,
adminOrSelf,
adminOrSelfIn,
authenticated,
buildRolesField,
hasMinimumRole,
@@ -17,6 +18,7 @@ export {
requireRole,
requireRoleField,
ROLE_HIERARCHY,
staffCollectionSlugs,
userMeetsRole,
} from './modules/access/index.js'
// Concrete files, not module barrels: a barrel that also re-exports 'use client'
@@ -325,7 +327,9 @@ export type {
} from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export { requireSecondFactor, secondFactorPassed } from './modules/security/totp/secondFactor.js'
export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
export type { 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'
export {
@@ -371,7 +375,7 @@ export { buildLlmsTxt } from './modules/seo/index.js'
// Site Settings → Title separator: stored name → character; SQL for the 1.14.x → GraphQL-safe values migration.
export { TITLE_SEPARATORS, titleSeparatorChar, titleSeparatorSql } from './modules/seo/index.js'
export type { TitleSeparatorName } from './modules/seo/index.js'
// Site Settings → Search & AI: verification codes and AI crawler rules, for custom metadata/robots routes.
// Site Settings → Search engines: verification codes and AI crawler rules, for custom metadata/robots routes.
export { robotsOptionsFrom, verificationFrom } from './modules/seo/index.js'
export type { AiBotRule, AiBotsPolicy, VerificationMetadata } from './modules/seo/index.js'
export { buildSitemapCss, buildSitemapIndexXml, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'
+34 -11
View File
@@ -8,35 +8,58 @@ import { hasMinimumRole, isAdmin } from './predicates.js'
* Collection-level access (returns boolean | Where).
* Use in collection `access.read/create/update/delete`.
*/
export const adminOnly: Access = ({ req: { user } }) => isAdmin(user)
export const adminOnly: Access = ({ req }) => isAdmin(req.user, req.payload)
export const adminOrEditor: Access = ({ req: { user } }) => hasMinimumRole(user, 'editor')
export const adminOrEditor: Access = ({ req }) => hasMinimumRole(req.user, 'editor', req.payload)
export const authenticated: Access = ({ req: { user } }) => Boolean(user)
/** Requires at least the given role. */
export const requireRole =
(minimum: Role): Access =>
({ req: { user } }) =>
hasMinimumRole(user, minimum)
({ req }) =>
hasMinimumRole(req.user, minimum, req.payload)
/** Admins see all; others are constrained to their own document. */
export const adminOrSelf: Access = ({ req: { user } }) => {
if (isAdmin(user)) {return true}
/**
* Admins see all; others are constrained to their own document.
*
* It cannot know which collection it guards, so "own document" means "the
* document with my id". In a project with a second auth collection use
* `adminOrSelfIn(slug)` instead: with numeric ids (Postgres, SQLite) customer
* no. 5 would otherwise match staff account no. 5.
*/
export const adminOrSelf: Access = ({ req }) => {
const { user } = req
if (isAdmin(user, req.payload)) {return true}
if (!user) {return false}
return { id: { equals: user.id } }
}
/**
* `adminOrSelf` for the auth collection `slug`: only an account OF THAT
* collection is "self". An account of another auth collection gets nothing.
*
* { slug: 'users', auth: true, access: { read: adminOrSelfIn('users'), update: adminOrSelfIn('users') } }
*/
export const adminOrSelfIn =
(slug: string): Access =>
({ req }) => {
const { user } = req
if (isAdmin(user, req.payload)) {return true}
if (!user || (user as { collection?: unknown }).collection !== slug) {return false}
return { id: { equals: user.id } }
}
/**
* Field-level access (returns boolean only — no Where support).
* Use in field `access.read/update`.
*/
export const adminOnlyField: FieldAccess = ({ req: { user } }) => isAdmin(user)
export const adminOnlyField: FieldAccess = ({ req }) => isAdmin(req.user, req.payload)
export const adminOrEditorField: FieldAccess = ({ req: { user } }) => hasMinimumRole(user, 'editor')
export const adminOrEditorField: FieldAccess = ({ req }) => hasMinimumRole(req.user, 'editor', req.payload)
/** Requires at least the given role, for field-level access. */
export const requireRoleField =
(minimum: Role): FieldAccess =>
({ req: { user } }) =>
hasMinimumRole(user, minimum)
({ req }) =>
hasMinimumRole(req.user, minimum, req.payload)
+2 -1
View File
@@ -4,12 +4,13 @@ export {
adminOrEditor,
adminOrEditorField,
adminOrSelf,
adminOrSelfIn,
authenticated,
requireRole,
requireRoleField,
} from './access.js'
export { injectRoles } from './injectRoles.js'
export { hasMinimumRole, isAdmin, isEditor, userMeetsRole } from './predicates.js'
export { clearStaffRegistry, hasMinimumRole, isAdmin, isEditor, registerStaffCollections, staffCollectionSlugs, userMeetsRole } from './predicates.js'
export { buildRolesField } from './rolesField.js'
export type { AccessOption, Role } from './types.js'
export { ROLE_HIERARCHY } from './types.js'
+115 -18
View File
@@ -2,6 +2,7 @@ import type { BasePayload } from 'payload'
import type { Role } from './types.js'
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { ROLE_HIERARCHY } from './types.js'
/**
@@ -12,6 +13,87 @@ import { ROLE_HIERARCHY } from './types.js'
*/
type MaybeUser = { roles?: null | Role[] } | null | Record<string, unknown> | undefined
/**
* Where the staff collections come from: `req.payload` (anything with the
* sanitized `config` on it), a config itself (also the client config from
* `useConfig()` — it has `admin.user`), or the list given outright.
*/
type StaffSource = { admin?: { user?: string }; config?: StaffConfig; custom?: unknown; staffCollections?: string[] } | null | undefined
type StaffConfig = { admin?: { user?: string }; custom?: unknown }
type MaybePayload = Pick<BasePayload, 'config'> | StaffSource
/**
* The staff lists of the configs ipalKit built in this process, by owner: the
* running Payload instance once it exists, a token of the config before that.
* Used when a predicate gets no source (`isAdmin(req.user)` in a hook).
*/
const registered = new Map<object, string[]>()
/**
* Called by ipalKit: at config time with a token, then with the Payload
* instance (`replaces` = that config's token) on init and after every reload.
* Not for projects.
*/
export function registerStaffCollections(owner: object, slugs: string[], replaces?: object): void {
if (replaces) {registered.delete(replaces)}
registered.set(owner, [...new Set(slugs.filter(Boolean))])
}
/** For tests. */
export function clearStaffRegistry(): void {
registered.clear()
}
/** For tests: how many configs / instances have a staff list filed. */
export const staffRegistrySize = (): number => registered.size
/**
* The staff collections every config in this process agrees on, or null when
* ipalKit never ran here (a browser bundle, Next middleware, the edge
* runtime). Two configs with different lists: only what both call staff — a
* call that does not say which config it means must not get the wider answer.
*/
function agreedStaff(): null | string[] {
if (!registered.size) {return null}
const lists = [...registered.values()]
return lists[0].filter((slug) => lists.every((list) => list.includes(slug)))
}
/**
* The auth collections whose accounts are staff: the one the admin panel logs
* in with (`admin.user`), the one that carries the plugin's roles
* (`access.authCollection`) and `access.staffCollections`. Accounts of any
* other auth collection — customers, members — are visitors to the plugin:
* no role and no staff check counts for them, whatever fields they have.
*
* Pass `req.payload` (or a config, or `{ staffCollections: [...] }`). Without
* an argument: what the configs built in this process agree on, `[]` when
* there is none.
*/
export function staffCollectionSlugs(source?: MaybePayload): string[] {
if (!source) {return agreedStaff() ?? []}
const given = (source as { staffCollections?: unknown }).staffCollections
if (Array.isArray(given)) {return given.filter((s): s is string => typeof s === 'string' && s !== '')}
const config = ((source as { config?: StaffConfig }).config ?? source) as StaffConfig
const extra = (config.custom as { ipal?: { staffCollections?: string[] } } | undefined)?.ipal?.staffCollections ?? []
return [...new Set([config.admin?.user, ...extra].filter((s): s is string => typeof s === 'string' && s !== ''))]
}
/**
* Whether this account's roles may count at all: it belongs to a staff
* collection. Checked before any role, and it fails closed:
* - an account without `collection` (a user object built by hand) is not staff;
* - 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'] })`.
*/
function isStaffAccount(user: MaybeUser, source?: MaybePayload): boolean {
if (!user || typeof user !== 'object') {return false}
const slug = (user as { collection?: unknown }).collection
return typeof slug === 'string' && staffCollectionSlugs(source).includes(slug)
}
/** Safely extracts the roles array from a loosely-typed user. */
function getRoles(user: MaybeUser): Role[] {
if (!user || typeof user !== 'object') {return []}
@@ -28,40 +110,55 @@ function highestRoleIndex(user: MaybeUser): number {
}
/**
* True if the user holds at least the given role in the hierarchy.
* True if the user is a staff account and holds at least the given role.
* admin satisfies 'editor' and 'user'; editor satisfies 'user'.
*
* Pass `req.payload` as the third argument where you have it (access
* 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.
*/
export function hasMinimumRole(user: MaybeUser, minimum: Role): boolean {
export function hasMinimumRole(user: MaybeUser, minimum: Role, payload?: MaybePayload): boolean {
if (!isStaffAccount(user, payload)) {return false}
return highestRoleIndex(user) >= ROLE_HIERARCHY.indexOf(minimum)
}
/** True if the user is an admin. */
export function isAdmin(user: MaybeUser): boolean {
return hasMinimumRole(user, 'admin')
/** True if the user is a staff account with the admin role. */
export function isAdmin(user: MaybeUser, payload?: MaybePayload): boolean {
return hasMinimumRole(user, 'admin', payload)
}
/** True if the user is an editor or higher (editor, admin). */
export function isEditor(user: MaybeUser): boolean {
return hasMinimumRole(user, 'editor')
/** True if the user is a staff account with the editor role or higher. */
export function isEditor(user: MaybeUser, payload?: MaybePayload): boolean {
return hasMinimumRole(user, 'editor', payload)
}
/**
* Role check for the plugin's own staff features (Site Integrations, the
* e-mail test, stats, consent records, form submissions, the settings
* globals): true when the user holds at least `minimum` — or, when the
* user's auth collection has no `roles` field (the project omitted `access`),
* for every logged-in user. Without roles all accounts are equal, as in
* Payload's own default; nobody being "admin" would lock those features away.
* globals). In this order:
*
* Pass `req` (it has `payload` and `user`). An unknown collection counts as
* having roles — the strict side. A project with its own role scheme in
* another field narrows access through globalOverrides / collection overrides.
* 1. The account must belong to a STAFF collection (staffCollectionSlugs).
* An account of any other auth collection never passes — also when its own
* collection has a `roles` field that says `admin`.
* 2. With 2FA on, an account that has TOTP set up must have entered the code
* in this session (secondFactorPassed).
* 3. It holds at least `minimum` — or its collection has no `roles` field at
* all (the project omitted `access`): then every account of that staff
* collection passes, as in Payload's own default.
*
* Pass `req` (it has `payload` and `user`). A project with its own role scheme
* in another field narrows access through globalOverrides / collection overrides.
*/
export function userMeetsRole({ payload, user }: { payload?: BasePayload; user?: unknown }, minimum: Role): boolean {
if (!user || typeof user !== 'object') {return false}
if (hasMinimumRole(user as MaybeUser, minimum)) {return true}
const slug = (user as { collection?: unknown }).collection
const fields = typeof slug === 'string' ? payload?.collections?.[slug as never]?.config.fields : undefined
if (typeof slug !== 'string' || !staffCollectionSlugs(payload).includes(slug)) {return false}
if (!secondFactorPassed({ payload, user })) {return false}
if (highestRoleIndex(user as MaybeUser) >= ROLE_HIERARCHY.indexOf(minimum)) {return true}
const collection = payload?.collections?.[slug as never]?.config
const fields = (collection?.flattenedFields ?? collection?.fields) as Array<{ name?: string }> | undefined
if (!fields) {return false}
return !fields.some((f) => 'name' in f && f.name === 'roles')
return !fields.some((f) => f.name === 'roles')
}
+3 -2
View File
@@ -34,8 +34,9 @@ export function buildRolesField(defaultRole: Role = 'user', { firstUserAdmin = t
type: 'select',
access: {
// Only admins may assign or change roles
create: ({ req: { user } }) => isAdmin(user),
update: ({ req: { user } }) => isAdmin(user),
// …of a staff collection: a role value on an account of another auth collection does not count
create: ({ req }) => isAdmin(req.user, req.payload),
update: ({ req }) => isAdmin(req.user, req.payload),
},
admin: {
description: {
+10
View File
@@ -34,4 +34,14 @@ export type AccessOption = {
* `false` = that account gets what was submitted (`defaultRole` by default).
*/
firstUserAdmin?: boolean
/**
* More auth collections whose accounts are staff, besides the one the admin
* panel logs in with (`admin.user`). Only accounts of a staff collection can
* pass the plugin's staff checks (`userMeetsRole`): the settings globals,
* Site integrations, form submissions, consent records, stats, the cookie
* scanner. A staff collection WITHOUT a `roles` field passes them all (every
* account is admin to the plugin); add `buildRolesField()` to it to tell
* admins, editors and users apart. Default: none.
*/
staffCollections?: string[]
}
+3 -2
View File
@@ -1,12 +1,13 @@
import { consentTexts } from './consent.js'
import { contentTexts } from './content.js'
import { integrationsTexts } from './integrations.js'
import { securityTexts } from './security.js'
import { settingsTexts } from './settings.js'
/** Every admin component text, by language. Payload reads them as `ipal:<key>`. */
export const adminTexts = {
en: { ...settingsTexts.en, ...integrationsTexts.en, ...consentTexts.en, ...contentTexts.en },
pl: { ...settingsTexts.pl, ...integrationsTexts.pl, ...consentTexts.pl, ...contentTexts.pl },
en: { ...settingsTexts.en, ...integrationsTexts.en, ...consentTexts.en, ...contentTexts.en, ...securityTexts.en },
pl: { ...settingsTexts.pl, ...integrationsTexts.pl, ...consentTexts.pl, ...contentTexts.pl, ...securityTexts.pl },
}
export type AdminTextKey = keyof typeof adminTexts.en
+11
View File
@@ -0,0 +1,11 @@
import { defineTexts } from '../define.js'
/** Admin component texts — two-step verification (2FA). Placeholders use Payload's {{name}} syntax. */
export const securityTexts = defineTexts({
en: {
twoFactorTooManyAttempts: 'Too many codes were tried for this account. Wait {{minutes}} min, then enter the current code from your app.',
},
pl: {
twoFactorTooManyAttempts: 'Dla tego konta wpisano zbyt wiele kodów. Odczekaj {{minutes}} min, a potem wpisz aktualny kod z aplikacji.',
},
})
+2 -1
View File
@@ -6,6 +6,7 @@ import type { CookieChange } from './scan.js'
import type { CookieScannerOptions, CookieStorage } from './types.js'
import { userMeetsRole } from '../../access/predicates.js'
import { secondFactorPassed } from '../../security/totp/secondFactor.js'
import { CONSENT_CATEGORIES } from '../categories.js'
import { COOKIE_REVIEW_SLUG } from './collection.js'
import { textFor } from './merge.js'
@@ -155,7 +156,7 @@ export async function approveCookies({
export function buildCookieApprovalEndpoints(options: CookieScannerOptions): Endpoint[] {
const approval = typeof options.approval === 'object' ? options.approval : {}
const allowed = async (req: PayloadRequest) =>
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
return [
{
handler: async (req) => {
@@ -6,6 +6,7 @@ import type { CookieScanLabels } from '../labels.js'
import type { CookieCrawlOptions, CookieScanContext, CookieScannerOptions } from '../types.js'
import { userMeetsRole } from '../../../access/predicates.js'
import { secondFactorPassed } from '../../../security/totp/secondFactor.js'
import {
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
@@ -59,7 +60,7 @@ export function buildCookieCrawlEndpoints({
}): Endpoint[] {
const crawl: CookieCrawlOptions = typeof options.crawl === 'object' ? options.crawl : {}
const isStaff = async (req: PayloadRequest) =>
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
const read = async (req: PayloadRequest) =>
(await req.payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0, overrideAccess: true, req })) as CrawlDoc
const write = (req: PayloadRequest, data: Partial<CrawlDoc>) =>
+2 -1
View File
@@ -3,6 +3,7 @@ import type { Endpoint, PayloadRequest } from 'payload'
import type { CookieIntegration, CookieScanContext, CookieScannerOptions } from './types.js'
import { userMeetsRole } from '../../access/predicates.js'
import { secondFactorPassed } from '../../security/totp/secondFactor.js'
import { DEFAULT_COOKIE_INTEGRATIONS, integrationLabel } from './integrations.js'
import { cookieScanContext, enabledCookieIntegrations, parseCookieNames, runCookieScan } from './scan.js'
@@ -16,7 +17,7 @@ export const COOKIE_SCAN_PATH = '/ipal/cookie-scan'
*/
export function buildCookieScanEndpoints(options: CookieScannerOptions, plugin: CookieScanContext['plugin']): Endpoint[] {
const allowed = async (req: PayloadRequest) =>
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
// Names in the admin language of the editor who asks.
const list = (items: CookieIntegration[], req: PayloadRequest) =>
+9 -1
View File
@@ -26,6 +26,14 @@ export const DOCTOR_USAGE = `Usage: ipal-doctor [dir] [options]
Exit: 0 ok · 1 findings at or above --fail-on · 2 could not run · 3 a rule crashed
Silence a rule with a reason in ipal-doctor.json — docs/doctor.md`
/**
* Whether this run stores first-seen dates in ipal-doctor.json: not with --sites or --json, and
* never when CI is set (a CI run must not change a tracked file).
*/
export function shouldWriteSeen(args: { json?: boolean; sites?: unknown }, env: Record<string, string | undefined> = process.env): boolean {
return !args.sites && !args.json && !env.CI
}
const RANK: Record<DoctorSeverity, number> = { error: 3, info: 1, warning: 2 }
type Args = {
@@ -132,7 +140,7 @@ export async function runDoctorCli(argv: string[], { cwd = process.cwd(), log =
skip: args.skip,
staging: args.staging,
url: args.sites ? undefined : args.url,
writeSeen: !args.sites && !args.json,
writeSeen: shouldWriteSeen(args),
}),
)
}
+4 -3
View File
@@ -12,14 +12,15 @@ export const NEXT_RECOMMENDED = '16.4.6'
* Packages from Payload's own dependency tree that Payload pins below a security fix (AGENT.md §4 item 12). Only the
* project's lockfile can lift them, with a `pnpm.overrides` entry. `major` limits the check to the line Payload uses.
*/
export const TRANSITIVE_MIN_SAFE: { major?: number; min: string; name: string; override: string; severity: 'error' | 'warning'; why: string }[] = [
export const TRANSITIVE_MIN_SAFE: { major?: number; min: string; name: string; override: string; severity: 'error' | 'warning'; upgrade?: string; why: string }[] = [
{
name: 'mongoose',
major: 8,
min: '8.24.7',
override: '"mongoose@>=8 <8.24.7": "~8.24.10"',
severity: 'error',
why: 'GHSA-pcrw-h46h-c93h (critical, sanitizeFilter not applied on countDocuments) and four more; @payloadcms/db-mongodb pins 8.24.1',
upgrade: 'upgrade payload and every @payloadcms/* to 3.94.1 (@payloadcms/db-mongodb 3.94.0+ ships 8.24.7), or ',
why: 'GHSA-pcrw-h46h-c93h (critical, sanitizeFilter not applied on countDocuments) and four more; @payloadcms/db-mongodb 3.90–3.93 pins 8.24.1',
},
{
name: 'happy-dom',
@@ -89,7 +90,7 @@ export const versionRules: DoctorRule[] = [
if (old.length) {
out.push({
file: 'package.json',
fix: `add ${dep.override} to pnpm.overrides in package.json, then pnpm install (AGENT.md §4 item 12)`,
fix: `${dep.upgrade ?? ''}add ${dep.override} to pnpm.overrides in package.json, then pnpm install (AGENT.md §4 item 12)`,
message: `${dep.name} ${old.join(', ')} < ${dep.min} — ${dep.why}`,
severity: dep.severity,
})
+3 -2
View File
@@ -7,6 +7,7 @@ import type { DoctorStatus } from './types.js'
import { countPendingCookies } from '../consent/scanner/approval.js'
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
/** The plugin's own version (package.json next to dist/ and src/). */
@@ -41,7 +42,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
}
export type DoctorEndpointOptions = {
/** Who may read the status besides a valid token, e.g. `({ req }) => req.user?.roles?.includes('admin')`. */
/** Who may read the status besides a valid token, e.g. `({ req }) => isAdmin(req.user, req.payload)` (a staff admin; the second factor is checked for you). */
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
/** Env variable that holds the token (≥ 32 characters). Default IPAL_DOCTOR_TOKEN. */
tokenVar?: string
@@ -67,7 +68,7 @@ export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoi
const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'ipal-doctor', windowMs: 60_000 })
if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests' })}
const given = (req.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, '').trim()
const allowed = (given && sameToken(given, token)) || (options.access ? await options.access({ req }) : false)
const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && (await options.access({ req })) : false)
if (!allowed) {return Response.json({ error: 'Unauthorized' }, { status: 401 })}
const status = await collectDoctorStatus(req.payload)
return Response.json(status, { headers: { 'cache-control': 'no-store' } })
+15 -1
View File
@@ -26,6 +26,11 @@ export type IpalEnvFeatures = {
* the client IP (see clientIp). Outside production it stays optional.
*/
ipHeader?: boolean
/**
* Minimum length of PAYLOAD_SECRET, checked in production only (NODE_ENV=production). Payload signs
* login tokens and encrypts API keys with it, so a short secret is weak. Default 32; 0 turns it off.
*/
secretMinLength?: number
/** Override the Payload secret var. Default 'PAYLOAD_SECRET'. */
secretVar?: string
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
@@ -75,6 +80,7 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
databaseVar = 'DATABASE_URI',
emailGraph = false,
ipHeader = false,
secretMinLength = 32,
secretVar = 'PAYLOAD_SECRET',
serverUrlVar = 'NEXT_PUBLIC_SERVER_URL',
storage = false,
@@ -83,7 +89,15 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
const rules: EnvRule[] = [
{ name: databaseVar, description: 'Database connection string (e.g. MongoDB URI)' },
{ name: secretVar, description: 'Payload secret used to sign tokens' },
{
name: secretVar,
description: 'Payload secret used to sign tokens',
...(secretMinLength > 0 && process.env.NODE_ENV === 'production' && {
validate: (value: string) =>
value.length >= secretMinLength ||
`${secretVar} must be at least ${secretMinLength} characters in production (got ${value.length}) — use a long random value, or ipalEnvRules({ secretMinLength }) to change the minimum (0 turns the check off)`,
}),
},
{ name: serverUrlVar, description: 'Public site origin, e.g. https://example.com', kind: 'url' },
{
name: 'NODE_ENV',
+3 -3
View File
@@ -504,7 +504,7 @@ export function createContentHelpers({
const robots = (): RobotsRules => buildRobots({ ...robotsOptions, baseUrl: origin })
/**
* `robots` plus what editors set in Site Settings → Search & AI (AI bot policy
* `robots` plus what editors set in Site Settings → Search engines (AI bot policy
* and per-bot exceptions), read per request. Use it instead of `robots` to
* let the panel manage AI crawlers:
*
@@ -546,8 +546,8 @@ export function createContentHelpers({
* the strongest fix for the metadata-in-head problem (stronger than ISR alone).
*
* Handles automatically:
* - pages collection + content collections (with their archive prefix)
* - excludes the homepage (maps to { slug: [] } — the root)
* - the pages collection only (content-collection entries render on first request)
* - the homepage as the root ({ slug: [] })
* - excludes drafts and 404/500/system slugs
* - KEEPS noindex pages (they must still render — noindex controls indexing,
* not existence; skipping them would force dynamic rendering)
+380
View File
@@ -0,0 +1,380 @@
import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payload'
/**
* ipal-kit's own second-factor check, next to the access wrapper of
* @clocklimited/payload-2fa.
*
* Why it exists: the package wraps the `access` functions of the collections
* and globals that are in the config at the moment it runs. Whatever is added
* afterwards — ipal-kit's globals and collections, a plugin listed after
* ipalKit — was left unwrapped, so a staff password without the TOTP code
* opened it over the API. This check does not depend on that order: ipalKit
* applies it to everything in the config when it finishes, and again in onInit
* to whatever other plugins added later; `userMeetsRole` asks it too.
*
* Every way past this check, and why it is safe — keep this list complete:
* 1. no user → the access function itself decides (anonymous visitors);
* 2. 2FA off or `twoFactor.guard: false` → there is no check (the project's choice);
* 3. an account of another auth collection → 2FA is about ONE collection; such an
* account is not staff unless the project names its collection in
* `access.staffCollections` (then it is staff WITHOUT a second factor — ipalKit
* logs a warning at start);
* 4. `_strategy === 'totp'` → set by the package's strategy after password and code;
* 5. `_strategy === 'api-key'` → an API key is its own credential (the package's rule);
* 6. `hasTotp === false` → TOTP not set up yet (the setup screen needs the session);
* 7. per-entity opt-out in the project's config (`custom.totp.disableAccessWrapper`,
* `custom.ipal.secondFactor`), or the package's global `disableAccessWrapper`;
* 8. `access.admin` (may this account open the panel) is not wrapped: the code is
* entered inside the panel;
* 9. endpoints are not access functions: the plugin's own check `userMeetsRole` /
* `secondFactorPassed`, the 2FA package's are wrapped (guardTotpEndpoint), a
* project's own must call `secondFactorPassed(req)`;
* 10. the Local API with `overrideAccess: true` (server code).
* There is no exception by slug, name or prefix, and a user object the check cannot
* read (no `collection`, an unknown `_strategy`, no `hasTotp`) is refused.
*
* It fails closed. An account of the 2FA collection passes only when
* - it came through the package's `totp` strategy (password AND code), or
* - it authenticated with an API key (the package's own rule), or
* - TOTP is not set up on it yet (`hasTotp === false`) — the setup screen
* needs that, and the package lets such an account through as well.
* Anything else — code not entered, or a user object this check does not
* understand (a renamed strategy, no `hasTotp`) — is refused.
*/
/** What ipalKit records in `config.custom.ipal.twoFactor` when 2FA is on and the guard is not switched off. */
export type TwoFactorGuardConfig = { collection: string }
type MaybeReq = { payload?: Pick<BasePayload, 'config'>; user?: unknown }
const guardConfig = (payload: MaybeReq['payload']): TwoFactorGuardConfig | undefined =>
(payload?.config?.custom as { ipal?: { twoFactor?: TwoFactorGuardConfig } } | undefined)?.ipal?.twoFactor
/**
* False only for an account that still owes the second factor: it belongs to
* the 2FA collection, has TOTP set up and has not entered the code in this
* session. True for everyone else — no user (the access function decides),
* accounts of other auth collections, 2FA off (`twoFactor: false`).
*
* Pass `req`. Use it in your own endpoints and access functions:
* if (!secondFactorPassed(req)) return Response.json({ ok: false }, { status: 403 })
*/
export function secondFactorPassed({ payload, user }: MaybeReq): boolean {
if (!user || typeof user !== 'object') {return true}
const guard = guardConfig(payload)
if (!guard) {return true}
const u = user as { _strategy?: unknown; collection?: unknown; hasTotp?: unknown }
// A user object that does not say which collection it is from cannot be told apart from a
// 2FA account: refused. (Payload's strategies and payload.auth() always set `collection`.)
if (typeof u.collection !== 'string') {return false}
if (u.collection !== guard.collection) {return true}
if (u._strategy === 'totp' || u._strategy === 'api-key') {return true}
// "Not set up yet" only when nothing says otherwise. The package computes `hasTotp` with a second
// database read and answers false when that read fails; the secret on the user object itself (it
// came with the account's own record) then still says the account has TOTP: refused.
return u.hasTotp === false && !(user as { totpSecret?: unknown }).totpSecret
}
const GUARDED = Symbol.for('ipal.secondFactorGuard')
type AnyAccess = (args: never) => unknown
type Guarded = { [GUARDED]?: true } & AnyAccess
/**
* Wraps one access function: refused while the second factor is owed,
* otherwise the function itself (or Payload's default, "logged in", when there
* is none). Wrapping twice is harmless — an already wrapped function is returned as is.
*
* access: { read: requireSecondFactor(({ req }) => isAdmin(req.user, req.payload)) }
*/
export function requireSecondFactor<T extends AnyAccess>(access?: T): T {
if (access && (access as Guarded)[GUARDED]) {return access}
const wrapped = ((args: { req: MaybeReq }) => {
if (!secondFactorPassed(args.req)) {return false}
return access ? access(args as never) : Boolean(args.req?.user)
}) as unknown as Guarded
wrapped[GUARDED] = true
return wrapped as unknown as T
}
/** `admin` (may this account open the panel) stays unwrapped: the code is entered inside the panel. */
const COLLECTION_OPERATIONS = ['create', 'delete', 'read', 'readVersions', 'unlock', 'update'] as const
const GLOBAL_OPERATIONS = ['read', 'readDrafts', 'readVersions', 'update'] as const
type AccessMap = Record<string, AnyAccess | undefined>
type GuardedEntity = { access?: unknown; custom?: Record<string, unknown>; slug: string }
type ConfigCustom = { totp?: { pluginOptions?: { disableAccessWrapper?: boolean } } } | undefined
/**
* Per-entity opt-out, operation by operation — the project's decision that
* this collection or global may be reached with the password alone:
* - the 2FA package's own key: `custom.totp.disableAccessWrapper.<operation>: true`
* (the package leaves that operation unwrapped; so does ipal-kit);
* - ipal-kit's key, for entities the package never sees (added after it ran):
* `custom.ipal.secondFactor: false` (every operation) or `{ <operation>: false }`.
*/
function optedOut(entity: GuardedEntity, operation: string): boolean {
const custom = entity.custom as
| { ipal?: { secondFactor?: false | Record<string, boolean> }; totp?: { disableAccessWrapper?: Record<string, boolean> } }
| undefined
if (custom?.totp?.disableAccessWrapper?.[operation]) {return true}
const own = custom?.ipal?.secondFactor
return own === false || (typeof own === 'object' && own?.[operation] === false)
}
/**
* Before the 2FA package runs: ipal-kit's opt-out written in the package's own
* key as well, so the package leaves those operations unwrapped too.
*/
export function passOptOutsToPackage(config: Config): Config {
const translate = <T extends GuardedEntity>(entity: T, operations: readonly string[]): T => {
const off = operations.filter((op) => optedOut(entity, op))
if (!off.length) {return entity}
const totp = (entity.custom?.totp ?? {}) as { disableAccessWrapper?: Record<string, boolean> }
return {
...entity,
custom: { ...entity.custom, totp: { ...totp, disableAccessWrapper: { ...totp.disableAccessWrapper, ...Object.fromEntries(off.map((op) => [op, true])) } } },
}
}
return {
...config,
collections: (config.collections ?? []).map((c) => translate(c as GuardedEntity, COLLECTION_OPERATIONS) as CollectionConfig),
globals: (config.globals ?? []).map((g) => translate(g as GuardedEntity, GLOBAL_OPERATIONS) as GlobalConfig),
}
}
/** The package's global switch (`disableAccessWrapper: true` passed to its factory): no access wrapping at all. */
const wrapperDisabled = (custom: unknown): boolean => Boolean((custom as ConfigCustom)?.totp?.pluginOptions?.disableAccessWrapper)
/** The operations of one entity that still need the guard. */
function unguarded(entity: GuardedEntity, operations: readonly string[]): string[] {
const access = (entity.access ?? {}) as AccessMap
return operations.filter((op) => !optedOut(entity, op) && !(access[op] as Guarded | undefined)?.[GUARDED])
}
function guardEntity<T extends GuardedEntity>(entity: T, operations: readonly string[]): T {
const todo = unguarded(entity, operations)
if (!todo.length) {return entity}
const access: AccessMap = { ...(entity.access as AccessMap | undefined) }
for (const op of todo) {access[op] = requireSecondFactor(access[op])}
return { ...entity, access }
}
/**
* The job queue has its own rules outside any collection: `jobs.access.run / queue / cancel`
* (POST /api/payload-jobs/run, `payload.jobs.queue()` / `.cancel()` with `overrideAccess: false`).
*
* Payload's defaults are kept exactly, by not inventing any: only a rule that EXISTS is wrapped
* ("…and not while the second factor is owed"). At config time that is what the project wrote;
* when Payload builds the config it fills the rest in itself (3.94.1, config/defaults.js: `run`,
* `queue` and `cancel` are all `defaultAccess`, a logged-in user — the `?? (() => true)` in
* queues/localAPI.js is never reached on a built config), and the sweep of the running config
* wraps those. So a request without a user gets whatever Payload itself answers.
*/
const JOB_OPERATIONS = ['cancel', 'queue', 'run'] as const
type JobsLike = { access?: AccessMap } | undefined
function guardJobs<T extends JobsLike>(jobs: T): T {
if (!jobs?.access) {return jobs}
const access: AccessMap = { ...jobs.access }
for (const op of JOB_OPERATIONS) {
if (access[op]) {access[op] = requireSecondFactor(access[op])}
}
return { ...jobs, access }
}
/** Every collection and global of a (not yet sanitized) config, guarded. Returns a new config. */
export function guardConfigAccess(config: Config): Config {
if (wrapperDisabled(config.custom)) {return config}
return {
...config,
...(config.jobs ? { jobs: guardJobs(config.jobs as JobsLike) as Config['jobs'] } : {}),
collections: (config.collections ?? []).map((c) => guardEntity(c as GuardedEntity, COLLECTION_OPERATIONS) as CollectionConfig),
globals: (config.globals ?? []).map((g) => guardEntity(g as GuardedEntity, GLOBAL_OPERATIONS) as GlobalConfig),
}
}
/**
* The same for a running Payload, in place: what plugins listed after ipalKit
* added, and what Payload itself adds when it sanitizes the config. Returns
* the slugs it had to guard.
*
* EVERY collection and global is guarded — there is no exception by name or
* prefix. That includes Payload's own collections (in 3.94.1:
* payload-preferences, payload-locked-documents, payload-migrations,
* payload-query-presets, payload-folders, payload-jobs, payload-kv and the
* global payload-jobs-stats) and any a later Payload adds: an account that
* still owes its code needs none of them — the verify and setup screens are
* rendered from the session. A plugin that names its collection `payload-…`
* (e.g. `payload-mcp-api-keys`) is therefore covered like any other.
*/
export function guardPayloadAccess(payload: Pick<BasePayload, 'config'>): string[] {
if (wrapperDisabled(payload.config.custom)) {return []}
const late: string[] = []
const sweep = (entity: GuardedEntity, operations: readonly string[]) => {
const todo = unguarded(entity, operations)
if (!todo.length) {return}
late.push(entity.slug)
const access: AccessMap = { ...(entity.access as AccessMap | undefined) }
for (const op of todo) {access[op] = requireSecondFactor(access[op])}
entity.access = access
}
for (const c of payload.config.collections ?? []) {sweep(c as GuardedEntity, COLLECTION_OPERATIONS)}
for (const g of payload.config.globals ?? []) {sweep(g as GuardedEntity, GLOBAL_OPERATIONS)}
const jobs = (payload.config as { jobs?: JobsLike }).jobs
if (jobs?.access && JOB_OPERATIONS.some((op) => jobs.access?.[op] && !(jobs.access[op] as Guarded)[GUARDED])) {
jobs.access = guardJobs(jobs).access
late.push('jobs')
}
return late
}
/** Configs already swept — a new sanitized config (start, dev hot reload) is swept once. */
const swept = new WeakSet<object>()
/**
* Sweeps `payload.config` once per config object. Returns the slugs guarded
* now, or null when this config was swept before.
*/
export function ensurePayloadGuarded(payload: Pick<BasePayload, 'config'>): null | string[] {
const config = payload?.config
if (!config || swept.has(config)) {return null}
swept.add(config)
return guardPayloadAccess(payload)
}
/**
* Makes `payload.config` an accessor on this instance, so the moment Payload
* swaps the config (its dev `reload()` assigns `payload.config = …` and runs no
* onInit) `onConfig` is called — before any request or Local API call can use
* the new config. Without it the first HTTP request would do the same (the
* guard strategy), but a Local API call made before that request would meet
* unguarded entities from plugins listed after ipalKit. Never throws.
*/
export function watchPayloadConfig(payload: BasePayload, onConfig: (payload: BasePayload) => void): void {
try {
const own = Object.getOwnPropertyDescriptor(payload, 'config')
if (!own || own.get || !own.configurable) {return}
let current = own.value as BasePayload['config']
Object.defineProperty(payload, 'config', {
configurable: true,
enumerable: own.enumerable ?? true,
get: () => current,
set: (next: BasePayload['config']) => {
current = next
try {
onConfig(payload)
} catch {
// the guard strategy repeats it on the next request
}
},
})
} catch {
// an instance we cannot instrument: the guard strategy still covers HTTP
}
}
/** Name of the auth strategy ipalKit adds to the 2FA collection (see buildGuardStrategy). */
export const GUARD_STRATEGY_NAME = 'ipal-second-factor-guard'
/**
* An auth strategy that authenticates nobody. Payload runs every strategy at
* the start of every request, before any access function, so this is the one
* place ipal-kit is called on each request with the config that is live right
* now. It makes sure that config is guarded — also after a dev hot reload,
* where Payload swaps in a freshly built config and does not run onInit, and
* when Payload was started with `disableOnInit`.
*/
export function buildGuardStrategy(onConfig?: (payload: BasePayload) => void) {
return {
name: GUARD_STRATEGY_NAME,
authenticate: ({ payload }: { payload: BasePayload }) => {
if (onConfig) {
onConfig(payload)
} else {
ensurePayloadGuarded(payload)
}
return { user: null }
},
}
}
/** The 2FA package's endpoints an account uses BEFORE it has passed the second factor. */
const BEFORE_SECOND_FACTOR = new Set(['/setup-totp', '/verify-totp'])
type EndpointLike = { handler: (req: never) => Promise<Response> | Response; path: string }
/**
* Guards one endpoint the 2FA package registered. The package trusts
* `req.user` whatever collection it comes from: `/setup-totp` writes the TOTP
* secret into the 2FA collection under the CALLER's id, so with numeric ids an
* account of another auth collection could set the secret of the staff account
* that has the same id. So:
* - a logged-in account of another collection is refused on every endpoint
* of the package (no user: the package answers as before);
* - everything except setup and verify (remove, the admin reset / remove
* endpoints, whatever a later version adds) also needs the second factor,
* so a password alone cannot reset or remove TOTP.
*/
export type TotpEndpointGuards = {
/**
* Called for a verify attempt of a logged-in account before the package sees
* it. Return a Response to refuse (too many attempts), null to let it through.
*/
limitVerify?: (req: never) => null | Promise<null | Response> | Response
}
export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collection: string, guards: TotpEndpointGuards = {}): T {
const handler = endpoint.handler as (req: MaybeReq) => Promise<Response> | Response
const refused = () => Response.json({ message: 'Not allowed.', ok: false }, { status: 403 })
return {
...endpoint,
handler: (async (req: MaybeReq) => {
const user = req.user as { collection?: unknown } | null | undefined
if (user && user.collection !== collection) {return refused()}
if (user && !BEFORE_SECOND_FACTOR.has(endpoint.path) && !secondFactorPassed(req)) {return refused()}
// 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)
if (limited) {return limited}
}
return handler(req)
}) as unknown as T['handler'],
}
}
/**
* The same for endpoints the package may register on a collection or a global
* (none in the versions seen; a later one might): every endpoint that was not
* there before the package ran gets `guardTotpEndpoint`.
*/
export function guardNewEntityEndpoints<T extends { endpoints?: unknown; slug: string }>(
entities: T[] | undefined,
before: Map<string, Set<unknown>>,
collection: string,
guards?: TotpEndpointGuards,
): T[] {
return (entities ?? []).map((entity) => {
if (!Array.isArray(entity.endpoints)) {return entity}
const known = before.get(entity.slug) ?? new Set()
if (entity.endpoints.every((e) => known.has(e))) {return entity}
return { ...entity, endpoints: entity.endpoints.map((e) => (known.has(e) ? e : guardTotpEndpoint(e as EndpointLike, collection, guards))) }
})
}
/**
* The parts of @clocklimited/payload-2fa the guard relies on, checked right
* after the injected factory ran. A missing part means a version this guard
* was not written for: it would refuse every staff request, or — worse — the
* package itself may no longer protect what it used to. Returns what is
* missing; ipalKit refuses to start with it.
*/
export function missingTotpParts(config: Config, collection: string): string[] {
const target = (config.collections ?? []).find((c) => c.slug === collection)
const fields = (target?.fields ?? []) as Array<{ name?: string }>
const strategies = typeof target?.auth === 'object' ? (target.auth.strategies ?? []) : []
const missing: string[] = []
if (!fields.some((f) => f.name === 'totpSecret')) {missing.push('the `totpSecret` field')}
if (!fields.some((f) => f.name === 'hasTotp')) {missing.push('the `hasTotp` field')}
if (!strategies.some((s) => s.name === 'totp')) {missing.push('the `totp` auth strategy')}
return missing
}
+64
View File
@@ -0,0 +1,64 @@
import type { PayloadRequest } from 'payload'
import { serverText } from '../../integrations/texts.js'
/**
* A limit on TOTP verify attempts. The 2FA package checks the code and never
* counts tries: a six-digit code with a ±1 step window has about three right
* answers in a million, so whoever holds the password could simply try.
*
* Counted per ACCOUNT, not per IP (an attacker changes addresses; the account
* is what is being guessed). Every attempt counts, right or wrong — nobody
* needs more than a handful of logins in the window. Only a session that
* 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.
*/
export type VerifyLimitOptions = {
/** Attempts per account in the window. Default 5. */
max?: number
/** Window in minutes; a refused account waits until it ends. Default 10. */
windowMinutes?: number
}
type Bucket = { count: number; resetAt: number }
const buckets = new Map<string, Bucket>()
/** For tests. */
export function clearVerifyLimits(): void {
buckets.clear()
}
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
return (req: PayloadRequest): 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".
const raw = (req.user as { id?: unknown }).id
const id = typeof raw === 'string' || typeof raw === 'number' ? String(raw) : JSON.stringify(raw ?? null)
const now = Date.now()
// keep the map small: forget windows that are over
if (buckets.size > 5000) {
for (const [key, bucket] of buckets) {
if (bucket.resetAt <= now) {buckets.delete(key)}
}
}
const key = `${collection}:${id}`
const current = buckets.get(key)
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))
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 },
{ headers: { 'Retry-After': String(retryAfter) }, status: 429 },
)
}
}
+2 -2
View File
@@ -62,7 +62,7 @@ const day = (iso?: string) => (iso ? iso.slice(0, 10) : undefined)
* and pages, so it can generate this automatically.
*
* Structure (llmstxt.org): H1 site name, a blockquote summary, the editor's
* note from Site Settings → Search & AI (when set), then — per
* note from Site Settings → Search engines (when set), then — per
* language when the site has several — one list per collection (pages first,
* then archive collections such as a blog) of Markdown links with descriptions.
* Section names are the project's own locale and collection labels; the plugin
@@ -115,7 +115,7 @@ export async function buildLlmsTxt({
const lines: string[] = [`# ${name}`, '']
if (description) {lines.push(`> ${description}`, '')}
// Site Settings → Search & AI: facts the editor wants assistants to know and quote.
// Site Settings → Search engines: facts the editor wants assistants to know and quote.
const intro = llmsIntroFrom(settings)
if (intro) {lines.push(intro, '')}
+1 -1
View File
@@ -125,7 +125,7 @@ type BuildMetadataArgs = {
siteName?: null | string
/** slug per locale for this document — drives canonical + hreflang. */
slugs: LocalizedSlugs
/** Site Settings → Search & AI verification codes; rendered as <meta> tags by Next. */
/** Site Settings → Search engines verification codes; rendered as <meta> tags by Next. */
verification?: VerificationMetadata
}
+1 -1
View File
@@ -50,7 +50,7 @@ export type RobotsOptions = {
/**
* Per-bot exceptions that win over `aiBots` — a listed bot leaves its policy
* group and gets its own allow or block. Unknown bots can be added this way.
* Site Settings → Search & AI fills it when you use `getRobots`.
* Site Settings → Search engines fills it when you use `getRobots`.
*/
aiBotRules?: readonly AiBotRule[]
/**
+1 -1
View File
@@ -29,7 +29,7 @@ export type SiteMetaConfig = {
/** Global fallback meta description. */
siteDescription?: null | string
siteName: null | string
/** Site Settings → Search & AI → verification codes (Search Console, Bing, Yandex). */
/** Site Settings → Search engines → verification codes (Search Console, Bing, Yandex). */
verification?: VerificationMetadata
}
+1 -1
View File
@@ -37,7 +37,7 @@ export type SeoOption = {
/** Optional: customize how meta titles are generated in the admin preview. */
generateTitle?: (args: { doc: Record<string, unknown> }) => string
/**
* Site Settings → "Search & AI" tab: Search Console / Bing / Yandex
* Site Settings → "Search engines" tab: Search Console / Bing / Yandex
* verification, AI crawler policy for robots.txt (getRobots), llms.txt note.
* On by default (empty fields change nothing); false removes the tab; a
* function gets the plugin's fields and returns the tab's fields (add, drop,
+16 -1
View File
@@ -45,6 +45,19 @@ const here = dirname(fileURLToPath(import.meta.url))
// dist/modules/starter → package root
const pkgRoot = resolve(here, '..', '..', '..')
/** Every vendored external skill (docs/agent/external/manifest.json) — what a bare `--external` installs. */
export function externalSkillNames(root = pkgRoot): string[] {
const manifest = join(root, 'docs', 'agent', 'external', 'manifest.json')
if (!existsSync(manifest)) {return []}
return (JSON.parse(readFileSync(manifest, 'utf8')) as { skills: { name: string }[] }).skills.map((skill) => skill.name)
}
/** The skills `--external` asks for: a list as given, a bare flag = every external skill, no flag = null. */
export function resolveExternal(external: null | string[], all: () => string[] = externalSkillNames): null | string[] {
if (external === null) {return null}
return external.length ? external : all()
}
function value(args: string[], name: string): string | undefined {
const i = args.indexOf(name)
if (i < 0) {return undefined}
@@ -129,7 +142,9 @@ async function readAnswers(options: CreateOptions): Promise<StarterAnswers> {
const answers = options.answersFile
? (JSON.parse(readFileSync(resolve(options.answersFile), 'utf8')) as StarterAnswers)
: await askInTerminal()
if (options.external?.length && answers.tooling) {answers.tooling.external = options.external}
// A bare --external means every external skill (CREATE_USAGE); without the flag the answers decide.
const external = resolveExternal(options.external)
if (external && answers.tooling) {answers.tooling.external = external}
return answers
}
+115 -5
View File
@@ -1,4 +1,4 @@
import type { Config, Plugin } from 'payload'
import type { BasePayload, Config, PayloadRequest, Plugin } from 'payload'
import { deepMergeSimple } from 'payload/shared'
@@ -11,7 +11,7 @@ import { buildNotifications } from './globals/Notifications/index.js'
import { applyGlobalOverrides } from './globals/overrides.js'
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js'
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js'
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
import { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
import { buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js'
@@ -33,7 +33,18 @@ import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.j
import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import {
buildGuardStrategy,
ensurePayloadGuarded,
guardConfigAccess,
guardNewEntityEndpoints,
guardTotpEndpoint,
missingTotpParts,
passOptOutsToPackage,
watchPayloadConfig,
} from './modules/security/totp/secondFactor.js'
import { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
import { buildVerifyLimit } from './modules/security/totp/verifyLimit.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
import { buildIndexNowHook } from './modules/seo/indexNow.js'
import { searchSettingsFields } from './modules/seo/searchSettings.js'
@@ -125,9 +136,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
access: {
create: adminOnly,
delete: adminOnly,
read: adminOrSelf,
// "self" = an account of THIS collection: with numeric ids a customer
// account no. 5 must not match staff account no. 5.
read: adminOrSelfIn(authSlug),
unlock: adminOnly,
update: adminOrSelf,
update: adminOrSelfIn(authSlug),
...options.access?.authAccess,
},
}
@@ -152,6 +165,24 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// or import it, so projects that opt out (twoFactor: false) needn't install it.
// Wrapping access control (not just admin UI) means TOTP gates data access —
// no API bypass.
// ipal-kit's own second-factor check (secondFactor.ts) covers what the 2FA
// package cannot: everything added to the config after the package ran.
let secondFactorGuard = false
/** The 2FA collection, when 2FA is on. */
let twoFactorCollection: null | string = null
/** This config's entry in the staff registry until a Payload instance takes it over. */
const staffToken = {}
/**
* A config has gone live on this instance (start, or a dev hot reload): guard what plugins
* listed after ipalKit added, and file its staff collections under the instance.
*/
const adoptConfig = (payload: BasePayload) => {
const token = (payload.config.custom as { ipal?: { staffToken?: object } } | undefined)?.ipal?.staffToken
registerStaffCollections(payload, staffCollectionSlugs(payload), token)
if (!secondFactorGuard) {return}
const late = ensurePayloadGuarded(payload)
if (late?.length) {payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`)}
}
if (options.twoFactor !== false) {
const tf = options.twoFactor
if (!tf?.issuer) {
@@ -197,12 +228,58 @@ export const ipalKit = (options: IpalOptions): Plugin => {
`"${adminSlug}", or pass twoFactor.allowCollectionMismatch: true if that is deliberate.`,
)
}
const endpointsBefore = new Set(config.endpoints ?? [])
const entityEndpointsBefore = new Map<string, Set<unknown>>(
[...(config.collections ?? []), ...(config.globals ?? [])].map((e) => [e.slug, new Set<unknown>(Array.isArray(e.endpoints) ? e.endpoints : [])]),
)
// custom.ipal.secondFactor (ipal-kit's per-entity opt-out) → the package's own key
config = passOptOutsToPackage(config)
config = await totp({
collection: target,
forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out
totp: { issuer: tf.issuer },
})(config)
// The package's endpoints (setup, verify, remove, admin reset / remove) take
// `req.user` from ANY auth collection and act on the 2FA collection by id.
// Only accounts of the 2FA collection may use them (guardTotpEndpoint) —
// whatever the package registered, also paths a later version adds.
const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, tf.verifyLimit)
const guards = limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}
config.endpoints = (config.endpoints ?? []).map((e) => (endpointsBefore.has(e) ? e : guardTotpEndpoint(e, target, guards as never)))
// …and the same for endpoints it may put on a collection or a global.
config.collections = guardNewEntityEndpoints(config.collections, entityEndpointsBefore, target, guards as never)
config.globals = guardNewEntityEndpoints(config.globals, entityEndpointsBefore, target, guards as never)
twoFactorCollection = target
// The package wraps only what is in the config right now. ipal-kit's own
// globals and collections come later, so they get ipal-kit's guard at the
// end of this function (and other plugins' in onInit). The guard reads the
// package's `totp` strategy and `hasTotp` field: when those are not there,
// this is a version it was not written for — refuse to start rather than
// run with a second factor that may protect nothing.
if (tf.guard !== false) {
const missing = missingTotpParts(config, target)
if (missing.length) {
throw new Error(
`[ipal] twoFactor: the injected 2FA plugin did not add ${missing.join(', ')} to "${target}". ` +
'ipal-kit enforces the second factor on its own globals and collections through them, so it ' +
'cannot do that with this version of @clocklimited/payload-2fa. Use a supported version, or pass ' +
'twoFactor.guard: false to rely on the package alone (docs/security.md — not recommended).',
)
}
secondFactorGuard = true
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, twoFactor: { collection: target } } }
// Called by Payload on every request before any access function: guards whatever
// the live config has that was added after ipalKit (start, dev hot reload).
const sweep = buildGuardStrategy(adoptConfig)
config.collections = (config.collections ?? []).map((c) =>
c.slug === target && typeof c.auth === 'object'
? { ...c, auth: { ...c.auth, strategies: [sweep as never, ...(c.auth.strategies ?? [])] } } // first: a strategy that finds a user ends the round
: c,
)
}
// The package's texts are long and informal: ipal-kit's (admin-ux.md) go over
// them, the project's own i18n.translations over both. The 2FA screens get a
// tab title instead of "Payload" (view meta is a plain string: the site's language).
@@ -273,7 +350,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }
const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }
// Vendor credit ("Technology by Intecion.com") under the nav — on by
// Vendor credit ("Technology support: Intecion.com") under the nav — on by
// default, hidden with credit:false, text/url overridable.
const creditOn = wl.credit !== false && agency !== false
const creditProps = {
@@ -355,6 +432,19 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// --- access: inject roles into the client's auth collection ---
if (options.access) {
config = injectRoles(config, options.access)
// Staff collections besides the panel's login collection: the one that carries
// the roles, and the ones the project names. Roles and staff checks count only
// 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 } }
}
// 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
// (adoptConfig), with `admin.user` as Payload resolved it.
{
const panel = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, staffToken } }
registerStaffCollections(staffToken, staffCollectionSlugs({ admin: { user: panel }, custom: config.custom }))
}
// --- seo: apply @payloadcms/plugin-seo directly ---
@@ -596,10 +686,30 @@ export const ipalKit = (options: IpalOptions): Plugin => {
},
}
// --- second factor on everything in the config by now: the project's
// collections (wrapped by the package already; twice is harmless), the
// plugin's globals and collections, the form builder's.
if (secondFactorGuard) {
config = guardConfigAccess(config)
}
// --- hooks: onInit ---
const incomingOnInit = config.onInit
config.onInit = async (payload) => {
if (incomingOnInit) {await incomingOnInit(payload)}
adoptConfig(payload)
// Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once.
watchPayloadConfig(payload, adoptConfig)
// Staff whose collection is not the 2FA collection log in without a second factor: say so.
if (twoFactorCollection) {
const uncovered = staffCollectionSlugs(payload).filter((slug) => slug !== twoFactorCollection)
if (uncovered.length) {
payload.logger.warn(
`[ipal] 2FA covers "${twoFactorCollection}" only. Staff accounts of ${uncovered.map((s) => `"${s}"`).join(', ')} ` +
'pass the staff checks with a password alone (docs/access.md "Who is staff").',
)
}
}
await migrateCookieSettingsSaveButton(payload)
await migrateTitleSeparator(payload, settingsSlug)
if (adminMeta) {await syncAdminMeta(payload, adminMeta, { nameField: brandFields.nameField, settingsSlug })}
+20 -2
View File
@@ -23,6 +23,7 @@ import type { FormsOption } from './modules/forms/types.js'
import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js'
import type { I18nConfig } from './modules/i18n/types.js'
import type { PagesOption } from './modules/pages/types.js'
import type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
import type { SeoOption } from './modules/seo/types.js'
import type { StatsOptions } from './modules/stats/collection.js'
@@ -172,7 +173,7 @@ export type IpalOptions = {
revalidatePath?: RevalidatePathFn
/**
* Site Settings → "Search & AI" tab (verification codes, AI crawler policy,
* Site Settings → "Search engines" tab (verification codes, AI crawler policy,
* llms.txt intro). On by default; `false` removes it; a function gets the
* plugin's fields and returns the tab's fields. Works without `seo`; wins
* over `seo.searchSettings`.
@@ -231,6 +232,15 @@ export type IpalOptions = {
* injects). Must be an auth collection.
*/
collectionSlug?: CollectionSlug
/**
* ipal-kit's own second-factor check on every collection and global —
* also the ones added after the 2FA package ran (ipal-kit's own, other
* plugins') — and in `userMeetsRole`. On by default. `false` leaves only
* the package's wrapper, which does not cover those: a staff password
* without the TOTP code then reads them over the API. Only for a 2FA
* package version the check does not recognise; docs/security.md.
*/
guard?: false
/** Name shown in the authenticator app (e.g. company/site name). */
issuer: string
/**
@@ -261,6 +271,14 @@ export type IpalOptions = {
* `i18n.translations.<lang>.totpPlugin` still wins. `false` keeps the package's.
*/
texts?: false
/**
* Limit on TOTP verify attempts (`POST /api/verify-totp`), per account: the
* 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).
*/
verifyLimit?: false | VerifyLimitOptions
}
| false
@@ -278,7 +296,7 @@ export type IpalOptions = {
whiteLabel?:
| {
/**
* Vendor credit ("Technology by Intecion.com") at the bottom of the
* Vendor credit ("Technology support: Intecion.com") at the bottom of the
* admin nav. Default on; `false` hides it, or override text/url.
*/
credit?:
+72 -11
View File
@@ -2,23 +2,26 @@ import type { FieldAccess, PayloadRequest } from 'payload'
import { describe, expect, test, vi } from 'vitest'
import { hasMinimumRole, isAdmin, isEditor } from '../src/modules/access/predicates.js'
import { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSelf, adminOrSelfIn, requireRole, requireRoleField } from '../src/modules/access/access.js'
import { hasMinimumRole, isAdmin, isEditor, registerStaffCollections, staffRegistrySize } from '../src/modules/access/predicates.js'
import { buildRolesField } from '../src/modules/access/rolesField.js'
import { testEmailEndpoint } from '../src/modules/email/test/testEmailEndpoint.js'
vi.mock('payload', () => ({ addDataAndFileToRequest: vi.fn(async () => {}) }))
const admin = { id: 1, roles: ['admin'] }
const editor = { id: 2, roles: ['editor'] }
const user = { id: 3, roles: ['user'] }
const admin = { id: 1, collection: 'users', roles: ['admin'] }
const editor = { id: 2, collection: 'users', roles: ['editor'] }
const user = { id: 3, collection: 'users', roles: ['user'] }
/** `req.payload` as far as the role checks read it: the panel logs in with `users`. */
const payload = { config: { admin: { user: 'users' } } } as never
describe('role predicates', () => {
test('hierarchy admin > editor > user', () => {
expect(isAdmin(admin)).toBe(true)
expect(isAdmin(editor)).toBe(false)
expect(isEditor(admin)).toBe(true)
expect(isEditor(user)).toBe(false)
expect(hasMinimumRole(user, 'user')).toBe(true)
expect(isAdmin(admin, payload)).toBe(true)
expect(isAdmin(editor, payload)).toBe(false)
expect(isEditor(admin, payload)).toBe(true)
expect(isEditor(user, payload)).toBe(false)
expect(hasMinimumRole(user, 'user', payload)).toBe(true)
})
test('unknown roles and odd shapes grant nothing', () => {
@@ -26,16 +29,74 @@ describe('role predicates', () => {
expect(isAdmin({ roles: 'admin' })).toBe(false)
expect(isAdmin(null)).toBe(false)
})
test('a role counts only on an account of a staff collection', () => {
const member = { id: 1, collection: 'members', roles: ['admin'] }
expect(isAdmin(member, payload)).toBe(false)
expect(isEditor(member, payload)).toBe(false)
expect(hasMinimumRole(member, 'user', payload)).toBe(false)
expect(isAdmin({ id: 1, roles: ['admin'] }, payload)).toBe(false) // no collection: not an authenticated staff account
expect(isAdmin(admin, payload)).toBe(true)
// named in access.staffCollections → its roles count
const withMembers = { config: { admin: { user: 'users' }, custom: { ipal: { staffCollections: ['members'] } } } } as never
expect(isAdmin(member, withMembers)).toBe(true)
})
test('where the staff collections are not known, nobody is staff (browser bundle, middleware)', () => {
// no ipalKit config in this process (test/setup.ts clears the registry) and no source given
expect(isAdmin(admin)).toBe(false)
expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false)
expect(hasMinimumRole(user, 'user')).toBe(false)
// …until the caller says where staff come from: the config (also the client config), or the list itself
expect(isAdmin(admin, { admin: { user: 'users' } })).toBe(true)
expect(isAdmin(admin, { staffCollections: ['users'] })).toBe(true)
expect(isAdmin({ collection: 'customers', roles: ['admin'] }, { staffCollections: ['users'] })).toBe(false)
})
test('two configs in one process: a call without a source gets only what both call staff', () => {
const a = {}
const b = {}
registerStaffCollections(a, ['users'])
expect(isAdmin(admin)).toBe(true)
registerStaffCollections(b, ['staff', 'customers'])
expect(isAdmin(admin)).toBe(false) // not staff in B
expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false) // not staff in A
registerStaffCollections(b, ['users', 'customers'])
expect(isAdmin(admin)).toBe(true)
expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false)
// with the source, each config gets its own answer
expect(isAdmin({ collection: 'customers', roles: ['admin'] }, { staffCollections: ['users', 'customers'] })).toBe(true)
// an instance taking over its config's token replaces the entry instead of adding one
const instance = {}
registerStaffCollections(instance, ['users'], a)
expect(staffRegistrySize()).toBe(2)
})
test('every ready access function refuses that account', () => {
const member = { id: 1, collection: 'members', roles: ['admin'] }
const req = { payload, user: member }
for (const fn of [adminOnly, adminOrEditor, requireRole('user'), adminOrSelfIn('users')]) {
expect(fn({ req } as never)).toBe(false)
}
for (const fn of [adminOnlyField, adminOrEditorField, requireRoleField('user')]) {
expect(fn({ req } as never)).toBe(false)
}
// adminOrSelf cannot know the collection it guards: no admin shortcut, only the id rule (use adminOrSelfIn)
expect(adminOrSelf({ req } as never)).toEqual({ id: { equals: 1 } })
expect(adminOnly({ req: { payload, user: admin } } as never)).toBe(true)
})
})
describe('roles field', () => {
const field = buildRolesField() as { access: { create: FieldAccess; update: FieldAccess } }
const call = (fn: FieldAccess, u: unknown) => fn({ req: { user: u } } as never)
const call = (fn: FieldAccess, u: unknown) => fn({ req: { payload, user: u } } as never)
test('only admins can set roles on create — no self-promotion via sign-up', () => {
expect(call(field.access.create, null)).toBe(false)
expect(call(field.access.create, user)).toBe(false)
expect(call(field.access.create, admin)).toBe(true)
// an "admin" of another auth collection is nobody here
expect(call(field.access.create, { id: 1, collection: 'members', roles: ['admin'] })).toBe(false)
})
test('only admins can change roles', () => {
@@ -49,7 +110,7 @@ describe('test-email endpoint', () => {
const sendEmail = vi.fn(async () => ({ sent: true }))
const req = {
data: { to: '[email protected]' },
payload: { logger: { error: vi.fn() }, sendEmail },
payload: { config: { admin: { user: 'users' } }, logger: { error: vi.fn() }, sendEmail },
user: u,
} as unknown as PayloadRequest
return { response: testEmailEndpoint.handler(req), sendEmail }
+5 -4
View File
@@ -5,6 +5,7 @@ import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = {
defaultLocale: 'pl',
@@ -17,9 +18,9 @@ const i18n: I18nConfig = {
const empty = (extra: Partial<Config> = {}): Config =>
({ collections: [], secret: 'x', ...extra }) as unknown as Config
const admin = { id: 1, roles: ['admin'] }
const editor = { id: 2, roles: ['editor'] }
const user = { id: 3, roles: ['user'] }
const admin = { id: 1, collection: 'users', roles: ['admin'] }
const editor = { id: 2, collection: 'users', roles: ['editor'] }
const user = { id: 3, collection: 'users', roles: ['user'] }
/** Runs a collection/global access function the way Payload does. */
const run = (fn: Access | undefined, u: unknown) =>
@@ -52,7 +53,7 @@ describe('injected auth collection', () => {
})
describe('2FA wraps the auth collection people log in with', () => {
const totp = () => vi.fn((_: unknown) => (c: Config) => c)
const totp = () => vi.fn((o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection))
test('defaults to access.authCollection, not a literal "users"', async () => {
const plugin = totp()
+12 -1
View File
@@ -6,7 +6,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vite
import type { DoctorConfig, DoctorReport } from '../src/modules/doctor/types.js'
import { expandSites, parseDoctorArgs, runDoctorCli } from '../src/modules/doctor/cli.js'
import { expandSites, parseDoctorArgs, runDoctorCli, shouldWriteSeen } from '../src/modules/doctor/cli.js'
import { formatDriftTable, formatReport } from '../src/modules/doctor/format.js'
import { bareHost, parseEnvFile, readAuditSkips } from '../src/modules/doctor/project.js'
import { planSkills } from '../src/modules/doctor/rules/agents.js'
@@ -142,6 +142,8 @@ describe('versions', () => {
expect(old.findings[0].message).toContain('mongoose 8.24.1 < 8.24.7')
expect(old.findings[0].message).toContain('GHSA-pcrw-h46h-c93h')
expect(old.findings[0].fix).toContain('"mongoose@>=8 <8.24.7": "~8.24.10"')
expect(old.findings[0].fix).toMatch(/^upgrade payload and every @payloadcms\/\* to 3\.94\.1/)
expect(old.findings[1].fix).toMatch(/^add "happy-dom/)
expect(old.findings[1].message).toContain('happy-dom 20.14.6 < 21.0.4')
expect(old.findings[1].fix).toContain('"happy-dom@<21.0.4": "^21.0.4"')
// 8.24.3 fixes only the critical one
@@ -450,3 +452,12 @@ describe('the reference site', () => {
for (const setting of Object.values(config.rules ?? {})) {expect(setting.reason?.trim()).toBeTruthy()}
})
})
describe('ipal-doctor: first-seen dates', () => {
test('are written only outside CI, and never with --json or --sites', () => {
expect(shouldWriteSeen({}, {})).toBe(true)
expect(shouldWriteSeen({}, { CI: 'true' })).toBe(false)
expect(shouldWriteSeen({ json: true }, {})).toBe(false)
expect(shouldWriteSeen({ sites: 'clients/*' }, {})).toBe(false)
})
})
+25 -1
View File
@@ -4,7 +4,7 @@ import { assertEnv } from '../src/modules/env/assertEnv.js'
import { checkDatabaseName, databaseNameFromUri, databaseNamesFor } from '../src/modules/env/databaseName.js'
import { ipalEnvRules } from '../src/modules/env/ipalEnvRules.js'
const base = { DATABASE_URI: 'mongodb://db/x', NEXT_PUBLIC_SERVER_URL: 'http://localhost:3000', PAYLOAD_SECRET: 's' }
const base = { DATABASE_URI: 'mongodb://db/x', NEXT_PUBLIC_SERVER_URL: 'http://localhost:3000', PAYLOAD_SECRET: 'a-long-random-test-secret-of-32-chars' }
const r2 = {
R2_ACCESS_KEY_ID: 'k',
R2_BUCKET: 'b',
@@ -90,3 +90,27 @@ describe('database naming rule', () => {
vi.unstubAllEnvs()
})
})
describe('PAYLOAD_SECRET minimum length', () => {
const env = { DATABASE_URI: 'mongodb://db/x', NEXT_PUBLIC_SERVER_URL: 'https://acme.pl', PAYLOAD_SECRET: 'short-secret' }
afterEach(() => vi.unstubAllEnvs())
test('a short secret fails in production', () => {
vi.stubEnv('NODE_ENV', 'production')
expect(() => assertEnv(ipalEnvRules(), { env })).toThrow(/PAYLOAD_SECRET must be at least 32 characters in production \(got 12\)/)
expect(() => assertEnv(ipalEnvRules(), { env: { ...env, PAYLOAD_SECRET: 'x'.repeat(32) } })).not.toThrow()
})
test('a short secret passes outside production', () => {
vi.stubEnv('NODE_ENV', 'development')
expect(() => assertEnv(ipalEnvRules(), { env })).not.toThrow()
})
test('secretMinLength: 0 turns the check off; a custom minimum is used', () => {
vi.stubEnv('NODE_ENV', 'production')
expect(() => assertEnv(ipalEnvRules({ secretMinLength: 0 }), { env })).not.toThrow()
expect(() => assertEnv(ipalEnvRules({ secretMinLength: 64 }), { env: { ...env, PAYLOAD_SECRET: 'x'.repeat(40) } })).toThrow(/at least 64 characters/)
expect(() => assertEnv(ipalEnvRules({ secretMinLength: 8 }), { env })).not.toThrow()
expect(() => assertEnv(ipalEnvRules({ secretVar: 'MY_SECRET' }), { env: { ...env, MY_SECRET: 'short' } })).toThrow(/MY_SECRET must be at least 32/)
})
})
+20
View File
@@ -13,6 +13,26 @@ import { vi } from 'vitest'
export const buildTestConfig = (config: Config) =>
buildConfig({ ...config, typescript: { ...config.typescript, autoGenerate: false } })
/**
* The parts of @clocklimited/payload-2fa that ipalKit checks for after the injected factory ran
* (missingTotpParts): the two fields and the `totp` strategy on the target collection.
* A fake 2FA factory in a test wraps its config in this.
*/
export function withTotpParts(config: Config, collection: string): Config {
return {
...config,
collections: (config.collections ?? []).map((c) =>
c.slug === collection
? {
...c,
auth: { ...(typeof c.auth === 'object' ? c.auth : {}), strategies: [{ name: 'totp', authenticate: () => ({ user: null }) }] },
fields: [...c.fields, { name: 'totpSecret', type: 'text' }, { name: 'hasTotp', type: 'checkbox', virtual: true }],
}
: c,
),
}
}
type FakeOptions = {
forms?: Record<string, { fields: Record<string, unknown>[] }>
integrations?: Record<string, unknown>
+25
View File
@@ -0,0 +1,25 @@
import { mongooseAdapter } from '@payloadcms/db-mongodb'
import { postgresAdapter } from '@payloadcms/db-postgres'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
/**
* The database of the HTTP security tests. SQLite in memory by default; `IPAL_TEST_POSTGRES_URI` points them at a
* real Postgres (numeric ids, like SQLite — the adapters where an id of one auth collection can equal an id of
* another):
* docker run -d --rm -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=test postgres:17
* IPAL_TEST_POSTGRES_URI=postgres://postgres:[email protected]:55432/postgres pnpm vitest run test/securityHttp.test.ts
* `IPAL_TEST_MONGO_URI` points them at MongoDB (what the client sites run):
* docker run -d --rm -p 127.0.0.1:27217:27017 mongo:7
* IPAL_TEST_MONGO_URI=mongodb://127.0.0.1:27217 pnpm vitest run test/securityHttp.test.ts
* Each test file gets its own schema / database (`name`), so the files can run one after another against one server.
*/
/** True on the adapters where ids are numbers counted per collection (an id can repeat across collections). */
export const numericIds = () => !process.env.IPAL_TEST_MONGO_URI
export function testDatabase(name: string) {
const mongo = process.env.IPAL_TEST_MONGO_URI
if (mongo) {return mongooseAdapter({ url: `${mongo.replace(/\/$/, '')}/${name}_${Date.now()}` })}
const uri = process.env.IPAL_TEST_POSTGRES_URI
if (uri) {return postgresAdapter({ pool: { connectionString: uri }, push: true, schemaName: `${name}_${Date.now()}` })}
return sqliteAdapter({ client: { url: 'file::memory:' }, push: true })
}
+89
View File
@@ -0,0 +1,89 @@
import type { SanitizedConfig } from 'payload'
import { GRAPHQL_POST, REST_DELETE, REST_GET, REST_PATCH, REST_POST } from '@payloadcms/next/routes'
import { AsyncLocalStorage } from 'node:async_hooks'
import { createServer, type Server } from 'node:http'
/**
* Payload's own REST and GraphQL route handlers (the ones a Next app mounts under /api) behind a real HTTP
* server, so a test sends real requests: login, cookies, `Authorization` headers.
*
* @clocklimited/payload-2fa reads and writes its cookie through `next/headers`, which only works inside a Next
* request. A test file that turns 2FA on mocks that module with `nextHeadersMock` below:
* vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
*/
type CookieJar = { incoming: Map<string, string>; outgoing: string[] }
const jar = new AsyncLocalStorage<CookieJar>()
export const nextHeadersMock = {
cookies: () => {
const store = jar.getStore()
return Promise.resolve({
get: (name: string) => (store?.incoming.has(name) ? { name, value: store.incoming.get(name)! } : undefined),
set: (name: string, value: string) => {
store?.outgoing.push(`${name}=${value}; Path=/; HttpOnly`)
},
})
},
headers: () => Promise.resolve(new Headers()),
}
export type TestServer = { close: () => Promise<void>; url: string }
export async function startPayloadServer(config: Promise<SanitizedConfig>): Promise<TestServer> {
const rest = { DELETE: REST_DELETE(config), GET: REST_GET(config), PATCH: REST_PATCH(config), POST: REST_POST(config) }
const graphql = GRAPHQL_POST(config)
const server: Server = createServer((req, res) => {
const chunks: Buffer[] = []
req.on('data', (c: Buffer) => chunks.push(c))
req.on('end', () => {
void (async () => {
const url = new URL(req.url ?? '/', `http://${req.headers.host}`)
const headers = new Headers()
for (const [k, v] of Object.entries(req.headers)) {
if (typeof v === 'string') {headers.set(k, v)}
}
const method = (req.method ?? 'GET').toUpperCase()
const body = method === 'GET' || method === 'HEAD' ? undefined : Buffer.concat(chunks)
const request = new Request(url, { body, headers, method })
const incoming = new Map(
(req.headers.cookie ?? '').split(';').map((p) => p.trim()).filter(Boolean).map((p) => {
const i = p.indexOf('=')
return [p.slice(0, i), p.slice(i + 1)] as [string, string]
}),
)
const store: CookieJar = { incoming, outgoing: [] }
try {
const response = await jar.run(store, async () => {
if (url.pathname === '/api/graphql') {return graphql(request)}
const handler = rest[method as keyof typeof rest]
if (!handler) {return new Response('Method not allowed', { status: 405 })}
const slug = url.pathname.replace(/^\/api\/?/, '').split('/').filter(Boolean)
return handler(request, { params: Promise.resolve({ slug }) })
})
const setCookies = [...response.headers.getSetCookie(), ...store.outgoing]
response.headers.forEach((value, key) => {
if (key !== 'set-cookie') {res.setHeader(key, value)}
})
if (setCookies.length) {res.setHeader('set-cookie', setCookies)}
res.statusCode = response.status
res.end(Buffer.from(await response.arrayBuffer()))
} catch (err) {
res.statusCode = 500
res.end(err instanceof Error ? err.stack : String(err))
}
})()
})
})
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
const address = server.address()
const port = typeof address === 'object' && address ? address.port : 0
return {
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
url: `http://127.0.0.1:${port}`,
}
}
/** `name=value` pairs of a response's Set-Cookie headers, ready for a `cookie` request header. */
export const cookiesOf = (res: Response): string[] => res.headers.getSetCookie().map((c) => c.split(';')[0])
+15
View File
@@ -0,0 +1,15 @@
import { createHmac } from 'node:crypto'
/** RFC 6238 TOTP (SHA-1, 6 digits, 30 s) — the code an authenticator app shows for `secret` (base32). */
export function totp(secret: string, now = Date.now()): string {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
let bits = ''
for (const ch of secret.replace(/=+$/, '').toUpperCase()) {bits += alphabet.indexOf(ch).toString(2).padStart(5, '0')}
const key = Buffer.from((bits.match(/.{8}/g) ?? []).map((b) => parseInt(b, 2)))
const counter = Buffer.alloc(8)
counter.writeBigUInt64BE(BigInt(Math.floor(now / 1000 / 30)))
const hmac = createHmac('sha1', key).update(counter).digest()
const offset = hmac[hmac.length - 1] & 0xf
const code = (hmac.readUInt32BE(offset) & 0x7fffffff) % 1_000_000
return code.toString().padStart(6, '0')
}
+5 -3
View File
@@ -5,6 +5,7 @@ import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = {
defaultLocale: 'pl',
@@ -40,7 +41,7 @@ describe('ipalKit — config transform', () => {
/no 2FA plugin was injected/,
)
const totp = vi.fn(() => (c: Config) => c)
const totp = vi.fn((o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection))
await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: totp as never } })(base())
expect(totp).toHaveBeenCalledWith(expect.objectContaining({ forceSetup: true, totp: { issuer: 'Acme' } }))
})
@@ -119,7 +120,8 @@ describe('options that keep features reachable and overridable', () => {
test('without `access` (no roles field) admin and editor features stay reachable for logged-in users', async () => {
const config = await ipalKit({ consentLog: true, forms: {}, i18n, stats: true, twoFactor: false })(base())
const users = config.collections!.find((c) => c.slug === 'users')!
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } } }, user }) as never
// `admin.user` is what Payload's sanitize fills in: the panel's login collection = the staff collection.
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } }, config: { admin: { user: 'users' } } }, user }) as never
const member = { id: 1, collection: 'users', email: '[email protected]' }
const run = (access: unknown, user: unknown) => (access as (a: { req: unknown }) => unknown)({ req: req(user) })
@@ -135,7 +137,7 @@ describe('options that keep features reachable and overridable', () => {
test('with `access` the roles still decide', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, stats: true, twoFactor: false })(base())
const users = config.collections!.find((c) => c.slug === 'users')!
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } } }, user }) as never
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } }, config: { admin: { user: 'users' } } }, user }) as never
const read = config.globals!.find((g) => g.slug === 'site-integrations')!.access!.read as (a: { req: unknown }) => unknown
expect(read({ req: req({ id: 1, collection: 'users', roles: ['editor'] }) })).toBe(false)
expect(read({ req: req({ id: 1, collection: 'users', roles: ['admin'] }) })).toBe(true)
+1 -1
View File
@@ -116,7 +116,7 @@ describe('IPAL_IP_HEADER', () => {
test('ipalEnvRules({ ipHeader }) requires it in production only', async () => {
const { assertEnv } = await import('../src/modules/env/assertEnv.js')
const { ipalEnvRules } = await import('../src/modules/env/ipalEnvRules.js')
const base = { DATABASE_URI: 'x', NEXT_PUBLIC_SERVER_URL: 'https://acme.pl', PAYLOAD_SECRET: 'x' }
const base = { DATABASE_URI: 'x', NEXT_PUBLIC_SERVER_URL: 'https://acme.pl', PAYLOAD_SECRET: 'a-long-random-test-secret-of-32-chars' }
vi.stubEnv('NODE_ENV', 'production')
expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: base })).toThrow(/IPAL_IP_HEADER/)
expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: { ...base, IPAL_IP_HEADER: 'cf-connecting-ip' } })).not.toThrow()
+301
View File
@@ -0,0 +1,301 @@
/**
* The rules behind test/securityHttp.test.ts, one by one: who is staff (userMeetsRole), when the second
* factor counts as passed, and what ipalKit does with a 2FA plugin it does not recognise.
*/
import type { Access, Config } from 'payload'
import { describe, expect, test } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { adminOrSelfIn } from '../src/modules/access/access.js'
import { isAdmin, staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js'
import { ensurePayloadGuarded, guardPayloadAccess, guardTotpEndpoint, requireSecondFactor, secondFactorPassed, watchPayloadConfig } from '../src/modules/security/totp/secondFactor.js'
import { buildVerifyLimit, clearVerifyLimits } from '../src/modules/security/totp/verifyLimit.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
const fakeTotp = (o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection)
/** A payload as the access functions see it: sanitized `admin.user`, the collections by slug, `custom`. */
const payloadOf = (config: Config, adminUser = 'users') =>
({
collections: Object.fromEntries((config.collections ?? []).map((c) => [c.slug, { config: c }])),
config: { admin: { user: adminUser }, collections: config.collections, custom: config.custom, globals: config.globals },
}) as never
const twoAuth = (): Config =>
({
collections: [
{ slug: 'customers', auth: true, fields: [] },
{ slug: 'partners', auth: true, fields: [] },
],
secret: 'x',
}) as unknown as Config
describe('userMeetsRole: who is staff', () => {
test('with roles: the role decides; an account of another auth collection never passes', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(twoAuth())
const payload = payloadOf(config)
expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true)
expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['user'] } }, 'editor')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'user')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'no-such-collection' } }, 'user')).toBe(false)
// a role value on an account of a non-staff collection counts for nothing
expect(userMeetsRole({ payload, user: { collection: 'customers', roles: ['admin'] } }, 'user')).toBe(false)
expect(userMeetsRole({ payload, user: { roles: ['admin'] } }, 'user')).toBe(false) // no collection at all
expect(userMeetsRole({ payload, user: null }, 'user')).toBe(false)
})
test('without `access`: every account of the panel collection passes, other auth collections do not', async () => {
const config = await ipalKit({ i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config)
const payload = payloadOf(config)
expect(staffCollectionSlugs(payload)).toEqual(['users'])
expect(userMeetsRole({ payload, user: { collection: 'users' } }, 'admin')).toBe(true)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
})
test('access.staffCollections names more staff collections, on purpose', async () => {
const config = await ipalKit({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: false })(twoAuth())
const payload = payloadOf(config)
expect(staffCollectionSlugs(payload)).toEqual(['users', 'partners'])
expect(userMeetsRole({ payload, user: { collection: 'partners' } }, 'admin')).toBe(true) // no roles field there: all equal
expect(userMeetsRole({ payload, user: { collection: 'customers', roles: ['admin'] } }, 'admin')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
})
test('without a payload: the staff collections of the config ipalKit built last; only a held role counts', async () => {
await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config)
expect(userMeetsRole({ user: { collection: 'users' } }, 'user')).toBe(false)
expect(userMeetsRole({ user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true)
expect(userMeetsRole({ user: { collection: 'customers', roles: ['admin'] } }, 'admin')).toBe(false)
expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false) // isAdmin(req.user) in a hook
expect(isAdmin({ collection: 'users', roles: ['admin'] })).toBe(true)
})
})
describe('adminOrSelfIn', () => {
const run = (fn: Access, user: unknown) => fn({ req: { payload: { config: { admin: { user: 'users' } } }, user } } as never)
test('"self" is an account of that collection only', () => {
const access = adminOrSelfIn('users')
expect(run(access, { id: 5, collection: 'users', roles: ['user'] })).toEqual({ id: { equals: 5 } })
expect(run(access, { id: 5, collection: 'customers' })).toBe(false) // same id, other collection
expect(run(access, { id: 1, collection: 'users', roles: ['admin'] })).toBe(true)
expect(run(access, null)).toBe(false)
})
})
describe('secondFactorPassed', () => {
const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users' } } } } } as never
const cases: [string, unknown, boolean][] = [
['no user', null, true],
['password and code (the totp strategy)', { _strategy: 'totp', collection: 'users', hasTotp: true }, true],
['API key', { _strategy: 'api-key', collection: 'users', hasTotp: true }, true],
['TOTP not set up yet', { _strategy: 'local-jwt', collection: 'users', hasTotp: false }, true],
['password only', { _strategy: 'local-jwt', collection: 'users', hasTotp: true }, false],
['a user object without the fields the check knows (fail closed)', { collection: 'users' }, false],
['an unknown strategy name (fail closed)', { _strategy: 'two-factor', collection: 'users', hasTotp: true }, false],
['an account of another auth collection', { _strategy: 'local-jwt', collection: 'customers' }, true],
['a user object that does not say its collection (fail closed)', { _strategy: 'totp', hasTotp: true }, false],
['`hasTotp` false although the record carries a secret (the package\'s lookup failed): refused', { _strategy: 'local-jwt', collection: 'users', hasTotp: false, totpSecret: 'JBSWY3DPEHPK3PXP' }, false],
]
test.each(cases)('%s', (_, user, expected) => {
expect(secondFactorPassed({ payload, user })).toBe(expected)
})
test('2FA off: everyone passes', () => {
expect(secondFactorPassed({ payload: { config: {} } as never, user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true } })).toBe(true)
})
test('requireSecondFactor wraps once and keeps the inner rule', () => {
const inner: Access = ({ req }) => Boolean((req.user as { ok?: boolean } | null)?.ok)
const wrapped = requireSecondFactor(inner)
expect(requireSecondFactor(wrapped)).toBe(wrapped)
const call = (user: unknown) => wrapped({ req: { payload, user } } as never)
expect(call({ _strategy: 'totp', collection: 'users', hasTotp: true, ok: true })).toBe(true)
expect(call({ _strategy: 'totp', collection: 'users', hasTotp: true })).toBe(false)
expect(call({ _strategy: 'local-jwt', collection: 'users', hasTotp: true, ok: true })).toBe(false)
})
})
describe('ipalKit and the 2FA plugin', () => {
const passwordOnly = { id: 1, _strategy: 'local-jwt', collection: 'users', hasTotp: true, roles: ['admin'] }
const verified = { ...passwordOnly, _strategy: 'totp' }
test('every collection and global in the config is guarded, whenever it was added', async () => {
const config = await ipalKit({
access: { authCollection: 'users' }, consentLog: true, cookieScanner: { crawl: true }, forms: {}, i18n, stats: true,
twoFactor: { issuer: 'A', plugin: fakeTotp as never },
})({ collections: [{ slug: 'pages', fields: [] }], globals: [{ slug: 'own', fields: [] }], secret: 'x' } as unknown as Config)
const payload = payloadOf(config)
const open: string[] = []
const check = (kind: string, slug: string, access: Record<string, unknown> | undefined, ops: string[]) => {
for (const op of ops) {
const fn = access?.[op] as ((a: unknown) => unknown) | undefined
if (!fn || fn({ req: { payload, user: passwordOnly } }) !== false) {open.push(`${kind} ${slug}.${op}`)}
}
}
for (const c of config.collections ?? []) {check('collection', c.slug, c.access as never, ['create', 'delete', 'read', 'readVersions', 'unlock', 'update'])}
for (const g of config.globals ?? []) {check('global', g.slug, g.access as never, ['read', 'readDrafts', 'readVersions', 'update'])}
expect(open).toEqual([])
// and a verified admin still gets in
const integrations = config.globals!.find((g) => g.slug === 'site-integrations')!
expect((integrations.access!.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true)
})
test('the sweep guards everything a later plugin or Payload itself added — no exception by name or prefix', () => {
const late = { slug: 'late', access: {} as Record<string, unknown> }
const prefixed = { slug: 'payload-vault', access: {} as Record<string, unknown> } // a plugin's collection, e.g. payload-mcp-api-keys
const internal = { slug: 'payload-preferences', access: {} as Record<string, unknown> }
const loggedIn = ({ req }: { req: { user?: unknown } }) => Boolean(req.user) // Payload's defaultAccess
const jobs = { access: { cancel: loggedIn, queue: loggedIn, run: loggedIn } as Record<string, unknown> }
const payload = { config: { collections: [late, prefixed, internal], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [{ slug: 'payload-jobs-stats' }], jobs } } as never
expect(guardPayloadAccess(payload)).toEqual(['late', 'payload-vault', 'payload-preferences', 'payload-jobs-stats', 'jobs'])
for (const entity of [late, prefixed, internal]) {
expect((entity.access.read as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false)
expect((entity.access.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true)
}
// the job queue's rules as Payload filled them in (3.94.1: all three "a logged-in user"): kept, plus
// "not while the second factor is owed"
const job = (op: string, user: unknown) => (jobs.access[op] as (a: unknown) => unknown)({ req: { payload, user } })
for (const op of ['run', 'queue', 'cancel']) {
expect([op, job(op, null), job(op, passwordOnly), job(op, verified)]).toEqual([op, false, false, true])
}
// a rule the project set is kept as it is; a rule nobody set is not invented (Payload fills it in)
const own = { access: { queue: () => true } as Record<string, unknown> }
guardPayloadAccess({ config: { collections: [], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [], jobs: own } } as never)
const ownQueue = (user: unknown) => (own.access.queue as (a: unknown) => unknown)({ req: { payload, user } })
expect([ownQueue(null), ownQueue(passwordOnly), ownQueue(verified)]).toEqual([true, false, true])
expect(own.access.run).toBeUndefined()
expect(own.access.cancel).toBeUndefined()
expect(guardPayloadAccess(payload)).toEqual([]) // nothing left to do the second time
expect(ensurePayloadGuarded(payload)).toEqual([])
expect(ensurePayloadGuarded(payload)).toBeNull() // this config object was done
})
test('a config swapped onto the instance (dev reload) is adopted at once, before any request', () => {
const adopted: unknown[] = []
const instance = { config: { name: 'first' } } as never as { config: { name: string } }
watchPayloadConfig(instance as never, (p) => adopted.push((p as never as { config: { name: string } }).config.name))
instance.config = { name: 'second' }
expect(adopted).toEqual(['second'])
expect(instance.config.name).toBe('second')
expect({ ...instance }.config.name).toBe('second') // still an ordinary enumerable property to readers
})
test('a 2FA plugin without the parts the guard relies on stops the start', async () => {
const unknown = () => (c: Config) => c
const run = (guard?: false) =>
ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: unknown as never, ...(guard === false ? { guard } : {}) } })({ collections: [], secret: 'x' } as unknown as Config)
await expect(run()).rejects.toThrow(/did not add the `totpSecret` field, the `hasTotp` field, the `totp` auth strategy/)
// twoFactor.guard: false = the package alone, as before
const config = await run(false)
expect((config.custom as { ipal?: { twoFactor?: unknown } } | undefined)?.ipal?.twoFactor).toBeUndefined()
})
test('per-entity opt-out: the package key and ipal-kit\'s key, operation by operation', async () => {
const config = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({
collections: [
{ slug: 'a', custom: { totp: { disableAccessWrapper: { read: true } } }, fields: [] },
{ slug: 'b', custom: { ipal: { secondFactor: false } }, fields: [] },
],
globals: [{ slug: 'g', custom: { ipal: { secondFactor: { read: false } } }, fields: [] }],
secret: 'x',
} as unknown as Config)
const payload = payloadOf(config)
// an operation without a function = Payload's default: any logged-in account
const call = (access: unknown, op: string) => {
const fn = (access as Record<string, ((a: unknown) => unknown) | undefined> | undefined)?.[op]
return fn ? fn({ req: { payload, user: passwordOnly } }) : true
}
const col = (slug: string) => config.collections!.find((c) => c.slug === slug)!.access
expect(call(col('a'), 'read')).toBe(true)
expect(call(col('a'), 'update')).toBe(false)
// opted out of everything and no rule of its own: left exactly as the project wrote it (Payload's default applies)
expect(col('b')).toBeUndefined()
const g = config.globals!.find((x) => x.slug === 'g')!.access
expect(call(g, 'read')).toBe(true)
expect(call(g, 'update')).toBe(false)
// ipal-kit's key reaches the package in its own key, so the package leaves the operation alone too
expect((config.globals!.find((x) => x.slug === 'g')!.custom as { totp: unknown }).totp).toEqual({ disableAccessWrapper: { read: true } })
})
test("the 2FA package's endpoints: accounts of the 2FA collection only; management needs the second factor", async () => {
const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users' } } } } }
const inner = () => Promise.resolve(Response.json({ ok: true }))
const call = async (path: string, user: unknown) => {
const endpoint = guardTotpEndpoint({ handler: inner as (req: never) => Promise<Response>, path }, 'users')
return (await endpoint.handler({ payload, user } as never)).status
}
const customer = { id: 1, collection: 'customers' }
const newcomer = { id: 2, _strategy: 'local-jwt', collection: 'users', hasTotp: false }
for (const path of ['/setup-totp', '/verify-totp', '/remove-totp', '/admin/reset-user-totp', '/some-future-endpoint']) {
expect([path, await call(path, customer)]).toEqual([path, 403])
expect([path, await call(path, null)]).toEqual([path, 200]) // no user: the package answers itself
}
expect(await call('/setup-totp', newcomer)).toBe(200)
expect(await call('/verify-totp', passwordOnly)).toBe(200)
expect(await call('/remove-totp', passwordOnly)).toBe(403)
expect(await call('/admin/reset-user-totp', passwordOnly)).toBe(403)
expect(await call('/some-future-endpoint', passwordOnly)).toBe(403)
expect(await call('/admin/reset-user-totp', verified)).toBe(200)
})
test('verify attempts are limited per account, and the limit can be changed or switched off', async () => {
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))!
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
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)
// wired by default; twoFactor.verifyLimit: false leaves the package's endpoint as it is
const base = () => ({ collections: [], endpoints: [], secret: 'x' }) as unknown as Config
const withEndpoint = (o: { collection: string }) => (c: Config) => ({ ...withTotpParts(c, o.collection), endpoints: [...(c.endpoints ?? []), { handler: () => Response.json({ ok: false }), method: 'post' as const, path: '/verify-totp' }] })
const call = async (config: Config, n: number) => {
const endpoint = config.endpoints!.find((e) => e.path === '/verify-totp')!
let last = 0
for (let i = 0; i < n; i++) {last = (await endpoint.handler(req(77))).status}
return last
}
clearVerifyLimits()
expect(await call(await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never } })(base()), 6)).toBe(429)
clearVerifyLimits()
expect(await call(await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never, verifyLimit: false } })(base()), 8)).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 payload = {
collections: {},
config: { admin: { user: 'users' }, collections: [], custom: config.custom, globals: [] },
count: () => ({ totalDocs: 0 }),
find: () => ({ docs: [] }),
findGlobal: () => ({}),
logger: { info: () => {}, warn: (m: string) => warnings.push(m) },
updateGlobal: () => ({}),
}
await Promise.resolve(config.onInit!(payload as never)).catch(() => {}) // later onInit steps need a real database
expect(warnings.join('\n')).toMatch(/2FA covers "users" only\. Staff accounts of "partners"/)
})
test('twoFactor: false — no guard, a password is enough (as documented)', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config)
const payload = payloadOf(config)
const read = config.globals!.find((g) => g.slug === 'site-integrations')!.access!.read as (a: unknown) => unknown
expect(read({ req: { payload, user: { collection: 'users', roles: ['admin'] } } })).toBe(true)
})
})
+499
View File
@@ -0,0 +1,499 @@
/**
* Who reaches what the plugin adds, through real HTTP requests (REST and GraphQL) against a running Payload:
* - a staff account that typed only its password (TOTP set up, code not entered) gets nothing;
* - an account of another auth collection (`customers`) gets no more than an anonymous visitor;
* - a fully verified staff account, an account that still has to set TOTP up, and an API key keep working.
*/
import type { CollectionConfig, Config, Payload, Plugin } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { numericIds, 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 TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
const PASSWORD = 'a-long-test-password-1'
/** A plugin the project lists AFTER ipalKit: its collection did not exist when ipalKit ran. */
const latePlugin: Plugin = (config: Config) => ({
...config,
collections: [
...(config.collections ?? []),
{ slug: 'late-notes', fields: [{ name: 'note', type: 'text' }] },
// A plugin may well call its collection `payload-…` (@payloadcms/plugin-mcp: `payload-mcp-api-keys`).
{ slug: 'payload-vault', access: { read: ({ req }) => Boolean(req.user) }, fields: [{ name: 'secret', type: 'text' }] },
],
globals: [...(config.globals ?? []), { slug: 'late-settings', fields: [{ name: 'note', type: 'text' }] }],
})
const projectCollections: CollectionConfig[] = [
// A visitor account collection with open sign-up — a shop or a client zone.
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
// Another one that happens to have its own `roles` field with the same values, settable at sign-up.
{
slug: 'members',
access: { create: () => true },
auth: true,
fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }],
},
// The 2FA package's own per-entity opt-out, and ipal-kit's.
{
slug: 'open-notes',
access: { read: ({ req }) => Boolean(req.user), update: ({ req }) => Boolean(req.user) },
custom: { totp: { disableAccessWrapper: { read: true } } },
fields: [{ name: 'note', type: 'text' }],
},
{
slug: 'open-tasks',
access: { read: ({ req }) => Boolean(req.user), update: ({ req }) => Boolean(req.user) },
custom: { ipal: { secondFactor: { read: false } } },
fields: [{ name: 'task', type: 'text' }],
},
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
]
const PROJECT_SLUGS = new Set(['customers', 'media', 'members', 'open-notes', 'open-tasks', 'pages'])
type Session = { headers: Record<string, string> }
let server: TestServer
let payload: Payload
let pluginCollections: string[]
let pluginGlobals: string[]
const sessions = {} as Record<'anonymous' | 'customer' | 'member' | 'newcomer' | 'passwordOnly' | 'verified', Session>
const api = (pathname: string, session: Session, init: RequestInit = {}) =>
fetch(`${server.url}/api${pathname}`, {
...init,
headers: { 'content-type': 'application/json', ...session.headers, ...(init.headers as Record<string, string>) },
})
const gql = async (session: Session, query: string) => {
const res = await api('/graphql', session, { body: JSON.stringify({ query }), method: 'POST' })
return (await res.json()) as { data?: null | Record<string, unknown>; errors?: { message: string }[] }
}
async function login(collection: string, email: string): Promise<{ cookies: string[]; token: string }> {
const res = await fetch(`${server.url}/api/${collection}/login`, {
body: JSON.stringify({ email, password: PASSWORD }),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
const body = (await res.json()) as { token?: string }
if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)}
return { cookies: cookiesOf(res), token: body.token }
}
const makeConfig = () =>
buildTestConfig({
admin: { user: 'users' }, // the panel logs in with the staff collection, not with `customers`
collections: projectCollections,
db: testDatabase('sechttp'),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
consentLog: true,
cookieScanner: { crawl: true },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
stats: true,
twoFactor: { issuer: 'Example', plugin: payloadTotp },
}),
latePlugin,
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
beforeAll(async () => {
const config = makeConfig()
payload = await getPayload({ config })
server = await startPayloadServer(config)
// The plugin's own and `late-notes`. Payload's built-in collections and the late plugin's `payload-vault` /
// `late-settings` have a describe of their own below (their rule is "any logged-in account", so the comparisons
// with an anonymous visitor do not apply to them).
pluginCollections = payload.config.collections.map((c) => c.slug).filter((s) => !PROJECT_SLUGS.has(s) && !s.startsWith('payload-'))
pluginGlobals = payload.config.globals.map((g) => g.slug).filter((slug) => slug !== 'late-settings')
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: 'S3CRET' } as never })
await payload.create({ collection: 'payload-vault' as never, data: { secret: 'VAULT' } as never })
const user = (email: string, extra: object) =>
payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['admin'], ...extra } as never })
await user('[email protected]', { totpSecret: TOTP_SECRET })
await user('[email protected]', {})
await payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
// Signed up over the API, asking for the admin role in its own collection.
const signUp = await fetch(`${server.url}/api/members`, {
body: JSON.stringify({ email: '[email protected]', password: PASSWORD, roles: ['admin'] }),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
expect(signUp.status).toBe(201)
sessions.member = { headers: { authorization: `JWT ${(await login('members', '[email protected]')).token}` } }
sessions.anonymous = { headers: {} }
sessions.passwordOnly = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
sessions.newcomer = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
sessions.customer = { headers: { authorization: `JWT ${(await login('customers', '[email protected]')).token}` } }
// The full login: password, then the code from the authenticator app → the 2FA cookie.
const full = await login('users', '[email protected]')
const verify = await fetch(`${server.url}/api/verify-totp`, {
body: JSON.stringify({ token: totp(TOTP_SECRET) }),
headers: { 'content-type': 'application/json', cookie: full.cookies.join('; ') },
method: 'POST',
})
const verified = (await verify.json()) as { message?: string; ok: boolean }
expect(verified, JSON.stringify({ cookies: full.cookies.map((c) => c.slice(0, 30)), verified })).toMatchObject({ ok: true })
sessions.verified = { headers: { cookie: [...full.cookies, ...cookiesOf(verify)].join('; ') } }
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
const readStatus = async (kind: 'collection' | 'global', slug: string, s: Session) =>
(await api(kind === 'collection' ? `/${slug}` : `/globals/${slug}`, s)).status
const writeStatus = async (kind: 'collection' | 'global', slug: string, s: Session) =>
(await api(kind === 'collection' ? `/${slug}` : `/globals/${slug}`, s, { body: '{}', method: 'POST' })).status
describe('what the test set up', () => {
test('the plugin added the entities this file is about', () => {
expect(pluginCollections).toEqual(expect.arrayContaining(['users', 'forms', 'form-submissions', 'consent-records', 'cookie-review', 'stats-visits', 'late-notes']))
expect(pluginGlobals).toEqual(expect.arrayContaining(['site-settings', 'site-integrations', 'cookie-settings', 'notifications', 'cookie-crawl']))
})
})
describe('REST: a staff password without the TOTP code opens nothing', () => {
test('every collection and global is refused, for reading and for writing', async () => {
const open: string[] = []
for (const [kind, slugs] of [['collection', [...pluginCollections, 'pages']], ['global', pluginGlobals]] as const) {
for (const slug of slugs) {
if ((await readStatus(kind, slug, sessions.passwordOnly)) !== 403) {open.push(`read ${kind} ${slug}`)}
if ((await writeStatus(kind, slug, sessions.passwordOnly)) !== 403) {open.push(`write ${kind} ${slug}`)}
}
}
expect(open).toEqual([])
})
test('the SMTP password is not returned', async () => {
const res = await api('/globals/site-integrations', sessions.passwordOnly)
expect(res.status).toBe(403)
expect(await res.text()).not.toContain('S3CRET')
})
test("the plugin's own endpoints refuse too", async () => {
expect((await api('/ipal/test-email', sessions.passwordOnly, { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })).status).toBe(403)
expect((await api('/ipal/cookie-scan', sessions.passwordOnly)).status).toBe(403)
expect((await api('/ipal/cookie-scan', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
expect((await api('/ipal/cookie-crawl', sessions.passwordOnly)).status).toBe(403)
expect((await api('/ipal/cookie-approval', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
})
})
describe('GraphQL: a staff password without the TOTP code opens nothing', () => {
test.each([
['Site integrations', '{ SiteIntegration { smtpPassword } }'],
['form submissions', '{ FormSubmissions { totalDocs } }'],
['consent records', '{ ConsentRecords { totalDocs } }'],
['stats', '{ StatsVisits { totalDocs } }'],
['cookie review', '{ CookieReviews { totalDocs } }'],
['Site settings (write)', 'mutation { updateSiteSetting(data: { siteName: "x" }) { siteName } }'],
['Notifications (write)', 'mutation { updateNotification(data: {}) { updatedAt } }'],
])('%s', async (_, query) => {
const out = await gql(sessions.passwordOnly, query)
expect(out.errors?.length, JSON.stringify(out)).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('S3CRET')
expect(Object.values(out.data ?? {}).filter((v) => v !== null)).toEqual([])
})
})
describe('an account of another auth collection (customers) is not staff', () => {
test('REST: it gets exactly what an anonymous visitor gets, nothing more', async () => {
const more: string[] = []
for (const [kind, slugs] of [['collection', pluginCollections.filter((s) => s !== 'late-notes')], ['global', pluginGlobals]] as const) {
for (const slug of slugs) {
const read = [await readStatus(kind, slug, sessions.customer), await readStatus(kind, slug, sessions.anonymous)]
if (read[0] !== read[1]) {more.push(`read ${kind} ${slug}: customer ${read[0]}, anonymous ${read[1]}`)}
// Creating a form submission over REST is open to every logged-in account (unchanged, see forms.md).
if (kind === 'collection' && slug === 'form-submissions') {continue}
const write = [await writeStatus(kind, slug, sessions.customer), await writeStatus(kind, slug, sessions.anonymous)]
if (write[0] !== write[1]) {more.push(`write ${kind} ${slug}: customer ${write[0]}, anonymous ${write[1]}`)}
}
}
expect(more).toEqual([])
})
test('REST: Site integrations, submissions, consent records and stats are refused', async () => {
for (const p of ['/globals/site-integrations', '/form-submissions', '/consent-records', '/stats-visits', '/cookie-review', '/globals/cookie-crawl']) {
expect([p, (await api(p, sessions.customer)).status]).toEqual([p, 403])
}
expect((await api('/globals/site-settings', sessions.customer, { body: JSON.stringify({ siteName: 'x' }), method: 'POST' })).status).toBe(403)
expect((await api('/ipal/test-email', sessions.customer, { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })).status).toBe(403)
expect((await api('/ipal/cookie-scan', sessions.customer)).status).toBe(403)
})
test('GraphQL: the same', async () => {
for (const query of ['{ SiteIntegration { smtpPassword } }', '{ FormSubmissions { totalDocs } }', '{ ConsentRecords { totalDocs } }', 'mutation { updateSiteSetting(data: { siteName: "x" }) { siteName } }']) {
const out = await gql(sessions.customer, query)
expect(out.errors?.length, `${query} → ${JSON.stringify(out)}`).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('S3CRET')
}
})
test('its own collection still works for it', async () => {
expect((await api('/customers/me', sessions.customer)).status).toBe(200)
})
})
describe('what must keep working', () => {
test('a fully verified admin reads and writes everything (REST)', async () => {
const closed: string[] = []
for (const [kind, slugs] of [['collection', [...pluginCollections, 'pages']], ['global', pluginGlobals]] as const) {
for (const slug of slugs) {
const status = await readStatus(kind, slug, sessions.verified)
if (status !== 200) {closed.push(`read ${kind} ${slug}: ${status}`)}
}
}
expect(closed).toEqual([])
const integrations = (await (await api('/globals/site-integrations', sessions.verified)).json()) as { smtpPassword?: string }
expect(integrations.smtpPassword).toBe('S3CRET')
expect((await api('/globals/site-settings', sessions.verified, { body: JSON.stringify({ siteName: 'Verified' }), method: 'POST' })).status).toBe(200)
expect((await api('/ipal/cookie-scan', sessions.verified)).status).toBe(200)
// 400 = past the login and role gates, stopped by the missing recipient
expect((await api('/ipal/test-email', sessions.verified, { body: '{}', method: 'POST' })).status).toBe(400)
})
test('a fully verified admin reads Site integrations (GraphQL)', async () => {
const out = await gql(sessions.verified, '{ SiteIntegration { smtpPassword } FormSubmissions { totalDocs } }')
expect(out.errors).toBeUndefined()
expect((out.data?.SiteIntegration as { smtpPassword: string }).smtpPassword).toBe('S3CRET')
})
test('an account that has not set TOTP up yet can still do so', async () => {
// The package lets such an account through until TOTP is set up (the setup screen needs it).
expect((await api('/users/me', sessions.newcomer)).status).toBe(200)
const setup = await api('/setup-totp', sessions.newcomer, { body: JSON.stringify({ secret: TOTP_SECRET, token: totp(TOTP_SECRET) }), method: 'POST' })
expect(setup.status).toBe(200)
expect(((await setup.json()) as { ok: boolean }).ok).toBe(true)
})
test('anonymous visitors still read the public globals and forms', async () => {
for (const p of ['/globals/site-settings', '/globals/notifications', '/globals/cookie-settings', '/forms']) {
expect([p, (await api(p, sessions.anonymous)).status]).toEqual([p, 200])
}
expect((await api('/globals/site-integrations', sessions.anonymous)).status).toBe(403)
})
})
describe('a role value on an account of a non-staff collection counts for nothing (members with roles: [admin])', () => {
test('REST: it gets exactly what an anonymous visitor gets', async () => {
const more: string[] = []
for (const [kind, slugs] of [['collection', pluginCollections.filter((s) => s !== 'late-notes')], ['global', pluginGlobals]] as const) {
for (const slug of slugs) {
const read = [await readStatus(kind, slug, sessions.member), await readStatus(kind, slug, sessions.anonymous)]
if (read[0] !== read[1]) {more.push(`read ${kind} ${slug}: member ${read[0]}, anonymous ${read[1]}`)}
if (kind === 'collection' && slug === 'form-submissions') {continue}
const write = [await writeStatus(kind, slug, sessions.member), await writeStatus(kind, slug, sessions.anonymous)]
if (write[0] !== write[1]) {more.push(`write ${kind} ${slug}: member ${write[0]}, anonymous ${write[1]}`)}
}
}
expect(more).toEqual([])
})
test('REST: no secrets, no user list, no submissions, no staff endpoints, no unlock, no role change', async () => {
const integrations = await api('/globals/site-integrations', sessions.member)
expect(integrations.status).toBe(403)
expect(await integrations.text()).not.toContain('S3CRET')
for (const p of ['/users', '/form-submissions', '/consent-records', '/stats-visits', '/ipal/cookie-scan']) {
expect([p, (await api(p, sessions.member)).status]).toEqual([p, 403])
}
expect((await api('/ipal/test-email', sessions.member, { body: '{}', method: 'POST' })).status).toBe(403)
expect((await api('/users/unlock', sessions.member, { body: JSON.stringify({ email: '[email protected]' }), method: 'POST' })).status).toBe(403)
const staff = await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })
const patch = await api(`/users/${staff.docs[0].id}`, sessions.member, { body: JSON.stringify({ roles: ['user'] }), method: 'PATCH' })
expect(patch.status).toBe(403)
const after = (await payload.findByID({ id: staff.docs[0].id, collection: 'users' as never })) as unknown as { roles: string[] }
expect(after.roles).toEqual(['admin'])
})
test('GraphQL: the same', async () => {
for (const query of ['{ SiteIntegration { smtpPassword } }', '{ Users { totalDocs } }', '{ FormSubmissions { totalDocs } }']) {
const out = await gql(sessions.member, query)
expect(out.errors?.length, `${query} → ${JSON.stringify(out)}`).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('S3CRET')
}
})
})
describe("the 2FA package's endpoints accept accounts of the 2FA collection only", () => {
const secretOf = async (email: string) => {
const found = await payload.find({ collection: 'users' as never, showHiddenFields: true, where: { email: { equals: email } } })
return (found.docs[0] as { id: number | string; totpSecret?: null | string })
}
test('an account of another collection cannot set the TOTP secret of the staff account with the same id', async () => {
// SQL adapters number each collection from 1: the first customer and the first staff account share an id.
const customer = (await (await api('/customers/me', sessions.customer)).json()) as { user: { id: number | string } }
const admin = await secretOf('[email protected]')
const ATTACKER = 'KRSXG5CTMVRXEZLU'
const res = await api('/setup-totp', sessions.customer, { body: JSON.stringify({ secret: ATTACKER, token: totp(ATTACKER) }), method: 'POST' })
expect(res.status).toBe(403)
expect(res.headers.getSetCookie().join(';')).not.toContain('payload-totp')
const after = await secretOf('[email protected]')
expect(after.totpSecret).toBe(TOTP_SECRET)
// the case this test is about: the two accounts really share an id (SQL adapters; on MongoDB ids never repeat)
if (numericIds()) {expect(String(customer.user.id)).toBe(String(admin.id))}
// an account of yet another auth collection is refused the same way
const member = await api('/setup-totp', sessions.member, { body: JSON.stringify({ secret: ATTACKER, token: totp(ATTACKER) }), method: 'POST' })
expect(member.status).toBe(403)
})
test('verify, remove and the admin management endpoints refuse it as well', async () => {
for (const p of ['/verify-totp', '/remove-totp', '/admin/remove-user-totp', '/admin/reset-user-totp']) {
const res = await api(p, sessions.customer, { body: JSON.stringify({ token: '000000', userId: '1' }), method: 'POST' })
expect([p, res.status]).toEqual([p, 403])
}
})
test('a staff password without the code cannot reset or remove TOTP', async () => {
const admin = await secretOf('[email protected]')
for (const p of ['/remove-totp', '/admin/remove-user-totp', '/admin/reset-user-totp']) {
const res = await api(p, sessions.passwordOnly, { body: JSON.stringify({ token: totp(TOTP_SECRET), userId: String(admin.id) }), method: 'POST' })
expect([p, res.status]).toEqual([p, 403])
}
expect((await secretOf('[email protected]')).totpSecret).toBe(TOTP_SECRET)
})
})
describe('per-entity opt-out from the second factor', () => {
test("the package's key: custom.totp.disableAccessWrapper.<operation>", async () => {
expect((await api('/open-notes', sessions.passwordOnly)).status).toBe(200) // read opted out
expect((await api('/open-notes', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403) // create not
expect((await api('/open-notes', sessions.anonymous)).status).toBe(403) // its own rule still applies
})
test("ipal-kit's key: custom.ipal.secondFactor", async () => {
expect((await api('/open-tasks', sessions.passwordOnly)).status).toBe(200)
expect((await api('/open-tasks', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
})
})
describe('no exception by name: a later plugin\'s `payload-…` collection is guarded like any other', () => {
test('REST (list, count, by id) and GraphQL refuse a password-only session; a verified one reads it', async () => {
for (const p of ['/payload-vault', '/payload-vault/count', '/globals/late-settings']) {
const res = await api(p, sessions.passwordOnly)
expect([p, res.status]).toEqual([p, 403])
expect(await res.text()).not.toContain('VAULT')
}
const out = await gql(sessions.passwordOnly, '{ PayloadVaults { docs { secret } } }')
expect(out.errors?.length, JSON.stringify(out)).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('VAULT')
const ok = await api('/payload-vault', sessions.verified)
expect(ok.status).toBe(200)
expect(await ok.text()).toContain('VAULT')
})
test("Payload's own collections answer a password-only session nothing either", async () => {
const own = payload.config.collections.map((c) => c.slug).filter((slug) => slug.startsWith('payload-') && slug !== 'payload-vault')
expect(own).toEqual(expect.arrayContaining(['payload-preferences', 'payload-locked-documents', 'payload-migrations']))
const open: string[] = []
for (const slug of own) {
const status = (await api(`/${slug}`, sessions.passwordOnly)).status
if (status === 200) {open.push(`${slug}: ${status}`)}
}
expect(open).toEqual([])
})
})
describe("the job queue keeps Payload's own defaults", () => {
// Payload's `defaultAccess` (3.94.1 fills run, queue and cancel with it when the config is built)
const payloadDefault = (user: unknown) => Boolean(user)
test('without a user: what Payload itself answers; a password-only session is refused; a verified one is not', async () => {
const access = payload.config.jobs.access!
const admin = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0]
const as = (user: unknown) => ({ req: { payload, user } }) as never
for (const op of ['queue', 'cancel', 'run'] as const) {
expect([op, await access[op]!(as(null))]).toEqual([op, payloadDefault(null)])
expect([op, await access[op]!(as({ ...admin, _strategy: 'local-jwt', collection: 'users' }))]).toEqual([op, false])
expect([op, await access[op]!(as({ ...admin, _strategy: 'totp', collection: 'users' }))]).toEqual([op, true])
}
// the Local API with access control on and no user: refused by Payload's own default, with or without the plugin
await expect(payload.jobs.queue({ input: {}, overrideAccess: false, task: 'no-such-task' } as never)).rejects.toThrow(/not allowed/i)
})
})
describe('the code cannot be guessed: verify attempts are limited per account', () => {
const GUESS_SECRET = 'ONSWG4TFORRW6ZDF'
let cookie: string
beforeAll(async () => {
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: GUESS_SECRET } as never })
cookie = (await login('users', '[email protected]')).cookies.join('; ')
})
const verify = (token: string, headers: Record<string, string> = { cookie }) =>
fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token }), headers: { 'content-type': 'application/json', ...headers }, method: 'POST' })
test('five wrong codes are answered, the sixth attempt is refused — also with the right code', async () => {
for (let i = 0; i < 5; i++) {
const res = await verify('000000')
expect(res.status).toBe(200)
expect(((await res.json()) as { ok: boolean }).ok).toBe(false)
}
const sixth = await verify('000000')
expect(sixth.status).toBe(429)
expect(Number(sixth.headers.get('retry-after'))).toBeGreaterThan(0)
const right = await verify(totp(GUESS_SECRET))
expect(right.status).toBe(429)
expect(right.headers.getSetCookie().join(';')).not.toContain('payload-totp')
expect((await fetch(`${server.url}/api/pages`, { headers: { cookie } })).status).toBe(403)
})
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++) {
await verify('000000', {})
await verify('000000', sessions.customer.headers)
}
// another staff account still verifies
const other = await login('users', '[email protected]')
const ok = await verify(totp(TOTP_SECRET), { cookie: other.cookies.join('; ') })
expect(((await ok.json()) as { ok: boolean }).ok).toBe(true)
})
})
// Last: it replaces the running config.
describe('dev hot reload', () => {
test('a freshly built config is guarded again, also what a later plugin added', async () => {
// What Payload's reload() does to the instance: a newly built and sanitized config, no onInit.
const fresh = await makeConfig()
payload.config = fresh
// Before any HTTP request: the Local API meets the new config guarded already.
const passwordOnlyUser = { ...(await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0], _strategy: 'local-jwt', collection: 'users' }
payload.collections = Object.fromEntries(
fresh.collections.map((c) => [c.slug, { config: c, customIDType: payload.collections[c.slug as never]?.customIDType }]),
) as never
payload.globals = { config: fresh.globals }
await expect(payload.find({ collection: 'late-notes' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow()
await expect(payload.find({ collection: 'payload-vault' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow()
await expect(payload.findGlobal({ slug: 'late-settings' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow()
expect((await api('/late-notes', sessions.passwordOnly)).status).toBe(403)
expect((await api('/late-notes', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
expect((await api('/globals/site-integrations', sessions.passwordOnly)).status).toBe(403)
expect((await api('/late-notes', sessions.verified)).status).toBe(200)
})
})
+92
View File
@@ -0,0 +1,92 @@
/**
* The same guarantees with the oldest supported 2FA package, @clocklimited/payload-2fa 3.0.0-beta.1 (installed
* here under the alias `payload-2fa-beta1`). The other HTTP tests run on the version in devDependencies, which is
* the one client sites use.
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { payloadTotp } from 'payload-2fa-beta1'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
import { totp } from './http/totp.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const SECRET = 'JBSWY3DPEHPK3PXP'
const PASSWORD = 'a-long-test-password-1'
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 get = (pathname: string, headers: Record<string, string>) => fetch(`${server.url}/api${pathname}`, { headers })
beforeAll(async () => {
const config = 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('sechttp_b1'),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: { issuer: 'Example', plugin: payloadTotp as never },
}),
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: 'S3CRET' } as never })
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'], totpSecret: SECRET } as never })
await payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
test('beta.1: password only → refused; password and code → allowed (REST and GraphQL)', async () => {
const login = await post('/users/login', { email: '[email protected]', password: PASSWORD })
const cookie = cookiesOf(login).join('; ')
for (const p of ['/globals/site-integrations', '/form-submissions', '/users', '/globals/site-settings']) {
expect([p, (await get(p, { cookie })).status]).toEqual([p, 403])
}
const before = (await (await post('/graphql', { query: '{ SiteIntegration { smtpPassword } }' }, { cookie })).json()) as { errors?: unknown[] }
expect(before.errors?.length).toBeGreaterThan(0)
const verify = await post('/verify-totp', { token: totp(SECRET) }, { cookie })
expect(((await verify.json()) as { ok: boolean }).ok).toBe(true)
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 get('/form-submissions', { cookie: full })).status).toBe(200)
})
test('beta.1: a customers account cannot use the 2FA endpoints or reach staff data', async () => {
const login = (await (await post('/customers/login', { email: '[email protected]', password: PASSWORD })).json()) as { token: string }
const authorization = `JWT ${login.token}`
const ATTACKER = 'KRSXG5CTMVRXEZLU'
expect((await post('/setup-totp', { secret: ATTACKER, token: totp(ATTACKER) }, { authorization })).status).toBe(403)
const admin = await payload.find({ collection: 'users' as never, showHiddenFields: true })
expect((admin.docs[0] as { totpSecret?: string }).totpSecret).toBe(SECRET)
expect((await get('/globals/site-integrations', { authorization })).status).toBe(403)
expect((await get('/form-submissions', { authorization })).status).toBe(403)
})
+79
View File
@@ -0,0 +1,79 @@
/**
* The documented non-interactive paths keep working with 2FA on (real HTTP, see securityHttp.test.ts):
* an API key of a staff account, and the bearer token of GET /api/ipal/doctor.
*/
import type { Payload } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { 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', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const API_KEY = 'b7f0c3a2-5d1e-4f6a-9c8b-0e1d2f3a4b5c'
const DOCTOR_TOKEN = 'doctor-token-0123456789-0123456789-abcdef'
let server: TestServer
let payload: Payload
beforeAll(async () => {
process.env.IPAL_DOCTOR_TOKEN = DOCTOR_TOKEN
const config = buildTestConfig({
collections: [
// The project's own staff collection, with API keys.
{ slug: 'users', auth: { useAPIKey: true }, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase('sechttp_tok'),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: { issuer: 'Example', plugin: payloadTotp },
}),
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
await payload.create({
collection: 'users' as never,
data: { apiKey: API_KEY, email: '[email protected]', enableAPIKey: true, password: 'a-long-test-password-1', roles: ['admin'], totpSecret: 'JBSWY3DPEHPK3PXP' } as never,
})
}, 120_000)
afterAll(async () => {
delete process.env.IPAL_DOCTOR_TOKEN
await server?.close()
await payload?.destroy?.()
})
const get = (pathname: string, authorization?: string) =>
fetch(`${server.url}/api${pathname}`, { headers: authorization ? { authorization } : {} })
test('an API key of an admin account reads Site integrations and form submissions without a TOTP code', async () => {
const key = `users API-Key ${API_KEY}`
expect((await get('/globals/site-integrations', key)).status).toBe(200)
expect((await get('/form-submissions', key)).status).toBe(200)
expect((await get('/users', key)).status).toBe(200)
expect((await get('/globals/site-integrations', 'users API-Key wrong-key')).status).toBe(403)
})
test('GET /api/ipal/doctor answers its bearer token, and nobody else', async () => {
const ok = await get('/ipal/doctor', `Bearer ${DOCTOR_TOKEN}`)
expect(ok.status).toBe(200)
expect(await ok.json()).toMatchObject({ usersWithout2fa: 0 })
expect((await get('/ipal/doctor')).status).toBe(401)
expect((await get('/ipal/doctor', 'Bearer not-the-token-0123456789-0123456789')).status).toBe(401)
})

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