Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 18:46:32 +01:00
Radosław SmolińskiandClaude Opus 5.5 45d52c4690 1.16.5 upgrade notes
CI / check (push) Failing after 5m27s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:50:25 +01:00
Radosław SmolińskiandClaude Opus 5.5 bef3a682b8 1.16.5
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:50:25 +01:00
Radosław SmolińskiandClaude Opus 5.5 f96b5c15d0 Merge claude/2fa-safe-back: the back link of the 2FA screens is checked on the server (twoFactor.safeBack)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:49:47 +01:00
Radosław SmolińskiandClaude Fable 5.2 3eee841dd0 ipal-doctor: the raw 2FA view warning only for a view component
R3-1: the warning fired on any mention of the 2FA package's setup / verify view
in the config, so it stayed after the fix its own text suggests (SafeTotpView
with the path as ipalTotpView, plus the path in admin.dependencies). It now
warns only when the path is a view's Component.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 17:49:06 +01:00
Radosław SmolińskiandClaude Fable 5.2 b2c1dca5da 2FA back link: the stale import-map notice never replaces the screen
R2-1: the notice was rendered instead of the 2FA screen, and its flag is a text
search of the importMap.js on disk — not the map in the build. A false alarm
(map generated in the build with the repository's file in the running image, a
re-exporting map) hid a working code form and locked everyone out. The notice
is now rendered above the screen, the log line says "may be", and the flag goes
to ipal-kit's own provider only.

R2-2: views are compared against copies, so a factory that reuses its view
objects is guarded too; copyViews, changedViewKeys, SAFE_TOTP_VIEW,
totpViewImportKey, findImportMapFile and missingImportMapEntries are exported;
ipal-doctor warns when the config registers the 2FA package's own view; docs
wording and a misplaced comment fixed.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 16:35:16 +01:00
Radosław SmolińskiandClaude Fable 5.2 ad51456eaa 2FA back link: review fixes — views guarded by object, client views, a loud stale import map
SB-1: the 2FA package replaces a view that already stands under its keys, so a
key that existed before the factory ran was wrongly treated as the project's own
and left unguarded (also with a double registration, or ipalKit over its own
output). Views are now compared by object, right after the factory.

SB-2: SafeTotpView renders through Payload's RenderServerComponent: a client
component set as a 2FA view gets only client props plus the checked back.

SB-3: a production build with the previous import map shows an empty 2FA screen.
twoFactor.importMapCheck (on, production only) reads the committed map at start:
an error in the log and a message on the 2FA screens. Docs name the real symptom.

SB-4: enabled: false restores admin.dependencies; wrapTotpViews keeps exportName.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 16:16:39 +01:00
Radosław SmolińskiandClaude Fable 5.2 93e75426ab 2FA screens: the back link is checked on the server (twoFactor.safeBack)
@clocklimited/payload-2fa sends the browser to the `back` query value after a
valid code without checking it (GHSA-rffw-fq79-g3ch upstream, not fixed in the
fork): a prepared link ran script in the panel or left the site.

SafeTotpView now stands in front of the package's setup and verify views and
passes on a checked value: a path on the site's origin inside the admin route,
else the admin root. The package's views stay in the import map through
admin.dependencies, so ipal-kit still never imports the package.

twoFactor.safeBack: false turns it off, a function replaces the rule;
safeAdminBack, wrapTotpViews and SafeTotpView are exported. Projects with 2FA
must regenerate the admin import map.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 15:29:06 +01:00
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
Radosław SmolińskiandClaude Opus 5.5 13b66413f8 1.16.2 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.16.2" section. PROGRAMISTA §6: item 63. Reference site: skills
and the AGENTS.md pointer on 1.16.2; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 00:19:11 +01:00
Radosław SmolińskiandClaude Opus 5.5 5d9bc10cfd 1.16.2
Version bump; the Unreleased section becomes 1.16.2: pnpm.overrides for Payload's
mongoose (8.24.1 → ~8.24.10; GHSA-pcrw-h46h-c93h critical and four more) and
happy-dom (20.x → ^21.0.4; two highs) in the reference site and the starter; new
ipal-doctor rule transitive-min and DoctorContext.installedAll(name). What projects
must update: every MongoDB site adds the two override lines (Postgres/SQLite: the
happy-dom one), reinstalls, rebuilds and redeploys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 00:19:11 +01:00
Radosław SmolińskiandClaude Opus 5.5 1917686b52 Merge claude/inspiring-goldstine-66f9c2: mongoose and happy-dom overrides, doctor rule transitive-min
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 00:18:49 +01:00
Radosław SmolińskiandClaude Fable 5.2 de8362820f Overrides for Payload's mongoose and happy-dom advisories; doctor rule transitive-min
@payloadcms/db-mongodb pins mongoose 8.24.1 (one critical, two high, two moderate
advisories, fixed by 8.24.7) and @lexical/headless 0.50 brings happy-dom 20.x (two
high, fixed by 21.0.4). Payload 3.93.0 fixes neither.

- reference/package.json (and so the starter): pnpm.overrides for mongoose
  (~8.24.10) and happy-dom (^21.0.4); pnpm audit --prod on the reference is clean
- root package.json: the happy-dom override for the plugin's own dev tree
- ipal-doctor: transitive-min reports mongoose 8.x < 8.24.7 (error) and
  happy-dom < 21.0.4 (warning) from the lockfile and prints the override line;
  DoctorContext.installedAll(name)
- AGENT.md §4 item 12, ipal-setup, ipal-upgrade, doctor.md, README, CHANGELOG

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-17 00:01:58 +01:00
Radosław SmolińskiandClaude Opus 5.5 7c034a07ef 1.16.1 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.16.1" section. PROGRAMISTA §6: item 62. Reference site: skills
and the AGENTS.md pointer on 1.16.1; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:49:14 +01:00
Radosław SmolińskiandClaude Opus 5.5 5c9eeaf330 1.16.1
Version bump; the Unreleased section becomes 1.16.1: Next.js 16.4.6 in the plugin,
the reference site and the starter; minimum safe version 16.4.5 because of
GHSA-mfr8-8qww-v76h (16.3.0–16.4.4); ipal-doctor next-min raised. What projects
must update: every site below 16.4.5 runs
`pnpm add [email protected] [email protected]` and redeploys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:49:10 +01:00
Radosław SmolińskiandClaude Opus 5.5 ad6011b66a Merge claude/next-16-4-6: Next.js 16.4.6, minimum safe 16.4.5 (GHSA-mfr8-8qww-v76h)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:49:02 +01:00
Radosław SmolińskiandClaude Opus 5.5 9b03c94979 Next.js 16.4.6; minimum safe version 16.4.5 (GHSA-mfr8-8qww-v76h)
Next.js 16.3.0–16.4.4 is affected by GHSA-mfr8-8qww-v76h (CVE-2026-119790, moderate:
information disclosure across root params when a 'use cache' function is called
through unstable_cache()), first patched in 16.4.5.

- next and eslint-config-next 16.4.6 in the plugin's dev dependencies and the
  reference site (the starter is generated from it); lockfiles refreshed.
- ipal-doctor next-min: error below 16.4.5, naming the advisory; fix
  `pnpm add [email protected] [email protected]`; still silenceable. Tests.
- AGENT.md §4 item 11, ipal-setup, ipal-upgrade, doctor.md: minimum 16.4.5;
  reference skills copy refreshed. CHANGELOG Unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:45:17 +01:00
Radosław SmolińskiandClaude Opus 5.5 ba3d57a77a 1.16.0 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.16.0" section. PROGRAMISTA §6: item 61. Reference site: skills
and the AGENTS.md pointer on 1.16.0; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 17:19:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 7f0c2f9d72 1.16.0
Version bump; the Unreleased section becomes 1.16.0: files on panel forms, checked,
e-mailed to the company and never stored (forms.attachments, File field, streamed
endpoint with the security wall and abort/timeout handling); attachments over SMTP
and Microsoft Graph (upload session, mailbox copy deleted); test e-mail with a
10 MB file; Turnstile reset and BuilderForm honeypot fixes; Graph token cache.
What projects must update: nothing required; to use files — option, File field,
migration on Postgres/SQLite, formClasses keys, proxy body limit, Graph
Mail.ReadWrite or SMTP. Verify on real systems: Graph 10 MB send and cleanup,
Traefik timeout on a slow upload, SMTP size limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 17:18:50 +01:00
Radosław SmolińskiandClaude Opus 5.5 3cde9974d0 Merge claude/form-attachments-9694cb: files on forms, e-mailed and never stored
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 17:13:55 +01:00
Radosław SmolińskiandClaude Fable 5.2 6f006825a4 Form files: an upload aborted while the gates are pending no longer leaves its attempt key registered
Re-review of 1.16.0: beforeFiles could resume after the request was answered and
register the attempt key with nobody left to release it. It now stops after every
await once the request is over; the registration has no await before it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:09:14 +01:00
Radosław SmolińskiandClaude Fable 5.2 7ecfb26eb1 Reference: refreshed skills copy (upload timeouts)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:04:03 +01:00
Radosław SmolińskiandClaude Fable 5.2 e24c918d4b Form files: a dropped, stalled or endless upload is aborted and frees its slot, attempt key and buffers
Security review of 1.16.0 (blocking): a request body that errored mid-file never
resolved, leaking the concurrency slot and the attempt key. Also: idle and request
timeouts (submit.idleTimeoutMs / timeoutMs), ImmutableId preference on every Graph
draft call, the remaining total in the too-large message, files sent to a form
without a File field are refused and logged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:02:10 +01:00
Radosław SmolińskiandClaude Fable 5.2 cd74d7decb Reference: refreshed skills copy and generated types for the file messages
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:52:18 +01:00
Radosław SmolińskiandClaude Fable 5.2 97202ee03e Form files: the visitor is told when the problem is the file — why and what to do; UTF-8 file names
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:51:05 +01:00
Radosław SmolińskiandClaude Fable 5.2 b6f9f34705 Form attachments: tests for project options and the concurrency guard
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:44:41 +01:00
Radosław SmolińskiandClaude Fable 5.2 ea43d94dd2 Reference index: describe the mail sink
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:43:41 +01:00
Radosław SmolińskiandClaude Fable 5.2 fdb6140c09 Form attachments: reference smoke test with a mail sink, Turnstile reset fix, docs
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:42:39 +01:00
Radosław SmolińskiandClaude Fable 5.2 387debc88c WIP: reference site — File field on the quote form, mail sink smoke test
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:34:34 +01:00
Radosław SmolińskiandClaude Fable 5.2 b7fb1b0e31 WIP: form attachments — agent guide, skills, seed template, changelog
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:32:45 +01:00
Radosław SmolińskiandClaude Fable 5.2 344574d6bd WIP: form attachments docs (forms, email, security, storage, deployment, notifications), honeypot value sent
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:30:44 +01:00
Radosław SmolińskiandClaude Fable 5.2 701bb420c1 WIP: form attachments — unit tests, test e-mail with attachment, lint
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:28:22 +01:00
Radosław SmolińskiandClaude Fable 5.2 02b1e96d3d WIP: form attachments tests
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:24:27 +01:00
Radosław SmolińskiandClaude Fable 5.2 6003b3d7d7 WIP: form attachments (e-mail only) — core, endpoint, Graph large upload
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:20:02 +01:00
Radosław SmolińskiandClaude Fable 5.2 0ba0014ed5 Form attachments proposal: Graph upload session recommended (Mail.ReadWrite already granted)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:04:07 +01:00
Radosław SmolińskiandClaude Fable 5.2 62bed415ed Form attachments proposal: e-mail only, no storage (revision 2)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:01:18 +01:00
Radosław SmolińskiandClaude Fable 5.2 d2caf8c2ae Form attachments: design proposal
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 15:55:45 +01:00
Radosław SmolińskiandClaude Opus 5.5 755f510c9f 1.15.5 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.5" section. PROGRAMISTA §6: item 60. Reference site: skills
and the AGENTS.md pointer on 1.15.5; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:35:22 +01:00
Radosław SmolińskiandClaude Opus 5.5 970307f3ab 1.15.5
Version bump; the Unreleased section becomes 1.15.5: required fields with
references are seeded complete; a stricter dry run (missing $form / $page is an
error there too). What projects must update: nothing required; a required reference
cycle now fails clearly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:35:22 +01:00
Radosław Smoliński c7e198fd92 Merge claude/seeder-required-refs: required fields with references are created complete
createSeeder's first pass resolves { $page } / { $form } references to existing
records, so a required layout is created complete; a forward $page is filled in
pass 2 and a record whose required field needs it waits for that page. Required
cycles and never-appearing targets are an error with nothing written; the dry run
reports the same, including a missing $form. Guards, create-only, the edit check
and SEED_ONLY are unchanged. Reported from vanstevpl-web.
2026-11-13 14:31:52 +01:00
Radosław SmolińskiandClaude Opus 5.5 748ef9286f Seeder: required fields with references are created complete (1.15.5)
A page whose required layout holds a { $page } / { $form } reference could not be
created: pass 1 left the whole field out, validation rejected the record, and the
dry run reported a create (vanstevpl-web, 1.15.4).

- pass 1 resolves references to records that exist (or were created earlier in
  the run), so the field is written complete
- a { $page } to a page later in the same call is null in pass 1 and filled in
  pass 2; a record whose required field needs it is retried once that page exists
- required links in a cycle and references to pages or forms that never appear
  are an error with nothing written; unknown page targets are found while
  planning, so the dry run reports them too
- dry run: a missing form is an error (was a placeholder); a form planned earlier
  in the same dry run counts as existing
- real-Payload tests (pl, en, de): the report's careers page, an existing form
  target, optional and required forward links, a cycle, missing page and form,
  create-only second runs, dry-run parity
- CHANGELOG Unreleased, seeding.md, api.md; reference skills refreshed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:29:41 +01:00
Radosław SmolińskiandClaude Opus 5.5 179d5b0d79 1.15.4 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.4" section (repair with SEED_UPDATE, live site with SEED_ONLY,
edited records and global arrays by hand). PROGRAMISTA §6: item 59. Reference site:
skills and the AGENTS.md pointer on 1.15.4; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:39:27 +01:00
Radosław SmolińskiandClaude Opus 5.5 2f00fe3ad6 1.15.4
Version bump; the Unreleased section becomes 1.15.4: seeding whole localized arrays
keeps every language. What projects must update: nothing required; repairing records
an earlier seed wrote needs SEED_UPDATE=1 (locally first; on production with SEED_ONLY
and IPAL_SEED_ALLOW_PROD_UPDATE=1 after a backup), edited records and global arrays
by hand.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:39:26 +01:00
Radosław Smoliński a79740cd44 Merge claude/seeder-localized-arrays: whole localized arrays keep every language
createSeeder / writeLocales: a value seeded per language as a whole (form fields,
nested select options, page layouts, global arrays) keeps the stored row ids in
every locale instead of only the last language surviving; localized: true fields
keep rows per locale. Seed guards, the edit check and SEED_ONLY are unchanged.
Reported from vanstevpl-web.
2026-11-12 15:35:38 +01:00
Radosław SmolińskiandClaude Opus 5.5 00e814e3ca Seeder: whole localized arrays keep every language (1.15.4)
createSeeder / writeLocales: a value written per locale as a whole —
fields: { pl: [...], en: [...], de: [...] }, a page layout, a global array —
returned the picked locale without walking into it, so each locale write made new
shared rows and only the last language survived (vanstevpl-web, 1.15.3).

- localize() localizes the picked value again with the stored rows, so row ids
  are shared across locales (arrays, blocks, nested arrays in blocks, groups)
- writeLocales passes the target's fields: a field that is itself localized
  (localized: true layout) never reuses another locale's row ids
- real-Payload regression test (pl, en, de): form with blocks and nested select
  options, shared and localized page layouts, global array via fillGlobal; a later
  PL save validates
- CHANGELOG Unreleased, seeding.md, api.md; reference skills refreshed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:33:35 +01:00
Radosław SmolińskiandClaude Opus 5.5 4d1de4c66a 1.15.3 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.3" section. PROGRAMISTA §6: item 58. Reference site: skills
and the AGENTS.md pointer on 1.15.3; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 13:03:14 +01:00
Radosław SmolińskiandClaude Opus 5.5 3edf8865ed 1.15.3
Version bump; the Unreleased section becomes 1.15.3: ipal-audit and ipal-doctor no
longer report the panel's bilingual labels (adminText(), { en, pl }) as hardcoded
text; public text is still reported. What projects must update: nothing required;
pnpm ipal:skills for the updated audit scripts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 13:03:14 +01:00
Radosław Smoliński 594b958bb2 Merge claude/audit-admin-labels: the panel's bilingual labels are not hardcoded text
ipal-audit and the doctor's i18n-literals read the syntax tree (polish-literals.mjs,
a plain grep without TypeScript): adminText(), { en, pl } as label, singular, plural,
description, placeholder or group, a rowLabel() fallback and const x: AdminText in a
schema file are accepted. Still reported: every .tsx file, Polish-only labels, other
keys, anything under defaultValue. Reported from the Niezly Dandys project.
2026-11-05 12:59:28 +01:00
Radosław SmolińskiandClaude Opus 5.5 f73465c3bb ipal-audit, ipal-doctor: the panel's bilingual labels are not hardcoded text
"Hardcoded Polish text in code" (i18n-literals) grepped every string, so adminText() and { en, pl }
labels in schema files were reported, though AGENT.md 6.5a asks for them. polish-literals.mjs reads
the syntax tree with the project's TypeScript (a plain grep without it) and spares those forms in
schema files only; every .tsx file, Polish-only labels, other keys and defaultValue still fail.
Reported by Niezly Dandys (1.15.2).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:55:44 +01:00
199 changed files with 16224 additions and 2091 deletions
+12 -9
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,16 +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` and
`graphql-scalars` (the last one even in the latest Payload) — add the three 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).
@@ -161,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.
+566
View File
@@ -8,6 +8,572 @@ 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.6
> **Read before upgrading — this is not a routine patch.** It turns on a new default for every site with 2FA: an
> account that has not set 2FA up can do nothing but set it up, and is **blocked after 72 hours** until an
> administrator reopens it. On Postgres / SQLite it also needs a **migration in the same deploy, or nobody can log
> in**. Work through the list below, and agree the deploy day with the owner.
### Requires project changes (what projects must update)
**Every site with 2FA on. Do all of it in ONE deploy.**
- **Before upgrading a live site:** `pnpm exec ipal-doctor --url <site>` → accounts without 2FA. Each sets 2FA up
now, or is removed. At least one administrator (better two) must have 2FA set up, or nobody can reopen setup
from the panel.
- **Agree the day with the owner:** the 72 hours of every existing account without 2FA start at the deploy,
once. Deploy when those people can act within three days (not before a holiday), or have them set 2FA up first.
- **In the same deploy:** the update, `pnpm payload generate:types`, `pnpm payload generate:importmap` (commit
`importMap.js`; new: `TwoFactorStatusField`, `TwoFactorAlert`), `rm -rf .next`, redeploy. Run
`pnpm exec ipal-doctor` before deploying: it reports a map without the new entries (then the panel has no "Reopen
setup"). Coming from before 1.16.5, the map must also have `SafeTotpView`, or the 2FA screens have no code form.
- **Postgres / SQLite — required, in the same deploy: `pnpm payload migrate:create`, commit, and the migration
applied when the new container starts** (`prodMigrations`, or `pnpm payload migrate && pnpm start` —
[deployment.md §4.3](./deployment.md#43-database-migrations-postgres); not Coolify's Pre-deployment command,
which runs in the old container). The 2FA collection gets the column `totp_setup_from`.
**Without it every login answers 500 — administrators with 2FA included — and nobody can sign in to the
panel.** The log says so at start (`NOBODY CAN LOG IN`), and `ipal-doctor` reports a SQL project whose
migrations do not mention the column. Every project with 2FA on needs it, also with `requireSetup: false`.
MongoDB: nothing.
- **An integration that logs in with a password and has no TOTP** stops working: give it an API key (passes as
before) or exempt it on purpose: `twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`.
- **Own code** calling `payload.find({ …, user, overrideAccess: false })` with a user fetched by id: refused for
every account of the 2FA collection now (before: only accounts with TOTP set up). Use `payload.auth({ headers })`.
- **A reset by an administrator logs that account out everywhere** and needs the administrator's own TOTP code. A
script on an API key needs `twoFactor.resetAccess`. After a suspected compromise change the password too.
- **Options:** `windowHours` is a number (0 or more) or `false`; `exempt` is a plain function returning exactly
`true`, never `async`. A wrong value stops the build and the start with a clear error.
- **After deploy:** read the log line `[ipal] 2FA: N existing account(s) without two-step verification…` and tell
the owner; after 72 hours such an account needs "Reopen setup" from an administrator. Tell the staff: a new account has
72 hours to set 2FA up. `pnpm ipal:skills`.
- **An SVG favicon** has no tab icon on the 2FA screens (use a PNG if that matters).
- **Every administrator is blocked:** security.md "Every administrator is blocked" (a script, or
`{ windowHours: false }` and a redeploy).
- **Not wanted on a site:** `twoFactor.requireSetup: false` (the previous behaviour), or
`{ windowHours: false }` to keep the lock without the time limit. Sites with `twoFactor: false` are not affected.
### Changed
- **An account without two-step verification can only set it up** (`twoFactor.requireSetup`, on by default with
2FA). Until now the panel redirected such an account to the setup screen, but over the API (REST, GraphQL) its
password alone opened everything its role allowed. Now every collection, global and plugin endpoint refuses it
until TOTP is set up; the setup screen and `POST /api/setup-totp` are all it reaches.
- **A setup window of 72 hours**, counted from the account's creation or from a reset by an administrator. After
it the account is blocked — setup is refused too — until an administrator reopens it. This limits how long an
account that never set 2FA up can be taken over by someone who learned its password.
- **Accounts that already exist** get their 72 hours from the **first start after the upgrade** (not from their
creation date), so nobody is blocked at the moment of the upgrade. The server log names how many there are.
That moment is written on each account once: later restarts, redeploys and further instances do not move it,
nor does editing the account.
- **A reset by an administrator ends the account's sessions**, and by default needs a session that entered its
own TOTP code (not an API key, not an exempt account).
- **`/api/ipal/admin-icon` answers with the favicon itself when it is a bitmap** (PNG, JPEG, GIF, WebP, ICO,
AVIF — recognised by its bytes) instead of a redirect, so the tab icon also loads on the 2FA screens. An SVG
favicon is never answered from there (an SVG can carry script): it keeps the redirect to the media file.
`adminMeta.serveIcon: false` = always the redirect. `buildUploadSecurityHeaders()` now also returns a rule for
the icon path (`adminIcon: false` leaves it out).
### Added
- On every account in the panel: **Two-step verification** (sidebar) — set up / open until a date / blocked — and
for administrators "Reset two-step verification" (a lost phone) and "Reopen setup" (a blocked account).
`POST /api/ipal/two-factor/reset` `{ userId }` does the same.
- A dashboard notice for administrators: accounts without two-step verification, and how many are blocked.
- A notice on the setup screen: until when setup has to be done, or that the time has passed. All texts in
English and Polish.
- Options: `twoFactor.requireSetup: false | { windowHours, exempt, dashboardNotice, statusField, setupNotice }`,
`twoFactor.resetAccess`, `whiteLabel.inlineImages`, `adminMeta.serveIcon`. Exports: `twoFactorSetupState`,
`twoFactorSetupDeadline`, `buildSetupFields`, `stampSetupFrom`, `backfillSetupFrom`,
`buildTwoFactorResetEndpoint`, `countAccountsWithoutTotp`, `resolveRequireSetup`, `strictExempt`,
`SETUP_FROM_FIELD`, `TWO_FACTOR_RESET_PATH`, `DEFAULT_SETUP_WINDOW_HOURS`, `fetchPublicImage`,
`publicImageDataUri`, `rasterImageType`, `siteOrigin`, `PUBLIC_IMAGE_MAX_BYTES`, `UPLOAD_SECURITY_HEADERS`; admin components
`TwoFactorStatusField`, `TwoFactorResetButton`, `TwoFactorAlert`.
- `requireSetup.exempt` is strict: only an answer of exactly `true` exempts. An `async` function, and a
`windowHours` that is not a number or `false`, stop the site at start with a clear error.
- The date field `totpSetupFrom` is on the 2FA collection whenever 2FA is on, so switching `requireSetup` or
`guard` never changes the schema (and never restarts anyone's window).
- The panel's tab icon and logo load on the verify and setup screens: `GET /api/ipal/admin-icon` answers with the
image itself when it is a bitmap (no redirect to the media file), and the logo components give a session that still owes its code
the picture as an anonymous visitor would get it. No change to who can read `media`.
- ipal-doctor: a SQL project without a migration for `totp_setup_from` (error), an import map without the two
new admin components (error).
- ipal-doctor: the `2fa` rule says how many accounts without 2FA are blocked (`usersSetupClosed` in the deep
status), warns when `requireSetup` is switched off and notes a missing setup window.
### Known limitations
- **Inside the window** someone who knows the password of an account without 2FA can still set it up with their own
authenticator; the owner is then refused ("already set") and has to ask an administrator. Set 2FA up at once.
- A session without 2FA keeps what Payload gives any session about itself: `/api/access`, token refresh, logout, its own
panel preferences.
- **An exempt account** works on its password alone, with everything its role allows: give it the lowest role.
- A second staff collection (`access.staffCollections`) is outside 2FA and outside this mode, as before. With
`twoFactor.guard: false` the mode is off and the reset endpoint does not exist.
- With `auth.useSessions: false` a reset has no sessions to end: tokens live until they expire. The 2FA package's own
remove / reset endpoints do not end sessions.
- The `ipal-doctor` migration check is a text search in `src/migrations` and `migrations`.
- A site that does not use `buildUploadSecurityHeaders()` still serves a scripted SVG from its media URL as before.
- **Not run for this release:** a generated migration, `prodMigrations` and a real Coolify deploy (the missing and the
added column were tested on Postgres 17 and SQLite); an upgrade of a real site; two containers; media on R2 / S3;
`useSessions: false`; the reset by an API-key admin over HTTP; payload-2fa beta.1 and the Polish notices in a
browser; Firefox / WebKit; a Docker image; a Next `basePath`; Payload below 3.94.1.
## 1.16.5
### Security
- **The 2FA setup and verify screens no longer follow an unchecked `back` link.** `@clocklimited/payload-2fa`
(beta.1 to beta.7) sends the browser to the `back` query value once the code is accepted, without checking it.
A panel user who had typed the password, opened a prepared link to `/admin/verify-totp` or `/admin/setup-totp`
and then entered the code could be sent to another site, or have script run in the panel under their freshly
verified session. The panel's CSP does not stop this. **Affects every site with 2FA on, in every earlier
version.** It needs the user to open such a link between the password and the code; a logged-out or a fully
logged-in user is not affected. The original package fixed it in `payload-totp` 3.0.5 (GHSA-rffw-fq79-g3ch);
the fork has not.
Now ipal-kit checks `back` on the server before the package's screen gets it: only a path on the site's own
origin, inside the admin route, is kept; anything else leads to the admin root
([security.md](./security.md) "The `back` link of the 2FA screens"). The 2FA package itself is unchanged.
### Added
- **`twoFactor.safeBack`** — on by default; `false` turns the check off, a function
`(back, { adminRoute, origin }) => string` replaces the rule.
- **`safeAdminBack`**, **`wrapTotpViews`** (`@intecion/ipal-kit`) and **`SafeTotpView`**
(`@intecion/ipal-kit/admin`) are exported for projects that register the 2FA views themselves.
- **ipal-doctor**: the import-map rule also expects `@intecion/ipal-kit/admin#SafeTotpView` when the installed
plugin has it and the config does not set `safeBack: false`.
- **A stale import map is reported** (`twoFactor.importMapCheck`, on by default, `false` turns it off): in
production the plugin searches the `importMap.js` on disk at start; when the entry above is not found it logs
an error and puts a notice above the 2FA screens. The notice never replaces the screen: the file on disk is
not always the map the build used (a Dockerfile with a separate runner stage, a re-exporting map file), and
then the notice is wrong and sign-in still works — turn the check off for such a project.
- **More building blocks exported** for a project that wraps the 2FA views itself: `copyViews`,
`changedViewKeys`, `SAFE_TOTP_VIEW`, `totpViewImportKey`, `findImportMapFile`, `missingImportMapEntries`.
- **ipal-doctor** warns when the config uses the 2FA package's own setup / verify view as a view's `Component`
(such a view is outside the check).
- **A project's own 2FA screen set through the wrapped factory** (a server or a client component) is rendered
behind the check and gets the checked `back`.
### Requires project changes
- **Every site with 2FA: upgrade, `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`,
redeploy — all in ONE deploy. Run `pnpm exec ipal-doctor` before deploying.** The plugin's view now stands in front of the package's two screens and
needs its import-map entry (`@intecion/ipal-kit/admin#SafeTotpView`). **If you skip this, the build still
passes and the site starts, but the 2FA setup and verify screens have no code form (HTTP 200), so nobody can
sign in to the panel.** There is no error page. What tells you: `pnpm exec ipal-doctor` before the deploy
(`import map lacks …SafeTotpView`); the line `[ipal] The admin import map may be out of date` in the log at
every start; and, where the form should be, the notice "Two-step verification may not be available". No
option, env, schema or migration. `pnpm ipal:skills` afterwards.
- **A project with its own 2FA screens or view registrations:** security.md "Your own 2FA screen".
- **Check after deploy:** log in with the password only, open
`/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F`, enter the code → you land on `/admin`. A normal login
still returns to the page you came from.
### Known limitations
- After the code, the screen always goes somewhere inside the panel. A `back` that pointed at a page of the
public site (not used by the plugin or the package) now leads to the admin root; pass your own rule if a
project relied on that.
- An absolute `back` on the site's own origin is kept only when the Payload config has `serverURL`; without it
only relative values are (the plugin and the package only ever produce relative ones).
- A missing `back` used to mean "go back in browser history"; it now means the admin root.
- `back=/admin/logout` is inside the panel and is followed: the user is logged out after the code.
- A client-side 2FA screen of your own that reads `useSearchParams()` gets the raw value; use the `back` prop.
- The stale import map check is a text search of the file on disk: it can warn although everything works, and
its notice text changes only with an own `twoFactor.provider`. The `ipal-doctor` warning about a raw view is a
text search too and misses unusual spellings.
- **Not run for this release:** the browser checks on Postgres, in Firefox or WebKit, with a Next `basePath` or in a
real Docker image with a runner stage; payload-2fa beta.2 to beta.6; Payload 3.90 to 3.93. They ran in Chromium on
MongoDB with beta.7 (production build) and, on an earlier commit of the same change, beta.1 (`next dev`).
## 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
- **`mongoose` and `happy-dom` overrides for Payload's own dependencies.** `@payloadcms/db-mongodb` pins `mongoose`
8.24.1 exactly (still so in Payload 3.93.0). 8.x below 8.24.7 has five advisories published 2026-11-10:
[GHSA-pcrw-h46h-c93h](https://github.com/advisories/GHSA-pcrw-h46h-c93h) (critical, `sanitizeFilter` not applied on
`countDocuments`; fixed in 8.24.3), [GHSA-gg4r-jv3p-qx3c](https://github.com/advisories/GHSA-gg4r-jv3p-qx3c) and
[GHSA-8332-j7wj-wjw4](https://github.com/advisories/GHSA-8332-j7wj-wjw4) (high),
[GHSA-wr5m-5jph-8m96](https://github.com/advisories/GHSA-wr5m-5jph-8m96) and
[GHSA-6972-9mcm-vhwj](https://github.com/advisories/GHSA-6972-9mcm-vhwj) (moderate) — all fixed in 8.24.7.
`@payloadcms/richtext-lexical` → `@lexical/headless` 0.50 brings `happy-dom` 20.x, which has
[GHSA-c8p4-j97h-3vg8](https://github.com/advisories/GHSA-c8p4-j97h-3vg8) (high, fixed in 21.0.0) and
[GHSA-834v-8h66-3h79](https://github.com/advisories/GHSA-834v-8h66-3h79) (high, fixed in 21.0.4). The plugin has no
part in either; only the project's lockfile can lift them. The reference site and the project starter now carry
`"mongoose@>=8 <8.24.7": "~8.24.10"` and `"happy-dom@<21.0.4": "^21.0.4"` in `pnpm.overrides`; with them
`pnpm audit --prod` on the reference site reports no known vulnerabilities, and its seed, production build, smoke
tests and doctor pass. The plugin forces neither override on a project.
### Added
- **ipal-doctor `transitive-min`** (group `versions`): reports a `mongoose` 8.x below 8.24.7 (error) and a `happy-dom`
below 21.0.4 (warning) anywhere in the dependency tree, read from `pnpm-lock.yaml`, and prints the exact
`pnpm.overrides` line. Silence it in `ipal-doctor.json` like any rule
(`"transitive-min": { "off": true, "reason": "…" }`). `DoctorContext.installedAll(name)` is the building block for
your own rules on transitive packages.
### Changed
- AGENT.md §4 item 12, the `ipal-setup` and `ipal-upgrade` skills, doctor.md and the README list five overrides.
### What projects must update
- **Every MongoDB site** (`@payloadcms/db-mongodb`): add the two lines to `pnpm.overrides` in `package.json`, next to
the existing `dompurify` / `graphql-scalars` / `undici` entries:
```json
"happy-dom@<21.0.4": "^21.0.4",
"mongoose@>=8 <8.24.7": "~8.24.10"
```
then `pnpm install`, `pnpm build`, commit `package.json` and `pnpm-lock.yaml`, redeploy on Coolify. No data change,
no migration, no import map change. The selectors only touch the vulnerable versions: a mongoose 9 or a mongoose
8.24.7 and later is left as it is.
- **Postgres / SQLite sites:** only the `happy-dom` line (they have no mongoose).
- **Verify:** `pnpm why mongoose happy-dom` → mongoose 8.24.10 (MongoDB sites), 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.
- `pnpm ipal:skills` for the updated `ipal-setup` / `ipal-upgrade` skills.
## 1.16.1
### Security
- **Next.js 16.4.6; the minimum safe version is now 16.4.5.** Next.js 16.3.0–16.4.4 is affected by
[GHSA-mfr8-8qww-v76h](https://github.com/advisories/GHSA-mfr8-8qww-v76h) (CVE-2026-119790, moderate): information
disclosure across root params when a `'use cache'` function is called through `unstable_cache()`. Fixed in 16.4.5.
This is the advisory behind the `pnpm dev` warning "Next.js 16.4.3 is affected by a known security vulnerability".
The plugin's dev dependencies (`next`, `eslint-config-next`), the reference site and the project starter move to
16.4.6. The Next.js 15 lines Payload 3.90 accepts are not affected by this advisory but still carry older critical
ones, so 16.4.x stays the only safe line. The plugin's peer range is unchanged (`next >=15`).
### Changed
- **ipal-doctor `next-min`** now reports `next` below 16.4.5 as an error, naming GHSA-mfr8-8qww-v76h (below 16.4.1 it
still names the RCE and DoS advisories). The fix it prints: `pnpm add next@16.4.6 eslint-config-next@16.4.6`. It can
be silenced in `ipal-doctor.json` as before (`"next-min": { "off": true, "reason": "…" }`).
- AGENT.md §4 item 11, the `ipal-setup` and `ipal-upgrade` skills and doctor.md state 16.4.5 as the minimum.
### What projects must update
- **Every client site below Next.js 16.4.5:** `pnpm add next@16.4.6 eslint-config-next@16.4.6`, `rm -rf .next`,
`pnpm build`, commit the lockfile and redeploy on Coolify. `pnpm ls next` → 16.4.6; `pnpm exec ipal-doctor` → no
`next-min` finding; `pnpm dev` prints no security warning. No plugin option, migration or import map change.
- `pnpm ipal:skills` brings the updated `ipal-setup` / `ipal-upgrade` skills.
## 1.16.0
### Added
- **Files on forms, sent by e-mail and never stored** (`forms: { attachments: true }`, [forms.md](./forms.md) "Files").
A new **File** field in the form builder: label and help text per language, required, allowed file types,
maximum size and number of files, "Show only when". A file a visitor attaches is checked, attached to the
company notification e-mail and dropped. There is no upload collection, bucket, disk write or download route;
the submission keeps the file's name, type and size and whether the mail server took the message.
- **Checks, in order, before a file is accepted:** same origin, rate limit, declared size, a concurrency guard,
honeypot, Turnstile, field validation and GDPR consent, then per file: count, name (double and refused
extensions), size while reading, content signature, container and macro checks. An upload that breaks off,
stalls (`submit.idleTimeoutMs`, 30 s) or runs too long (`submit.timeoutMs`, 5 minutes) is given up and frees
everything it held. Programs, scripts,
macro-enabled Office files, archives, HTML and SVG are refused unless the project allows the extension
(`allowRisky`). **No antivirus is built in** — `attachments.scan` is the hook for one.
- **E-mail:** the file goes to every e-mail of the form whose recipients are fixed addresses from the panel; an
e-mail addressed with a placeholder (the confirmation to the visitor) never carries it. `{{field}}`, `{{*}}` and
`{{*:table}}` show the file name.
- **The visitor is told when the problem is the file:** too large (with the limit), a format the field does not
take (with the formats), a refused file (a program, an archive, macros, content that does not match), too many
files, or a file that could not be e-mailed. Each message names the file, says what to do, shows at the File
field, and on an optional field adds "You can also send the form without the file." What the visitor typed
stays in the form. A failure that is not about the file keeps its own message.
- **A failed send is visible:** the visitor sees "We could not send the file …" and can retry, staff get the
notification without the file, the submission is marked **File delivery: Not sent**. A repeated request
(double click, a resend) sends nothing twice.
- Browser: `RenderForm` / `BuilderForm` render a native file input with help text, the list of picked files and
a "Remove" button; `useBuilderForm` gains `getFileProps`, `getFiles`, `removeFile`, `helpId`,
`getHoneypotProps`; new `classNames` keys `file`, `help`, `fileList`, `fileItem`, `fileRemove`.
- New texts in Form messages → **Files** (`fileTooLarge`, `fileType`, `fileRefused`, `fileCount`, `fileNotSent`,
`fileOptional`, `fileRemove`), English and Polish defaults.
- New exports: `buildFileBlock`, `fileBlock`, `FORM_FILE_TYPES`, `RISKY_FILE_EXTENSIONS`, `formatFileSize`,
`mailAttachmentLimit` (root); `fileFieldRules`, `fileFieldError`, `formatFileSize` (`/client`);
`splitFormFiles` (`/server`); `submitForm({ files, attemptKey })`; result codes `kind: 'file_too_large' |
'file_type' | 'file_refused' | 'file_count'` and `reason: 'delivery'`.
- **Attachments over both e-mail transports** ([email.md](./email.md) "Attachments"). SMTP passes them through.
Microsoft Graph sends attachments under 3 MB in the one `sendMail` call; larger ones go through a draft and an
upload session, and the copy the mailbox keeps is deleted afterwards. That path needs the `Mail.ReadWrite`
application permission (limit it to the forms mailbox — steps in email.md). Without the permission the message
goes over SMTP when the panel has SMTP settings; otherwise the form's file limit drops to about 2.8 MB.
`mailAdapter({ graph: { largeAttachments: false } })` turns the large path off.
- **Test e-mail with a 10 MB file:** a checkbox next to "Send test e-mail" (endpoint body `attachmentMB`) — shows
whether the mail server takes a file of that size.
### Fixed
- **A form can be sent again after the server refused it.** After a refused submission (a field error from the
server, a failed e-mail) `useTurnstile().reset()` cleared the token but never asked the widget for a new one, so
with Turnstile on, the next click on Send answered "The form could not be sent" without sending anything.
`reset()` now makes the widget issue a new token (`Turnstile` takes a `resetSignal` prop for your own wiring).
No project change.
- **The honeypot of `BuilderForm` / `RenderForm` now reaches the server.** The hidden field was rendered, but its
value was not part of what the form sent, so a bot that filled it was not dropped. It is now sent with the
submission (`createSubmitAction` checks and strips it, as before). A hand-written action that calls `submitForm`
directly must strip `HONEYPOT_FIELD` first, as the example in forms.md always did — otherwise a filled honeypot
is answered with "unknown field" instead of the fake success.
### Changed
- The Microsoft Graph access token is cached in the process until a minute before it expires (it was fetched on
every send).
### What projects must update
- **Nothing is required; existing forms need nothing.** Without `forms.attachments` the forms config, collections,
routes and e-mails are unchanged, and a form without a File field behaves as before even with the option on.
`pnpm ipal:skills` brings the updated `ipal-form` / `ipal-reference` skills.
- **Import map:** no new admin component — `pnpm payload generate:importmap` changes nothing (running it is harmless).
- To use files on forms: set `forms: { attachments: true }`, add a **File** field to the form (panel or seed), keep
one e-mail with a fixed recipient on that form, run `pnpm generate:types`. **Postgres / SQLite:**
`pnpm payload migrate:create` (the File block tables, three columns and one array table on submissions, the new
Form messages columns — all additive). MongoDB: no migration.
- Add the classes `file`, `help`, `fileList`, `fileItem`, `fileRemove` to `src/components/forms/formClasses.ts`
(template in the `ipal-form` skill) and fill Form messages → Files for languages other than English and Polish.
- **Proxy body limit** ([deployment.md](./deployment.md) "Form files"): the browser posts up to `maxTotalMB`
(10 MB) plus the answers to `/api/ipal/forms/submit`. Coolify's Traefik and Caddy have no body limit by default; an
nginx in front needs `client_max_body_size 12m;`; Cloudflare (proxied) allows 100 MB. Keep `/api` out of the i18n
proxy matcher (the default one does).
- **Mail transport for files:** with Microsoft Graph, grant `Mail.ReadWrite` (application permission) limited to the
forms mailbox with an application access policy ([email.md](./email.md)), **or** fill SMTP settings in Site
integrations (files of 3 MB and more then go over SMTP), **or** accept a limit of about 2.8 MB per form. With SMTP
only, nothing to grant — the mail server's own size limit applies. Send the test e-mail with the 10 MB file once
per site.
### Verify on your real systems
The plugin's tests use a mock of Microsoft Graph and a local mail sink; check these once on the real setup:
- [ ] **Graph, 10 MB file:** a form submission with a 10 MB file arrives with the attachment; the sender mailbox keeps
**no draft and no copy in Sent Items** a minute later, and no draft after a failed send either. Checklist:
[email.md](./email.md) "Verify on the real tenant".
- [ ] **Traefik timeout on a slow upload:** a 10 MB upload over a throttled connection (browser dev tools, "Slow 4G")
finishes; if it is cut, raise the entry point's `respondingTimeouts.readTimeout`.
- [ ] **SMTP size limit:** the test e-mail with the 10 MB file is accepted by the SMTP server (many limit a message to
10–25 MB, and base64 adds a third); if not, lower `maxSizeMB` / `maxTotalMB` or use Graph.
## 1.15.5
### Fixed
- **Seeding a required field with references** (`createSeeder`, `upsertBySlug` / `upsertBy`): a page whose required
`layout` holds a `{ $page }` or `{ $form }` reference can be created. The first pass used to leave the whole field out,
so validation rejected the record ("The following field is invalid: … > Layout") while the dry run reported a create.
Now references to records that exist are resolved in the first pass, so the field is written complete. A link to a
page created later in the same call is filled in the second pass, and a record whose required field needs that page
waits until it exists. Required links in a cycle, and links to a page or form that never appears, are an error with
nothing written. The dry run now reports the same outcome, including a missing form. Seed scripts need no change.
### Changed
- **A stricter dry run:** `SEED_DRY_RUN=1` with a `{ $form }` to a form that neither exists nor is seeded earlier in the
same run is now an error, as the real run would be (before, the dry run printed a placeholder and reported a create).
The same holds for a `{ $page }` that never appears.
### What projects must update
- Nothing is required: seed scripts need no change.
- A seed with a required reference cycle (two new pages whose required fields link to each other) now stops with a
clear error naming the pages, and nothing is written for them; make one of the links optional or seed one page
first. Before, such a run could look successful in the dry run and fail on validation in the real one.
- A dry run that now reports a missing form or page: seed that record first (or create it in the panel), then run again.
## 1.15.4
### Fixed
- **Seeding whole localized arrays** (`createSeeder`, `writeLocales`): a value written per language as a whole —
`fields: { pl: [...], en: [...], de: [...] }`, a page `layout`, a global array — now keeps the stored row ids in every
language. Before, each locale write made new shared rows and only the last language survived (form fields, nested
select options, layouts, global arrays); an editor's later save could then fail validation. Fields that are
themselves `localized: true` (a localized layout) keep rows per language, as before. Seed scripts need no change;
repairing records an earlier seed already wrote: "What projects must update".
### What projects must update
- Nothing is required: seed scripts need no change.
- A project that seeded whole localized arrays (form fields with options, a page `layout`, a global array written as
`{ pl: [...], en: [...] }`) and lost languages: a plain re-run skips existing records (create-only), so rewrite them
with `SEED_UPDATE=1` — **locally first**, then check every language in the panel. On a live site only for the named
records: `SEED_ONLY="forms:<title>,pages:<slug>" SEED_UPDATE=1 IPAL_SEED_ALLOW_PROD_UPDATE=1`, `SEED_DRY_RUN=1` first,
after a backup (Coolify). Records an editor changed since seeding are skipped — fix those in the panel. A global
array: `fillGlobal` fills empty fields only, so clear the field in the panel before the run, or fix it by hand.
## 1.15.3
### Fixed
- **ipal-audit and ipal-doctor no longer report the panel's own bilingual labels as hardcoded text.** "Hardcoded Polish
text in code" (`i18n-literals` in the doctor) flagged `adminText('Title', 'Tytuł')` and `{ en: 'Title', pl: 'Tytuł' }`,
the labels AGENT.md §6.5a asks for. The check now reads the syntax tree (`polish-literals.mjs`, with the project's
TypeScript; a plain grep without it). In a schema file — a `.ts` file under `collections/`, `globals/`, `fields/` or
`blocks/`, or one importing Payload's schema types — it accepts `adminText()`, `{ en, pl }` as `label`, `singular`,
`plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback and a `const x: AdminText`, also over several
lines. Still reported: every `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`.
### What projects must update
- Nothing is required.
- Run `pnpm ipal:skills` after upgrading, so the updated audit scripts reach the project: the **ipal-audit** skill runs
the project's own copy in `.agents/skills/ipal-audit/scripts` (`audit.sh`, `polish-literals.mjs`); `ipal-doctor` already
uses the plugin's.
## 1.15.2
### Fixed
+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: the account has set TOTP up and has entered the code in this session
([security.md](./security.md) → "What the second factor covers", "Setup required");
3. it holds at least the role `minimum` — **or** its collection has no `roles` field at all. Then every account
of that staff collection passes, as in Payload's default (without roles all accounts are equal).
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`
+79 -26
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`, `SafeTotpView`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading; a login with the password only gets `403` from `/api/globals/site-integrations` and `/api/form-submissions` — security.md "What the second factor covers"); own endpoints: `secondFactorPassed(req)` / `userMeetsRole(req, role)`; **an account without 2FA can only set it up** (`twoFactor.requireSetup`, default: nothing else answers, 72 h from creation or an admin's reset, then blocked until an admin chooses "Reopen setup" on the account) — so set 2FA up right after creating an account; `ipal-doctor --url` must report 0 accounts without 2FA; Postgres/SQLite: migration for `totpSetupFrom`; `IPAL_IP_HEADER` in production | security.md, forms.md | A |
| 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging with `IPAL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A |
| 15 | System pages | Site settings → System pages: homepage, 404, privacy policy, cookies; legal links in the footer by role (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P |
| 16 | **Nothing hardcoded** | every text, link, image, file, company data from the panel; domains and keys from `.env` (§2) | — | A, P |
@@ -220,6 +224,7 @@ Do not make the provider or the widget conditional in code — always wire them.
| Instead of the plugin | Why not | Use |
|---|---|---|
| your own form with fields in JSX, `react-hook-form`, `formik`, your own form renderer | the client cannot change the fields; no Turnstile, rate limit, GDPR consent; a copy of the engine passes addresses from the Emails tab into HTML | the builder in the panel + `<RenderForm>` (look: `formClasses`, unusual cases: `useBuilderForm`) |
| a file input wired by hand, your own upload route, form files saved to Media / R2 / disk | candidate and customer documents end up public or kept forever; no type, size or macro checks; the gates are skipped | `forms: { attachments: true }` + the **File** field — the file is e-mailed to the company and never stored (forms.md "Files") |
| your own `api/contact` / `api/send` / `api/form` route, `nodemailer` / `resend` / `@sendgrid` in the project | bypasses the `submitForm` validation and gates, a second mail transport | the `sendForm` server action → `submitForm`, mails from Forms → Emails via `mailAdapter()` |
| reCAPTCHA, hCaptcha, your own captcha | a second mechanism, no status in the panel | Turnstile from the plugin |
| a hand-written `<script type="application/ld+json">` | no escaping, drifts from the panel | `JsonLdGraph` |
@@ -504,32 +509,52 @@ No abbreviations (`HeroSection`, not `HeroSec`). Do not create `lib/pages.ts`,
9. **RSC by default.** `'use client'` only for state/interaction, in a separate file;
the section stays a server component and passes data to it. Secrets: `import 'server-only'`.
10. **Blocks do not import `lib/*`** (cycle). Server-side data → `enhanceProps`.
11. **Next.js 16.4.1 or later** (minimum safe version). 16.0.0–16.4.0 have unauthenticated RCE and DoS
advisories (GHSA-2464-fhr4-w9xw, GHSA-673q-mjm6-r5xr, GHSA-p3m5-59mp-jv5r); Payload supports no patched
15.x line. Pin `next` and `eslint-config-next` to the same 16.4.x (≥ 16.4.1) and make sure `sharp` resolves to
0.35.5 or later (`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.1, sharp ≥ 0.35.5; `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
11. **Next.js 16.4.5 or later** (minimum safe version; the plugin, the reference site and the starter use 16.4.6).
16.0.0–16.4.0 have unauthenticated RCE and DoS advisories (GHSA-2464-fhr4-w9xw, GHSA-673q-mjm6-r5xr,
GHSA-p3m5-59mp-jv5r); 16.3.0–16.4.4 have GHSA-mfr8-8qww-v76h (information disclosure across root params when a
`'use cache'` function is called through `unstable_cache()`, moderate; fixed in 16.4.5). Payload supports no
patched 15.x line. Pin `next` and `eslint-config-next` to the same 16.4.x (≥ 16.4.5):
`pnpm add [email protected] [email protected]`, and make sure `sharp` resolves to 0.35.5 or later
(`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 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 three packages are pinned exactly 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` 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"
```
`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` → only the fixed versions; 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.
---
@@ -555,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).
@@ -748,7 +792,8 @@ empty fields, without guessing, without numbered slots. You design the schema fo
(`ctaUrl` → "Cta Url"). Label 1–3 words, ≤ 30 characters.
- Texts are `{ en: '…', pl: '…' }` (one key per admin language of the project):
`label`, `admin.description`, option `label`, tab `label`, `labels.singular/plural`,
`admin.group`. Type: `AdminText` from `@intecion/ipal-kit`.
`admin.group`. Type: `AdminText` from `@intecion/ipal-kit`; shorthand `adminText('Title', 'Tytuł')` from
`@intecion/ipal-kit/blocks`. In a schema file `ipal-audit` accepts both; the same words in a component are an error.
- `admin.description` only when the label is not enough — one sentence ≤ 120 characters:
what it does / where it shows, with a format example (`'Section id for #links, e.g. "pricing".'`),
never how the code works (no component, function, env-var or package names).
@@ -1014,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**
@@ -1035,9 +1080,10 @@ project → **plugin gap**, not a copy.
| Unusual form markup | `BuilderForm renderField` / `useBuilderForm` (`/client`) | forms.md |
| A field filled in by the page (product variant, category) | `RenderForm values` / `prepareBuilderForm` + `BuilderForm values` | forms.md |
| Sending | `createSubmitAction({ getCachedPayload, headers })` (`/server`) | forms.md |
| A file on a form (CV, specification) | `forms: { attachments: true }` + a **File** field in the panel; the file is e-mailed to the company and **never stored** (no Media, no bucket, no download). Options `FormAttachmentsOption` (`maxSizeMB`, `maxTotalMB`, `maxFiles`, `fileTypes`: `FormFileType` / `FormFileDetect`, `allowRisky`, `scan`: `FormFileScanInput` → `FormFileScanResult`, `strictPdf`, `notice`, `maxConcurrent`, `path`, `submit`: `FormSubmitEndpointOptions`); block `buildFileBlock` / `fileBlock`; types `FORM_FILE_TYPES`, refused `RISKY_FILE_EXTENSIONS`; own markup `getFileProps` / `getFiles` / `removeFile`, `fileFieldRules`, `fileFieldError`, `formatFileSize`, `BuilderFileLimits`, `BuilderFile`; own transfer `submitForm({ files })` + `splitFormFiles`; transport ceiling `mailAttachmentLimit` | forms.md "Files", email.md "Attachments" |
| Message texts and step button texts | Form messages → `getFormTexts(locale)` | notifications.md |
| A form in the database | seed `ipal-form/resources/seed-form.template.ts` | forms.md, seeding.md |
| Antispam / limit / IP | honeypot in `BuilderForm`, Turnstile from `SiteProviders` (`createSubmitAction({ turnstileHostnames })` pins the domain), `clientIp`, `setRateLimitStore`, `setUnknownIpFactor` | forms.md, turnstile.md |
| Antispam / limit / IP | honeypot in `BuilderForm` (`getHoneypotProps` on `useBuilderForm`), Turnstile from `SiteProviders` (`createSubmitAction({ turnstileHostnames })` pins the domain), `clientIp`, `setRateLimitStore`, `setUnknownIpFactor` | forms.md, turnstile.md |
| GTM event after sending | `buildFormAnalyticsFields` (panel) — `RenderForm` sends it itself | forms.md |
| A form outside the builder (e.g. filters) | `useForm` + `buildValidator`, `required`, `email`… | forms.md |
@@ -1106,7 +1152,8 @@ 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 |
| Staff features without `access` (no roles field): every logged-in account passes (`userMeetsRole`) | add `access` (roles decide) | `globalOverrides`, `forms.formSubmissionOverrides`, `consentLog.collectionOverrides`, `stats.collectionOverrides` |
| 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 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 })` |
@@ -1118,6 +1165,12 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Injected `users`: admin manages everyone, others only themselves | — | `access.authAccess` (your keys win); your own `users` collection wins whole |
| First registered account = admin | `access.firstUserAdmin: false` | `buildRolesField(defaultRole, { firstUserAdmin })` |
| 2FA on the panel's login collection, mismatch = startup error; redirect to the 2FA screens by `TotpRedirectProvider` | `twoFactor: false` (discouraged) | `twoFactor.collectionSlug`, `allowCollectionMismatch: true`, `twoFactor.provider` (own component, or `false` for the package's) |
| 2FA setup required: an account without TOTP reaches only the setup screen; 72 h window from creation / admin reset, then blocked; status and "Reopen setup" on the account page, notice on the dashboard, `POST /api/ipal/two-factor/reset` | `twoFactor.requireSetup: false`; parts: `requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }` | `requireSetup: { windowHours, exempt }` (`exempt` returns exactly `true`, never `async`), `twoFactor.resetAccess` (default: an admin who entered its own code; the reset ends the account's sessions), texts `twoFactor*`; `twoFactorSetupState(req)`, `buildSetupFields`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`. **Postgres/SQLite: migration for `totp_setup_from` applied when the new container starts (`prodMigrations` or `pnpm payload migrate && pnpm start`; never a pre-deployment command — deployment.md §4.3), or every login answers 500** |
| The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints |
| At most 5 verify attempts per account in 10 minutes (`POST /api/verify-totp` → `429`) | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes }` |
| The `back` link of the 2FA setup and verify screens is checked on the server (`SafeTotpView` in front of the package's views): only a path on the site's origin inside the admin route is kept, anything else (`javascript:`, another host) becomes the admin root. Needs `generate:importmap` in the same deploy — with a stale map the 2FA screens have no code form and nobody can sign in (`ipal-doctor`, the start log and a notice above the screen report it; the notice is a hint from the file on disk and never replaces the screen; `twoFactor.importMapCheck: false` turns it off); check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → lands on `/admin` | `twoFactor.safeBack: false` | `safeBack: (back, { adminRoute, origin }) => string`; `safeAdminBack`, `wrapTotpViews` (`@intecion/ipal-kit`), `SafeTotpView` (`@intecion/ipal-kit/admin`) for own views |
| The 2FA package's endpoints (`/api/setup-totp`, `verify-totp`, `remove-totp`, `admin/*`) answer accounts of the 2FA collection only; reset and remove need the second factor | — (always on with 2FA) | `adminManageAccess` through the wrapped factory (security.md "Resetting 2FA") |
| Roles count only for accounts of a staff collection, in every predicate and access function | — | `access.staffCollections` |
| `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 |
+23 -4
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.15.2 ("Example Studio", made up) that uses
The reference site is one complete client site on ipal-kit 1.16.6 ("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:
@@ -911,6 +911,11 @@ export const formClasses: BuilderFormClassNames = {
fields: 'grid grid-cols-12 gap-4',
form: 'grid gap-6',
formError: 'rounded-control bg-danger-surface p-3 text-danger',
file: 'block w-full text-fg file:mr-3 file:rounded-control file:border-0 file:bg-surface-muted file:px-3 file:py-2 file:text-fg-strong',
fileItem: 'flex flex-wrap items-center gap-2',
fileList: 'mt-2 grid gap-1 text-sm',
fileRemove: 'underline underline-offset-2',
help: 'mt-1 text-sm text-fg-muted',
input: control,
label: 'mb-1 block font-medium text-fg-strong',
legend: 'mb-1 font-medium text-fg-strong',
@@ -1152,9 +1157,12 @@ Rules: AGENT.md §8a.
| File | What it shows |
|---|---|
| `e2e/create-test-admin.ts` | a test admin with a known TOTP secret (local / CI database only) (below) |
| `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms, sitemap, SEO/GEO, headers, consent, 2FA |
| `e2e/create-test-admin.ts` | a test admin with a known TOTP secret, and e-mail sending pointed at the tests' mail sink (local / CI database only) (below) |
| `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA |
| `e2e/smtp-sink.ts` | a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments) |
| `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test (below) |
| `e2e/two-factor-back.spec.ts` | browser test of the 2FA screens' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed |
| `e2e/two-factor-setup.spec.ts` | browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator's reset on the account page |
### `e2e/create-test-admin.ts`
@@ -1164,7 +1172,8 @@ Rules: AGENT.md §8a.
* the real 2FA screen instead of skipping it. LOCAL / CI database only:
* pnpm payload run e2e/create-test-admin.ts
* Values come from E2E_ADMIN_EMAIL / E2E_ADMIN_PASSWORD / E2E_TOTP_SECRET (.env.example). Not a seed: seeds
* never create users (docs/seeding.md).
* never create users (docs/seeding.md). It also points e-mail sending at the tests' local mail sink
* (E2E_SMTP_PORT, default 2526).
*/
import config from '@payload-config'
import { isLocalDatabase } from '@intecion/ipal-kit/seed'
@@ -1184,6 +1193,16 @@ if (found.docs[0]) {
await payload.create({ collection: 'users', data: data as never, overrideAccess: true })
}
console.log(`[e2e] test admin ready: ${email}`)
// E-mail for the smoke tests goes to a local sink the test itself starts (e2e/smtp-sink.ts), so the test can
// read what the site sent — the form file as an attachment. Without the sink running, sends simply fail.
const smtpPort = Number(process.env.E2E_SMTP_PORT ?? 2526)
await payload.updateGlobal({
slug: 'site-integrations',
data: { emailTransport: 'smtp', smtpFromAddress: 'site@example-studio.test', smtpHost: '127.0.0.1', smtpPassword: 'e2e-sink', smtpPort, smtpUser: 'e2e' } as never,
overrideAccess: true,
})
console.log(`[e2e] e-mail sending points at the local sink 127.0.0.1:${smtpPort}`)
process.exit(0)
```
+6
View File
@@ -30,6 +30,12 @@ following the hint (PROGRAMISTA §2) — do not ask whether it is needed. The on
a client decision recorded in `AGENTS.md` as `ipal-audit-skip: <keys> — <reason>` (keys
in AGENT.md §0b). Never add that line yourself just to make the audit pass.
## Polish text and panel labels (AGENT.md §2, §6.5a)
`hardcoded Polish text in code` covers public text. In a schema file (a `.ts` file under `collections/`, `globals/`,
`fields/` or `blocks/`, or one importing Payload's schema types) the panel's own labels are fine: `adminText('Title', 'Tytuł')`,
`{ en, pl }` as `label`, `singular`, `plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback, a
`const x: AdminText`. Still an error: any `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`.
## Design tokens (AGENT.md §6.11)
The script checks: hex in classes and inline styles (error), `dark:` on colour utilities and `var(--color-…)` in
classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warning — a site not yet migrated),
@@ -238,8 +238,10 @@ fi
if [ -n "$FRONT" ]; then
report ERROR "logic keyed on content text" "§2 the editor can rename it any time — a style/flag is a panel field (e.g. buildLinkField({ appearances: [...] }))" \
"$(g "\.(label|title|heading|name|text)\??\.(toLowerCase|toUpperCase|trim)\(\) *[!=]==? *['\"]|\.(label|title|heading)\?? *[!=]==? *['\"][^'\"]+['\"]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '==')"
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields" \
"$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')"
# The panel's own { en, pl } / adminText() labels in schema files are not public text (polish-literals.mjs); without TypeScript, a plain grep.
POLISH=$(node "$(dirname "$0")/polish-literals.mjs" $FRONT 2>/dev/null) || \
POLISH=$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields; panel labels: adminText() or { en, pl } in a schema file" "$POLISH"
fi
GLOBALS=$(dirs src/globals)
if [ -n "$GLOBALS" ]; then
@@ -0,0 +1,98 @@
#!/usr/bin/env node
// Polish text hardcoded in code (AGENT.md §2) — prints "file:line: source line" per finding, exit 0.
// node polish-literals.mjs <dir> [<dir> …]
// 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/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ł' }
// Anything under defaultValue is public content, so it is reported. So is a Polish-only label.
// Exit 3 = TypeScript not found (audit.sh falls back to a plain grep).
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { createRequire } from 'node:module'
import { join } from 'node:path'
const load = (from) => {
try {
return createRequire(from)('typescript')
} catch {
return null
}
}
const ts = load(join(process.cwd(), 'package.json')) ?? load(import.meta.url)
if (!ts) process.exit(3)
const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/
const SCHEMA_KEYS = new Set(['label', 'singular', 'plural', 'description', 'placeholder', 'group'])
const SCHEMA_DIR = /(?:^|\/)(?:collections|globals|fields|blocks)\//
const SCHEMA_TYPES = /import\s+type\s*\{[^}]*\b(?:Block|CollectionConfig|Field|GlobalConfig|Tab)\b[^}]*\}\s*from\s*['"]payload['"]/
const IPAL = /^@intecion\/ipal-kit(?:\/|$)/
const files = []
const walk = (p) => {
let st
try { st = statSync(p) } catch { return }
if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n))
else if (/\.tsx?$/.test(p) && !/\.d\.ts$|\/\(payload\)\//.test(p)) files.push(p)
}
process.argv.slice(2).forEach(walk)
const keyName = (node) => (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) || ts.isStringLiteralLike(node.name)) ? node.name.text : null)
for (const file of files) {
const text = readFileSync(file, 'utf8')
if (!POLISH.test(text)) continue
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS)
const schemaFile = !file.endsWith('x') && !/^['"]use client['"]/m.test(text) && (SCHEMA_DIR.test(file) || SCHEMA_TYPES.test(text))
// Local names of the plugin's helpers (`import { adminText as t } …`); a lookalike of your own does not count.
const helpers = new Map()
for (const st of source.statements) {
if (!ts.isImportDeclaration(st) || !IPAL.test(st.moduleSpecifier.text)) continue
const named = st.importClause?.namedBindings
if (!named || !ts.isNamedImports(named)) continue
for (const el of named.elements) {
const name = (el.propertyName ?? el.name).text
if (name === 'adminText' || name === 'rowLabel') helpers.set(el.name.text, name)
}
}
const isBilingual = (node) =>
ts.isObjectLiteralExpression(node) && ['en', 'pl'].every((k) => node.properties.some((p) => keyName(p) === k))
// Is this literal one of the panel's own labels? Walks up from the literal.
const isAdminLabel = (literal) => {
let inside = false
for (let node = literal; node.parent; node = node.parent) {
const parent = node.parent
if (keyName(parent) === 'defaultValue') return false
if (inside) continue
if (ts.isCallExpression(parent) && parent.arguments.includes(node) && ts.isIdentifier(parent.expression)) {
const helper = helpers.get(parent.expression.text)
if (helper === 'adminText') inside = true
// rowLabel(fields, fallback): the fallback only, as { en, pl }
if (helper === 'rowLabel' && node === parent.arguments[1] && isBilingual(node)) inside = true
}
if (ts.isPropertyAssignment(parent) && parent.initializer === node && SCHEMA_KEYS.has(keyName(parent)) && isBilingual(node)) inside = true
if (ts.isVariableDeclaration(parent) && parent.initializer === node && parent.type?.getText(source) === 'AdminText' && isBilingual(node)) inside = true
}
return inside
}
const seen = new Set()
const visit = (node) => {
if (ts.isImportDeclaration(node)) return
const literal = ts.isStringLiteralLike(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)
if (literal && POLISH.test(node.text) && !(schemaFile && isAdminLabel(node))) {
const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line
if (!seen.has(line)) {
seen.add(line)
console.log(`${file}:${line + 1}:${text.split('\n')[line]}`)
}
}
ts.forEachChild(node, visit)
}
visit(source)
}
+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, and 2FA (setup required included) does not apply to them. Check: its token → `403` from
`/api/globals/site-integrations` and `/api/form-submissions`.
5. `pnpm generate:types`, `pnpm payload generate:importmap`.
6. Postgres with migrations → `pnpm payload migrate:create`.
## 4. Check
The **ipal-audit** skill. By hand: an entry in the panel → visible at `/<locale>/<archive>/<slug>`,
+19
View File
@@ -34,6 +34,21 @@ 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'] })` |
| an account logs in but every page and request answers 403 / the setup screen says "The time to set up two-step verification has passed" | 2FA setup required: the account did not set TOTP up within the window (72 h from its creation, an admin's reset, or the first start after the upgrade) | an administrator opens the account in the panel → Two-step verification → "Reopen setup" (or `POST /api/ipal/two-factor/reset` `{ userId }`); every administrator is blocked: security.md "Every administrator is blocked" — a script with the Local API, `payload.update({ collection: 'users', id, data: { totpSetupFrom: new Date().toISOString() } })` (`pnpm payload run`), then log in and set TOTP up; or `requireSetup: { windowHours: false }`, redeploy, set up, put it back |
| a new account gets `403` from the API although its role allows the request | 2FA setup required: until TOTP is set up the account reaches only the setup screen | set TOTP up (log in to the panel); an integration: use an API key, or `twoFactor.requireSetup.exempt` |
| after an upgrade EVERY panel login answers `500` (also `/api/users/init`), administrators with 2FA included; log: `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN` or `column users.totp_setup_from does not exist` | Postgres/SQLite: the migration that adds the 2FA column has not run (needed whenever 2FA is on) | `pnpm payload migrate:create` if no migration has it, commit, and redeploy with migrations run when the new container starts — `prodMigrations` in the adapter or the start command `pnpm payload migrate && pnpm start` (deployment.md §4.3; not Coolify's Pre-deployment command, which runs in the old container); nothing is lost. `ipal-doctor` reports a project whose migrations lack `totp_setup_from` |
| the site does not start: `[ipal] twoFactor.requireSetup.exempt must not be async` / `…windowHours must be a number` | `exempt` is an `async` function, or `windowHours` is a string / negative | `exempt: ({ user }) => user.email === '…'` (returns `true` / `false` at once); `windowHours: 72` or `false` |
| log: `[ipal] twoFactor.requireSetup.exempt returned a Promise … The account is NOT exempt` (and the service account gets 403) | `exempt` does not return exactly `true` | return a boolean decided from the fields on `user` |
| an administrator's "Reset two-step verification" answers 403 from a script with an API key, or for an exempt account | by default the reset needs a session that entered its own TOTP code | reset from the panel after logging in with the code; or `twoFactor.resetAccess: ({ req }) => …` |
| after "Reset two-step verification" the user is logged out everywhere | intended: the reset ends the account's sessions | the user logs in again with the password and sets 2FA up; after a suspected compromise also change the password |
| no "Two-step verification" box on the account page / no "Reopen setup" | the import map lacks `TwoFactorStatusField` (not regenerated), or `requireSetup: { statusField: false }` | `pnpm payload generate:importmap`, commit, redeploy; meanwhile `POST /api/ipal/two-factor/reset` `{ userId }` works |
| "Two-step verification" is missing on the account page / the dashboard shows a missing component | the import map is stale | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy |
| startup: `[ipal] twoFactor: the injected 2FA plugin did not add the totpSecret field / hasTotp field / totp auth strategy` | the installed `@clocklimited/payload-2fa` is not a version ipal-kit's second-factor check recognises (tested: 3.0.0-beta.1 and beta.7), or a custom factory was injected | install a supported version; stop-gap only: `twoFactor.guard: false` (the plugin's own data is then not covered by 2FA — security.md) |
| own route or script gets `403` / "not allowed" on `form-submissions`, `forms`, a settings global with `overrideAccess: false`, although the user is an admin | the `user` was fetched by id and passed by hand: it does not carry how the account logged in, so the second-factor check refuses it | take the user from `payload.auth({ headers })` (it sets `collection` and how the account logged in), or (server-only code that needs no access check) leave `overrideAccess` at its default; a hand-built user needs at least `collection: 'users'` for its role to count |
| an account of a second auth collection (`customers`) gets `403` from a settings global, submissions, `/api/ipal/*`, `/api/setup-totp`, or `isAdmin` / `adminOnly` say no although it has `roles: ['admin']`, after an upgrade | by design since 1.16.4: roles and staff checks count only for accounts of a staff collection | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") |
| `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) |
@@ -52,6 +67,10 @@ through this procedure. Ask only when you are missing something you cannot get y
| Symptom | Cause | Fix |
|---|---|---|
| `PayloadComponent not found in importMap` (e.g. `@intecion/ipal-kit/admin#RowLabel`) | importMap out of date after a plugin update / adding `rowLabel` | `pnpm payload generate:importmap`, restart |
| after an upgrade the 2FA setup / verify screen has no code form (HTTP 200), only the notice "Two-step verification may not be available" (or nothing at all with `importMapCheck: false` / an own provider); nobody can sign in; the log has `[ipal] The admin import map may be out of date` and `getFromImportMap: PayloadComponent not found in importMap … @intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after the upgrade that added the `back` link check (`twoFactor.safeBack`); the production build uses the committed, old `importMap.js` | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy; `pnpm exec ipal-doctor` shows it before a deploy. The opposite case (wrapper present, package view missing) throws `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` — same fix |
| the notice "Two-step verification may not be available" and the log line `[ipal] The admin import map may be out of date` appear, but the code form is there and sign-in works | false alarm: the check searches the `importMap.js` on disk, which is not the map inside the build (map generated during the build and a Dockerfile runner stage that copies the repository's file; a map file that re-exports or computes its entries) | `twoFactor: { …, importMapCheck: false }`; or ship the generated `importMap.js` in the image |
| an own 2FA screen (set through the wrapped factory) ignores the check on `back` | a client component reading `useSearchParams()` gets the raw query value | read the `back` prop (or `searchParams.back`) the wrapper passes — both are checked (security.md "Your own 2FA screen") |
| after the 2FA code the user lands on `/admin` instead of the page in `back` | `back` pointed outside the admin route or to another origin (the check keeps only a path inside `routes.admin`; an absolute URL only on the `serverURL` origin) | expected; for another rule pass `twoFactor.safeBack: (back, { adminRoute, origin }) => string` (security.md) |
| new admin stuck on `/admin/setup-totp?back=null` (the page keeps redirecting to itself) | ipal-kit ≤ 1.14.1: the 2FA package's provider needs an `x-pathname` header nothing sets on `/admin`; or `twoFactor.provider: false` without that header | update ipal-kit, `pnpm payload generate:importmap` (`TotpRedirectProvider`), restart; check: `/admin/setup-totp?back=%2Fadmin` shows the QR (security.md) |
| `Cannot destructure property 'config'` / UI hooks without context | two copies of `@payloadcms/ui` | `pnpm why @payloadcms/ui`; one version + `pnpm.overrides`; `ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms` = empty |
| empty SEO tab, no Forms | mismatched `@payloadcms/*` versions | all `@payloadcms/*` = the `payload` version |
+1 -1
View File
@@ -50,7 +50,7 @@ Existing client sites are not gated on it; run it there as a report only.
## The status endpoint
`GET /api/ipal/doctor` is added by `ipalKit` and answers 404 until the site has `IPAL_DOCTOR_TOKEN` (≥ 32 characters).
Then `Authorization: Bearer <token>`; counts only (`usersWithout2fa`, `pendingCookies`, `plugin`, `node`). With the same
Then `Authorization: Bearer <token>`; counts only (`usersWithout2fa`, `usersSetupClosed` = of those, blocked because the 2FA setup window has passed, `pendingCookies`, `plugin`, `node`). With the same
`IPAL_DOCTOR_TOKEN` in the doctor's environment, `--url` reads it. Off: `ipalKit({ doctor: false })`; adapt:
`ipalKit({ doctor: { tokenVar, access } })`.
+46 -1
View File
@@ -62,6 +62,7 @@ Underneath is `BuilderForm` (client) — clean, accessible HTML **without styles
checkbox, **Checkbox group** (multiple choice, min/max), message, **Step** (splits into steps),
country, state (on by default in form-builder, rendered as a text field).
Turning a type off: `forms.fields: { country: false, state: false }`.
With `forms: { attachments: true }` there is also **File** (section 3a).
- **Multi-step form:** the editor inserts a **Step** block (title, description) — the fields below it form one
screen. The Next/Back buttons and "Step 1 of 3" come from **Form messages → Form messages** (next, back,
stepOf). Next validates only the current step; a server error returns to the step with the field; focus
@@ -82,6 +83,41 @@ Custom field type in the panel: the `FormsOption['fields']` type only accepts `b
(at runtime the block object passes through to form-builder, but TS rejects it), and the server treats
an unknown type as text anyway — if you need a custom type or validation → **plugin gap** (`ipal-plugin-gap`).
## 3a. A file on a form (CV, specification, photo) — `forms.attachments`
The file is **e-mailed to the company and never stored**: no Media record, no bucket, no disk, no download link.
Never build this by hand (your own `<input type="file">`, upload route or upload collection = an error).
1. Config: `forms: { attachments: true }` (defaults: 10 MB per file and per submission, at most 3 files per field).
Options (`FormAttachmentsOption`): `maxSizeMB`, `maxTotalMB`, `maxFiles`, `fileTypes` (add / replace / `false`),
`allowRisky`, `scan` (antivirus hook), `strictPdf`, `notice`, `maxConcurrent`, `path`, `submit`
(`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`,
`idleTimeoutMs` 30 s, `timeoutMs` 5 min — a stalled or dropped upload is given up and frees its slot).
Postgres: `pnpm payload migrate:create`; then `pnpm generate:types`.
2. Form: a **File** field — in the seed
`{ blockType: 'file', name: 'attachment', allowedTypes: ['pdf', 'doc', 'docx'], maxSizeMB: 10, maxFiles: 1, label: {…}, help: {…} }`
(the template has the line, commented). Types: `pdf`, `doc`, `docx`, `odt`, `rtf`, `xls`, `xlsx`, `jpg`, `png`, `webp`.
The label and the help text ("PDF or DOCX, up to 10 MB") are written per language in the panel / seed.
3. E-mails: the file goes to **every e-mail whose To / CC / BCC are fixed addresses** — the company notification.
An e-mail addressed with `{{email}}` (the confirmation to the customer) never gets it. A form with a File field
and no fixed-recipient e-mail cannot be saved. `{{attachment}}` / `{{*:table}}` show the file name.
4. Code: nothing. `RenderForm` renders the field (native input, help text, file list, "Remove" button), and the
browser posts files to the plugin's endpoint `POST /api/ipal/forms/submit` — no route file, no `next.config`
change. Classes: `file`, `help`, `fileList`, `fileItem`, `fileRemove` in `formClasses.ts`. Your own markup:
`f.getFileProps(field)`, `f.getFiles(field)`, `f.removeFile(field, i)`, `f.helpId(field)`.
5. Texts: Form messages → **Files** (`fileTooLarge`, `fileType`, `fileRefused`, `fileCount`, `fileNotSent`,
`fileOptional`, `fileRemove`) — English and Polish defaults; fill every other language of the site. Each tells
the visitor that the problem is the **file**, why, and what to do (a smaller file, another format; on an
optional field also "send the form without the file"). They show at the File field; what the visitor typed stays.
6. Mail size: **Site integrations → E-mail sending → Test e-mail** with **Attach a 10 MB test file** must arrive.
SMTP: the provider's limit decides (a 10 MB server limit carries only ~7 MB of file — lower the field's
maximum). Microsoft Graph: files of 3 MB and more need the `Mail.ReadWrite` permission on the agency app
(email.md "Attachments"); without it they go over SMTP when the panel has SMTP settings, else the form's limit
drops to about 2.8 MB by itself. Keep Graph small on purpose: `mailAdapter({ graph: { largeAttachments: false } })`.
Tell the client plainly: **there is no antivirus scan** (the e-mail says so), the macro check of old `.doc` / `.xls`
files is best-effort, and when the e-mail cannot be sent the file is gone — the visitor sees "We could not send the
file …" at the File field, staff get a notice without the file, and the submission shows **File delivery: Not sent**.
## 4. Page — block data once (blocks do not import `lib/*`)
From `createPageRoute` (PROGRAMISTA §2.8):
```tsx
@@ -139,11 +175,16 @@ 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;
- [ ] multi-step form: Next with an empty step → errors, the step stays; Back keeps the entered values;
- [ ] form with a **File** field: a PDF arrives attached to the company e-mail, the customer e-mail has no file,
the submission shows *Files* and *File delivery: Handed to the mail server*, Media has no new record;
a `.exe` renamed to `.pdf` → "The file … was refused: …" at the File field, no submission, the typed answers
still there; a file over the limit → "…is too large. Choose a file of up to N MB." before sending; each
message in every language of the site; keyboard only: Tab to the field, pick a file, Tab to "Remove …", Enter removes it;
- [ ] `ipal-audit --quick` → zero hardcoding in FormBlock, no copy of the form engine;
- [ ] `ipal-consent-check` → still 0 violations (Turnstile is necessary, not tracking).
@@ -155,6 +196,10 @@ Details the seed already covers, which you check after every manual change in th
| `reason: 'validation'`, `kind: 'unknown_fields'` | the frontend sends a field the form does not have (custom renderer with an extra field, typo in `name`) |
| "Next/Back" buttons in English | empty Form messages → next / back / stepOf in that language |
| `reason: 'not_found'` | `formId` from another database (seeded on dev, another ID on prod) — use a relationship from the panel, not a fixed ID in code |
| "We could not send the file …", submission says *Not sent* | the mail server refused the message (size limit: see the note on the submission), or Graph without `Mail.ReadWrite` and no SMTP settings → Test e-mail with the 10 MB file; lower the field's maximum or fix the transport (email.md "Attachments") |
| the form with a File field cannot be saved ("Add an e-mail with a fixed recipient…") | every e-mail of the form is addressed with a placeholder → add the company notification with a fixed address |
| the File field does not appear in the builder | `forms.attachments` is off, or `forms.fields.file: false` |
| a file is refused although its type is ticked | the content does not match the extension, the name has a second extension (`cv.pdf.docx`), the document has macros, or it is password-protected |
| submission exists, no email | missing `email: mailAdapter()`, empty Emails tab, transport in the panel; server logs |
| always `turnstile` | wrong key pair / domain in Cloudflare (BuilderForm resets the token after an error) |
| the page became dynamic (`ƒ`) | `headers()` in a component instead of in the action |
@@ -27,6 +27,12 @@ export const formClasses: BuilderFormClassNames = {
choices: 'grid gap-2', // radio / checkbox group <fieldset>
legend: 'mb-1 font-medium text-fg-strong',
choice: 'flex items-center gap-2',
// File field (forms.attachments): the native input, its help text, the list of picked files.
file: 'block w-full text-fg file:mr-3 file:rounded-control file:border-0 file:bg-surface-muted file:px-3 file:py-2 file:text-fg-strong',
help: 'mt-1 text-sm text-fg-muted',
fileList: 'mt-2 grid gap-1 text-sm',
fileItem: 'flex flex-wrap items-center gap-2',
fileRemove: 'underline underline-offset-2',
error: 'mt-1 text-sm text-danger',
formError: 'rounded-control bg-danger-surface p-4 text-danger',
actions: 'flex flex-wrap gap-3',
@@ -44,6 +44,11 @@ const FORM = {
// options: [{ value: 's', label: { pl: 'do 10 tys.', en: 'up to 10k' } }, …] },
// { blockType: 'checkboxGroup', name: 'services', maxSelected: 3, label: {…}, options: [ …same shape… ] },
// { blockType: 'date', name: 'deadline', label: { pl: 'Termin', en: 'Deadline' } },
// A file sent to the company by e-mail — never stored on the site (needs `forms: { attachments: true }`).
// It rides on the notification below (fixed recipient); the confirmation to {{email}} never carries it.
// { blockType: 'file', name: 'attachment', required: false, width: 100, allowedTypes: ['pdf', 'doc', 'docx'],
// maxSizeMB: 10, maxFiles: 1, label: { pl: 'Załącznik (opcjonalnie)', en: 'Attachment (optional)' },
// help: { pl: 'PDF, DOC lub DOCX, do 10 MB', en: 'PDF, DOC or DOCX, up to 10 MB' } },
// GDPR consent — name MUST stay `consent`; never pre-ticked (the plugin enforces it server-side).
{
blockType: 'checkbox',
+24 -12
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,18 +25,28 @@ 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 | — |
| `twoFactor.plugin` | — (required) | injected `payloadTotp` (the plugin does not import the peer) | missing function → throws |
| `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.safeBack` | on | the `back` query value of the 2FA setup and verify screens is checked on the server before the package's view gets it (`SafeTotpView` registered in place of the package's four views): kept only as a path on the site's origin inside `routes.admin`, else the admin root — no `javascript:` / off-site redirect after the code. Needs `generate:importmap` (`@intecion/ipal-kit/admin#SafeTotpView`) | `false` = the package's views untouched; a function `(back, { adminRoute, origin }) => string` = your own rule |
| `twoFactor.importMapCheck` | on | production only: at start searches the `importMap.js` on disk (where Payload looks for it) for `@intecion/ipal-kit/admin#SafeTotpView`; when not found, logs `[ipal] The admin import map may be out of date …` and ipal-kit's `TotpRedirectProvider` puts the notice "Two-step verification may not be available" above the 2FA screens (never instead of them). A hint only — the map in the build can differ from the file on disk (Dockerfile runner stage, re-exporting map); a file that is not found is not reported | `false` = no file read, log line or notice |
| `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations.<lang>.totpPlugin.<key>` (security.md) |
| `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.<op>`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way |
| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit |
| `twoFactor.requireSetup` | on, `{ windowHours: 72 }` | an account without TOTP reaches nothing but the setup screen and `/api/setup-totp` (REST, GraphQL and the panel's data answer 403); it has `windowHours` from its creation or from an admin's reset, then it is blocked until an admin reopens setup. Adds the field `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`; the date field `totpSetupFrom` is there whenever 2FA is on (also with `requireSetup: false` / `guard: false`). Existing accounts get their window at the first start after the upgrade, written once. **Postgres/SQLite: the migration must be applied when the new container starts — `prodMigrations` or `pnpm payload migrate && pnpm start`, not a pre-deployment command (deployment.md §4.3) — or every login answers 500**; `generate:importmap`. `exempt` must return exactly `true` at once (an `async` one, or a `windowHours` that is not a number / `false`, stops the start) | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) |
| `twoFactor.requireSetup.dashboardNotice` / `.statusField` / `.setupNotice` | on | the administrators' notice on the dashboard; the status and reset control on the account page; the notice on the setup screen | `false` each (the lock and the reset endpoint stay) |
| `twoFactor.resetAccess` (the endpoint exists with `twoFactor.guard` on; `guard: false` = no endpoint, 404) | a staff admin whose session entered its own TOTP code (not an API key, not an `exempt` account) | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`). The reset clears the secret and the account's sessions. A session that still owes its code is always refused | `({ req }) => boolean` — replaces the rule, so keep `req.user?._strategy === 'totp' &&` in it unless API-key / exempt admins should reset; only `true` allows; `req.user._strategy` tells `'totp'`, `'api-key'`, `'local-jwt'` apart |
| `whiteLabel.inlineImages` | on | on the 2FA screens the logo / icon is fetched by the server as an anonymous visitor gets it (max 512 KB) and inlined as `data:` — the session there is refused `media` | `false` = the browser tries the media URL |
| `adminMeta.serveIcon` | on | `/api/ipal/admin-icon` answers with the favicon's bytes when it is a bitmap (PNG, JPEG, GIF, WebP, ICO, AVIF by its bytes); an SVG favicon always gets a redirect to the media file (never SVG bytes from the site's origin) | `false` = always the redirect |
| `twoFactor.allowCollectionMismatch` | `false` | allows `collectionSlug` ≠ `admin.user` (panel users of the other collection then skip 2FA) | `true` only when you protect a second auth collection on purpose |
| `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site settings + vendor credit | omit / `false`; `true` = defaults |
| `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — |
@@ -59,7 +69,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 |
@@ -68,6 +77,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `forms.redirectRelationships` | none | collections a form can redirect to | `['pages']` |
| `forms.emailLayout` | `false` | `beforeEmail` with a layout (logo, colour, footer) + Site settings → **Emails** tab; `{{*:table}}` readable | `true` |
| `forms.beforeEmail` | none | your own e-mail changes (after the layout) | form-builder function |
| `forms.attachments` | off | **File** field in the form builder; a file is checked (size, count, type by content, refused extensions), attached to the company e-mail and dropped — **never stored**; adds `POST /api/ipal/forms/submit`, the fields `submissionFiles` / `filesDelivery` / `filesDeliveryNote` / `attemptKey` on `form-submissions`, and the **Files** texts in Form messages | `true` / `FormAttachmentsOption`: `maxSizeMB` (10), `maxTotalMB`, `maxFiles` (3), `fileTypes`, `allowRisky`, `scan` (antivirus hook — none built in), `strictPdf`, `notice`, `maxConcurrent` (2), `path`, `submit` (`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`, `idleTimeoutMs`, `timeoutMs`); block only: `forms.fields.file: false` or `buildFileBlock(…)`. Postgres: `migrate:create`. Check: submit a PDF → attached to the company e-mail, absent from the customer e-mail, submission shows *File delivery: Handed to the mail server* (forms.md "Files") |
| `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins |
| `consentLog` | off | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (default 1095) |
| `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === '[email protected]' } }` — narrows who reads records in a project without roles |
@@ -88,8 +98,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 |
@@ -110,7 +120,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| global `cookie-settings` | banner texts, categories, cookie list; public read, write editor+ | `globalOverrides` | always present; `globalOverrides` |
| global `notifications` | form messages per language; public read, write editor+ | `globalOverrides` | always present; `globalOverrides` |
| global revalidation hook | `afterChange` on the four globals → `revalidatePath('/', 'layout')` | `revalidatePath` | omit `revalidatePath` |
| `POST /api/ipal/test-email` | SMTP/Graph test (admin only) | — | **currently always** |
| `POST /api/ipal/test-email` | SMTP/Graph test (admin only); body `{ to, attachmentMB? }` — `attachmentMB` attaches a dummy file to measure the mail server's size limit | — | **currently always** |
| `POST /api/ipal/forms/submit` | a panel form **with files** posts here (multipart, read as a stream; same gates as `sendForm`); same-origin only | `forms.attachments` (`path`, `submit`) | off by default |
| `POST /api/ipal/consent` | saves consent | `consentLog` | off by default |
| `POST /api/ipal/hit` | page view for stats | `stats` | off by default |
| `GET`/`POST /api/ipal/cookie-crawl`, `POST /api/ipal/cookie-crawl/results` | crawl status / start (editor+ or bearer token) / the scanner service's callback (token, running job only) | `cookieScanner.crawl` | off by default |
@@ -137,7 +148,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 |
@@ -176,10 +187,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 |
@@ -229,13 +241,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` |
@@ -31,11 +31,15 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `CookieApprovalForm` | `@intecion/ipal-kit/admin` | Client part of the view: tick boxes, markers (New / Changed / Needs description), Edit links, the button. Props `pending`, `gone`, `unknownCategory`, `labels?`, `adminRoute?` — reuse it in your own view. |
| `CookieCrawlAlert` | `@intecion/ipal-kit/admin` | Server Component: dashboard warning — "Waiting for approval: N" with a link to the approval view, and with the crawl violations or a failed crawl; renders nothing otherwise. Props `approval`, `crawl`. Injected with `cookieScanner` (`approval.dashboard: false` / `crawl.dashboard: false` drop its parts); after turning it on, `pnpm generate:importmap`. |
| `CookieScanButton` | `@intecion/ipal-kit/admin` | "Scan cookies" box above the *Cookie review* list: integrations in use, optional extra names, runs `POST /api/ipal/cookie-scan`. Injected by the plugin with `cookieScanner`; after turning it on, `pnpm generate:importmap`. |
| `SafeTotpView` | `@intecion/ipal-kit/admin` | Server admin view in front of the 2FA package's setup and verify views: replaces the `back` query value with a checked one and renders the view named by the serverProp `ipalTotpView` (a path or `{ path, exportName }`, found in the import map) the way Payload renders a view: a server component gets all server props, a client component only Payload's client props, `ipalTotpClientProps`, `back` and `searchParams` (both checked). `ipalSafeBack` = own rule. Registered by the plugin with `twoFactor` (`twoFactor.safeBack`, on by default). After upgrading, `pnpm generate:importmap`. Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → `/admin`. Own registration: `Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<path>' } }` + that path in `admin.dependencies`. |
| `TotpRedirectProvider` | `@intecion/ipal-kit/admin` | Client admin provider: sends a user without TOTP to `/admin/setup-totp?back=…` and a user whose session has not passed TOTP to `/admin/verify-totp?back=…` (path read in the browser; never redirects away from those screens or logout; renders nothing while redirecting). Injected by the plugin with `twoFactor` in place of the package's header-based provider; swap with `twoFactor.provider`. After upgrading, `pnpm generate:importmap`. Check: a new admin lands on `setup-totp?back=%2Fadmin` with the QR code. Props type `TotpRedirectProviderProps` (`forceSetup`) |
| `TwoFactorStatusField` | `@intecion/ipal-kit/admin` | Server component, the `totpSetupStatus` UI field ipalKit adds to the 2FA collection (sidebar of an account): "Set up", "Not set up… until <date>" or "blocked", and for an administrator on someone else's account the reset / "Reopen setup" button. Wired by the plugin with `twoFactor.requireSetup`; needs `generate:importmap`. |
| `TwoFactorResetButton` | `@intecion/ipal-kit/admin` | Client button inside `TwoFactorStatusField`: `POST /api/ipal/two-factor/reset` `{ userId }`, then reloads the view. Props `{ kind: 'reset' \| 'reopen', userId }`. |
| `TwoFactorAlert` | `@intecion/ipal-kit/admin` | Server component on the dashboard (`beforeDashboard`), administrators only: accounts without two-step verification and how many are blocked. Wired by the plugin with `twoFactor.requireSetup`; renders nothing when every account has it. |
| `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology support: Intecion.com" (admin language; `agency` prop = the name) below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }` or `agency: false`. |
| `buildAdminMeta({ agency, apiRoute?, defaultLocale?, meta?, options? })` | `@intecion/ipal-kit` | The `adminMeta` step: static panel meta (robots, preview image, icon) without overwriting keys in `meta`; returns `{ meta, resolved }` |
| `adminMetaForSite(site, resolved)`, `syncAdminMeta(payload, resolved, { nameField?, settingsSlug? })` | `@intecion/ipal-kit` | Site-name parts (suffix, description, siteName); `syncAdminMeta` writes them into the live config (onInit + Site settings afterChange, never throws) |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (favicon redirect or initials) — already added by `adminMeta` |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (the favicon itself, or initials) — already added by `adminMeta` |
| `DEFAULT_AGENCY`, `ADMIN_META_TEXTS` | `@intecion/ipal-kit` | Default agency `{ name: 'Intecion.com', url }`; en/pl meta texts (`{site}`, `{agency}`). Types `AdminMetaOptions`, `AgencyOption`, `ResolvedAdminMeta` |
## Readable array rows in the panel (`admin-ui`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
@@ -53,20 +57,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? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
@@ -277,7 +283,8 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection,
|---|---|---|
| `mailAdapter({ smtp?, graph?, fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | recommended adapter for `buildConfig({ email })`: on every send picks SMTP or Graph per the panel setting and saves the integration status; the plugin does not set `config.email` itself |
| `panelSmtpAdapter({ fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | Payload adapter that always sends through the SMTP configured in Site integrations |
| `graphAdapter({ fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | Payload adapter through Microsoft Graph (Exchange/M365; `GRAPH_*` credentials from env) |
| `graphAdapter({ fallbackFromAddress?, fallbackFromName?, largeAttachments?, cleanupDelaysMs? })` | `@intecion/ipal-kit` | Payload adapter through Microsoft Graph (Exchange/M365; `GRAPH_*` credentials from env). Attachments under 3 MB ride in `sendMail`; larger ones go through a draft + upload session (needs `Mail.ReadWrite`) and the mailbox copy is deleted; `largeAttachments: false` turns that path off (email.md "Attachments") |
| `mailAttachmentLimit(payload)` | `@intecion/ipal-kit` | Total attachment bytes the site's e-mail adapter can carry, or `null` (no ceiling of its own). About 3 MB on Graph without the large-file path and without SMTP settings — form File fields use it for the limit they show |
| `sendEmail({ payload, to, subject, html, text?, from?, replyTo? })` | `@intecion/ipal-kit/server` | sends your own e-mail (your HTML) always through SMTP from the panel → `{ sent: true, messageId }` / `{ sent: false, error }`; does not throw; server code only |
**Types:** `MailAdapterArgs`, `PanelSmtpAdapterArgs`, `GraphAdapterArgs` — adapter options; `SendEmailArgs`, `SendEmailResult` (`/server`) — `sendEmail` arguments and result.
@@ -287,7 +294,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 |
@@ -378,6 +385,11 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|---|---|---|
| `buildFormsPlugin(forms)` | `@intecion/ipal-kit` | Wires `@payloadcms/plugin-form-builder` (Forms + Form Submissions, field types, closed REST for submissions); the plugin wires it itself with the `forms` option — do not call |
| `stepBlock` | `@intecion/ipal-kit` | Form-builder "Step" block (splits the form into steps, with "Show only when"); the plugin adds it itself (`forms.fields.step`) — only for your own form-builder configuration |
| `buildFileBlock(options?)`, `fileBlock` | `@intecion/ipal-kit` | "File" block of the form builder (label, help text, allowed types, maximum size and files); the plugin adds it with `forms.attachments`. `buildFileBlock({ maxSizeMB, fileTypes, … })` for your own variant in `forms.fields.file`; `fileBlock` = the default one |
| `FORM_FILE_TYPES`, `RISKY_FILE_EXTENSIONS` | `@intecion/ipal-kit` | Built-in file types of the File field (`pdf`, `doc`, `docx`, `odt`, `rtf`, `xls`, `xlsx`, `jpg`, `png`, `webp` → label, extensions, MIME type) and the extensions refused unless `attachments.allowRisky` lists them |
| `formatFileSize(bytes)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | "2.1 MB" / "640 KB" for a file list |
| `fileFieldRules(field)`, `fileFieldError(field, files, texts)` | `@intecion/ipal-kit/client` | The limits of a File field in the browser (from `field.resolved`, set by the server) and the first problem with the picked files as the visitor's message — `useBuilderForm` uses both |
| `splitFormFiles(values)` | `@intecion/ipal-kit/server` | Splits `File` values from the answers → `{ fields, files }` for `submitForm({ data: fields, files })` in your own action or route; `createSubmitAction` already does it |
| `checkboxGroupBlock` | `@intecion/ipal-kit` | "Checkbox group" block (multiple choice, `minSelected`/`maxSelected`, value `string[]`); the plugin adds it itself (`forms.fields.checkboxGroup`) |
| `timeBlock` | `@intecion/ipal-kit` | "Time" block (`<input type="time">`, value `HH:MM`); the plugin adds it itself (`forms.fields.time`) |
| `placeholderField` | `@intecion/ipal-kit` | Payload `placeholder` field (localized hint in an empty field) for your own form blocks |
@@ -411,7 +423,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
| Export | Import from | What it does / when |
|---|---|---|
| `createSubmitAction({ getCachedPayload, headers, … })` | `@intecion/ipal-kit/server` | Creates the server action `sendForm(formId, locale, values, token?)`: honeypot → `clientIp` → `submitForm` → text from Notifications; returns `SubmitActionResult`. Standard: `export const sendForm = createSubmitAction({ getCachedPayload, headers })` in `actions.ts` |
| `submitForm({ payload, formId, data, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `ipalKit({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission; returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
| `submitForm({ payload, formId, data, files?, attemptKey?, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `ipalKit({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission; returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
### Honeypot
@@ -444,7 +456,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|---|---|---|
| `formAnalyticsOnSuccess(config)` | `@intecion/ipal-kit/client` | Turns `form.analytics` (panel) into an `onSuccess` handler that calls `pushDataLayer(event, params)` (a value like `$topic` — `$` + field name — is taken from the submitted data; empty event = no-op); `useBuilderForm` calls it itself — by hand only with `useForm`/`useContactForm` |
**Types:** `BuilderField`, `BuilderOption`, `BuilderStep`, `BuilderFormDoc`, `BuilderFormTexts`, `FieldCondition` (root, `/client`; `BuilderOption` only `/client`) — shape of the panel form, field, option, step, texts and the "Show only when" condition. `BuilderFormProps`, `BuilderFormClassNames`, `BuilderFieldRenderArgs`, `BuilderFormAction`, `BuilderFormApi`, `UseBuilderFormOptions` (`/client`) — `BuilderForm` props/classes/`renderField`, the bound action and the `useBuilderForm` result. `RenderFormProps`, `SendFormAction`, `PrepareBuilderFormArgs`, `PreparedBuilderForm` (`/rsc`) — `RenderForm` props, `sendForm` signature, `prepareBuilderForm` input/output. `SubmitFormArgs`, `SubmitFormResult`, `SubmitActionResult` (`/server`) — `submitForm` arguments and result codes, and the `sendForm` result (`{ success, message, reason?, field? }`). `FormErrors`, `FormSubmitAction`, `Validator`, `Rule` (root, `/client`), `ContactFormValues`, `ContactFormErrors`, `SubmitAction` (`/client`) — `useForm`/`useContactForm` and validator types. `FormAnalyticsConfig` (`/client`) — form analytics configuration from the panel. `FormsOption`, `FormsCollectionOverrides`, `FormsFieldsOverride` (root) — the plugin's `forms` option and collection overrides.
**Types:** `BuilderField`, `BuilderOption`, `BuilderStep`, `BuilderFormDoc`, `BuilderFormTexts`, `FieldCondition` (root, `/client`; `BuilderOption` only `/client`) — shape of the panel form, field, option, step, texts and the "Show only when" condition. `BuilderFileLimits` (root, `/client`) — what the server resolved for a File field (`field.resolved`: `maxSizeMB`, `maxTotalMB`, `maxFiles`, `accept`, `extensions`, `typeLabels`); `BuilderFile` (`/client`) — `{ name, size }`, a browser `File` fits. `FormAttachmentsOption`, `FormSubmitEndpointOptions`, `FormFileType`, `FormFileDetect`, `FormFileScanInput`, `FormFileScanResult` (root) — the `forms.attachments` option, its `submit` gates, a file type and its `detect`, and the `scan` hook's input and result. `BuilderFormProps`, `BuilderFormClassNames`, `BuilderFieldRenderArgs`, `BuilderFormAction`, `BuilderFormApi`, `UseBuilderFormOptions` (`/client`) — `BuilderForm` props/classes/`renderField`, the bound action and the `useBuilderForm` result. `RenderFormProps`, `SendFormAction`, `PrepareBuilderFormArgs`, `PreparedBuilderForm` (`/rsc`) — `RenderForm` props, `sendForm` signature, `prepareBuilderForm` input/output. `SubmitFormArgs`, `SubmitFormResult`, `SubmitActionResult` (`/server`) — `submitForm` arguments and result codes, and the `sendForm` result (`{ success, message, reason?, field? }`). `FormErrors`, `FormSubmitAction`, `Validator`, `Rule` (root, `/client`), `ContactFormValues`, `ContactFormErrors`, `SubmitAction` (`/client`) — `useForm`/`useContactForm` and validator types. `FormAnalyticsConfig` (`/client`) — form analytics configuration from the panel. `FormsOption`, `FormsCollectionOverrides`, `FormsFieldsOverride` (root) — the plugin's `forms` option and collection overrides.
## Links (`links`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
@@ -558,13 +570,13 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| Export | Import from | What it does / when |
|---|---|---|
| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, formsCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local, only }`. `only` (or `SEED_ONLY`) = the records the run may touch (`pages:kontakt`, `forms:<title>`, `global:<slug>`, `pages:*`), the rest → `skip (not listed)`; a run without it against production / a non-local database throws unless `IPAL_SEED_ALLOW_FULL=1` / `guard.allowFull: true` (after launch: named records only; dry runs are never refused; `guard: false` turns every guard off). Create-only by default, natural keys, never deletes, globals: empty fields only, every locale with `fallbackLocale: false` onto the same row ids, skips records edited since seeding, writes with `context` `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }`. Throws when `update` runs on production / a non-local database without `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Both seed templates use it. |
| `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`). |
| `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) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids. |
| `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). |
| `seedHash(value)` | `@intecion/ipal-kit/seed` | Stable hash for the hidden `seedHash` field (key order, row ids, nulls ignored). |
| `projectOnto(seed, current)` | `@intecion/ipal-kit/seed` | Current values at the keys the seed writes — hash them to compare with the stored hash. |
| `editedSinceSeed({ doc, currentHash?, hashField?, untouchedSeconds? })` | `@intecion/ipal-kit/seed` | `null` = untouched; otherwise the reason (stored hash differs / `updatedAt` too late after `createdAt`). |
@@ -577,6 +589,20 @@ 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`. |
| `safeAdminBack(back, { adminRoute, origin? })` | `@intecion/ipal-kit` | The default `back` rule of the 2FA screens: returns `back` as a path when it resolves to the site's origin (the placeholder origin for relative values, `origin` for absolute ones), over HTTP(S), without credentials, inside `adminRoute`; otherwise the admin root. `safeAdminBack('javascript:alert(1)', { adminRoute: '/admin' })` → `'/admin'`; `safeAdminBack('/admin/collections/pages?page=2', { adminRoute: '/admin' })` → the same path. Use it in your own rule or view. |
| `wrapTotpViews(views, added, rule?, wrapper?)` | `@intecion/ipal-kit` | Puts `SafeTotpView` in front of the views whose route is `setup-totp` / `verify-totp` and for which `added(key)` is true (keeps `exportName`, `serverProps`; `clientProps` travel as `ipalTotpClientProps`); returns `{ views, dependencies }` (`dependencies` → `admin.dependencies`, so the wrapped views stay in the import map). What `ipalKit` runs after the 2FA factory; for a project that registers the 2FA package itself. |
| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". |
| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. |
| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)<admin route>/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. |
| `buildSetupFields({ statusField? })`, `stampSetupFrom`, `backfillSetupFrom(payload, collection)` | `@intecion/ipal-kit` | The parts of "2FA setup required" for a project that wires them itself: the fields for the 2FA collection (`totpSetupFrom`, and the panel's `totpSetupStatus` unless `statusField: false`), the `beforeChange` hook that stamps the window start (on create, and when an account loses its TOTP secret), and the start-up step that gives accounts without TOTP and without a start their window (returns how many; once per account). |
| `buildTwoFactorResetEndpoint(collection, { access? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). `ipalKit` registers it only with `twoFactor.guard` on. |
| `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. |
| `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. |
| `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. `rasterImageType(bytes)` → the media type of a bitmap by its first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF) or `null` — never trust a claimed type before answering a file's bytes from the site's origin; an SVG gives `null`. |
| `UPLOAD_SECURITY_HEADERS` | `@intecion/ipal-kit` | The two headers of `buildUploadSecurityHeaders` (`Content-Security-Policy: default-src 'none'; … sandbox`, `X-Content-Type-Options: nosniff`) for a route of your own that returns an uploaded file's bytes from the site's origin. In a Next project a site-wide `headers()` rule with the same key overrides a header the route sets itself: add a `headers()` rule for the path after the site-wide one (as `buildUploadSecurityHeaders({ collections, adminIcon })` does for the upload routes and `/api/ipal/admin-icon`), and never answer with an SVG. |
| `twoFactorSetupState(req)`, `twoFactorSetupDeadline(req)` | `@intecion/ipal-kit` | Where an account stands with TOTP setup, from `{ payload, user }`: `'set-up'`, `'open'` (may set it up now), `'closed'` (the setup window has passed: blocked until an admin reopens it), `'exempt'` (`requireSetup.exempt`, or `requireSetup: false`), `'not-applicable'` (no user, another collection, 2FA off); and the moment setup closes (`Date`, or `null` without a window). Types: `TwoFactorSetupState`, `RequireSetupOptions`. |
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
| `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` |
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
| `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 ---------------------------------------------------------------
+48 -12
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
@@ -93,10 +93,16 @@ legacy-peer-deps=true
pnpm add @intecion/ipal-kit @payloadcms/plugin-seo @payloadcms/plugin-form-builder \
@payloadcms/storage-s3 @clocklimited/payload-2fa@3.0.0-beta.7 tailwindcss @tailwindcss/postcss
```
**Next.js 16.4.1 or later** (minimum safe version: 16.0.0–16.4.0 have critical advisories, AGENT.md §4 item 11):
`pnpm add next@^16.4.1 eslint-config-next@^16.4.1 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` and `undici` overrides from AGENT.md §4 item 12.
**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].6 [email protected].6 sharp@^0.35.5` when
create-payload-app gave you an older one.
**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
@@ -104,7 +110,7 @@ plugin-seo, plugin-form-builder, storage-s3) in `pnpm.overrides` **to the exact
`"build": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" next build --webpack"`.
**Check.** `ls node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` exists;
`pnpm ls payload @payloadcms/ui @payloadcms/plugin-seo` — one, identical version; `pnpm ls next sharp` → next ≥ 16.4.1,
`pnpm ls payload @payloadcms/ui @payloadcms/plugin-seo` — one, identical version; `pnpm ls next sharp` → next ≥ 16.4.5,
sharp ≥ 0.35.5; `ls src/middleware.ts` → not found.
404 on `pnpm add` = missing `@intecion:registry` line; 401 = stale `_authToken` in `~/.npmrc` (PROGRAMISTA §1).
@@ -193,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.
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider` and `#SafeTotpView`); `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, 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`.
@@ -211,11 +217,41 @@ 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`).
The `back` link of the setup and verify screens is checked on the server (`twoFactor.safeBack`, on by default:
only a path inside the admin route is kept; `false` turns it off, a function replaces the rule). It needs the
import map entry `@intecion/ipal-kit/admin#SafeTotpView` — run `pnpm payload generate:importmap` and commit
(a production build with a map that lacks it shows 2FA screens without a code form: nobody can sign in;
`ipal-doctor`, the start log and a notice above the screen report it; `twoFactor.importMapCheck: false` turns the
log line and the notice off — needed when the `importMap.js` on disk is not the one the build used).
Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → you land on `/admin`.
**Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone
opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`.
**Setup required** (`twoFactor.requireSetup`, default): an account without TOTP reaches only the setup screen; it
has 72 h from its creation (or an admin's "Reopen setup" on the account page), then it is blocked. So create an
account, hand over the password and have the owner set 2FA up at once. **Postgres/SQLite: `pnpm payload
migrate:create` and have the migration applied when the container starts, before the site serves** — `prodMigrations`
or the start command `pnpm payload migrate && pnpm start`, never a pre-deployment command (deployment.md §4.3)
(column `totp_setup_from`, there whenever 2FA is
on) — without it every login answers 500; `pnpm payload generate:importmap` (`TwoFactorStatusField`,
`TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }` (a plain function
returning exactly `true`; never `async`); an API key needs nothing. Parts to switch off: `requireSetup:
{ dashboardNotice: false, statusField: false, setupNotice: false }`. An admin's reset ends the account's
sessions and needs the admin's own TOTP code (`twoFactor.resetAccess` changes who). Have two administrators
with 2FA: when all are blocked, only a script or a redeploy helps (security.md "Every administrator is
blocked"). One entity reachable without the code: `custom.ipal.secondFactor`.
- 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
@@ -505,7 +541,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.
+198 -7
View File
@@ -82,13 +82,38 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
`buildGlobalRevalidateHook({ revalidatePath })`; `consentFieldName` passed only because the option was ignored →
`forms.consentFieldName` works now; your own seed guard / upsert code → `@intecion/ipal-kit/seed` (`createSeeder`).
**Every upgrade — Next.js 16.4.1 or later** (AGENT.md §4 item 11): `pnpm ls next sharp`; below 16.4.1 →
`pnpm add next@^16.4.1 eslint-config-next@^16.4.1 sharp@^0.35.5`, `rm -rf .next`, build, redeploy on Coolify
(a new image ships the fixed next and sharp). **Check:** `pnpm dev` prints no security-upgrade warning.
**Every upgrade — Next.js 16.4.5 or later** (AGENT.md §4 item 11): `pnpm ls next sharp`; below 16.4.5 →
`pnpm add [email protected].6 [email protected].6 sharp@^0.35.5`, `rm -rf .next`, build, redeploy on Coolify
(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` and `undici` overrides, `pnpm install`, audit again. **Check:** no high or critical (the
`deepmerge` low has no fix yet).
**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",
"undici@>=7 <7.30.1": "^7.30.1"
```
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)
@@ -98,7 +123,7 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
`engines`. Remove `nodemailer` and `@types/nodemailer` from the project's own `package.json` if someone added them
(the plugin's copy is the one `mailAdapter` uses). **Check:** Site integrations → E-mail sending → send a test
e-mail over SMTP (and over Microsoft Graph when the project uses it).
3. **Next.js 16.4.1 or later** — the "Every upgrade — Next.js" step above (`next@^16.4.3`, `sharp@^0.35.5`).
3. **Next.js** — the "Every upgrade — Next.js" step above (today 16.4.5 or later, `sharp@^0.35.5`).
4. **Dependency advisories** — the "Every upgrade — dependency advisories" step above (`dompurify` / `graphql-scalars` /
`undici` overrides on payload 3.90.x). **Check:** `pnpm audit --prod` → no high or critical.
5. **Cookie list kept by hand** → offer `cookieScanner: true` (+ `crawl: true` with `IPAL_COOKIE_SCAN_URL`,
@@ -230,6 +255,172 @@ and the browser tab shows the same separator.
2. Two frontend candidates reported → `"layout": { "frontend": "src/app/(<group>)" }` in `ipal-doctor.json`.
**Check:** `pnpm exec ipal-doctor --strict` → no `layout-required` finding for the site's own route group.
**→ 1.15.3 (PROGRAMISTA §6, item 58; ipal-audit, bilingual panel labels; ipal-audit skill) — nothing required:**
1. `pnpm ipal:skills`, so the updated `audit.sh` and `polish-literals.mjs` reach the project.
2. Remove a temporary `i18n-literals` silence or `ipal-audit-skip` added because of `adminText()` / `{ en, pl }` labels.
**Check:** `pnpm exec ipal-doctor --strict` → no `i18n-literals` finding for a schema file's bilingual labels; Polish
text in a `.tsx` component is still reported.
**→ 1.15.4 (PROGRAMISTA §6, item 59; seeding whole localized arrays; seeding.md) — nothing required:**
1. Did a seed write a whole localized array (`{ pl: [...], en: [...] }` for form fields, a page `layout`, a global
array) and the panel shows only the last language? A plain re-run skips existing records (create-only): rewrite
them locally with `SEED_UPDATE=1 pnpm seed` and check every language in the panel.
2. Live site, only the affected records: `SEED_ONLY="forms:<title>,pages:<slug>" SEED_UPDATE=1
IPAL_SEED_ALLOW_PROD_UPDATE=1 SEED_DRY_RUN=1 pnpm seed`, back up the database (Coolify), then the same without
`SEED_DRY_RUN`. Records an editor changed since seeding are skipped (`skip (edited)`) — fix them in the panel.
3. A global array: `fillGlobal` fills empty fields only — clear the field in the panel before the run, or fix it by hand.
**Check:** the panel shows the seeded rows in every language; a second run reports `skip`, not new rows.
**→ 1.15.5 (PROGRAMISTA §6, item 60; required fields with references in seeds; seeding.md) — nothing required:**
1. A seed that failed with "The following field is invalid: … > Layout" for a page whose required layout links to
another page or a form: run it again — the record is now created complete (`SEED_DRY_RUN=1` first).
2. The dry run is stricter: a `{ $form }` / `{ $page }` to a record that neither exists nor is seeded earlier in the run is
an error. Seed that record first or create it in the panel.
3. A "cycle of required links" error: make one of the two links optional, or seed one of the pages first.
**Check:** `SEED_DRY_RUN=1 pnpm seed` reports 0 errors; the real run creates the same records.
**→ 1.16.0 (PROGRAMISTA §6, item 61; files on forms, e-mailed and never stored; forms.md "Files") — nothing required:**
1. `pnpm ipal:skills`. Existing forms need nothing; without `forms.attachments` nothing changes. No import map change.
2. Only if the site wants files on a form (ask the owner): `ipalKit({ forms: { attachments: true } })`, a **File** field on
the form (panel or seed — `ipal-form` skill), one e-mail of that form with a fixed recipient (no `{{field}}`),
`pnpm generate:types`; Postgres/SQLite: `pnpm payload migrate:create` (additive). Add the `formClasses` keys `file`,
`help`, `fileList`, `fileItem`, `fileRemove`; fill Form messages → Files for languages other than en/pl.
3. A hand-built upload path for a form (own collection, bucket, route): replace it with the File field and remove it
(after the owner confirms nothing else uses the stored files).
4. Deploy: a proxy body limit of at least 12 MB on `/api/ipal/forms/submit` (Coolify's Traefik: none by default;
nginx: `client_max_body_size 12m;`). Mail: Graph needs `Mail.ReadWrite` limited to the forms mailbox for files of
3 MB and more, or SMTP settings in Site integrations; otherwise the limit is about 2.8 MB.
**Check:** Site integrations → "Send test e-mail" with the 10 MB file arrives; a form submission with a file arrives with
the attachment, and the submission shows **File delivery: Sent**; with Graph, no draft or Sent Items copy is left in the
sender mailbox a minute later.
**→ 1.16.1 (PROGRAMISTA §6, item 62; Next.js minimum 16.4.5, GHSA-mfr8-8qww-v76h; AGENT.md §4 item 11) — required for
every site below Next.js 16.4.5:**
1. `pnpm add [email protected] [email protected]`, `rm -rf .next`, `pnpm build`; commit `package.json` and the lockfile,
redeploy on Coolify (the new image ships the fixed Next.js).
2. `pnpm ipal:skills` (updated `ipal-setup` / `ipal-upgrade`).
**Check:** `pnpm ls next` → 16.4.6; `pnpm exec ipal-doctor` → no `next-min` finding; `pnpm dev` prints no security warning.
**→ 1.16.2 (PROGRAMISTA §6, item 63; Payload's mongoose and happy-dom advisories; AGENT.md §4 item 12) — required for
every site:**
1. Add to `pnpm.overrides` in `package.json`: `"mongoose@>=8 <8.24.7": "~8.24.10"` (MongoDB sites only) and
`"happy-dom@<21.0.4": "^21.0.4"` (every site). Then `pnpm install`, `pnpm build`; commit `package.json` and the
lockfile, redeploy on Coolify. No data change, no migration.
2. `pnpm ipal:skills` (updated `ipal-setup` / `ipal-upgrade`).
**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.
**→ 1.16.5 (PROGRAMISTA §6, item 67; CHANGELOG 1.16.5; security.md "The `back` link of the 2FA screens") — required with 2FA on:**
1. **Do this in ONE deploy with the upgrade, or the panel is locked for everyone.** Run `pnpm exec ipal-doctor`
before deploying.
`pnpm payload generate:importmap` — the plugin puts `@intecion/ipal-kit/admin#SafeTotpView` in front of the
2FA package's setup and verify views; commit `importMap.js`, `rm -rf .next`, redeploy on Coolify. With the old
import map the build passes and the site starts, but the 2FA screens have no code form (HTTP 200) — nobody can
sign in. Signs: `pnpm exec ipal-doctor` → `import map lacks …SafeTotpView` (run it before deploying); the log
line `[ipal] The admin import map may be out of date` at start; the notice "Two-step verification may not be
available" where the form should be. Fix: the same command, commit, redeploy.
The log line and the notice with a **working** code form mean a false alarm (the `importMap.js` on disk is not
the one the build used — a Dockerfile runner stage, a re-exporting map): sign-in works; set
`twoFactor.importMapCheck: false`.
**Check:** log in with the password only → open `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → enter
the code → you land on `/admin` (not on example.com); a normal login still returns to the page you came from.
No option, env, schema or migration. A project that registered its own 2FA views, or wrote a proxy rule that
strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off).
2. `pnpm ipal:skills`.
**→ 1.16.6 — 2FA setup required (CHANGELOG 1.16.6; PROGRAMISTA §6, item 68; security.md "Setup required") — required with 2FA on:**
**Not a routine patch, although the number is one.** From this version an account without 2FA can only set it up and is
blocked after 72 hours; on Postgres / SQLite a missing migration locks everyone out of the panel. Do not upgrade a live
site without steps 1–3 and a deploy day agreed with the owner. Steps 2, 3 and 5 go in ONE deploy.
1. **Before upgrading a live site:** `pnpm exec ipal-doctor --url <site>` (doctor token) → accounts without 2FA.
Tell the owner: from the upgrade on, such an account can only set 2FA up, and has 72 hours for it; after that
an administrator must reopen setup on the account's page. Have them set it up now, or remove unused accounts.
Make sure at least one administrator (better two) has 2FA set up — otherwise nobody can reopen setup from the panel.
The 72 hours of existing accounts start at the first start after the deploy and are counted once (restarts
and redeploys do not extend them): agree the deploy day with the owner.
2. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`,
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`),
then `pnpm exec ipal-doctor` before deploying.
3. **Postgres/SQLite — required, same deploy, or nobody can log in:** `pnpm payload migrate:create` (adds the
column `totp_setup_from` to the 2FA collection; needed whenever 2FA is on, also with `requireSetup: false`),
commit, and have it applied **when the new container starts**: `prodMigrations` in the database adapter, or the
start command `pnpm payload migrate && pnpm start` (deployment.md §4.3). **Never Coolify's Pre-deployment
command** — it runs in the old container, without the new migration, and the new version then starts without
the column. Without the column every login answers 500, administrators included; the log says
`[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN`. `pnpm exec ipal-doctor` reports
it before the deploy. MongoDB: nothing.
4. An integration that logs in with a password and has no TOTP: give it an API key, or
`twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`. `grep -rn "overrideAccess: false" src`:
a `user` fetched by id is refused for every account now — take it from `payload.auth({ headers })`.
5. `rm -rf .next`, build, redeploy on Coolify. Read the first lines of the log: `[ipal] 2FA: N existing account(s)
without two-step verification…` — pass that number to the owner. The line appears on that first start only.
Postgres/SQLite: if logins answer 500 after the deploy, the migration from step 3 did not run — check that it
is committed and that the container runs migrations at start (deployment.md §4.3), then redeploy.
6. `requireSetup.exempt` must be a plain function returning `true` / `false` (an `async` one stops the start).
A script on an API key is refused by `POST /api/ipal/two-factor/reset` by default — pass
`twoFactor.resetAccess` if that is wanted. A reset ends the account's sessions (it logs in again); after a
suspected compromise change the password too. An SVG favicon has no tab icon on the 2FA screens.
7. Tell the owner what to tell the staff: a new account has 72 hours to set 2FA up, then an administrator must
choose "Reopen setup". Not wanted: `twoFactor.requireSetup: false`, or `{ windowHours: false }`.
**Every administrator is blocked** (all missed the 72 h): security.md "Every administrator is blocked" — a
`pnpm payload run` script that sets `totpSetupFrom` to now for one administrator, or
`requireSetup: { windowHours: false }` + redeploy, set 2FA up, put it back.
**Check:** create a throwaway account → its token gets `403` from `/api/users/me`; in the panel it lands on the
setup screen with "Set up two-step verification by …"; after the code it is in. As an administrator open that
account → "Two-step verification: Set up." and the reset button; delete the account.
## 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
+35 -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
@@ -400,6 +414,25 @@ With R2 (recommended) media live outside the container and survive redeploys and
the container disk → add a Coolify **Persistent Storage** volume for the upload directory (the upload collection's
`staticDir` — by default a folder named after the slug, e.g. `media`; check the absolute path inside the container), otherwise every redeploy deletes them. See storage.md.
### Form files (`forms.attachments`)
Files on forms are e-mailed, not stored — **no volume and no bucket** for them. What the deploy needs:
- **Request size.** The browser posts a form with a file to `/api/ipal/forms/submit` (up to `maxTotalMB`, 10 MB by
default, plus the answers). Coolify's Traefik and Caddy have no body limit by default. An nginx in front needs
`client_max_body_size 12m;`. Cloudflare (proxied) allows 100 MB. Next's Server Action limit does not apply, and
the i18n proxy must keep `/api` out of its matcher (the default one does).
- **Time.** The request stays open while the file uploads and the e-mail is sent. On a slow connection a 10 MB
upload can take over a minute — check the proxy's read timeout (Traefik: `respondingTimeouts.readTimeout` of the
entry point) if visitors on mobile networks report failures. Not measured by the plugin's tests; verify once on
the real server with a throttled upload. The plugin itself gives an upload up after 30 s without a byte and
after 5 minutes in total (`attachments.submit.idleTimeoutMs` / `timeoutMs`), so a dropped connection never
holds a slot.
- **Memory.** A file is held in memory while it is checked and sent (about 2.4 × its size); at most two file
submissions run at once per instance (`attachments.maxConcurrent`).
- **Mail.** Send the test e-mail with the 10 MB file after every change of mail provider
([email.md](./email.md) "Attachments").
### Integrations in the panel
Mail (SMTP/Graph) and Turnstile errors are visible in the panel after deploy: an alert on the dashboard and a banner on
@@ -418,6 +451,7 @@ media in R2 or on a persistent disk.
- [ ] Home page `/` redirects to a locale (`/pl`)
- [ ] Panel `/admin` works, login OK
- [ ] The form sends (test from the panel: Send test)
- [ ] Forms with a File field: the test e-mail with the 10 MB file arrives; a real submission with a file arrives with the attachment
- [ ] Media display — through the app: `curl -sI https://klient.pl/api/media/file/<file>` → 200; media domain: no 403
- [ ] Coolify: health check green, a scheduled backup exists (§4.4, §4.6)
- [ ] Favicon in `<head>` (see seo.md — Google caches it slowly)
+29 -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 |
@@ -665,6 +665,17 @@ Do one item at a time, build, check. Order by importance:
| 55 | **1.15.0** — a production seed runs everything; no design tokens / block library; no site check | `SEED_ONLY` for production seeds (full seed refused, `IPAL_SEED_ALLOW_FULL=1` with the owner's OK); optional tokens.css + the block library (block by block, `migrate:create`); CookieButton above the footer (`avoid={false}`); `pnpm ipal:skills`; `pnpm exec ipal-doctor` (`--url`); new sites with `ipal-kit create` | CHANGELOG 1.15.0, seeding.md, design-tokens.md, block-library.md, doctor.md, project-starter.md |
| 56 | **1.15.1** — a seed in Coolify's Terminal ends with exit 0 and no output (it stopped before Payload started) | `guardSeedExit()` first in every seed script, `seed.summary()` at the end; check `echo $?` after a seed; `pnpm ipal:skills` | CHANGELOG 1.15.1, seeding.md |
| 57 | **1.15.2** — ipal-doctor reports missing routes for a site whose pages live in `app/(site)` (not `(frontend)`), or a `notFoundView.tsx` | nothing to change; remove the temporary `layout-required` silence; two candidates → `layout.frontend` in `ipal-doctor.json`; `pnpm ipal:skills` | CHANGELOG 1.15.2, doctor.md |
| 58 | **1.15.3** — ipal-audit / ipal-doctor report `adminText()` or `{ en, pl }` panel labels as hardcoded Polish text | `pnpm ipal:skills`; remove a temporary `i18n-literals` silence added for such labels; public text is still reported | CHANGELOG 1.15.3, ipal-audit skill |
| 59 | **1.15.4** — a seeded form / layout / global array shows only the last language (whole localized arrays) | nothing to change in the seed; repair: `SEED_UPDATE=1` locally, on production `SEED_ONLY` + `SEED_UPDATE=1` + `IPAL_SEED_ALLOW_PROD_UPDATE=1` after a backup; edited records and global arrays by hand | CHANGELOG 1.15.4, seeding.md |
| 60 | **1.15.5** — a seeded page with a required layout linking to a page or form fails validation ("… > Layout") | nothing to change in the seed; run it again (dry run first); a missing `$form` / `$page` is now an error in the dry run too; a required link cycle: make one link optional | CHANGELOG 1.15.5, seeding.md |
| 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" |
| 67 | **1.16.5 — security** — with 2FA on, `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` sends the user to example.com after the code (and `back=javascript:…` runs script in the panel) | Upgrade and, **in ONE deploy**, `pnpm payload generate:importmap` (adds `@intecion/ipal-kit/admin#SafeTotpView`), commit `importMap.js`, `rm -rf .next`, redeploy on Coolify — with the old map the 2FA screens have no code form and nobody can sign in (run `pnpm exec ipal-doctor` before deploying; the start log says so too); check: the link above ends on `/admin`. `pnpm ipal:skills`. No option, env or migration; off / own rule: `twoFactor.safeBack` | CHANGELOG 1.16.5, security.md "The `back` link of the 2FA screens" |
| 68 | **1.16.6 — 2FA setup required** (not a routine patch: a new default that can lock accounts out) — an account that has not set 2FA up still reads data over the API with its password; or after the upgrade an account "can do nothing" / is blocked | Before upgrading: `ipal-doctor --url` → accounts without 2FA set it up or are removed; one admin (better two) must have 2FA; deploy day agreed with the owner. Then, in ONE deploy: update, `generate:types`, `generate:importmap` (`TwoFactorStatusField`, `TwoFactorAlert`), **Postgres/SQLite: `migrate:create` and the migration applied in the same deploy when the new container starts — `prodMigrations` or `pnpm payload migrate && pnpm start`, never a pre-deployment command (deployment.md §4.3) — (column `totp_setup_from`); without it every login answers 500**, build, redeploy. Existing accounts get 72 h from the first start; blocked later → admin: account page → "Reopen setup". Password-login integrations: API key or `requireSetup.exempt`. `pnpm ipal:skills` | CHANGELOG 1.16.6, security.md "Setup required" |
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`.
@@ -738,9 +749,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).
@@ -787,7 +798,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`**
+337
View File
@@ -0,0 +1,337 @@
# Form attachments — design proposal (revision 2: e-mail only)
> **Status: built.** This is the design record (revision 2, e-mail only). The owner's decisions on §10:
> (1) build the Microsoft Graph large-file upload, (2) the visitor sees an error when the e-mail fails, (3) allow
> legacy `.doc` / `.xls` and refuse macros. What shipped and how to use it: [forms.md](../forms.md) "Files" and
> [email.md](../email.md) "Attachments" — where this record and those pages differ, the pages are right.
> **Request:** `vanstevpl-web/docs/plugin-requests/2026-11-13-candidate-form-attachments.md`.
> **Owner's decision (2026-11-13):** "files are not stored at all. just send on e-mail. up to 10MB, filetypes,
> add security wall."
## 1. Summary
A new opt-in option, `forms.attachments`, adds a **File** field to the form builder. A file a visitor attaches:
1. passes every existing gate and a set of file checks,
2. is held in memory for that one request,
3. is attached to the company notification e-mail through the project's e-mail adapter,
4. is dropped. Nothing is written to disk, a bucket, the database or a Media record. There is no download route.
The submission keeps only **metadata**: file name, type, size, and whether the e-mail was handed to the mail server.
The customer confirmation never carries the file.
Without `forms.attachments` nothing changes: no new block, field, table or route.
```ts
ipalKit({
forms: {
attachments: true, // or { maxSizeMB, maxTotalMB, maxFiles, fileTypes, allowRisky, scan, maxConcurrent }
},
})
```
Not used: form-builder 3.90.2 has its own `upload` block and `submissionUploads` field. Both exist to store files
in an upload collection, so they stay off.
## 2. Transfer
**Forms with a file post to one plugin endpoint that reads the request as a stream.** Text-only forms keep
using the Server Action exactly as today.
- Endpoint: `POST /api/ipal/forms/submit`, registered by the plugin when `attachments` is on (the same way the
cookie-scan endpoints are). **No route file and no `next.config` change in the project.**
- `useBuilderForm` picks the path: a file selected → `multipart/form-data` to the endpoint, text fields first,
files last; no file → the bound Server Action. Both end in the same `submitForm` and return the same result
shape, with the visitor message in the page's language.
- Why not the Server Action for files: Next receives and buffers the whole body before the action runs, so no
gate can act before the file is on the server, and the default body limit is 1 MB. A stream lets the wall in §3
stand in front of the file.
- Why not a separate "upload first" route: there is nothing to upload to. One request carries the answers and
the file; nothing can be referenced later by an ID.
**Body limits for 10 MB, end to end:**
| Layer | Limit | Action |
|---|---|---|
| The endpoint (Payload's `/api` route handler) | none from Next; ours: `maxTotalMB` + 64 KB of fields, enforced while reading | — |
| Next.js Server Actions `bodySizeLimit` (1 MB) | does not apply — files never go through the action | — |
| Next.js proxy buffer `proxyClientMaxBodySize` (10 MB) | does not apply — the standard proxy matcher excludes `/api` | `ipal-doctor` warns when a project's matcher covers `/api/ipal` |
| Coolify's Traefik or Caddy | no body limit by default | to confirm on a real deploy: the read timeout on a slow mobile upload |
| Cloudflare, when proxied | 100 MB | — |
| nginx, if a project adds one | 1 MB | `client_max_body_size 12m` |
A `Content-Length` over the limit is refused before a byte is read; a body that lies about its length is cut off
at the limit.
## 3. The security wall
Every step runs before the next one starts. A failure stops the request; nothing after it runs.
| # | Check | Before any file byte is accepted? |
|---|---|---|
| 1 | Method, same-origin (`Origin` / `Sec-Fetch-Site`), content type | Yes — headers only |
| 2 | **Rate limit** per IP (the existing limiter and bucket) | Yes — headers only |
| 3 | Declared size over the limit → refused | Yes — headers only |
| 4 | Concurrency guard: at most `maxConcurrent` (default 2) file submissions at once per instance; more get "try again in a moment" | Yes |
| 5 | Text fields read (small, capped). **Honeypot** → fake success, connection closed | Yes |
| 6 | **Turnstile** verified | Yes |
| 7 | Form loaded; **field validation and GDPR consent**, as today | Yes |
| 8 | The form has a file field under this key, the field is visible ("Show only when"), and an e-mail can carry it (§5) | Yes |
| 9 | File name: path parts and control characters removed; **double extensions** (`cv.pdf.exe`) and blocked extensions refused; extension must be one of the field's allowed types | Yes — part header only |
| 10 | **Count** per field (`maxFiles`) | Yes |
| 11 | **Size** per file (`maxSizeMB`) and per submission (`maxTotalMB`), counted **while reading**; the read stops at the limit | During the read |
| 12 | **Signature** of the first bytes must match the type the extension claims | On the first chunk |
| 13 | Whole-file checks: container structure, macros, encrypted archives (table below) | After the read, in memory |
| 14 | Optional `scan` hook (antivirus) | After the read |
| 15 | E-mail built and sent; buffers released | — |
A file part that arrives before the text fields, a file under a key that is not a file field, or text under a file
key is refused. The endpoint is not a bypass: it runs the same `submitForm` gates, and REST creation of
submissions stays "logged-in users only".
**Type checks — by content, never by name or browser MIME alone:**
| Type | Check |
|---|---|
| PDF | starts with `%PDF-` |
| DOCX, XLSX, ODT | ZIP signature **and** the archive directory lists the entries that type must have (`[Content_Types].xml` + `word/document.xml` for DOCX). The directory is read without unpacking, so there is no zip-bomb exposure. Refused: a macro project inside (`vbaProject.bin`), an encrypted entry, an executable entry. |
| DOC, XLS | OLE signature `D0 CF 11 E0 A1 B1 1A E1`; refused when the file carries a VBA macro storage (decision 3) |
| RTF, JPG, PNG, WebP | their signatures |
**Refused by default, whatever the field allows:** executables and scripts (`exe, dll, msi, bat, cmd, com, scr,
js, vbs, ps1, sh, jar, apk, app, dmg, lnk, hta` and the like, by extension and by signature: MZ, ELF, Mach-O,
`#!`), macro-enabled Office files (`docm, xlsm, pptm, dotm`), archives (`zip, rar, 7z, tar, gz`), disk images,
HTML and SVG. A project that really needs one states it: `attachments.allowRisky: ['zip']`. A project adds its
own type with `attachments.fileTypes: { dwg: { label, extensions, mimeType, detect } }`.
**Further cheap checks included:**
- The attachment's name is rebuilt, never passed through: the cleaned stem (letters, digits, space, `.-_`, 80
characters) + the extension of the **detected** type; an empty result becomes `attachment-<id>.<ext>`.
- The attachment's content type is set from the detected type, with `Content-Disposition: attachment`.
- An empty file is refused. A password-protected Office file is refused (its container does not match).
- The company e-mail gets one line: "This file came from a public form and was not checked for viruses."
- Optional, off by default: `strictPdf` refuses PDFs that declare JavaScript, launch actions or embedded files
(a byte search; it can miss compressed objects and can refuse a harmless file).
**No antivirus.** The plugin does not scan files for malware. These checks stop the wrong *kind* of file; they do
not prove a PDF or DOC is safe. A project that needs scanning plugs it in:
`attachments.scan: async ({ name, type, size, data }) => ({ ok, reason? })` (ClamAV, a scanning API). A refusal
is reported to the visitor as a file-type error.
New result codes, additive: `reason: 'validation'` with `kind: 'file_too_large' | 'file_type' | 'file_count'`,
and `reason: 'delivery'` (§6).
## 4. E-mail size — the real maximum per path
Base64 adds 37%: a 10 MB file is a 13.7 MB message. `maxTotalMB` (default 10) caps one submission, so one e-mail
never exceeds about 14 MB.
**SMTP** (`panelSmtpAdapter`, nodemailer): attachments already pass through the adapter; no size limit of our own.
The limit is the mail server's, and it counts the encoded message:
| Server limit (typical — check the provider) | Largest file |
|---|---|
| 10 MB (some shared hosting, Postmark) | about 7 MB — **a 10 MB field would fail** |
| 25 MB (Google Workspace, Mailgun) | about 18 MB |
| 35 MB (Microsoft 365 default) | about 25 MB |
The recipient's mailbox has its own limit as well. The values above are from memory, not measured; the build adds
a real test instead of trusting them: **Send test e-mail** in the panel gets "with a 10 MB attachment".
**Microsoft Graph** (`graphAdapter`), checked against Microsoft's documentation on 2026-11-13:
- `sendMail` with the file inline works for attachments **under 3 MB**, with today's `Mail.Send` permission and
`saveToSentItems: false`.
- **3 MB to 150 MB needs an upload session**: create a draft in the sender mailbox, upload the file in chunks,
send the draft. That needs the **`Mail.ReadWrite`** application permission, which lets the app read mailboxes
unless it is scoped to the one sender mailbox. The draft is sent *from the mailbox*, so a copy passes through
Drafts and lands in Sent Items, and must be deleted afterwards. Microsoft lists a known issue with upload
sessions on shared mailboxes, and `GRAPH_SENDER` is one.
- The agency's Azure app **already has `Mail.ReadWrite`** (application, admin consent granted — confirmed by the
owner on 2026-11-13, together with `Mail.Read` and `Mail.Send`). So the upload session needs no Azure change.
- So the real maximum on Graph is under 3 MB with the code as it is, and 10 MB once the upload session is built
(decision 1).
**The limit the visitor sees is the limit that works.** The effective maximum is the lowest of: the field's
`maxSizeMB`, the plugin cap `attachments.maxSizeMB`, and the transport's cap (3 MB on Graph without a large-file
path). The form uses that number for its check and its message, and the panel shows a notice on a form whose
field asks for more than the current e-mail settings can send.
**When the mail provider rejects the message:**
- *At send time* (SMTP `552`/size refusal, Graph `4xx`, timeout, wrong credentials): the adapter reports it, and
§6 applies. The site's e-mail status in the panel turns "degraded", as today.
- *After acceptance* (the recipient's server bounces it, Exchange refuses it after `202 Accepted`): the site
cannot know. The bounce goes to the sender mailbox. The submission therefore says **"Handed to the mail
server"**, never "delivered". The docs say this plainly.
## 5. Which e-mail carries the file
- The file is attached to every e-mail of the form whose **To, CC and BCC are fixed addresses written in the
panel**. An e-mail addressed with a placeholder (`{{email}}`) never gets a file — that is the customer
confirmation, and no setting can change it.
- A form with a file field and no fixed-recipient e-mail cannot deliver anything. The panel refuses to save it:
"Add an e-mail with a fixed recipient. Files are sent by e-mail only." At submit time the same condition
refuses the file before it is read (wall step 8).
- The answers get a text row per file field — `CV Jan Kowalski.pdf (2.1 MB)` — so `{{attachment}}`, `{{*}}`,
`{{*:table}}` and the readable summary of `emailLayout` show a filename in every e-mail, never `[object File]`.
- Mechanics: the files travel in the request context to form-builder's `beforeEmail`. The plugin's hook takes the
file-carrying e-mails out, sends them itself to see the result, and hands the rest back only after success.
`forms.beforeEmail` still runs on all of them. A custom e-mail adapter must support `attachments`.
## 6. Failure handling — the file is lost by design
If the e-mail cannot be sent, the file is gone: there is no copy to retry with. The design makes that visible to
both sides (decision 2):
**The visitor** sees an error, not the confirmation — "We could not send your file. Try again, or send it by
e-mail." (`fileNotSent`, per language) — and keeps their answers and selected file, so one click retries.
The customer confirmation is **not** sent for a failed attempt.
**Staff** get a notification *without* the file, sent once: the answers plus "The visitor attached CV.pdf
(9.8 MB), but it could not be sent. Ask them to send it again." If the mail system is down entirely, that
notice fails too, and the panel is the record.
**The submission** is stored with the answers and:
| Field | Value |
|---|---|
| Files | name, type, size per file |
| File delivery | "Handed to the mail server" / "Not sent" |
| Note | the reason, in plain words ("The mail server refused the message: too large.") |
"Not sent" submissions are marked in the list, so staff can find them and ask again.
**Retries without duplicate e-mails:**
- Each submit carries an **attempt key** from the browser. The key changes only after the server has answered.
A double click, a browser resend or a proxy retry carries the same key: the server answers with the first
result and sends nothing again. The key is stored on the submission, so this holds across instances and restarts.
- The plugin sends each e-mail **once** — no automatic resend, no background queue (there is no file to resend).
- A visitor's retry after "Not sent" is a new attempt: one new submission, one staff e-mail with the file, one
customer confirmation. The failed attempt stays in the panel, marked.
## 7. Builder and renderer
**Panel block `file`** — English and Polish, wording per `admin-ux.md`:
| Field | Type | Default | Label (en / pl) |
|---|---|---|---|
| `name` | text, required | — | Field key / Klucz pola |
| `label` | text, localized | — | Label / Etykieta |
| `help` | text, localized | — | Help text / Tekst pomocy — "Shown under the field, e.g. accepted types and size." |
| `width`, `required` | as other blocks | | |
| `allowedTypes` | select, many | PDF, DOC, DOCX | Allowed file types / `Dozwolone typy plików` |
| `maxSizeMB` | number, 1…cap | 10 | Maximum size (MB) / Maksymalny rozmiar (MB) |
| `maxFiles` | number, 1…cap | 1 | Maximum files / `Maksymalna liczba plików` |
| `showWhen` | as other blocks | | |
Block name: **File / Plik**. `forms.fields.file: false` hides it; `forms.fields.file: <Block>` replaces it;
`fileBlock` is exported. Caps in code: `attachments.maxSizeMB` (10), `maxTotalMB` (10), `maxFiles` (3) — the
editor cannot promise more than the server accepts.
**Types:** `FormsOption.attachments`, `FormsOption.fields.file`; `BuilderField` gains `help`, `allowedTypes`,
`maxSizeMB`, `maxFiles`; `publicForm` passes them to the browser.
**`useBuilderForm`** — a file field's value is `File[]`:
- `getFileProps(field)` → `id`, `name`, `type: 'file'`, `accept`, `multiple`, `required`, `onChange`,
`aria-invalid`, `aria-describedby` (help + error), `ref`.
- `getFiles(field)` → `{ name, size }[]`; `removeFile(field, index)` clears the native input and returns focus to it.
- `helpId(field)`; browser checks for count, size and extension with the server's messages.
- `isSubmitting` is the pending state; the input is cleared on success and kept after an error.
**`BuilderForm` / `RenderForm`** — a native `<input type="file">` with a real `<label>`, the help text, the
selected files in a list (`aria-live="polite"`), and a **Remove** button per file named "Remove {file}". Every
control is native, so keyboard and touch work. New `classNames` keys: `file`, `help`, `fileList`, `fileItem`,
`fileRemove`; `data-type="file"`. Files survive moving between steps. `renderField` and custom markup work as for
any field. `RenderForm` needs no new prop; a hand-built form on the hook gets the endpoint path from the prepared form.
**Visitor texts** — new keys in Form messages, defaults in English and Polish, editable per language in the panel
(that is where DE and NL come from; label and help are localized panel fields):
| Key | English default | Polish default |
|---|---|---|
| `fileTooLarge` | "{file}" is too large. The limit is {max} MB. | `Plik „{file}” jest za duży. Limit to {max} MB.` |
| `fileType` | "{file}" is not an accepted file type. Accepted: {types}. | Plik „{file}” ma niedozwolony typ. Dozwolone: {types}. |
| `fileCount` | Attach at most {max} files in "{field}". | `W polu „{field}” można dodać najwyżej {max} plików.` |
| `fileNotSent` | We could not send your file. Try again, or send it by e-mail. | `Nie udało się wysłać pliku. Spróbuj ponownie lub wyślij go e-mailem.` |
| `fileRemove` | Remove {file} | `Usuń {file}` |
## 8. What the submission keeps, and GDPR
- Kept: the answers (with the filename row), the file metadata, the delivery state and note, the attempt key.
- Not kept: the file. After the response there is no copy on the server, in the database, in a bucket or in a
backup. Memory use is about 2.4 × the file while sending; the concurrency guard bounds it.
- The file then lives in the recipients' mailboxes. Its retention is the company's mailbox policy, not the
site's; the docs say so, for the client's privacy notice.
## 9. Compatibility
- Opt-in. Without `forms.attachments` the generated config is identical to 1.15.5.
- Existing forms, submissions, e-mail templates, `submitForm` calls and hand-written actions keep working; every
API change is an added optional argument, field or union member. Text-only forms never touch the endpoint.
- New dependency: `busboy` (the streaming multipart parser Payload already ships).
- **MongoDB:** no migration.
- **Postgres / SQLite projects that turn it on:** one `pnpm payload migrate:create`. Additive only: the block
tables for `file` (+ locales, + allowed types), the submission's files array table and three columns (delivery,
note, attempt key), the new Form messages columns. No upload collection, so no `_rels` or locked-documents changes.
- After upgrading and enabling: `generate:types`. No import-map change, no env variable, no storage setup.
- Version: a minor release.
## 10. Decisions for the owner
Recommendation first in each.
1. **Sites that send through Microsoft Graph, files of 3 MB and more.**
**Build the Graph upload session**, since the agency app already has `Mail.ReadWrite`: 10 MB works on Graph
with no Azure change. Files under 3 MB keep the inline path. Cost to accept: each larger file passes through
the sender mailbox's Drafts and Sent Items; the plugin deletes the draft on failure and the sent copy after
sending, and a failed clean-up is logged. The build first tests Microsoft's known issue with shared
mailboxes on `GRAPH_SENDER`; if it blocks the upload, the fallback is the alternative below.
— *or* send those e-mails through the SMTP settings in the panel; without SMTP the limit on Graph is 3 MB.
Nothing touches the mailbox, but every Graph site that wants 10 MB needs SMTP set up too.
Separate from this feature, for the agency to consider: the app's permissions cover **all mailboxes** of the
tenant, and its secret sits in every project's environment. Limiting the app to the forms mailbox (an
application access policy in Exchange) would shrink that. Not part of this build.
2. **When the e-mail cannot be sent.**
**The visitor sees an error and can retry; staff get a notice without the file; the submission is marked
"Not sent".** — *or* the visitor sees the normal confirmation and staff must ask again.
3. **Legacy `.doc` (and `.xls`).** The client asked for DOC, but the old format can carry macros and can only be
checked roughly.
**Allow it, refuse files with a macro storage, and say in the docs that this check is best-effort.**
— *or* leave `.doc` out of the default types (PDF and DOCX only); a project can still tick it.
## 11. Build plan after the go-ahead
1. Prove the transfer: a streamed multipart request to a Payload endpoint on the reference site, with the read
cut off at the limit; confirm the proxy matcher and Traefik behaviour.
2. `forms.attachments`, the `file` block, the endpoint, the wall, the type registry and blocklist, the `scan` hook.
3. E-mail: attachments through `mailAdapter` on SMTP and Graph (inline under 3 MB, then decision 1), the
file-carrying rule, the failure notice, delivery state on the submission, the attempt key, the large test e-mail.
4. `useBuilderForm`, `BuilderForm`, `RenderForm`, the new messages.
5. Tests on a real Payload instance. The request's seven acceptance tests, re-read for e-mail only:
(1) text-only submit unchanged · (2) PDF, DOC, DOCX each → one submission with metadata, the file attached to
the staff e-mail, byte-identical, and absent from the customer e-mail · (3) oversized, mismatched,
unsupported, executable, macro, archive, double-extension and extra files, and direct calls to the endpoint →
no submission, no e-mail · (4) consent, Turnstile, honeypot and rate limit with a file → nothing read past the
gate, nothing sent · (5) *replaces the download test:* no route serves a file, nothing is on disk or in the
database after the request, and the endpoint refuses cross-origin calls · (6) retry after a failed send, a
repeated request with the same attempt key, removing a selection → one e-mail, no duplicates, the failed
attempt marked · (7) texts in four languages, keyboard operation, existing form tests still pass.
Plus: SMTP refusal and Graph refusal → "Not sent", the notice e-mail, the visitor error.
6. Docs in the same change: `docs/forms.md`, `docs/email.md`, `docs/security.md`, `docs/storage.md` (one
paragraph: form files are not stored), `docs/deployment.md` (proxy limits), `AGENT.md`, the `ipal-form` and
`ipal-reference` skills, the seed template, CHANGELOG "## Unreleased"; a file field on a reference demo form.
7. Gate: `test:int`, typecheck, lint, build, `build:starter`, `starter:gate`, the reference doctor static run,
the reference smoke tests on a free port. No version bump, push, merge or release.
## 12. To confirm during the build
- A Payload custom endpoint receives the body as an unread stream on Next 16.4.
- Traefik's read timeout in Coolify on a slow 10 MB upload (needs a real deploy).
- The SMTP size limits of the providers our projects use (the large test e-mail measures it).
- On Graph: the exact request size at which inline `sendMail` starts to fail (Microsoft documents "under 3 MB"),
and whether the upload session works on the shared `GRAPH_SENDER` mailbox.
+7 -6
View File
@@ -66,10 +66,10 @@ Added by `ipalKit` and **off until the site has `IPAL_DOCTOR_TOKEN`** (at least
returns counts only — never names, e-mails or values:
```json
{ "node": "v22.20.0", "pendingCookies": 0, "plugin": "1.15.0", "usersWithout2fa": 0 }
{ "node": "v22.20.0", "pendingCookies": 0, "plugin": "1.15.0", "usersSetupClosed": 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`.
@@ -79,8 +79,9 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
|---|---|---|---|
| versions | `plugin-installed` | error | `node_modules` has `@intecion/ipal-kit` and it satisfies `package.json` |
| | `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.1; `eslint-config-next` on the same minor (warning) |
| | `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; 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) |
@@ -88,7 +89,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
| | `layout-forbidden` | error | no `middleware.ts`, no `lib/{pages,locales,navigation}.ts`, `fields/{link,sectionHeader,sectionSettings}.ts` |
| | `layout-extra` | info | `src/` entries outside the allow list (AGENT.md §3 + `seed/`, `design/`, `db.ts`, `env.rules.ts`, `content.config.ts`; extend with `layout.allow`) |
| | `naming` | warning | block folders, collection and global files PascalCase, `scripts/*` kebab-case, no `index.ts` barrels |
| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA, R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one |
| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA incl. `SafeTotpView`, `TwoFactorStatusField`, `TwoFactorAlert`; R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one. Warning: the config uses the 2FA package's own setup / verify view as a view's `Component` (outside the `back` link check — security.md); not for that path as `ipalTotpView` of `SafeTotpView` or in `admin.dependencies` |
| | `tsconfig-skills` | error | `tsconfig.json` excludes the skills folder |
| env | `db-name` | error | `DATABASE_URI` in `.env` and `.env.example` names `<domain without dots>_dev`; a local `.env` on `_prod` is an error; `--env-file` checks `_prod` (`databaseNamesFor`) |
| | `env-rules` | error / warning | `instrumentation.ts` calls `assertEnv(ipalEnvRules(…))` from `/env`, with `storage` (R2), `cookieCrawl` (crawl), `ipHeader`; `databaseName` suggested (info) |
@@ -97,7 +98,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
| security | `security-headers` | error | `buildSecurityHeaders`; live: HSTS, nosniff, Referrer-Policy, Permissions-Policy, frame protection |
| | `powered-by` | error | `withSecurityConfig`; live: no `X-Powered-By` on `/` and the admin |
| | `csp` | warning / info | CSP on the site and the admin; report-only is info, a warning after 4 weeks (`seen`) |
| | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP |
| | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP (the message says how many of them are blocked because their setup window has passed); error: a Postgres / SQLite project whose migrations do not mention the 2FA column `totp_setup_from` (every login would answer 500; a warning when there is no migrations folder — the doctor cannot see a schema that gets there another way); warning: `twoFactor.requireSetup: false`; info: no setup window (`windowHours: false`) |
| | `cookie-scanner` | error / warning / info | `cookieScanner` on (with `crawl`, else info); deep: nothing waits for approval (warning) |
| admin | `admin-meta` | warning | ipal-kit ≥ 1.14.5, no `adminMeta: false` / `agency: false`; live: the admin `og:image` is `/api/ipal/admin-og` |
| | `admin-noindex` | error | (live) the admin login page is noindex |
@@ -110,7 +111,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
| | `blocks-duplicate` | warning | a project block whose `slug` (or `interfaceName`) matches a library block — also a slug renamed through the block's `slug` option — unless it is an override in `createBlockRegistry({ components })` |
| | `blocks-helper-copy` | warning | no local copy of a plugin field builder (`blockLibraryManifest.fieldBuilders`), `ctaHref`, `buildActionButtonsField` |
| | `blocks-tokens` | error / warning | from `ipal-audit`: hex colours, the token standard not wired, `ipal-tokens --check` |
| audit | `i18n-literals` | error / warning | from `ipal-audit`: hardcoded text in blocks (error) and components (warning), Polish literals in code |
| audit | `i18n-literals` | error / warning | from `ipal-audit`: hardcoded text in blocks (error) and components (warning), Polish literals in code (not the panel's `adminText()` / `{ en, pl }` labels in a schema file — the `ipal-audit` skill) |
| | `audit:<title>` | as reported | every other `ipal-audit --quick` finding, one per file |
| live | `live-reachable`, `live-health`, `live-noindex`, `live-seo` | error / warning | the URL answers; `/api/health` 200; production not noindex (staging must be); every `ipal-seo-check` error and warning |
| deep | `deep-status` | error | the deep check could not finish |
+82 -8
View File
@@ -139,8 +139,9 @@ [email protected] # one mailbox for all projects
(no name → the `from` field is omitted, Graph uses the mailbox's default name),
- `smtpFromAddress` → **Reply-To** (unless the message has its own `replyTo`).
Options `graphAdapter({ fallbackFromAddress, fallbackFromName })` — only placeholders
Payload requires at startup.
Options `graphAdapter({ fallbackFromAddress, fallbackFromName, largeAttachments, cleanupDelaysMs })` —
the first two are placeholders Payload requires at startup; the other two are for attachments ("Attachments" below).
`fetchImpl` is for tests.
### Wiring — choosing the transport (recommended: `mailAdapter`)
@@ -188,9 +189,80 @@ email: process.env.GRAPH_CLIENT_ID ? graphAdapter() : panelSmtpAdapter()
The adapter does **not** send from the address in the panel — From is always the `GRAPH_SENDER` address
(only the display name changes), and `smtpFromAddress` from the panel goes into
Reply-To. So Exchange does not need Send-As on other domains; replies go
to the client's address. The OAuth token is fetched on every send (no cache),
to the client's address. The OAuth token is cached in the process until a minute before it expires,
`saveToSentItems: false`.
## Attachments
`payload.sendEmail({ …, attachments: [{ filename, content: Buffer, contentType }] })` works on both transports
(nodemailer's shape). Form files use it: a file a visitor attaches is e-mailed and never stored
([forms.md](./forms.md) "Files"). Base64 adds 37 %: a 10 MB file is a 13.7 MB message.
### SMTP
The adapter passes attachments straight to nodemailer; the plugin sets no limit. The limit is the **mail server's**,
and it counts the encoded message: a server limit of 10 MB carries about a 7 MB file, 25 MB about 18 MB, 35 MB
about 25 MB. The recipient's mailbox has its own limit too. Do not trust a table — **measure**: Site integrations →
E-mail sending → **Test e-mail** with **Attach a 10 MB test file** ticked (endpoint: `POST /api/ipal/test-email`,
body `{ to, attachmentMB }`, 1–25). A server that refuses the size answers at send time (`552 …`); the adapter
reports `{ sent: false, detail }`.
### Microsoft Graph
| Attachments in one message | How it is sent | Permission | Left in the mailbox |
|---|---|---|---|
| under 3,000,000 bytes in total | inside the one `sendMail` call | `Mail.Send` | nothing (`saveToSentItems: false`) |
| more | a **draft** is created in the sender mailbox, files are added (an **upload session** for files of 3 MiB and more, in pieces of 3.2 MB), the draft is sent | `Mail.ReadWrite` | a copy passes through Drafts and Sent Items; **the plugin deletes it** |
The large path, step by step, and what happens when it fails:
- Any failure before the send (creating the draft, an upload, the send call) → the draft is deleted at once and the
result is `{ sent: false, code: 'graph-error' }`. Nothing with the file stays in the mailbox.
- After a successful send the copy in Sent Items is deleted: the plugin looks at the message after 2 s, 5 s, 15 s and
60 s (`cleanupDelaysMs`), and deletes it once it has left Drafts — never earlier, so the send is not cancelled.
It uses `permanentDelete`, and a plain delete when that is not available. If the copy could not be removed, the
server log says `delete it by hand (it holds a form file)`.
- The app's token lacks `Mail.ReadWrite` → nothing is created; the result is `code: 'graph-permission'` and the
log names the permission. With `mailAdapter()`:
- the panel has SMTP settings → the message goes **over SMTP** instead;
- no SMTP settings → the send fails, and the form's file limit drops to about 2.8 MB so visitors are not offered
more than can be sent; the panel shows "Microsoft Graph cannot send files of 3 MB and more here…".
- **Turn it off:** `mailAdapter({ graph: { largeAttachments: false } })` (or `graphAdapter({ largeAttachments: false })`)
— Graph keeps to small attachments; larger ones go over SMTP when the panel has SMTP settings, else the limit
is about 2.8 MB.
- `mailAttachmentLimit(payload)` (root) → the ceiling in bytes the current transport can carry, or `null`.
#### Azure / Exchange steps for large attachments (one-time, outside the code)
1. **Azure portal → App registrations → the app → API permissions → Add → Microsoft Graph → Application
permissions → `Mail.ReadWrite` → Grant admin consent.** Keep `Mail.Send`. `Mail.Read` is not used by the
plugin — remove it if nothing else needs it.
2. **Limit the app to the forms mailbox.** Application permissions cover *every* mailbox of the tenant, and the
app's secret sits in the environment of every project. In Exchange Online PowerShell:
```powershell
# a mail-enabled security group that holds only the sender mailbox
New-DistributionGroup -Name "ipal-forms-mailbox" -Type Security -Members forms@intecion.pl
New-ApplicationAccessPolicy -AppId <GRAPH_CLIENT_ID> -PolicyScopeGroupId ipal-forms-mailbox `
-AccessRight RestrictAccess -Description "ipal-kit: only the forms mailbox"
Test-ApplicationAccessPolicy -AppId <GRAPH_CLIENT_ID> -Identity forms@intecion.pl # AccessCheckResult: Granted
Test-ApplicationAccessPolicy -AppId <GRAPH_CLIENT_ID> -Identity someone.else@intecion.pl # AccessCheckResult: Denied
```
A new policy can take up to an hour to apply. (Microsoft is moving this to "RBAC for Applications" in
Exchange Online; a management scope limited to the same mailbox does the same job.)
3. Nothing changes in the project: the same four `GRAPH_*` variables.
**Verify on the real tenant** (the plugin's tests run against a mocked Graph — no test touched a real mailbox):
- [ ] Test e-mail with the 10 MB file, transport = Microsoft Graph → arrives with the file intact.
- [ ] After a minute, **Drafts and Sent Items of the sender mailbox do not contain the message** (also check
Deleted Items and Recoverable Items — whether `permanentDelete` is honoured on your tenant).
- [ ] `GRAPH_SENDER` is a **shared mailbox**: Microsoft lists a known issue with upload sessions on shared
mailboxes. If the test fails with an access or "item not found" error, use `largeAttachments: false`
(large files then go over SMTP) and report it.
- [ ] With the access policy in place, the send still works, and `Test-ApplicationAccessPolicy` denies other mailboxes.
- [ ] A file of 2.9–3.1 MB (both sides of the switch) arrives.
- [ ] Server log after a send: no `delete it by hand`.
## Transport switch — mailAdapter
`mailAdapter()` is a dispatcher: one adapter wired in the config, it picks the transport
@@ -204,15 +276,16 @@ 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).
## Test send — button in the panel
The E-mail sending tab has a **Send test** button: enter an address, click, and a test
mail goes out through the CURRENT transport (`payload.sendEmail`). It shows the result (✓/✗ with the error). Endpoint
`POST /api/ipal/test-email`, body `{ to }` (`admin` role only — needs roles from the `access` option:
mail goes out through the CURRENT transport (`payload.sendEmail`). It shows the result (✓/✗ with the error).
Tick **Attach a 10 MB test file** to check that the mail server takes a file of that size ("Attachments" above). Endpoint
`POST /api/ipal/test-email`, body `{ to, attachmentMB? }` (`admin` role only — needs roles from the `access` option:
not logged in → 401, other role → 403, bad address → 400, failed send → 502).
Save your changes before the test — the endpoint reads from the database, not from the field on screen.
@@ -226,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.
@@ -246,6 +319,7 @@ send (e.g. **Send test**) the current one appears.
- **Choosing the transport:** `mailAdapter()` (the panel decides) or a fixed `panelSmtpAdapter()` /
`graphAdapter()`; any other Payload adapter (e.g. `@payloadcms/email-nodemailer`) also works —
then you skip the panel SMTP and the send status.
- **Override:** `fallbackFromAddress` / `fallbackFromName`, in `mailAdapter` separately `smtp` and `graph`.
- **Override:** `fallbackFromAddress` / `fallbackFromName`, in `mailAdapter` separately `smtp` and `graph`
(`graph.largeAttachments: false` keeps Graph to attachments under 3 MB — "Attachments").
- **Extend:** form mail content is modified by `forms.beforeEmail` (see [forms.md](./forms.md));
your own mail — `sendEmail` (SMTP) or `payload.sendEmail` (through the wired adapter).
+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.
+205 -9
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`)
@@ -54,6 +54,7 @@ ipalKit({
| Option | Default | Description |
|---|---|---|
| `adminGroup` | `'Forms'` | group in the panel; `false` = Payload's default; `admin.group` in overrides wins |
| `attachments` | `false` | files on forms: adds the **File** field; a file is checked, e-mailed to the company and dropped — never stored ("Files" below) |
| `fields` | see below | builder field types; `false` turns a type off, an object (block) replaces it; `true` = the default ipal block |
| `redirectRelationships` | — | collections a form can redirect to |
| `formOverrides` / `formSubmissionOverrides` | — | collection overrides (`fields` as a function + any collection settings) |
@@ -87,7 +88,7 @@ import { RenderForm } from '@intecion/ipal-kit/rsc'
the plugin has no styles at all. Keys: `form, progress, step, stepTitle, stepDescription, fields,
field, fieldHalf, fieldFull, label, input, textarea, select, checkbox, checkboxLabel, choices,
legend, choice, choiceInput, choiceLabel, message, error, formError, turnstile, actions, back,
next, submit, success, required, fixed`. For CSS there are also `data-ipal="form"`, `data-type`, `data-width`, `data-step`.
next, submit, success, required, fixed, file, help, fileList, fileItem, fileRemove`. For CSS there are also `data-ipal="form"`, `data-type`, `data-width`, `data-step`.
- options: `requiredMark` (e.g. `" *"`), `converters` / `richTextClassName` (rich text looks),
`linkOptions` (`await getLinkOptions(locale)` — redirect to a page from the panel), `turnstileTheme`
(default `'page'`), `values` (below).
@@ -99,7 +100,8 @@ a hand-written `<FormRenderer form={form}>` used to send them in the HTML. Under
### Field types in the panel
text, email, textarea, number, **date**, **time** (1.11.1), select, **radio**, checkbox, **Checkbox group**,
message, **Step** (+ country/state as text). Turning a type off: `forms.fields: { date: false }`.
message, **Step** (+ country/state as text), and **File** when `forms.attachments` is on ("Files" below).
Turning a type off: `forms.fields: { date: false }`.
**Placeholder** (1.11.1): text, email, textarea and number have a localized "Placeholder" field — a hint
in the empty field ("e.g. 10:00–12:00"). `BuilderForm` and `useBuilderForm` (`getInputProps`, `getTextareaProps`)
@@ -112,6 +114,7 @@ the time block: `timeBlock`. New fields in form blocks = a migration (`pnpm payl
| Checkbox group | `string[]` (stored as "www, seo") | only values from the panel, no duplicates, `minSelected`/`maxSelected` |
| date | `YYYY-MM-DD` | a real date |
| time | `HH:MM` (`<input type="time">`) | a time 00:00–23:59 |
| File | files (never a text value) | field, count, size, type by content — "Files" below |
| Step | — (split) | not a field |
### Multi-step form
@@ -174,12 +177,201 @@ pass the raw form document to the browser.
`stepIndex`, `total`, `isFirst/isLast`, `next()`, `back()`, `goTo(i)`, `submit`, `values`,
`errors`, `errorMessage`, `isSubmitting`, `isSuccess`, `resultMessage`, `isFixed`, `getFieldProps`,
`getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`,
`TurnstileWidget`. Example: `ipal-form/resources/CustomForm.example.tsx`.
`TurnstileWidget`; for a File field `getFileProps`, `getFiles`, `removeFile`, `helpId`. Example: `ipal-form/resources/CustomForm.example.tsx`.
3. Pure logic (also on the server / in tests): `splitSteps`, `initialBuilderValues`,
`validateBuilderFields`, `stepOfField`, `inputFields`, `visibleFields`, `autoCompleteFor` (autocomplete hint from the field's type and name).
`validateBuilderFields`, `stepOfField`, `inputFields`, `visibleFields`, `autoCompleteFor` (autocomplete hint from the field's type and name),
`fileFieldRules`, `fileFieldError`, `formatFileSize` (File field).
`useOptionalTurnstile()` — like `useTurnstile`, but without a provider it returns `enabled: false` instead of throwing.
## Files — sent by e-mail, never stored (`attachments`)
A visitor attaches a file (a CV, a specification); the company gets it **as an attachment of the notification
e-mail**. The site does not keep it: no upload collection, no bucket, no disk, no download route. The submission
records only the file's name, type and size and whether the mail server took the message.
### Set up
```ts
// payload.config.ts
ipalKit({ forms: { attachments: true } }) // adds the File field to the form builder
```
1. Turn the option on (above). Postgres / SQLite projects: `pnpm payload migrate:create` (new block and submission
columns). MongoDB: nothing. Then `pnpm generate:types`.
2. In the panel (or the form seed) add a **File** field to the form: field key, label, help text, required, allowed
file types, maximum size (MB), maximum files, "Show only when".
3. The form needs an e-mail whose **To / CC / BCC are fixed addresses** (Forms → the form → E-mails) — that e-mail
carries the file. The panel refuses to save a form with a File field and no such e-mail.
4. Nothing else: `RenderForm` / `BuilderForm` render the field, and the plugin registers the endpoint the browser
posts files to (`POST /api/ipal/forms/submit`). No route file, no `next.config` change, no env variable.
5. Check that your mail server takes the size: **Site integrations → E-mail sending → Test e-mail** with
"Attach a 10 MB test file" ticked ([email.md](./email.md) "Attachments").
**Verify:** submit the form with a PDF → the confirmation shows; the company e-mail has the file attached and the
line "…was not checked for viruses"; the confirmation e-mail to the visitor has no file; Form Submissions shows
**Files** (name, type, size) and **File delivery: Handed to the mail server**. Rename a `.exe` to `.pdf` and submit →
the File field shows "The file … was refused: …", nothing is stored or sent.
### Options (`FormAttachmentsOption`)
| Option | Default | Description |
|---|---|---|
| `maxSizeMB` | `10` | ceiling for a field's "Maximum size (MB)" — the editor cannot set more |
| `maxTotalMB` | = `maxSizeMB` | ceiling for all files of one submission together (= one e-mail) |
| `maxFiles` | `3` | ceiling for a field's "Maximum files" |
| `fileTypes` | built-in | add a type (`{ dwg: { label, extensions, mimeType, detect } }`), replace one, or remove one (`{ rtf: false }`) |
| `allowRisky` | `[]` | extensions from the refused list this project accepts after all, e.g. `['zip']` (the type must also exist in `fileTypes`) |
| `scan` | — | antivirus hook: `async ({ name, type, size, data, field }) => ({ ok })` — `ok: false` (or a throw) refuses the file |
| `strictPdf` | `false` | refuse PDFs that declare JavaScript, launch actions or embedded files (a byte search) |
| `notice` | built-in text | the "not checked for viruses" line in the e-mail: `false` = none, a string or `(locale) => string` = your own |
| `maxConcurrent` | `2` | file submissions handled at once per instance (each holds its files in memory); more get the "too many attempts" message; `0` = no guard |
| `path` | `'/ipal/forms/submit'` | endpoint path under the API route |
| `submit` | `{}` | the endpoint's gates, same meaning as in `createSubmitAction`: `maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`; `allowedOrigins` (other origins allowed to post, e.g. a front end on another domain); `idleTimeoutMs` (default `30000`: no byte of the upload for this long → the request is given up, `0` = off) and `timeoutMs` (default `300000`: ceiling for the whole request, `0` = off) |
Built-in types (`FORM_FILE_TYPES`): PDF, DOC, DOCX, ODT, RTF, XLS, XLSX, JPG, PNG, WebP. A new field has PDF, DOC and
DOCX ticked.
### The security wall — in this order
Each step runs before the next; a failure ends the request and nothing after it happens.
1. Same origin (`Origin` / `Sec-Fetch-Site`), `multipart/form-data`.
2. **Rate limit** per IP — from the headers, before any of the body is read.
3. A request that declares a body over the limit is refused unread.
4. Concurrency guard (`maxConcurrent`).
5. The answers are read (they come first in the request): **honeypot** → fake success; **Turnstile**; **field
validation and GDPR consent** — exactly the checks of a text-only form.
6. The form has a visible File field under that key, and an e-mail that can carry a file.
7. Per file, before its bytes: **count**, then the **name** — the last extension must be one of the field's types;
a refused extension anywhere in the name (`cv.pdf.exe`, `cv.exe.pdf`) or a second known extension
(`cv.pdf.docx`) is refused.
8. **Size** is counted while the file is read (per file and per submission); the read stops keeping data at the limit.
9. **Signature** of the first bytes must match the type the extension claims; programs (Windows, Linux, macOS,
`#!` scripts) are refused under any name.
10. Whole-file checks: DOCX / XLSX / ODT must be a ZIP whose directory lists the entries that type requires
(read without unpacking — no zip-bomb exposure), with no macro project, no encrypted entry and no program
inside; DOC / XLS must not carry a VBA macro storage.
11. `scan`, when the project provides one.
12. The e-mail is sent, the buffers are released.
**An upload that breaks off, stalls or never ends** is given up at once: the connection dropped (400), no byte
arrived for `submit.idleTimeoutMs` (408), the whole request ran past `submit.timeoutMs` (408), or a body without a
declared length went over the ceiling (413 — the read stops there). On every way out the endpoint lets go of what
it held: the buffered bytes, its slot in the concurrency guard and the attempt key, so the next upload — and the
browser's retry — work.
**Refused by default whatever the field allows** (`RISKY_FILE_EXTENSIONS`): programs and scripts (`exe`, `dll`,
`msi`, `bat`, `js`, `ps1`, `sh`, `jar`…), macro-enabled Office files (`docm`, `xlsm`, `pptm`…), archives and disk
images (`zip`, `rar`, `7z`, `iso`…), HTML, SVG and XML.
**What this is not.** It is **not an antivirus**. The checks stop the wrong *kind* of file; they cannot tell a
harmful PDF or DOC from a harmless one. The macro check for legacy `.doc` / `.xls` is **best-effort**: it finds
ordinary macro-enabled documents, not one built to hide. Need scanning → plug a scanner into `scan`. The e-mail
says so to the recipient ("This file came from a public form and was not checked for viruses.").
The attachment's name is rebuilt, never passed through: no path, no control or bidi characters, at most 80
characters, the extension of the detected type (`CV Jan Kowalski.pdf`; an empty name becomes `attachment.pdf`).
### Limits
- The limit a visitor sees and the server enforces is the lowest of: the field's value, `attachments.maxSizeMB`,
and what the e-mail transport can carry. On Microsoft Graph without the large-file path and without SMTP
settings that is about 2.8 MB ([email.md](./email.md) "Attachments"). The form document read through Payload
carries the result per File field in `resolved` (`maxSizeMB`, `maxTotalMB`, `maxFiles`, `accept`, `extensions`,
`typeLabels`) and `fileSubmitUrl` — `RenderForm` passes them on; nothing to wire.
- **Request size:** files do not go through the Server Action, so `serverActions.bodySizeLimit` (1 MB by default)
does not apply. The proxy from `createProxy` does not match `/api` (its buffer limit of 10 MB would otherwise
apply — keep `/api` out of your matcher). Coolify's Traefik has no body limit by default; an nginx in front
needs `client_max_body_size 12m`. [deployment.md](./deployment.md) "Form files".
- Memory: a file is held in memory while it is checked and sent (about 2.4 × its size during the send); nothing
touches the disk.
### E-mails
- The file is attached to **every e-mail of the form whose To, CC and BCC are fixed addresses from the panel**.
An e-mail addressed with a placeholder (`{{email}}` — the confirmation to the visitor) **never** gets it.
- The answers get a text row per File field — `CV Jan Kowalski.pdf (2.1 MB)` — so `{{attachment}}`, `{{*}}`,
`{{*:table}}` and the readable summary of `emailLayout` show the file name in every e-mail.
- `forms.beforeEmail` still runs on every e-mail (before the files are attached). A custom e-mail adapter must
support `attachments` (nodemailer's shape); `mailAdapter()` does on both transports.
### When the e-mail cannot be sent
The file is not kept, so there is nothing to retry with. Then:
- the **visitor** sees an error **at the File field** — Form messages → **File not sent** ("We could not send the
file "cv.pdf". Choose a smaller file or another format and try again.") — keeps their answers and the selected
file, and can try again. The mail server's own words never reach the visitor. No confirmation e-mail goes out;
- **staff** get the notification once more **without** the file: "The visitor attached a file: … but it could not
be sent. Ask them to send it again.";
- the **submission** is stored and marked **File delivery: Not sent**, with a note (the mail server's reason). The
Form Submissions list shows the "File delivery" column.
"Handed to the mail server" means the mail server accepted the message. A later bounce (the recipient's server
refuses it) cannot be seen by the site; it arrives in the sender mailbox.
**No duplicates:** each submit carries an attempt key from the browser; a repeated request with the same key
(double click, a resend by the browser or a proxy) gets the first answer and sends nothing again. The plugin sends
each e-mail once — there is no automatic resend.
### What the visitor is told
**When a submission fails because of the file, the message says it is the file, why, and what to do** — and it
shows at the File field (the result carries `field`). Everything the visitor typed stays in the form.
| Problem | Code | Text (Form messages → Files) | English default |
|---|---|---|---|
| too large | `kind: 'file_too_large'` (`file`, `max`) | `fileTooLarge` | The file "cv.pdf" is too large. Choose a file of up to 10 MB. |
| a format the field does not take | `kind: 'file_type'` (`file`, `types`) | `fileType` | The file "cv.txt" is in a format we do not accept. Choose one of: PDF, DOC, DOCX. |
| refused: a program, an archive, macros, a doubled extension, content that does not match the type, the scanner said no | `kind: 'file_refused'` (`file`, `types`) | `fileRefused` | The file "cv.docx" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file (PDF, DOC, DOCX). |
| too many files | `kind: 'file_count'` (`max`) | `fileCount` | Too many files in "Attachment". Remove some: the limit is 1. |
| the e-mail with the file could not be sent | `reason: 'delivery'` (`field`, `file`) | `fileNotSent` | We could not send the file "cv.pdf". Choose a smaller file or another format and try again. |
- On a File field that is **not required**, every one of these ends with `fileOptional` — "You can also send the
form without the file." (the result carries `optional: true`).
- A required File field left empty is `kind: 'required'` → the ordinary field text ("Check the field …").
- A failure that is **not** about the file keeps its own text: consent, a field error, the rate limit, the
general error.
- The texts are in the panel like every form message: Form messages → **Files**, per language, with English and
Polish defaults — fill the other languages of the site ([notifications.md](./notifications.md)). The browser
shows the size, format and count messages before anything is sent; the server answers with the same texts.
### Your own markup
`BuilderForm` renders a native `<input type="file">` with its label, the help text, the list of selected files
(`aria-live`) and a "Remove {file}" button per file. On `useBuilderForm`:
```tsx
const props = f.getFileProps(field) // id, name, type, accept, multiple, onChange, ref, aria-*
<label htmlFor={props.id}>{field.label}</label>
<input {...props} />
{field.help ? <p id={f.helpId(field)}>{field.help}</p> : null}
{f.getFiles(field).map((file, i) => (
<button key={file.name} onClick={() => f.removeFile(field, i)} type="button">Remove {file.name} ({formatFileSize(file.size)})</button>
))}
```
`fileFieldRules(field)` gives the limits in the browser, `fileFieldError(field, files, texts)` the first problem as
the visitor's message. `isSubmitting` is the pending state (there is no upload percentage).
### Your own transfer path
`submitForm({ data, files })` takes files as whole buffers (`{ [fieldKey]: [{ name, data }] }`) and runs the same
checks and the same delivery — for an action or route that receives files itself. `splitFormFiles(values)`
(`/server`) splits `File` values from the answers; `createSubmitAction` already does it, so a hand-built form may
pass `File`s through the action (then raise `experimental.serverActions.bodySizeLimit` in `next.config.ts`).
`mailAttachmentLimit(payload)` returns the transport's ceiling in bytes (or `null`).
### Turn off, override, extend
- Off: leave `attachments` out. Only the block: `forms.fields: { file: false }`. Your own block:
`forms.fields: { file: buildFileBlock({ maxSizeMB: 5 }) }` (`fileBlock` = the default one).
- The endpoint's gates and path: `attachments.submit`, `attachments.path`; the browser can post elsewhere with
`BuilderForm fileSubmitUrl`.
- Submission fields (`submissionFiles`, `filesDelivery`, `filesDeliveryNote`, `attemptKey`) are appended to the
default fields — change them in `formSubmissionOverrides.fields`.
## Front end — submitForm (server)
Call it in a Server Action. The shape matches `useForm` / `useContactForm` 1:1
@@ -216,7 +408,7 @@ const f = useForm({ initialValues, validate, submitAction: sendForm.bind(null, f
```
`submitForm` result: `{ success: true, submissionId }` or `{ success: false, reason, … }`
(codes below). Options: `payload`, `formId`, `data` (required), `ip`, `locale`, `turnstileToken`,
(codes below). Options: `payload`, `formId`, `data` (required), `files`, `attemptKey` ("Files" above), `ip`, `locale`, `turnstileToken`,
`maxPerMinute` (default 5, `0` turns it off; without `ip` — the shared `unknown-ip` bucket, below),
`consentFieldName` (default from `ipalKit({ forms })`, then `'consent'`), `turnstileOnConfigError`
(`'allow'` | `'reject'`, default `'allow'`), `turnstileHostnames` (see [turnstile.md](./turnstile.md)).
@@ -343,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),
@@ -386,7 +581,8 @@ 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' }
| { 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 }
| { success: false; reason: 'error' }
@@ -638,7 +834,7 @@ filter it out on the client.
## Turn off, override, extend
- **Turn off:** without the `forms` option the plugin does not wire the form-builder (no Forms / Form Submissions collections).
Single field types: `forms.fields.<type>: false`.
Single field types: `forms.fields.<type>: false`. Files: `forms.attachments` is off unless you set it ("Files").
- **Override the collections:** `formOverrides` / `formSubmissionOverrides` — fields (the `fields` function), `labels`,
`admin`, `access`, `hooks`. The default submissions access (`create`: logged-in users, `read`: editor+, `delete`: admin)
is overridden by keys in `formSubmissionOverrides.access`; forms access (`create`/`update`/`delete`:
+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 |
+27 -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
@@ -57,14 +57,36 @@ if (!result.success) {
This replaces a hardcoded `Error: ${result.reason}` — now a friendly text from the panel,
per language.
## File field texts
With `forms.attachments` ([forms.md](./forms.md) "Files") the **Files** group of Form messages holds:
Each one tells the visitor that the problem is the file, why, and what to do next.
| Key | Placeholders | English default |
|---|---|---|
| `fileTooLarge` | `{file}`, `{max}` (MB) | `The file "{file}" is too large. Choose a file of up to {max} MB.` |
| `fileType` | `{file}`, `{types}` | `The file "{file}" is in a format we do not accept. Choose one of: {types}.` |
| `fileRefused` | `{file}`, `{types}` | `The file "{file}" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file ({types}).` |
| `fileCount` | `{field}`, `{max}` | `Too many files in "{field}". Remove some: the limit is {max}.` |
| `fileNotSent` | `{file}` | `We could not send the file "{file}". Choose a smaller file or another format and try again.` |
| `fileOptional` | — | `You can also send the form without the file.` — added to the five above when the File field is not required |
| `fileRemove` | `{file}` | `Remove {file}` |
Polish defaults ship too; any other language is filled in the panel (an empty field falls back to English there).
`resolveFormMessage` maps `kind: 'file_too_large' | 'file_type' | 'file_refused' | 'file_count'` and
`reason: 'delivery'` to them and appends `fileOptional` when the result says `optional`; a texts object without
these keys falls back to `validation` / `error`. The result carries `field`, so the message shows at the File field.
## {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
+426 -8
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,235 @@ 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`). An account that has **not set TOTP up yet** is refused as well ("Setup required" below; the
package alone lets it through). Everything else is refused, including a user object the check does not recognise. Accounts of other auth
collections, anonymous visitors, bearer-token routes (`/api/ipal/doctor`, the cookie-crawl callback, MCP) and
the Local API with `overrideAccess: true` (the default) are not affected.
### Setup required (`twoFactor.requireSetup`, on by default)
An account that has **not set TOTP up yet** reaches nothing at the access level — REST, GraphQL, the panel's
data, the plugin's endpoints — until it has. It gets the setup screen and `POST /api/setup-totp`, and what
Payload gives any logged-in session about itself (`/api/access`, token refresh, logout, its own panel
preferences), nothing else.
The 2FA package alone only redirects such an account inside the panel; over the API its password would open
everything its role allows.
**The setup window.** An account has **72 hours** to set TOTP up, counted from its creation or from the last
reset by an administrator. After that it is **blocked**: setup is refused too, until an administrator reopens
it. Without the window, whoever learns the password of an account that never set TOTP up could enrol their own
authenticator at any time; with it, that is possible only in the first days of the account.
| Situation | What happens |
|---|---|
| New account (also the first admin of a fresh site) | logs in → setup screen with the notice "Set up two-step verification by <date>…" → after the code, the panel |
| Not set up within the window | login still works, every request answers 403, the setup screen says the time has passed and to ask an administrator |
| Administrator reopens setup / resets a lost phone | the account's page in the panel → **Two-step verification** (sidebar) → "Reopen setup" / "Reset two-step verification"; or `POST /api/ipal/two-factor/reset` with `{ "userId": "…" }`. A new window starts |
| Administrators' overview | a notice on the dashboard: accounts without two-step verification, and how many of them are blocked; `ipal-doctor --url` reports the same as an error |
| API key (`auth.useAPIKey`) | passes, whatever the setup state |
| Seeds, scripts, the Local API with `overrideAccess` (the default) | not affected |
| Bearer-token routes (`/api/ipal/doctor`, the cookie-crawl callback), MCP | not affected (no user) |
| `twoFactor: false` | none of this exists |
**Accounts that existed before this mode** (an upgrade): their window starts at the **first start of the site
after the upgrade**, not at their creation date, so nobody is blocked the moment a site upgrades. The server log
says how many there are: `[ipal] 2FA: N existing account(s) without two-step verification. They have 72 h from
now to set it up…`. From that moment they can only set TOTP up; after 72 hours they are blocked until an
administrator reopens setup. **Before upgrading a live site, run `pnpm exec ipal-doctor --url <site>`** (accounts
without 2FA) and have those accounts set TOTP up, or remove the ones nobody uses.
That starting moment is **written once**, on each such account (`totpSetupFrom`), by the start that first finds
the account without one. Later starts, redeploys and further instances find nothing left to do (the log line
appears on that first start only), and editing the account or logging in does not move it — so a redeploy never
hands out another 72 hours. Only an administrator's reset / "Reopen setup" opens a new window. An existing
account that **has** TOTP gets no start; if its TOTP is removed later, its window starts then. On Postgres /
SQLite the migration that adds the column must run in the same deploy (see "Data" below) — the first start
after it is the one that counts.
```ts
twoFactor: {
issuer: 'Company Name',
plugin: payloadTotp,
// requireSetup: { windowHours: 24 }, // another window
// requireSetup: { windowHours: false }, // no time limit (0 works too): locked until set up, never blocked
// requireSetup: { exempt: ({ user }) => user.email === 'integration@example.com' }, // a service account that logs in with a password, on purpose
// requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }, // each panel part can be switched off; the lock stays
// requireSetup: false, // the 2FA package's rule: redirect in the panel, API open until setup
// who may reset / reopen. Default: a staff admin whose session entered its own TOTP code. Your function replaces
// that rule, so keep the code check in it unless you mean to let API-key / exempt admins reset:
// resetAccess: ({ req }) => req.user?._strategy === 'totp' && isAdmin(req.user, req.payload),
}
```
- **Data.** The 2FA collection gets a date field `totpSetupFrom` (hidden, written by the plugin only) **whenever
2FA is on** — also with `requireSetup: false` or `guard: false`, so that switching the mode does not change the
schema — and, with the mode on, a panel-only field `totpSetupStatus`. MongoDB: nothing to do.
**Postgres / SQLite: the migration is a required step of the same deploy.** Run `pnpm payload migrate:create`, commit the migration, and
have it applied **when the new container starts** — `prodMigrations` in the database adapter, or the start command `pnpm payload migrate && pnpm start` ([deployment.md §4.3](./deployment.md#43-database-migrations-postgres)). **Not Coolify's Pre-deployment command:** it runs in the old container, which does not have the new migration, so the new version would start without the column.
Without the column every query on the 2FA collection fails: **every login answers 500 —
administrators with 2FA included — and nobody can sign in to the panel** (the public site keeps working). The
log says `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN …` at start;
`ipal-doctor` reports a SQL project whose migrations do not mention `totp_setup_from` (error; a warning when
there is no migrations folder at all — it cannot see a schema that is pushed some other way). Recovery: run
the migration; no data is lost.
- **`exempt` must answer `true` or `false` at once.** It runs inside access checks, which cannot wait. An
`async` function stops the site at start with a clear error; any answer other than exactly `true` (a Promise,
a string, an error) exempts nobody and is logged once. Decide from the fields on `user`. An exempt account
works on its password alone, so give it the lowest role that does its job.
- **`windowHours`** must be a number (0 or more) or `false`; anything else (`'24'`, `-1`) stops the site at start.
- **Import map.** The status field and the dashboard notice are admin components: `pnpm payload
generate:importmap` after upgrading (`TwoFactorStatusField`, `TwoFactorAlert`); `ipal-doctor` reports a map
that lacks them. Without them the panel has no "Reopen setup" button (the endpoint still works).
- **Switch a part off:** `requireSetup: { dashboardNotice: false }` (the administrators' notice),
`{ statusField: false }` (the status / reset control on the account; the endpoint stays),
`{ setupNotice: false }` (the notice on the setup screen). None of them changes who is refused. The logo and
icon fetched by the server for the 2FA screens: `whiteLabel.inlineImages: false`, `adminMeta.serveIcon: false`
([white-label.md](./white-label.md)).
- **Building blocks** (`@intecion/ipal-kit`), for a project that wires the mode itself: `buildSetupFields`,
`stampSetupFrom`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`, `countAccountsWithoutTotp`,
`resolveRequireSetup`, `strictExempt`, `SETUP_FROM_FIELD`, `TWO_FACTOR_RESET_PATH`, `DEFAULT_SETUP_WINDOW_HOURS`.
- **Per collection or global:** the opt-out below (`custom.ipal.secondFactor`) also lets an account without TOTP
in, because it takes the entity out of the second-factor check altogether.
- **Needs** ipal-kit's check (`twoFactor.guard`, on by default); with `guard: false` the mode is off.
- **Project code** that calls `payload.find({ …, user, overrideAccess: false })` with a user fetched by id: refused
for every account of the 2FA collection now — before, only for accounts that had TOTP set up. Take the user from
`payload.auth({ headers })`.
- **In your own code:** `twoFactorSetupState(req)` → `'set-up' | 'open' | 'closed' | 'exempt' | 'not-applicable'`,
`twoFactorSetupDeadline(req)` → `Date | null`.
- **Texts** (English and Polish; override in `i18n.translations.<lang>.ipal`): `twoFactorSetupDeadline`,
`twoFactorSetupRequired`, `twoFactorSetupClosed`, `twoFactorStatus*`, `twoFactorReopen`, `twoFactorReset*`,
`twoFactorAlert*`.
**The brand on the setup and verify screens.** A session that still owes its code is refused `media` like every
other collection, so the browser could not load the panel's logo or tab icon from it. The plugin therefore hands
such a session the picture itself — fetched on the server without any credentials, exactly as an anonymous visitor
gets it (`AdminLogo` / `AdminIcon` as a `data:` address; `GET /api/ipal/admin-icon` answers with the image
instead of a redirect when the favicon is a bitmap — never with an SVG, which keeps the redirect). Nothing is opened by this: when `media` is not publicly readable, or the file is larger
than 512 KB, the site name (or the browser's own attempt) is used instead.
**What it does not do.** Inside the window, someone who knows the password of an account that has not set TOTP up
can still set it up with their own authenticator. The real owner then cannot ("already set") and has to ask an
administrator — the takeover is visible, and the window keeps it to the first days. So still: **create the
account, hand over the password, and have the owner set 2FA up at once.**
**Check:** create an account, log in over the API with its password → `403` from `/api/users/me` and
`/api/globals/site-settings`; open the panel as that account → the setup screen with the notice; enter the code →
the panel. As an administrator open the account → "Two-step verification: Set up."
**Verify attempts are limited** (`twoFactor.verifyLimit`). The package checks the code and never counts tries;
a six-digit code has about three right answers in a million, so whoever held the password could guess. ipalKit
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 — only with `requireSetup: false` or when the project
exempts it ("Setup required" below); by default it is refused. (5) Entities the project opted out (below).
(6) `access.admin`. (7) Endpoints that are not the plugin's or the 2FA package's: your own endpoints and other
plugins' endpoints check whatever they check — add `secondFactorPassed(req)` to yours. (8) Server code using the
Local API with `overrideAccess: true`. Nothing is skipped by slug, name or prefix, and a user object the check
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
@@ -399,8 +630,9 @@ ipal-kit upgrade, run:
pnpm generate:importmap
```
`src/app/(payload)/admin/importMap.js` must list `@intecion/ipal-kit/admin#TotpRedirectProvider` and
`@clocklimited/payload-2fa/rsc#TOTPSetup` / `#TOTPVerify` / `#TOTPField`. Commit the file.
`src/app/(payload)/admin/importMap.js` must list `@intecion/ipal-kit/admin#TotpRedirectProvider`,
`@intecion/ipal-kit/admin#SafeTotpView` and `@clocklimited/payload-2fa/rsc#TOTPSetup` / `#TOTPVerify` /
`#TOTPField`. Commit the file.
### Texts of the 2FA screens (`twoFactor.texts`)
@@ -437,6 +669,99 @@ No project change is needed apart from `generate:importmap`.
The provider only steers the UI. Data access is still checked by the package's access wrapper.
### The `back` link of the 2FA screens (`twoFactor.safeBack`)
The setup and verify screens take a `back` query value (`/admin/verify-totp?back=%2Fadmin%2Fcollections%2Fpages`)
and the 2FA package sends the browser there once the code is accepted, without looking at it. A link with
`back=javascript:…` therefore ran script in the panel, as the user who had just passed the second factor, and a
link with an outside address sent the user off the site straight after a real login step. The original package
fixed this in `payload-totp` 3.0.5 (GHSA-rffw-fq79-g3ch); `@clocklimited/payload-2fa` (beta.1 to beta.7) has not.
The panel's CSP does not stop it: the admin needs inline script.
ipal-kit closes it without changing the package. `SafeTotpView` (`@intecion/ipal-kit/admin`) is registered in
place of the package's four views (`setup-totp`, `verify-totp`, each with and without a leading slash). It checks
`back` on the server and renders the package's view with the checked value. The package's views stay in the
import map through `admin.dependencies`, so ipal-kit still never imports the package.
The rule (`safeAdminBack`, the same as upstream's): `back` is resolved the way a browser resolves it and kept
only when it stays on the site's origin, over HTTP(S), without credentials, inside the admin route
(`routes.admin`, also a custom one). Everything else gives the admin root: `javascript:` in any case or with
leading spaces, `data:`, `https://other.example`, `//other.example`, `/\other.example`, `\\other.example`,
`https:other.example`, a path outside the panel, a repeated `back`, no `back` at all. The value passed on is
always a path, never an absolute URL. An absolute `back` on the site's own origin is accepted only when the
config has `serverURL`.
- **On by default** with `twoFactor`. **After upgrading run `pnpm payload generate:importmap` and commit
`importMap.js`** — see "A stale import map" below for what happens otherwise.
- **Your own rule:** `twoFactor: { …, safeBack: (back, { adminRoute, origin }) => string }`. It gets the raw value
(`undefined` when absent or repeated) and returns where to go. Return a path on your own origin.
- **Off:** `twoFactor: { …, safeBack: false }` — the package's views exactly as it registers them. Only when a
later version of the 2FA package checks `back` itself, or something in front of the site does.
- **Building blocks:** `safeAdminBack(back, { adminRoute, origin })` and `wrapTotpViews(views, added, rule)` from
`@intecion/ipal-kit`; `SafeTotpView` from `@intecion/ipal-kit/admin` for your own 2FA view registration (give it
the serverProp `ipalTotpView: '<import-map path of the view to render>'` and list that path in
`admin.dependencies`).
**Which views are guarded.** Every view the injected 2FA factory registers on the routes `setup-totp` and
`verify-totp`, whatever stood under its keys before. The package replaces a view the project has under the keys
`SetupTOTP`, `SetupTOTPBackslash`, `VerifyTOTP` or `VerifyTOTPBackslash`, so such a view is the package's, and
guarded. The same holds when the project also lists `payloadTotp(...)` in `plugins` itself.
**Your own 2FA screen.** Two ways, both keep the check:
- Through the wrapped factory (the pattern from "Resetting 2FA"): set `views.VerifyTOTP.Component` (or `SetupTOTP`)
on the config the factory returns. ipal-kit puts `SafeTotpView` in front of it. A server component gets every
server prop with `searchParams.back` checked. A client component (`'use client'`) gets Payload's client props,
your `clientProps`, and `back` plus `searchParams` — both checked; read `back` from the props, not from
`useSearchParams()`, which still holds the raw query value.
- From a plugin listed after `ipalKit`, or under another key or route: that view is yours and is not wrapped. Use
`wrapTotpViews` or `safeAdminBack` in it. `ipal-doctor` warns when the config uses the package's own view
(`@clocklimited/payload-2fa/rsc#TOTPVerify` / `#TOTPSetup`) as a view's `Component`; the same path as the
`ipalTotpView` of `SafeTotpView`, or in `admin.dependencies`, is fine.
Wrapping views yourself, for a project that runs the 2FA package without `ipalKit`'s `twoFactor` (all from
`@intecion/ipal-kit`):
```ts
const before = copyViews(config.admin?.components?.views) // copies: the factory's views are then never "the same object"
config = await payloadTotp(options)({ ...config, admin: { ...config.admin, components: { ...config.admin?.components, views: before } } })
const fromPackage = changedViewKeys(before, config.admin?.components?.views ?? {}) // by object — the package replaces views under its keys
const { dependencies, views } = wrapTotpViews(config.admin?.components?.views ?? {}, (key) => fromPackage.has(key), undefined)
config.admin = { ...config.admin, components: { ...config.admin?.components, views }, dependencies: { ...config.admin?.dependencies, ...dependencies } }
```
`SAFE_TOTP_VIEW` is the wrapper's import-map path; `findImportMapFile` / `missingImportMapEntries` are the
stale-map check below (a hint from the file on disk — warn on it, never block on it).
**A stale import map (read this before upgrading a site with 2FA).** The check needs the import-map entry
`@intecion/ipal-kit/admin#SafeTotpView`. A production build made with the import map of the previous version
passes and the site starts, but Payload renders nothing for a path its map lacks: the 2FA setup and verify
screens have no code form (HTTP 200), so nobody can sign in to the panel. Payload's only trace is
`getFromImportMap: PayloadComponent not found in importMap` in the server log. Development is not affected (Payload
regenerates the map there). ipal-kit reports it in three places:
- **Before deploy:** `pnpm exec ipal-doctor` reports `import map lacks @intecion/ipal-kit/admin#SafeTotpView` (error).
- **At every start in production:** the log has `[ipal] The admin import map may be out of date: … was not found
in <file> …`.
- **On the screen:** a notice above the 2FA screen, "Two-step verification may not be available", with what a
developer has to run. With a really stale map the notice is all the user sees (the form is missing); it is
shown by ipal-kit's `TotpRedirectProvider` only — with your own `twoFactor.provider`, or `provider: false`,
there is the log line alone.
The start-up check is a guess, and is built so that a wrong guess costs a wrong notice and nothing else: it
searches the text of the `importMap.js` **on disk** where Payload looks for it (`admin.importMap.importMapFile`,
else `app/(payload)<admin route>/` or `src/app/(payload)<admin route>/` under `admin.importMap.baseDir` or the
working directory), while the map the site really uses is inside the build. The two differ when the map is
generated during the build and the running image carries the repository's file (a Dockerfile with a separate
runner stage), or when the map file re-exports or computes its entries. Then the log line and the notice appear
although the screen works — the code form stays on the page and sign-in is not affected. Turn the check off for
such a project: `twoFactor: { …, importMapCheck: false }` (no file read, no log line, no notice). A file that is
not found is not reported. Building in place (Coolify's Nixpacks) reads the same file the build used.
**Fix for a really stale map:** `pnpm payload generate:importmap`, commit `importMap.js`, rebuild, redeploy.
A second error exists for the opposite case — the wrapper is in the map but the package's view is not:
`[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` (same fix).
**Check:** log in with the password only, open
`/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F`, enter the code: you must land on `/admin`, not on
example.com. With `back=%2Fadmin%2Fcollections%2Fpages` you must land on that list.
### Turning it off (DISCOURAGED)
```ts
@@ -448,7 +773,8 @@ twoFactor: false // ONLY when the project really cannot use 2FA (rare)
### How it works for the user
1. Logs in (email + password)
2. On first login: redirected to TOTP Setup (`/admin/setup-totp?back=%2Fadmin`, QR + secret)
2. On first login: redirected to TOTP Setup (`/admin/setup-totp?back=%2Fadmin`, QR + secret), with a notice
saying until when it has to be done. Until it is done the account can do nothing else ("Setup required")
3. Scans the QR with an app (Google Authenticator, Authy, 1Password, Microsoft Authenticator)
4. Enters the code → 2FA is active, back to the page from `back`
5. Next logins: email + password + TOTP code (`/admin/verify-totp?back=…`)
@@ -459,17 +785,65 @@ show the QR code. `back=null` or a page that keeps reloading means the import ma
### Resetting 2FA (admin)
An admin can reset another user's 2FA (when they lose their phone) — through
An admin resets another user's 2FA (a lost phone) or reopens setup for a blocked account on that account's page
in the panel: **Two-step verification** in the sidebar → "Reset two-step verification" / "Reopen setup". Behind
it: `POST /api/ipal/two-factor/reset` `{ userId }`. The account must set TOTP up again within a new window.
The endpoint comes with ipal-kit's own check: with `twoFactor.guard: false` it does not exist (404), and neither
does the control in the panel.
- **Who may reset.** By default a staff admin whose session has **entered its own TOTP code**. An admin on an API
key, and an admin that `requireSetup.exempt` lets work on its password, are refused: removing someone's second
factor should take one. `twoFactor.resetAccess: ({ req }) => boolean` replaces the rule; a session that still
owes its code is refused whatever the function says, and only an answer of exactly `true` allows
(`req.user._strategy` is `'totp'`, `'api-key'` or `'local-jwt'`). Example that keeps the default's strength and
narrows it to one address: `({ req }) => req.user?._strategy === 'totp' && req.user.email === '[email protected]'`.
`({ req }) => isAdmin(req.user, req.payload)` alone would let an API-key or exempt admin reset.
- **A reset ends the account's sessions.** Every token of that account stops working at once; its owner logs
in again with the password and sets TOTP up. This matters when the account may be in someone else's hands: a
session that had passed 2FA could otherwise enrol a new authenticator without the password (`/api/setup-totp`
asks for none). **After a suspected compromise also change the account's password** — the reset does not, and
whoever knows the password can log in and set TOTP up within the new window. With `auth.useSessions: false`
on the collection there are no sessions to end: tokens live until they expire.
- The 2FA package's own remove / reset endpoints (below) do **not** end sessions.
#### Every administrator is blocked
When no administrator can get in (each one missed the window, or the only one did), nobody can press "Reopen
setup". Two ways out, both need a deploy or shell access — which is the point: the panel alone cannot undo it.
1. **A script, no redeploy** (`pnpm payload run scripts/reopen-2fa.ts` on the server; Local API, no access
check):
```ts
import config from '@payload-config'
import { getPayload } from 'payload'
const payload = await getPayload({ config })
const { docs } = await payload.find({ collection: 'users', where: { email: { equals: 'admin@example.com' } } })
await payload.update({ id: docs[0].id, collection: 'users', data: { totpSetupFrom: new Date().toISOString() } })
process.exit(0)
```
The administrator then logs in and sets TOTP up within the new window, and reopens the others from the panel.
2. **No script, one redeploy each way:** set `twoFactor.requireSetup: { windowHours: false }` and deploy — the
lock stays (nothing but setup), the time limit is gone, so every blocked account can set TOTP up. When the
administrators have, put the option back and deploy again. Accounts that still have not set TOTP up are
blocked again from that moment (their start did not move).
Avoid it: at least two administrators with 2FA, and `ipal-doctor --url <site>` before an upgrade.
The 2FA package has its own reset, off unless you turn it on — through
`adminManageAccess` in the @clocklimited configuration. ipalKit passes it only `collection`,
`forceSetup` and `issuer`; pass other options by wrapping the injected factory:
`plugin: (opts) => payloadTotp({ ...opts, adminManageAccess: ({ req }) => isAdmin(req.user) })`.
`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 +857,37 @@ 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
the company e-mail and dropped. The checks, in order — origin, rate limit, declared size, concurrency guard,
honeypot, Turnstile, field validation and consent, then per file: count, name (double and refused extensions),
size while reading, content signature, container and macro checks, an optional `scan` hook — are listed in
[forms.md](./forms.md) "The security wall".
- There is **no antivirus**. The checks stop the wrong kind of file; they do not prove a file is harmless. Plug a
scanner into `forms.attachments.scan` when the client needs one. The macro check for legacy `.doc` / `.xls` is
best-effort.
- Programs, scripts, macro-enabled Office files, archives, HTML and SVG are refused unless the project lists
the extension in `allowRisky`.
- The submit endpoint (`POST /api/ipal/forms/submit`) accepts same-origin requests only
(`attachments.submit.allowedOrigins` adds others) and runs the same gates as the server action; REST creation
of submissions stays "logged-in users only".
- Microsoft Graph: files of 3 MB and more need `Mail.ReadWrite` — limit the app to the forms mailbox
([email.md](./email.md) "Attachments").
## Access control (since the version after 1.12.3)
- Injected auth collection with roles: a `user` account reads and edits only itself; only an
@@ -498,6 +903,19 @@ data access, not just the UI.
## Turn off, override, extend
- **Verify limit:** `twoFactor.verifyLimit: { max, windowMinutes }`, or `false`.
- **`back` link check of the 2FA screens:** `twoFactor.safeBack: false`, or a function as your own rule;
`safeAdminBack`, `wrapTotpViews`, `copyViews`, `changedViewKeys`, `SAFE_TOTP_VIEW`, `SafeTotpView` are exported.
The stale import-map notice that comes with it: `twoFactor.importMapCheck: false`; its parts
(`findImportMapFile`, `missingImportMapEntries`) are exported too.
- **Setup required:** `twoFactor.requireSetup: false` (off), `{ windowHours }` (another window, `false` / `0` = none),
`{ exempt }` (a service account), `{ dashboardNotice: false }`, `{ statusField: false }`, `{ setupNotice: false }`,
`twoFactor.resetAccess` (who reopens); exported: `twoFactorSetupState`, `twoFactorSetupDeadline`,
`buildSetupFields`, `stampSetupFrom`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`,
`countAccountsWithoutTotp`, `resolveRequireSetup`, `strictExempt`, `SETUP_FROM_FIELD`.
- **2FA check:** per entity `custom.ipal.secondFactor` / `custom.totp.disableAccessWrapper` (one operation or
all); `twoFactor.guard: false` turns ipal-kit's own second-factor check off everywhere (not recommended);
`requireSecondFactor` / `secondFactorPassed` are exported for your own access functions and endpoints.
- **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;
+19 -3
View File
@@ -197,17 +197,33 @@ process.exit(seed.summary().errors ? 1 : 0)
**Seed values.** Write each value once, every language side by side. An object whose keys are all
locale codes is one value per locale (`{ pl: 'Kontakt', en: 'Contact' }`); anything else is the same
in every locale. A locale missing from such an object is left untouched in that locale.
This works at any level: a text (`label: { pl, en }`) or a whole array, layout or group (`fields: { pl: [...], en: [...] }`).
Rows of a field that is not localized are shared by every language — the helper reuses their ids, so give each
language the same rows in the same order (its texts differ; non-localized values such as an option's `value` come
from the last language written). A field with `localized: true` keeps its own rows per language.
`{ $page: 'kontakt' }` becomes the ID of the page whose default-locale slug is `kontakt`;
`{ $form: 'Contact form' }` becomes the ID of the form with that title (seed the form first). A missing form
is an error for that record, never an empty relation. Ready pages made of library blocks:
is an error for that record, never an empty relation.
**References and required fields.** A new record is created complete, so a required field (a `layout` whose block
links to a page or form) passes validation:
- a reference to a record that exists — or was created earlier in the run — becomes its ID in the first write;
- a `{ $page }` to a page created later **in the same `upsertBySlug` call** is filled in the second pass; when the
field that holds it is required, the record waits until that page exists. Pages that link to each other belong in
one call (an array);
- required links in a cycle (A needs B, B needs A) and a reference to a page or form that does not exist and is not
planned are an **error** for those records, and nothing is written for them. Make one of the links optional, or seed
one of the pages first;
- the dry run reports the same outcome. A form planned earlier in the same dry run counts as existing. Only a required
cycle shows up first in the real run, because the dry run does not validate fields. Ready pages made of library blocks:
`pageTemplates` in [block-library.md](./block-library.md#page-templates).
| Method | What it does |
|---|---|
| `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (without fields that hold `$page` / `$form` links), then every record gets its full content, so pages can link to each other in any order |
| `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
+4
View File
@@ -8,6 +8,10 @@ and configures the adapter.
> `.env` — like DATABASE_URI, PAYLOAD_SECRET, GRAPH_*. NOT into the admin panel (they are agency
> secrets, bound at startup, the editor does not change them).
> **Form files are not stored.** A file a visitor attaches to a form (`forms.attachments`) is checked, e-mailed to the
> company and dropped — it never becomes a Media record and never reaches R2 or the disk. Nothing on this page
> applies to it; see [forms.md](./forms.md) "Files".
## .env variables
Where to get the values: Cloudflare → R2 → bucket (name), Overview → S3 API (endpoint `https://<ACCOUNT_ID>.r2.cloudflarestorage.com`), Manage R2 API Tokens → "Object Read & Write" (a key pair; the secret is shown once). All 4 variables → R2; any missing → local disk (partial configuration = a warning in the log).
+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.
+6 -4
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
@@ -188,9 +188,10 @@ function ContactForm() {
`reset()` → after submitting. `enabled` → false when the provider got `siteKey: null` (the widget does not
render; server-side verification is decided by `getTurnstileConfig` anyway).
`reset()` only **clears `token` in React state** — it does not call `turnstile.reset()` on the
Cloudflare widget. A new token appears only when the widget generates one again
(e.g. after expiry, about 300 s) or is mounted again.
`reset()` clears `token` **and makes the widget run its challenge again**, so a new token arrives a moment later
— a token is single-use, and a form the server refused can be sent again. (Up to 1.15.5 it only cleared the
React state, and the next send had no token until the old one expired.) Your own `<Turnstile>` outside the
provider: change its `resetSignal` prop to get the same.
`useTurnstile()` outside `<TurnstileProvider>` throws. `useOptionalTurnstile()`
(also from `/client`) returns `enabled: false` there instead of throwing — `BuilderForm` uses it.
@@ -202,6 +203,7 @@ Cloudflare widget. A new token appears only when the widget generates one again
| `siteKey` | `string` | — | empty → renders nothing |
| `onToken` | `(token: string \| null) => void` | — | token once solved; `null` on expiry / error / theme change |
| `theme` | `'page' \| 'auto' \| 'light' \| 'dark'` | `'page'` | `'page'` = the site's theme (`data-theme`, ThemeScript), no theme → `'auto'` |
| `resetSignal` | `number` | `0` | change the value → the widget issues a new token (what `reset()` does for the provider's widget) |
### Why Turnstile is NOT fully "drop in and forget" like CookieBanner
+7 -1
View File
@@ -51,6 +51,12 @@ values win over yours); `afterLogin` / `afterNavLinks` are appended.
## Technology support credit — "Technology support: Intecion.com"
**On the 2FA screens** (a session that has typed its password but not its code, or has not set 2FA up) the
panel's logo and icon cannot be loaded by the browser: that session is refused every collection, `media`
included. The server fetches them the way an anonymous visitor gets them (no cookies, images only, at most
512 KB) and puts them into the page as a `data:` image. `whiteLabel: { inlineImages: false }` turns the fetch
off (the site name is shown instead of a refused image); `fetchPublicImage` / `publicImageDataUri` are exported.
A discreet line **"Technology support: Intecion.com"** (pl `Wsparcie technologiczne: Intecion.com`,
a link to `https://intecion.com`) appears in **two places**:
- **under the panel navigation** (`afterNavLinks`, variant `nav` — left-aligned),
@@ -84,7 +90,7 @@ image. The plugin now fills the panel's `<head>` from Site settings, **with or w
| `og:site_name` | the site name | your `admin.meta.openGraph.siteName` wins |
| description | "Administration panel of <site>. Built on Payload CMS, technology support: Intecion.com." (Polish when the site's default locale is `pl`) | `adminMeta: { description: 'Panel of {site}' }` (string or `{ en, pl }`), `false`; `language: 'en' \| 'pl'`; your `admin.meta.description` wins |
| preview image | `GET /api/ipal/admin-og` — 1200×630 PNG: the site's logo (or name), "Administration panel", "Technology support: Intecion.com" | `adminMeta: { image: '/my-og.png' }` or `false`; your `admin.meta.openGraph.images` wins |
| icon | `GET /api/ipal/admin-icon` — redirects to the site's favicon, or draws the initials | `adminMeta: { icons: false }`; your `admin.meta.icons` win |
| icon | `GET /api/ipal/admin-icon` — answers with the site's favicon itself when it is a bitmap (PNG, JPEG, GIF, WebP, ICO, AVIF, recognised by its bytes; fetched as an anonymous visitor would get it, at most 512 KB). **An SVG favicon is never answered from here** — an SVG can carry script and a site-wide CSP rule overrides a route's own header — it gets a redirect to the media file, as does anything that cannot be fetched; so with an SVG favicon the tab icon is missing on the 2FA screens (use a PNG there). No favicon: the initials are drawn | `adminMeta: { icons: false }`; `adminMeta: { serveIcon: false }` = always the redirect to the media file; your `admin.meta.icons` win |
| everything | on | `adminMeta: false` = Payload's defaults |
- **How:** Payload builds every panel page's metadata from `config.admin.meta`. The plugin sets the
+36 -30
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.15.2",
"version": "1.16.6",
"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",
@@ -130,8 +130,9 @@
"typecheck": "tsc --noEmit -p . && tsc -p test"
},
"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"
},
@@ -148,39 +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",
"@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.3",
"eslint-config-next": "16.4.6",
"graphql": "^16.8.1",
"next": "16.4.3",
"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",
"next": "16.4.6",
"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",
@@ -201,7 +207,7 @@
"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",
"undici@>=7 <7.30.1": "^7.30.1"
+1835 -1011
View File
File diff suppressed because it is too large Load Diff
@@ -30,6 +30,12 @@ following the hint (PROGRAMISTA §2) — do not ask whether it is needed. The on
a client decision recorded in `AGENTS.md` as `ipal-audit-skip: <keys> — <reason>` (keys
in AGENT.md §0b). Never add that line yourself just to make the audit pass.
## Polish text and panel labels (AGENT.md §2, §6.5a)
`hardcoded Polish text in code` covers public text. In a schema file (a `.ts` file under `collections/`, `globals/`,
`fields/` or `blocks/`, or one importing Payload's schema types) the panel's own labels are fine: `adminText('Title', 'Tytuł')`,
`{ en, pl }` as `label`, `singular`, `plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback, a
`const x: AdminText`. Still an error: any `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`.
## Design tokens (AGENT.md §6.11)
The script checks: hex in classes and inline styles (error), `dark:` on colour utilities and `var(--color-…)` in
classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warning — a site not yet migrated),
@@ -238,8 +238,10 @@ fi
if [ -n "$FRONT" ]; then
report ERROR "logic keyed on content text" "§2 the editor can rename it any time — a style/flag is a panel field (e.g. buildLinkField({ appearances: [...] }))" \
"$(g "\.(label|title|heading|name|text)\??\.(toLowerCase|toUpperCase|trim)\(\) *[!=]==? *['\"]|\.(label|title|heading)\?? *[!=]==? *['\"][^'\"]+['\"]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '==')"
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields" \
"$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')"
# The panel's own { en, pl } / adminText() labels in schema files are not public text (polish-literals.mjs); without TypeScript, a plain grep.
POLISH=$(node "$(dirname "$0")/polish-literals.mjs" $FRONT 2>/dev/null) || \
POLISH=$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields; panel labels: adminText() or { en, pl } in a schema file" "$POLISH"
fi
GLOBALS=$(dirs src/globals)
if [ -n "$GLOBALS" ]; then
@@ -0,0 +1,98 @@
#!/usr/bin/env node
// Polish text hardcoded in code (AGENT.md §2) — prints "file:line: source line" per finding, exit 0.
// node polish-literals.mjs <dir> [<dir> …]
// 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/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ł' }
// Anything under defaultValue is public content, so it is reported. So is a Polish-only label.
// Exit 3 = TypeScript not found (audit.sh falls back to a plain grep).
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { createRequire } from 'node:module'
import { join } from 'node:path'
const load = (from) => {
try {
return createRequire(from)('typescript')
} catch {
return null
}
}
const ts = load(join(process.cwd(), 'package.json')) ?? load(import.meta.url)
if (!ts) process.exit(3)
const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/
const SCHEMA_KEYS = new Set(['label', 'singular', 'plural', 'description', 'placeholder', 'group'])
const SCHEMA_DIR = /(?:^|\/)(?:collections|globals|fields|blocks)\//
const SCHEMA_TYPES = /import\s+type\s*\{[^}]*\b(?:Block|CollectionConfig|Field|GlobalConfig|Tab)\b[^}]*\}\s*from\s*['"]payload['"]/
const IPAL = /^@intecion\/ipal-kit(?:\/|$)/
const files = []
const walk = (p) => {
let st
try { st = statSync(p) } catch { return }
if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n))
else if (/\.tsx?$/.test(p) && !/\.d\.ts$|\/\(payload\)\//.test(p)) files.push(p)
}
process.argv.slice(2).forEach(walk)
const keyName = (node) => (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) || ts.isStringLiteralLike(node.name)) ? node.name.text : null)
for (const file of files) {
const text = readFileSync(file, 'utf8')
if (!POLISH.test(text)) continue
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS)
const schemaFile = !file.endsWith('x') && !/^['"]use client['"]/m.test(text) && (SCHEMA_DIR.test(file) || SCHEMA_TYPES.test(text))
// Local names of the plugin's helpers (`import { adminText as t } …`); a lookalike of your own does not count.
const helpers = new Map()
for (const st of source.statements) {
if (!ts.isImportDeclaration(st) || !IPAL.test(st.moduleSpecifier.text)) continue
const named = st.importClause?.namedBindings
if (!named || !ts.isNamedImports(named)) continue
for (const el of named.elements) {
const name = (el.propertyName ?? el.name).text
if (name === 'adminText' || name === 'rowLabel') helpers.set(el.name.text, name)
}
}
const isBilingual = (node) =>
ts.isObjectLiteralExpression(node) && ['en', 'pl'].every((k) => node.properties.some((p) => keyName(p) === k))
// Is this literal one of the panel's own labels? Walks up from the literal.
const isAdminLabel = (literal) => {
let inside = false
for (let node = literal; node.parent; node = node.parent) {
const parent = node.parent
if (keyName(parent) === 'defaultValue') return false
if (inside) continue
if (ts.isCallExpression(parent) && parent.arguments.includes(node) && ts.isIdentifier(parent.expression)) {
const helper = helpers.get(parent.expression.text)
if (helper === 'adminText') inside = true
// rowLabel(fields, fallback): the fallback only, as { en, pl }
if (helper === 'rowLabel' && node === parent.arguments[1] && isBilingual(node)) inside = true
}
if (ts.isPropertyAssignment(parent) && parent.initializer === node && SCHEMA_KEYS.has(keyName(parent)) && isBilingual(node)) inside = true
if (ts.isVariableDeclaration(parent) && parent.initializer === node && parent.type?.getText(source) === 'AdminText' && isBilingual(node)) inside = true
}
return inside
}
const seen = new Set()
const visit = (node) => {
if (ts.isImportDeclaration(node)) return
const literal = ts.isStringLiteralLike(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)
if (literal && POLISH.test(node.text) && !(schemaFile && isAdminLabel(node))) {
const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line
if (!seen.has(line)) {
seen.add(line)
console.log(`${file}:${line + 1}:${text.split('\n')[line]}`)
}
}
ts.forEachChild(node, visit)
}
visit(source)
}
@@ -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, and 2FA (setup required included) does not apply to them. Check: its token → `403` from
`/api/globals/site-integrations` and `/api/form-submissions`.
5. `pnpm generate:types`, `pnpm payload generate:importmap`.
6. Postgres with migrations → `pnpm payload migrate:create`.
## 4. Check
The **ipal-audit** skill. By hand: an entry in the panel → visible at `/<locale>/<archive>/<slug>`,
@@ -34,6 +34,21 @@ 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'] })` |
| an account logs in but every page and request answers 403 / the setup screen says "The time to set up two-step verification has passed" | 2FA setup required: the account did not set TOTP up within the window (72 h from its creation, an admin's reset, or the first start after the upgrade) | an administrator opens the account in the panel → Two-step verification → "Reopen setup" (or `POST /api/ipal/two-factor/reset` `{ userId }`); every administrator is blocked: security.md "Every administrator is blocked" — a script with the Local API, `payload.update({ collection: 'users', id, data: { totpSetupFrom: new Date().toISOString() } })` (`pnpm payload run`), then log in and set TOTP up; or `requireSetup: { windowHours: false }`, redeploy, set up, put it back |
| a new account gets `403` from the API although its role allows the request | 2FA setup required: until TOTP is set up the account reaches only the setup screen | set TOTP up (log in to the panel); an integration: use an API key, or `twoFactor.requireSetup.exempt` |
| after an upgrade EVERY panel login answers `500` (also `/api/users/init`), administrators with 2FA included; log: `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN` or `column users.totp_setup_from does not exist` | Postgres/SQLite: the migration that adds the 2FA column has not run (needed whenever 2FA is on) | `pnpm payload migrate:create` if no migration has it, commit, and redeploy with migrations run when the new container starts — `prodMigrations` in the adapter or the start command `pnpm payload migrate && pnpm start` (deployment.md §4.3; not Coolify's Pre-deployment command, which runs in the old container); nothing is lost. `ipal-doctor` reports a project whose migrations lack `totp_setup_from` |
| the site does not start: `[ipal] twoFactor.requireSetup.exempt must not be async` / `…windowHours must be a number` | `exempt` is an `async` function, or `windowHours` is a string / negative | `exempt: ({ user }) => user.email === '…'` (returns `true` / `false` at once); `windowHours: 72` or `false` |
| log: `[ipal] twoFactor.requireSetup.exempt returned a Promise … The account is NOT exempt` (and the service account gets 403) | `exempt` does not return exactly `true` | return a boolean decided from the fields on `user` |
| an administrator's "Reset two-step verification" answers 403 from a script with an API key, or for an exempt account | by default the reset needs a session that entered its own TOTP code | reset from the panel after logging in with the code; or `twoFactor.resetAccess: ({ req }) => …` |
| after "Reset two-step verification" the user is logged out everywhere | intended: the reset ends the account's sessions | the user logs in again with the password and sets 2FA up; after a suspected compromise also change the password |
| no "Two-step verification" box on the account page / no "Reopen setup" | the import map lacks `TwoFactorStatusField` (not regenerated), or `requireSetup: { statusField: false }` | `pnpm payload generate:importmap`, commit, redeploy; meanwhile `POST /api/ipal/two-factor/reset` `{ userId }` works |
| "Two-step verification" is missing on the account page / the dashboard shows a missing component | the import map is stale | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy |
| startup: `[ipal] twoFactor: the injected 2FA plugin did not add the totpSecret field / hasTotp field / totp auth strategy` | the installed `@clocklimited/payload-2fa` is not a version ipal-kit's second-factor check recognises (tested: 3.0.0-beta.1 and beta.7), or a custom factory was injected | install a supported version; stop-gap only: `twoFactor.guard: false` (the plugin's own data is then not covered by 2FA — security.md) |
| own route or script gets `403` / "not allowed" on `form-submissions`, `forms`, a settings global with `overrideAccess: false`, although the user is an admin | the `user` was fetched by id and passed by hand: it does not carry how the account logged in, so the second-factor check refuses it | take the user from `payload.auth({ headers })` (it sets `collection` and how the account logged in), or (server-only code that needs no access check) leave `overrideAccess` at its default; a hand-built user needs at least `collection: 'users'` for its role to count |
| an account of a second auth collection (`customers`) gets `403` from a settings global, submissions, `/api/ipal/*`, `/api/setup-totp`, or `isAdmin` / `adminOnly` say no although it has `roles: ['admin']`, after an upgrade | by design since 1.16.4: roles and staff checks count only for accounts of a staff collection | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") |
| `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) |
@@ -52,6 +67,10 @@ through this procedure. Ask only when you are missing something you cannot get y
| Symptom | Cause | Fix |
|---|---|---|
| `PayloadComponent not found in importMap` (e.g. `@intecion/ipal-kit/admin#RowLabel`) | importMap out of date after a plugin update / adding `rowLabel` | `pnpm payload generate:importmap`, restart |
| after an upgrade the 2FA setup / verify screen has no code form (HTTP 200), only the notice "Two-step verification may not be available" (or nothing at all with `importMapCheck: false` / an own provider); nobody can sign in; the log has `[ipal] The admin import map may be out of date` and `getFromImportMap: PayloadComponent not found in importMap … @intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after the upgrade that added the `back` link check (`twoFactor.safeBack`); the production build uses the committed, old `importMap.js` | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy; `pnpm exec ipal-doctor` shows it before a deploy. The opposite case (wrapper present, package view missing) throws `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` — same fix |
| the notice "Two-step verification may not be available" and the log line `[ipal] The admin import map may be out of date` appear, but the code form is there and sign-in works | false alarm: the check searches the `importMap.js` on disk, which is not the map inside the build (map generated during the build and a Dockerfile runner stage that copies the repository's file; a map file that re-exports or computes its entries) | `twoFactor: { …, importMapCheck: false }`; or ship the generated `importMap.js` in the image |
| an own 2FA screen (set through the wrapped factory) ignores the check on `back` | a client component reading `useSearchParams()` gets the raw query value | read the `back` prop (or `searchParams.back`) the wrapper passes — both are checked (security.md "Your own 2FA screen") |
| after the 2FA code the user lands on `/admin` instead of the page in `back` | `back` pointed outside the admin route or to another origin (the check keeps only a path inside `routes.admin`; an absolute URL only on the `serverURL` origin) | expected; for another rule pass `twoFactor.safeBack: (back, { adminRoute, origin }) => string` (security.md) |
| new admin stuck on `/admin/setup-totp?back=null` (the page keeps redirecting to itself) | ipal-kit ≤ 1.14.1: the 2FA package's provider needs an `x-pathname` header nothing sets on `/admin`; or `twoFactor.provider: false` without that header | update ipal-kit, `pnpm payload generate:importmap` (`TotpRedirectProvider`), restart; check: `/admin/setup-totp?back=%2Fadmin` shows the QR (security.md) |
| `Cannot destructure property 'config'` / UI hooks without context | two copies of `@payloadcms/ui` | `pnpm why @payloadcms/ui`; one version + `pnpm.overrides`; `ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms` = empty |
| empty SEO tab, no Forms | mismatched `@payloadcms/*` versions | all `@payloadcms/*` = the `payload` version |
@@ -50,7 +50,7 @@ Existing client sites are not gated on it; run it there as a report only.
## The status endpoint
`GET /api/ipal/doctor` is added by `ipalKit` and answers 404 until the site has `IPAL_DOCTOR_TOKEN` (≥ 32 characters).
Then `Authorization: Bearer <token>`; counts only (`usersWithout2fa`, `pendingCookies`, `plugin`, `node`). With the same
Then `Authorization: Bearer <token>`; counts only (`usersWithout2fa`, `usersSetupClosed` = of those, blocked because the 2FA setup window has passed, `pendingCookies`, `plugin`, `node`). With the same
`IPAL_DOCTOR_TOKEN` in the doctor's environment, `--url` reads it. Off: `ipalKit({ doctor: false })`; adapt:
`ipalKit({ doctor: { tokenVar, access } })`.
+46 -1
View File
@@ -62,6 +62,7 @@ Underneath is `BuilderForm` (client) — clean, accessible HTML **without styles
checkbox, **Checkbox group** (multiple choice, min/max), message, **Step** (splits into steps),
country, state (on by default in form-builder, rendered as a text field).
Turning a type off: `forms.fields: { country: false, state: false }`.
With `forms: { attachments: true }` there is also **File** (section 3a).
- **Multi-step form:** the editor inserts a **Step** block (title, description) — the fields below it form one
screen. The Next/Back buttons and "Step 1 of 3" come from **Form messages → Form messages** (next, back,
stepOf). Next validates only the current step; a server error returns to the step with the field; focus
@@ -82,6 +83,41 @@ Custom field type in the panel: the `FormsOption['fields']` type only accepts `b
(at runtime the block object passes through to form-builder, but TS rejects it), and the server treats
an unknown type as text anyway — if you need a custom type or validation → **plugin gap** (`ipal-plugin-gap`).
## 3a. A file on a form (CV, specification, photo) — `forms.attachments`
The file is **e-mailed to the company and never stored**: no Media record, no bucket, no disk, no download link.
Never build this by hand (your own `<input type="file">`, upload route or upload collection = an error).
1. Config: `forms: { attachments: true }` (defaults: 10 MB per file and per submission, at most 3 files per field).
Options (`FormAttachmentsOption`): `maxSizeMB`, `maxTotalMB`, `maxFiles`, `fileTypes` (add / replace / `false`),
`allowRisky`, `scan` (antivirus hook), `strictPdf`, `notice`, `maxConcurrent`, `path`, `submit`
(`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`,
`idleTimeoutMs` 30 s, `timeoutMs` 5 min — a stalled or dropped upload is given up and frees its slot).
Postgres: `pnpm payload migrate:create`; then `pnpm generate:types`.
2. Form: a **File** field — in the seed
`{ blockType: 'file', name: 'attachment', allowedTypes: ['pdf', 'doc', 'docx'], maxSizeMB: 10, maxFiles: 1, label: {…}, help: {…} }`
(the template has the line, commented). Types: `pdf`, `doc`, `docx`, `odt`, `rtf`, `xls`, `xlsx`, `jpg`, `png`, `webp`.
The label and the help text ("PDF or DOCX, up to 10 MB") are written per language in the panel / seed.
3. E-mails: the file goes to **every e-mail whose To / CC / BCC are fixed addresses** — the company notification.
An e-mail addressed with `{{email}}` (the confirmation to the customer) never gets it. A form with a File field
and no fixed-recipient e-mail cannot be saved. `{{attachment}}` / `{{*:table}}` show the file name.
4. Code: nothing. `RenderForm` renders the field (native input, help text, file list, "Remove" button), and the
browser posts files to the plugin's endpoint `POST /api/ipal/forms/submit` — no route file, no `next.config`
change. Classes: `file`, `help`, `fileList`, `fileItem`, `fileRemove` in `formClasses.ts`. Your own markup:
`f.getFileProps(field)`, `f.getFiles(field)`, `f.removeFile(field, i)`, `f.helpId(field)`.
5. Texts: Form messages → **Files** (`fileTooLarge`, `fileType`, `fileRefused`, `fileCount`, `fileNotSent`,
`fileOptional`, `fileRemove`) — English and Polish defaults; fill every other language of the site. Each tells
the visitor that the problem is the **file**, why, and what to do (a smaller file, another format; on an
optional field also "send the form without the file"). They show at the File field; what the visitor typed stays.
6. Mail size: **Site integrations → E-mail sending → Test e-mail** with **Attach a 10 MB test file** must arrive.
SMTP: the provider's limit decides (a 10 MB server limit carries only ~7 MB of file — lower the field's
maximum). Microsoft Graph: files of 3 MB and more need the `Mail.ReadWrite` permission on the agency app
(email.md "Attachments"); without it they go over SMTP when the panel has SMTP settings, else the form's limit
drops to about 2.8 MB by itself. Keep Graph small on purpose: `mailAdapter({ graph: { largeAttachments: false } })`.
Tell the client plainly: **there is no antivirus scan** (the e-mail says so), the macro check of old `.doc` / `.xls`
files is best-effort, and when the e-mail cannot be sent the file is gone — the visitor sees "We could not send the
file …" at the File field, staff get a notice without the file, and the submission shows **File delivery: Not sent**.
## 4. Page — block data once (blocks do not import `lib/*`)
From `createPageRoute` (PROGRAMISTA §2.8):
```tsx
@@ -139,11 +175,16 @@ 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;
- [ ] multi-step form: Next with an empty step → errors, the step stays; Back keeps the entered values;
- [ ] form with a **File** field: a PDF arrives attached to the company e-mail, the customer e-mail has no file,
the submission shows *Files* and *File delivery: Handed to the mail server*, Media has no new record;
a `.exe` renamed to `.pdf` → "The file … was refused: …" at the File field, no submission, the typed answers
still there; a file over the limit → "…is too large. Choose a file of up to N MB." before sending; each
message in every language of the site; keyboard only: Tab to the field, pick a file, Tab to "Remove …", Enter removes it;
- [ ] `ipal-audit --quick` → zero hardcoding in FormBlock, no copy of the form engine;
- [ ] `ipal-consent-check` → still 0 violations (Turnstile is necessary, not tracking).
@@ -155,6 +196,10 @@ Details the seed already covers, which you check after every manual change in th
| `reason: 'validation'`, `kind: 'unknown_fields'` | the frontend sends a field the form does not have (custom renderer with an extra field, typo in `name`) |
| "Next/Back" buttons in English | empty Form messages → next / back / stepOf in that language |
| `reason: 'not_found'` | `formId` from another database (seeded on dev, another ID on prod) — use a relationship from the panel, not a fixed ID in code |
| "We could not send the file …", submission says *Not sent* | the mail server refused the message (size limit: see the note on the submission), or Graph without `Mail.ReadWrite` and no SMTP settings → Test e-mail with the 10 MB file; lower the field's maximum or fix the transport (email.md "Attachments") |
| the form with a File field cannot be saved ("Add an e-mail with a fixed recipient…") | every e-mail of the form is addressed with a placeholder → add the company notification with a fixed address |
| the File field does not appear in the builder | `forms.attachments` is off, or `forms.fields.file: false` |
| a file is refused although its type is ticked | the content does not match the extension, the name has a second extension (`cv.pdf.docx`), the document has macros, or it is password-protected |
| submission exists, no email | missing `email: mailAdapter()`, empty Emails tab, transport in the panel; server logs |
| always `turnstile` | wrong key pair / domain in Cloudflare (BuilderForm resets the token after an error) |
| the page became dynamic (`ƒ`) | `headers()` in a component instead of in the action |
@@ -27,6 +27,12 @@ export const formClasses: BuilderFormClassNames = {
choices: 'grid gap-2', // radio / checkbox group <fieldset>
legend: 'mb-1 font-medium text-fg-strong',
choice: 'flex items-center gap-2',
// File field (forms.attachments): the native input, its help text, the list of picked files.
file: 'block w-full text-fg file:mr-3 file:rounded-control file:border-0 file:bg-surface-muted file:px-3 file:py-2 file:text-fg-strong',
help: 'mt-1 text-sm text-fg-muted',
fileList: 'mt-2 grid gap-1 text-sm',
fileItem: 'flex flex-wrap items-center gap-2',
fileRemove: 'underline underline-offset-2',
error: 'mt-1 text-sm text-danger',
formError: 'rounded-control bg-danger-surface p-4 text-danger',
actions: 'flex flex-wrap gap-3',
@@ -44,6 +44,11 @@ const FORM = {
// options: [{ value: 's', label: { pl: 'do 10 tys.', en: 'up to 10k' } }, …] },
// { blockType: 'checkboxGroup', name: 'services', maxSelected: 3, label: {…}, options: [ …same shape… ] },
// { blockType: 'date', name: 'deadline', label: { pl: 'Termin', en: 'Deadline' } },
// A file sent to the company by e-mail — never stored on the site (needs `forms: { attachments: true }`).
// It rides on the notification below (fixed recipient); the confirmation to {{email}} never carries it.
// { blockType: 'file', name: 'attachment', required: false, width: 100, allowedTypes: ['pdf', 'doc', 'docx'],
// maxSizeMB: 10, maxFiles: 1, label: { pl: 'Załącznik (opcjonalnie)', en: 'Attachment (optional)' },
// help: { pl: 'PDF, DOC lub DOCX, do 10 MB', en: 'PDF, DOC or DOCX, up to 10 MB' } },
// GDPR consent — name MUST stay `consent`; never pre-ticked (the plugin enforces it server-side).
{
blockType: 'checkbox',
@@ -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,18 +25,28 @@ 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 | — |
| `twoFactor.plugin` | — (required) | injected `payloadTotp` (the plugin does not import the peer) | missing function → throws |
| `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.safeBack` | on | the `back` query value of the 2FA setup and verify screens is checked on the server before the package's view gets it (`SafeTotpView` registered in place of the package's four views): kept only as a path on the site's origin inside `routes.admin`, else the admin root — no `javascript:` / off-site redirect after the code. Needs `generate:importmap` (`@intecion/ipal-kit/admin#SafeTotpView`) | `false` = the package's views untouched; a function `(back, { adminRoute, origin }) => string` = your own rule |
| `twoFactor.importMapCheck` | on | production only: at start searches the `importMap.js` on disk (where Payload looks for it) for `@intecion/ipal-kit/admin#SafeTotpView`; when not found, logs `[ipal] The admin import map may be out of date …` and ipal-kit's `TotpRedirectProvider` puts the notice "Two-step verification may not be available" above the 2FA screens (never instead of them). A hint only — the map in the build can differ from the file on disk (Dockerfile runner stage, re-exporting map); a file that is not found is not reported | `false` = no file read, log line or notice |
| `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations.<lang>.totpPlugin.<key>` (security.md) |
| `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.<op>`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way |
| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit |
| `twoFactor.requireSetup` | on, `{ windowHours: 72 }` | an account without TOTP reaches nothing but the setup screen and `/api/setup-totp` (REST, GraphQL and the panel's data answer 403); it has `windowHours` from its creation or from an admin's reset, then it is blocked until an admin reopens setup. Adds the field `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`; the date field `totpSetupFrom` is there whenever 2FA is on (also with `requireSetup: false` / `guard: false`). Existing accounts get their window at the first start after the upgrade, written once. **Postgres/SQLite: the migration must be applied when the new container starts — `prodMigrations` or `pnpm payload migrate && pnpm start`, not a pre-deployment command (deployment.md §4.3) — or every login answers 500**; `generate:importmap`. `exempt` must return exactly `true` at once (an `async` one, or a `windowHours` that is not a number / `false`, stops the start) | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) |
| `twoFactor.requireSetup.dashboardNotice` / `.statusField` / `.setupNotice` | on | the administrators' notice on the dashboard; the status and reset control on the account page; the notice on the setup screen | `false` each (the lock and the reset endpoint stay) |
| `twoFactor.resetAccess` (the endpoint exists with `twoFactor.guard` on; `guard: false` = no endpoint, 404) | a staff admin whose session entered its own TOTP code (not an API key, not an `exempt` account) | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`). The reset clears the secret and the account's sessions. A session that still owes its code is always refused | `({ req }) => boolean` — replaces the rule, so keep `req.user?._strategy === 'totp' &&` in it unless API-key / exempt admins should reset; only `true` allows; `req.user._strategy` tells `'totp'`, `'api-key'`, `'local-jwt'` apart |
| `whiteLabel.inlineImages` | on | on the 2FA screens the logo / icon is fetched by the server as an anonymous visitor gets it (max 512 KB) and inlined as `data:` — the session there is refused `media` | `false` = the browser tries the media URL |
| `adminMeta.serveIcon` | on | `/api/ipal/admin-icon` answers with the favicon's bytes when it is a bitmap (PNG, JPEG, GIF, WebP, ICO, AVIF by its bytes); an SVG favicon always gets a redirect to the media file (never SVG bytes from the site's origin) | `false` = always the redirect |
| `twoFactor.allowCollectionMismatch` | `false` | allows `collectionSlug` ≠ `admin.user` (panel users of the other collection then skip 2FA) | `true` only when you protect a second auth collection on purpose |
| `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site settings + vendor credit | omit / `false`; `true` = defaults |
| `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — |
@@ -59,7 +69,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 |
@@ -68,6 +77,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `forms.redirectRelationships` | none | collections a form can redirect to | `['pages']` |
| `forms.emailLayout` | `false` | `beforeEmail` with a layout (logo, colour, footer) + Site settings → **Emails** tab; `{{*:table}}` readable | `true` |
| `forms.beforeEmail` | none | your own e-mail changes (after the layout) | form-builder function |
| `forms.attachments` | off | **File** field in the form builder; a file is checked (size, count, type by content, refused extensions), attached to the company e-mail and dropped — **never stored**; adds `POST /api/ipal/forms/submit`, the fields `submissionFiles` / `filesDelivery` / `filesDeliveryNote` / `attemptKey` on `form-submissions`, and the **Files** texts in Form messages | `true` / `FormAttachmentsOption`: `maxSizeMB` (10), `maxTotalMB`, `maxFiles` (3), `fileTypes`, `allowRisky`, `scan` (antivirus hook — none built in), `strictPdf`, `notice`, `maxConcurrent` (2), `path`, `submit` (`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`, `idleTimeoutMs`, `timeoutMs`); block only: `forms.fields.file: false` or `buildFileBlock(…)`. Postgres: `migrate:create`. Check: submit a PDF → attached to the company e-mail, absent from the customer e-mail, submission shows *File delivery: Handed to the mail server* (forms.md "Files") |
| `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins |
| `consentLog` | off | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (default 1095) |
| `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === '[email protected]' } }` — narrows who reads records in a project without roles |
@@ -88,8 +98,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 |
@@ -110,7 +120,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| global `cookie-settings` | banner texts, categories, cookie list; public read, write editor+ | `globalOverrides` | always present; `globalOverrides` |
| global `notifications` | form messages per language; public read, write editor+ | `globalOverrides` | always present; `globalOverrides` |
| global revalidation hook | `afterChange` on the four globals → `revalidatePath('/', 'layout')` | `revalidatePath` | omit `revalidatePath` |
| `POST /api/ipal/test-email` | SMTP/Graph test (admin only) | — | **currently always** |
| `POST /api/ipal/test-email` | SMTP/Graph test (admin only); body `{ to, attachmentMB? }` — `attachmentMB` attaches a dummy file to measure the mail server's size limit | — | **currently always** |
| `POST /api/ipal/forms/submit` | a panel form **with files** posts here (multipart, read as a stream; same gates as `sendForm`); same-origin only | `forms.attachments` (`path`, `submit`) | off by default |
| `POST /api/ipal/consent` | saves consent | `consentLog` | off by default |
| `POST /api/ipal/hit` | page view for stats | `stats` | off by default |
| `GET`/`POST /api/ipal/cookie-crawl`, `POST /api/ipal/cookie-crawl/results` | crawl status / start (editor+ or bearer token) / the scanner service's callback (token, running job only) | `cookieScanner.crawl` | off by default |
@@ -137,7 +148,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 |
@@ -176,10 +187,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 |
@@ -229,13 +241,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` |
@@ -31,11 +31,15 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `CookieApprovalForm` | `@intecion/ipal-kit/admin` | Client part of the view: tick boxes, markers (New / Changed / Needs description), Edit links, the button. Props `pending`, `gone`, `unknownCategory`, `labels?`, `adminRoute?` — reuse it in your own view. |
| `CookieCrawlAlert` | `@intecion/ipal-kit/admin` | Server Component: dashboard warning — "Waiting for approval: N" with a link to the approval view, and with the crawl violations or a failed crawl; renders nothing otherwise. Props `approval`, `crawl`. Injected with `cookieScanner` (`approval.dashboard: false` / `crawl.dashboard: false` drop its parts); after turning it on, `pnpm generate:importmap`. |
| `CookieScanButton` | `@intecion/ipal-kit/admin` | "Scan cookies" box above the *Cookie review* list: integrations in use, optional extra names, runs `POST /api/ipal/cookie-scan`. Injected by the plugin with `cookieScanner`; after turning it on, `pnpm generate:importmap`. |
| `SafeTotpView` | `@intecion/ipal-kit/admin` | Server admin view in front of the 2FA package's setup and verify views: replaces the `back` query value with a checked one and renders the view named by the serverProp `ipalTotpView` (a path or `{ path, exportName }`, found in the import map) the way Payload renders a view: a server component gets all server props, a client component only Payload's client props, `ipalTotpClientProps`, `back` and `searchParams` (both checked). `ipalSafeBack` = own rule. Registered by the plugin with `twoFactor` (`twoFactor.safeBack`, on by default). After upgrading, `pnpm generate:importmap`. Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → `/admin`. Own registration: `Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<path>' } }` + that path in `admin.dependencies`. |
| `TotpRedirectProvider` | `@intecion/ipal-kit/admin` | Client admin provider: sends a user without TOTP to `/admin/setup-totp?back=…` and a user whose session has not passed TOTP to `/admin/verify-totp?back=…` (path read in the browser; never redirects away from those screens or logout; renders nothing while redirecting). Injected by the plugin with `twoFactor` in place of the package's header-based provider; swap with `twoFactor.provider`. After upgrading, `pnpm generate:importmap`. Check: a new admin lands on `setup-totp?back=%2Fadmin` with the QR code. Props type `TotpRedirectProviderProps` (`forceSetup`) |
| `TwoFactorStatusField` | `@intecion/ipal-kit/admin` | Server component, the `totpSetupStatus` UI field ipalKit adds to the 2FA collection (sidebar of an account): "Set up", "Not set up… until <date>" or "blocked", and for an administrator on someone else's account the reset / "Reopen setup" button. Wired by the plugin with `twoFactor.requireSetup`; needs `generate:importmap`. |
| `TwoFactorResetButton` | `@intecion/ipal-kit/admin` | Client button inside `TwoFactorStatusField`: `POST /api/ipal/two-factor/reset` `{ userId }`, then reloads the view. Props `{ kind: 'reset' \| 'reopen', userId }`. |
| `TwoFactorAlert` | `@intecion/ipal-kit/admin` | Server component on the dashboard (`beforeDashboard`), administrators only: accounts without two-step verification and how many are blocked. Wired by the plugin with `twoFactor.requireSetup`; renders nothing when every account has it. |
| `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology support: Intecion.com" (admin language; `agency` prop = the name) below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }` or `agency: false`. |
| `buildAdminMeta({ agency, apiRoute?, defaultLocale?, meta?, options? })` | `@intecion/ipal-kit` | The `adminMeta` step: static panel meta (robots, preview image, icon) without overwriting keys in `meta`; returns `{ meta, resolved }` |
| `adminMetaForSite(site, resolved)`, `syncAdminMeta(payload, resolved, { nameField?, settingsSlug? })` | `@intecion/ipal-kit` | Site-name parts (suffix, description, siteName); `syncAdminMeta` writes them into the live config (onInit + Site settings afterChange, never throws) |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (favicon redirect or initials) — already added by `adminMeta` |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (the favicon itself, or initials) — already added by `adminMeta` |
| `DEFAULT_AGENCY`, `ADMIN_META_TEXTS` | `@intecion/ipal-kit` | Default agency `{ name: 'Intecion.com', url }`; en/pl meta texts (`{site}`, `{agency}`). Types `AdminMetaOptions`, `AgencyOption`, `ResolvedAdminMeta` |
## Readable array rows in the panel (`admin-ui`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
@@ -53,20 +57,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? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
@@ -277,7 +283,8 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection,
|---|---|---|
| `mailAdapter({ smtp?, graph?, fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | recommended adapter for `buildConfig({ email })`: on every send picks SMTP or Graph per the panel setting and saves the integration status; the plugin does not set `config.email` itself |
| `panelSmtpAdapter({ fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | Payload adapter that always sends through the SMTP configured in Site integrations |
| `graphAdapter({ fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | Payload adapter through Microsoft Graph (Exchange/M365; `GRAPH_*` credentials from env) |
| `graphAdapter({ fallbackFromAddress?, fallbackFromName?, largeAttachments?, cleanupDelaysMs? })` | `@intecion/ipal-kit` | Payload adapter through Microsoft Graph (Exchange/M365; `GRAPH_*` credentials from env). Attachments under 3 MB ride in `sendMail`; larger ones go through a draft + upload session (needs `Mail.ReadWrite`) and the mailbox copy is deleted; `largeAttachments: false` turns that path off (email.md "Attachments") |
| `mailAttachmentLimit(payload)` | `@intecion/ipal-kit` | Total attachment bytes the site's e-mail adapter can carry, or `null` (no ceiling of its own). About 3 MB on Graph without the large-file path and without SMTP settings — form File fields use it for the limit they show |
| `sendEmail({ payload, to, subject, html, text?, from?, replyTo? })` | `@intecion/ipal-kit/server` | sends your own e-mail (your HTML) always through SMTP from the panel → `{ sent: true, messageId }` / `{ sent: false, error }`; does not throw; server code only |
**Types:** `MailAdapterArgs`, `PanelSmtpAdapterArgs`, `GraphAdapterArgs` — adapter options; `SendEmailArgs`, `SendEmailResult` (`/server`) — `sendEmail` arguments and result.
@@ -287,7 +294,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 |
@@ -378,6 +385,11 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|---|---|---|
| `buildFormsPlugin(forms)` | `@intecion/ipal-kit` | Wires `@payloadcms/plugin-form-builder` (Forms + Form Submissions, field types, closed REST for submissions); the plugin wires it itself with the `forms` option — do not call |
| `stepBlock` | `@intecion/ipal-kit` | Form-builder "Step" block (splits the form into steps, with "Show only when"); the plugin adds it itself (`forms.fields.step`) — only for your own form-builder configuration |
| `buildFileBlock(options?)`, `fileBlock` | `@intecion/ipal-kit` | "File" block of the form builder (label, help text, allowed types, maximum size and files); the plugin adds it with `forms.attachments`. `buildFileBlock({ maxSizeMB, fileTypes, … })` for your own variant in `forms.fields.file`; `fileBlock` = the default one |
| `FORM_FILE_TYPES`, `RISKY_FILE_EXTENSIONS` | `@intecion/ipal-kit` | Built-in file types of the File field (`pdf`, `doc`, `docx`, `odt`, `rtf`, `xls`, `xlsx`, `jpg`, `png`, `webp` → label, extensions, MIME type) and the extensions refused unless `attachments.allowRisky` lists them |
| `formatFileSize(bytes)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | "2.1 MB" / "640 KB" for a file list |
| `fileFieldRules(field)`, `fileFieldError(field, files, texts)` | `@intecion/ipal-kit/client` | The limits of a File field in the browser (from `field.resolved`, set by the server) and the first problem with the picked files as the visitor's message — `useBuilderForm` uses both |
| `splitFormFiles(values)` | `@intecion/ipal-kit/server` | Splits `File` values from the answers → `{ fields, files }` for `submitForm({ data: fields, files })` in your own action or route; `createSubmitAction` already does it |
| `checkboxGroupBlock` | `@intecion/ipal-kit` | "Checkbox group" block (multiple choice, `minSelected`/`maxSelected`, value `string[]`); the plugin adds it itself (`forms.fields.checkboxGroup`) |
| `timeBlock` | `@intecion/ipal-kit` | "Time" block (`<input type="time">`, value `HH:MM`); the plugin adds it itself (`forms.fields.time`) |
| `placeholderField` | `@intecion/ipal-kit` | Payload `placeholder` field (localized hint in an empty field) for your own form blocks |
@@ -411,7 +423,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
| Export | Import from | What it does / when |
|---|---|---|
| `createSubmitAction({ getCachedPayload, headers, … })` | `@intecion/ipal-kit/server` | Creates the server action `sendForm(formId, locale, values, token?)`: honeypot → `clientIp` → `submitForm` → text from Notifications; returns `SubmitActionResult`. Standard: `export const sendForm = createSubmitAction({ getCachedPayload, headers })` in `actions.ts` |
| `submitForm({ payload, formId, data, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `ipalKit({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission; returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
| `submitForm({ payload, formId, data, files?, attemptKey?, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `ipalKit({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission; returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
### Honeypot
@@ -444,7 +456,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|---|---|---|
| `formAnalyticsOnSuccess(config)` | `@intecion/ipal-kit/client` | Turns `form.analytics` (panel) into an `onSuccess` handler that calls `pushDataLayer(event, params)` (a value like `$topic` — `$` + field name — is taken from the submitted data; empty event = no-op); `useBuilderForm` calls it itself — by hand only with `useForm`/`useContactForm` |
**Types:** `BuilderField`, `BuilderOption`, `BuilderStep`, `BuilderFormDoc`, `BuilderFormTexts`, `FieldCondition` (root, `/client`; `BuilderOption` only `/client`) — shape of the panel form, field, option, step, texts and the "Show only when" condition. `BuilderFormProps`, `BuilderFormClassNames`, `BuilderFieldRenderArgs`, `BuilderFormAction`, `BuilderFormApi`, `UseBuilderFormOptions` (`/client`) — `BuilderForm` props/classes/`renderField`, the bound action and the `useBuilderForm` result. `RenderFormProps`, `SendFormAction`, `PrepareBuilderFormArgs`, `PreparedBuilderForm` (`/rsc`) — `RenderForm` props, `sendForm` signature, `prepareBuilderForm` input/output. `SubmitFormArgs`, `SubmitFormResult`, `SubmitActionResult` (`/server`) — `submitForm` arguments and result codes, and the `sendForm` result (`{ success, message, reason?, field? }`). `FormErrors`, `FormSubmitAction`, `Validator`, `Rule` (root, `/client`), `ContactFormValues`, `ContactFormErrors`, `SubmitAction` (`/client`) — `useForm`/`useContactForm` and validator types. `FormAnalyticsConfig` (`/client`) — form analytics configuration from the panel. `FormsOption`, `FormsCollectionOverrides`, `FormsFieldsOverride` (root) — the plugin's `forms` option and collection overrides.
**Types:** `BuilderField`, `BuilderOption`, `BuilderStep`, `BuilderFormDoc`, `BuilderFormTexts`, `FieldCondition` (root, `/client`; `BuilderOption` only `/client`) — shape of the panel form, field, option, step, texts and the "Show only when" condition. `BuilderFileLimits` (root, `/client`) — what the server resolved for a File field (`field.resolved`: `maxSizeMB`, `maxTotalMB`, `maxFiles`, `accept`, `extensions`, `typeLabels`); `BuilderFile` (`/client`) — `{ name, size }`, a browser `File` fits. `FormAttachmentsOption`, `FormSubmitEndpointOptions`, `FormFileType`, `FormFileDetect`, `FormFileScanInput`, `FormFileScanResult` (root) — the `forms.attachments` option, its `submit` gates, a file type and its `detect`, and the `scan` hook's input and result. `BuilderFormProps`, `BuilderFormClassNames`, `BuilderFieldRenderArgs`, `BuilderFormAction`, `BuilderFormApi`, `UseBuilderFormOptions` (`/client`) — `BuilderForm` props/classes/`renderField`, the bound action and the `useBuilderForm` result. `RenderFormProps`, `SendFormAction`, `PrepareBuilderFormArgs`, `PreparedBuilderForm` (`/rsc`) — `RenderForm` props, `sendForm` signature, `prepareBuilderForm` input/output. `SubmitFormArgs`, `SubmitFormResult`, `SubmitActionResult` (`/server`) — `submitForm` arguments and result codes, and the `sendForm` result (`{ success, message, reason?, field? }`). `FormErrors`, `FormSubmitAction`, `Validator`, `Rule` (root, `/client`), `ContactFormValues`, `ContactFormErrors`, `SubmitAction` (`/client`) — `useForm`/`useContactForm` and validator types. `FormAnalyticsConfig` (`/client`) — form analytics configuration from the panel. `FormsOption`, `FormsCollectionOverrides`, `FormsFieldsOverride` (root) — the plugin's `forms` option and collection overrides.
## Links (`links`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
@@ -558,13 +570,13 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| Export | Import from | What it does / when |
|---|---|---|
| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, formsCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local, only }`. `only` (or `SEED_ONLY`) = the records the run may touch (`pages:kontakt`, `forms:<title>`, `global:<slug>`, `pages:*`), the rest → `skip (not listed)`; a run without it against production / a non-local database throws unless `IPAL_SEED_ALLOW_FULL=1` / `guard.allowFull: true` (after launch: named records only; dry runs are never refused; `guard: false` turns every guard off). Create-only by default, natural keys, never deletes, globals: empty fields only, every locale with `fallbackLocale: false` onto the same row ids, skips records edited since seeding, writes with `context` `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }`. Throws when `update` runs on production / a non-local database without `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Both seed templates use it. |
| `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`). |
| `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) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids. |
| `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). |
| `seedHash(value)` | `@intecion/ipal-kit/seed` | Stable hash for the hidden `seedHash` field (key order, row ids, nulls ignored). |
| `projectOnto(seed, current)` | `@intecion/ipal-kit/seed` | Current values at the keys the seed writes — hash them to compare with the stored hash. |
| `editedSinceSeed({ doc, currentHash?, hashField?, untouchedSeconds? })` | `@intecion/ipal-kit/seed` | `null` = untouched; otherwise the reason (stored hash differs / `updatedAt` too late after `createdAt`). |
@@ -577,6 +589,20 @@ 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`. |
| `safeAdminBack(back, { adminRoute, origin? })` | `@intecion/ipal-kit` | The default `back` rule of the 2FA screens: returns `back` as a path when it resolves to the site's origin (the placeholder origin for relative values, `origin` for absolute ones), over HTTP(S), without credentials, inside `adminRoute`; otherwise the admin root. `safeAdminBack('javascript:alert(1)', { adminRoute: '/admin' })` → `'/admin'`; `safeAdminBack('/admin/collections/pages?page=2', { adminRoute: '/admin' })` → the same path. Use it in your own rule or view. |
| `wrapTotpViews(views, added, rule?, wrapper?)` | `@intecion/ipal-kit` | Puts `SafeTotpView` in front of the views whose route is `setup-totp` / `verify-totp` and for which `added(key)` is true (keeps `exportName`, `serverProps`; `clientProps` travel as `ipalTotpClientProps`); returns `{ views, dependencies }` (`dependencies` → `admin.dependencies`, so the wrapped views stay in the import map). What `ipalKit` runs after the 2FA factory; for a project that registers the 2FA package itself. |
| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". |
| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. |
| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)<admin route>/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. |
| `buildSetupFields({ statusField? })`, `stampSetupFrom`, `backfillSetupFrom(payload, collection)` | `@intecion/ipal-kit` | The parts of "2FA setup required" for a project that wires them itself: the fields for the 2FA collection (`totpSetupFrom`, and the panel's `totpSetupStatus` unless `statusField: false`), the `beforeChange` hook that stamps the window start (on create, and when an account loses its TOTP secret), and the start-up step that gives accounts without TOTP and without a start their window (returns how many; once per account). |
| `buildTwoFactorResetEndpoint(collection, { access? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). `ipalKit` registers it only with `twoFactor.guard` on. |
| `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. |
| `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. |
| `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. `rasterImageType(bytes)` → the media type of a bitmap by its first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF) or `null` — never trust a claimed type before answering a file's bytes from the site's origin; an SVG gives `null`. |
| `UPLOAD_SECURITY_HEADERS` | `@intecion/ipal-kit` | The two headers of `buildUploadSecurityHeaders` (`Content-Security-Policy: default-src 'none'; … sandbox`, `X-Content-Type-Options: nosniff`) for a route of your own that returns an uploaded file's bytes from the site's origin. In a Next project a site-wide `headers()` rule with the same key overrides a header the route sets itself: add a `headers()` rule for the path after the site-wide one (as `buildUploadSecurityHeaders({ collections, adminIcon })` does for the upload routes and `/api/ipal/admin-icon`), and never answer with an SVG. |
| `twoFactorSetupState(req)`, `twoFactorSetupDeadline(req)` | `@intecion/ipal-kit` | Where an account stands with TOTP setup, from `{ payload, user }`: `'set-up'`, `'open'` (may set it up now), `'closed'` (the setup window has passed: blocked until an admin reopens it), `'exempt'` (`requireSetup.exempt`, or `requireSetup: false`), `'not-applicable'` (no user, another collection, 2FA off); and the moment setup closes (`Date`, or `null` without a window). Types: `TwoFactorSetupState`, `RequireSetupOptions`. |
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
| `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` |
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
| `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 ---------------------------------------------------------------
+48 -12
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
@@ -93,10 +93,16 @@ legacy-peer-deps=true
pnpm add @intecion/ipal-kit @payloadcms/plugin-seo @payloadcms/plugin-form-builder \
@payloadcms/storage-s3 @clocklimited/payload-2fa@3.0.0-beta.7 tailwindcss @tailwindcss/postcss
```
**Next.js 16.4.1 or later** (minimum safe version: 16.0.0–16.4.0 have critical advisories, AGENT.md §4 item 11):
`pnpm add next@^16.4.1 eslint-config-next@^16.4.1 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` and `undici` overrides from AGENT.md §4 item 12.
**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].6 [email protected].6 sharp@^0.35.5` when
create-payload-app gave you an older one.
**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
@@ -104,7 +110,7 @@ plugin-seo, plugin-form-builder, storage-s3) in `pnpm.overrides` **to the exact
`"build": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" next build --webpack"`.
**Check.** `ls node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` exists;
`pnpm ls payload @payloadcms/ui @payloadcms/plugin-seo` — one, identical version; `pnpm ls next sharp` → next ≥ 16.4.1,
`pnpm ls payload @payloadcms/ui @payloadcms/plugin-seo` — one, identical version; `pnpm ls next sharp` → next ≥ 16.4.5,
sharp ≥ 0.35.5; `ls src/middleware.ts` → not found.
404 on `pnpm add` = missing `@intecion:registry` line; 401 = stale `_authToken` in `~/.npmrc` (PROGRAMISTA §1).
@@ -193,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.
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider` and `#SafeTotpView`); `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, 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`.
@@ -211,11 +217,41 @@ 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`).
The `back` link of the setup and verify screens is checked on the server (`twoFactor.safeBack`, on by default:
only a path inside the admin route is kept; `false` turns it off, a function replaces the rule). It needs the
import map entry `@intecion/ipal-kit/admin#SafeTotpView` — run `pnpm payload generate:importmap` and commit
(a production build with a map that lacks it shows 2FA screens without a code form: nobody can sign in;
`ipal-doctor`, the start log and a notice above the screen report it; `twoFactor.importMapCheck: false` turns the
log line and the notice off — needed when the `importMap.js` on disk is not the one the build used).
Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → you land on `/admin`.
**Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone
opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`.
**Setup required** (`twoFactor.requireSetup`, default): an account without TOTP reaches only the setup screen; it
has 72 h from its creation (or an admin's "Reopen setup" on the account page), then it is blocked. So create an
account, hand over the password and have the owner set 2FA up at once. **Postgres/SQLite: `pnpm payload
migrate:create` and have the migration applied when the container starts, before the site serves** — `prodMigrations`
or the start command `pnpm payload migrate && pnpm start`, never a pre-deployment command (deployment.md §4.3)
(column `totp_setup_from`, there whenever 2FA is
on) — without it every login answers 500; `pnpm payload generate:importmap` (`TwoFactorStatusField`,
`TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }` (a plain function
returning exactly `true`; never `async`); an API key needs nothing. Parts to switch off: `requireSetup:
{ dashboardNotice: false, statusField: false, setupNotice: false }`. An admin's reset ends the account's
sessions and needs the admin's own TOTP code (`twoFactor.resetAccess` changes who). Have two administrators
with 2FA: when all are blocked, only a script or a redeploy helps (security.md "Every administrator is
blocked"). One entity reachable without the code: `custom.ipal.secondFactor`.
- 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
@@ -505,7 +541,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.
+198 -7
View File
@@ -82,13 +82,38 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
`buildGlobalRevalidateHook({ revalidatePath })`; `consentFieldName` passed only because the option was ignored →
`forms.consentFieldName` works now; your own seed guard / upsert code → `@intecion/ipal-kit/seed` (`createSeeder`).
**Every upgrade — Next.js 16.4.1 or later** (AGENT.md §4 item 11): `pnpm ls next sharp`; below 16.4.1 →
`pnpm add next@^16.4.1 eslint-config-next@^16.4.1 sharp@^0.35.5`, `rm -rf .next`, build, redeploy on Coolify
(a new image ships the fixed next and sharp). **Check:** `pnpm dev` prints no security-upgrade warning.
**Every upgrade — Next.js 16.4.5 or later** (AGENT.md §4 item 11): `pnpm ls next sharp`; below 16.4.5 →
`pnpm add [email protected].6 [email protected].6 sharp@^0.35.5`, `rm -rf .next`, build, redeploy on Coolify
(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` and `undici` overrides, `pnpm install`, audit again. **Check:** no high or critical (the
`deepmerge` low has no fix yet).
**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",
"undici@>=7 <7.30.1": "^7.30.1"
```
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)
@@ -98,7 +123,7 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
`engines`. Remove `nodemailer` and `@types/nodemailer` from the project's own `package.json` if someone added them
(the plugin's copy is the one `mailAdapter` uses). **Check:** Site integrations → E-mail sending → send a test
e-mail over SMTP (and over Microsoft Graph when the project uses it).
3. **Next.js 16.4.1 or later** — the "Every upgrade — Next.js" step above (`next@^16.4.3`, `sharp@^0.35.5`).
3. **Next.js** — the "Every upgrade — Next.js" step above (today 16.4.5 or later, `sharp@^0.35.5`).
4. **Dependency advisories** — the "Every upgrade — dependency advisories" step above (`dompurify` / `graphql-scalars` /
`undici` overrides on payload 3.90.x). **Check:** `pnpm audit --prod` → no high or critical.
5. **Cookie list kept by hand** → offer `cookieScanner: true` (+ `crawl: true` with `IPAL_COOKIE_SCAN_URL`,
@@ -230,6 +255,172 @@ and the browser tab shows the same separator.
2. Two frontend candidates reported → `"layout": { "frontend": "src/app/(<group>)" }` in `ipal-doctor.json`.
**Check:** `pnpm exec ipal-doctor --strict` → no `layout-required` finding for the site's own route group.
**→ 1.15.3 (PROGRAMISTA §6, item 58; ipal-audit, bilingual panel labels; ipal-audit skill) — nothing required:**
1. `pnpm ipal:skills`, so the updated `audit.sh` and `polish-literals.mjs` reach the project.
2. Remove a temporary `i18n-literals` silence or `ipal-audit-skip` added because of `adminText()` / `{ en, pl }` labels.
**Check:** `pnpm exec ipal-doctor --strict` → no `i18n-literals` finding for a schema file's bilingual labels; Polish
text in a `.tsx` component is still reported.
**→ 1.15.4 (PROGRAMISTA §6, item 59; seeding whole localized arrays; seeding.md) — nothing required:**
1. Did a seed write a whole localized array (`{ pl: [...], en: [...] }` for form fields, a page `layout`, a global
array) and the panel shows only the last language? A plain re-run skips existing records (create-only): rewrite
them locally with `SEED_UPDATE=1 pnpm seed` and check every language in the panel.
2. Live site, only the affected records: `SEED_ONLY="forms:<title>,pages:<slug>" SEED_UPDATE=1
IPAL_SEED_ALLOW_PROD_UPDATE=1 SEED_DRY_RUN=1 pnpm seed`, back up the database (Coolify), then the same without
`SEED_DRY_RUN`. Records an editor changed since seeding are skipped (`skip (edited)`) — fix them in the panel.
3. A global array: `fillGlobal` fills empty fields only — clear the field in the panel before the run, or fix it by hand.
**Check:** the panel shows the seeded rows in every language; a second run reports `skip`, not new rows.
**→ 1.15.5 (PROGRAMISTA §6, item 60; required fields with references in seeds; seeding.md) — nothing required:**
1. A seed that failed with "The following field is invalid: … > Layout" for a page whose required layout links to
another page or a form: run it again — the record is now created complete (`SEED_DRY_RUN=1` first).
2. The dry run is stricter: a `{ $form }` / `{ $page }` to a record that neither exists nor is seeded earlier in the run is
an error. Seed that record first or create it in the panel.
3. A "cycle of required links" error: make one of the two links optional, or seed one of the pages first.
**Check:** `SEED_DRY_RUN=1 pnpm seed` reports 0 errors; the real run creates the same records.
**→ 1.16.0 (PROGRAMISTA §6, item 61; files on forms, e-mailed and never stored; forms.md "Files") — nothing required:**
1. `pnpm ipal:skills`. Existing forms need nothing; without `forms.attachments` nothing changes. No import map change.
2. Only if the site wants files on a form (ask the owner): `ipalKit({ forms: { attachments: true } })`, a **File** field on
the form (panel or seed — `ipal-form` skill), one e-mail of that form with a fixed recipient (no `{{field}}`),
`pnpm generate:types`; Postgres/SQLite: `pnpm payload migrate:create` (additive). Add the `formClasses` keys `file`,
`help`, `fileList`, `fileItem`, `fileRemove`; fill Form messages → Files for languages other than en/pl.
3. A hand-built upload path for a form (own collection, bucket, route): replace it with the File field and remove it
(after the owner confirms nothing else uses the stored files).
4. Deploy: a proxy body limit of at least 12 MB on `/api/ipal/forms/submit` (Coolify's Traefik: none by default;
nginx: `client_max_body_size 12m;`). Mail: Graph needs `Mail.ReadWrite` limited to the forms mailbox for files of
3 MB and more, or SMTP settings in Site integrations; otherwise the limit is about 2.8 MB.
**Check:** Site integrations → "Send test e-mail" with the 10 MB file arrives; a form submission with a file arrives with
the attachment, and the submission shows **File delivery: Sent**; with Graph, no draft or Sent Items copy is left in the
sender mailbox a minute later.
**→ 1.16.1 (PROGRAMISTA §6, item 62; Next.js minimum 16.4.5, GHSA-mfr8-8qww-v76h; AGENT.md §4 item 11) — required for
every site below Next.js 16.4.5:**
1. `pnpm add [email protected] [email protected]`, `rm -rf .next`, `pnpm build`; commit `package.json` and the lockfile,
redeploy on Coolify (the new image ships the fixed Next.js).
2. `pnpm ipal:skills` (updated `ipal-setup` / `ipal-upgrade`).
**Check:** `pnpm ls next` → 16.4.6; `pnpm exec ipal-doctor` → no `next-min` finding; `pnpm dev` prints no security warning.
**→ 1.16.2 (PROGRAMISTA §6, item 63; Payload's mongoose and happy-dom advisories; AGENT.md §4 item 12) — required for
every site:**
1. Add to `pnpm.overrides` in `package.json`: `"mongoose@>=8 <8.24.7": "~8.24.10"` (MongoDB sites only) and
`"happy-dom@<21.0.4": "^21.0.4"` (every site). Then `pnpm install`, `pnpm build`; commit `package.json` and the
lockfile, redeploy on Coolify. No data change, no migration.
2. `pnpm ipal:skills` (updated `ipal-setup` / `ipal-upgrade`).
**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.
**→ 1.16.5 (PROGRAMISTA §6, item 67; CHANGELOG 1.16.5; security.md "The `back` link of the 2FA screens") — required with 2FA on:**
1. **Do this in ONE deploy with the upgrade, or the panel is locked for everyone.** Run `pnpm exec ipal-doctor`
before deploying.
`pnpm payload generate:importmap` — the plugin puts `@intecion/ipal-kit/admin#SafeTotpView` in front of the
2FA package's setup and verify views; commit `importMap.js`, `rm -rf .next`, redeploy on Coolify. With the old
import map the build passes and the site starts, but the 2FA screens have no code form (HTTP 200) — nobody can
sign in. Signs: `pnpm exec ipal-doctor` → `import map lacks …SafeTotpView` (run it before deploying); the log
line `[ipal] The admin import map may be out of date` at start; the notice "Two-step verification may not be
available" where the form should be. Fix: the same command, commit, redeploy.
The log line and the notice with a **working** code form mean a false alarm (the `importMap.js` on disk is not
the one the build used — a Dockerfile runner stage, a re-exporting map): sign-in works; set
`twoFactor.importMapCheck: false`.
**Check:** log in with the password only → open `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → enter
the code → you land on `/admin` (not on example.com); a normal login still returns to the page you came from.
No option, env, schema or migration. A project that registered its own 2FA views, or wrote a proxy rule that
strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off).
2. `pnpm ipal:skills`.
**→ 1.16.6 — 2FA setup required (CHANGELOG 1.16.6; PROGRAMISTA §6, item 68; security.md "Setup required") — required with 2FA on:**
**Not a routine patch, although the number is one.** From this version an account without 2FA can only set it up and is
blocked after 72 hours; on Postgres / SQLite a missing migration locks everyone out of the panel. Do not upgrade a live
site without steps 1–3 and a deploy day agreed with the owner. Steps 2, 3 and 5 go in ONE deploy.
1. **Before upgrading a live site:** `pnpm exec ipal-doctor --url <site>` (doctor token) → accounts without 2FA.
Tell the owner: from the upgrade on, such an account can only set 2FA up, and has 72 hours for it; after that
an administrator must reopen setup on the account's page. Have them set it up now, or remove unused accounts.
Make sure at least one administrator (better two) has 2FA set up — otherwise nobody can reopen setup from the panel.
The 72 hours of existing accounts start at the first start after the deploy and are counted once (restarts
and redeploys do not extend them): agree the deploy day with the owner.
2. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`,
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`),
then `pnpm exec ipal-doctor` before deploying.
3. **Postgres/SQLite — required, same deploy, or nobody can log in:** `pnpm payload migrate:create` (adds the
column `totp_setup_from` to the 2FA collection; needed whenever 2FA is on, also with `requireSetup: false`),
commit, and have it applied **when the new container starts**: `prodMigrations` in the database adapter, or the
start command `pnpm payload migrate && pnpm start` (deployment.md §4.3). **Never Coolify's Pre-deployment
command** — it runs in the old container, without the new migration, and the new version then starts without
the column. Without the column every login answers 500, administrators included; the log says
`[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN`. `pnpm exec ipal-doctor` reports
it before the deploy. MongoDB: nothing.
4. An integration that logs in with a password and has no TOTP: give it an API key, or
`twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`. `grep -rn "overrideAccess: false" src`:
a `user` fetched by id is refused for every account now — take it from `payload.auth({ headers })`.
5. `rm -rf .next`, build, redeploy on Coolify. Read the first lines of the log: `[ipal] 2FA: N existing account(s)
without two-step verification…` — pass that number to the owner. The line appears on that first start only.
Postgres/SQLite: if logins answer 500 after the deploy, the migration from step 3 did not run — check that it
is committed and that the container runs migrations at start (deployment.md §4.3), then redeploy.
6. `requireSetup.exempt` must be a plain function returning `true` / `false` (an `async` one stops the start).
A script on an API key is refused by `POST /api/ipal/two-factor/reset` by default — pass
`twoFactor.resetAccess` if that is wanted. A reset ends the account's sessions (it logs in again); after a
suspected compromise change the password too. An SVG favicon has no tab icon on the 2FA screens.
7. Tell the owner what to tell the staff: a new account has 72 hours to set 2FA up, then an administrator must
choose "Reopen setup". Not wanted: `twoFactor.requireSetup: false`, or `{ windowHours: false }`.
**Every administrator is blocked** (all missed the 72 h): security.md "Every administrator is blocked" — a
`pnpm payload run` script that sets `totpSetupFrom` to now for one administrator, or
`requireSetup: { windowHours: false }` + redeploy, set 2FA up, put it back.
**Check:** create a throwaway account → its token gets `403` from `/api/users/me`; in the panel it lands on the
setup screen with "Set up two-step verification by …"; after the code it is in. As an administrator open that
account → "Two-step verification: Set up." and the reset button; delete the account.
## 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):
+2
View File
@@ -56,4 +56,6 @@ INDEXNOW_KEY=
E2E_ADMIN_EMAIL=[email protected]
E2E_ADMIN_PASSWORD=e2e-RC2nC29eKC8HJHfg
E2E_TOTP_SECRET=JPURUZNWYTZX2L42MT4SS7736WWNQWBL
# Port of the mail sink the smoke tests start (e2e/smtp-sink.ts); create-test-admin.ts points e-mail sending at it
E2E_SMTP_PORT=2526
# @starter:endif
+1 -1
View File
@@ -47,7 +47,7 @@ Write everything in this file in English.
<!-- /starter:decisions -->
<!-- ipal-kit:start -->
## ipal-kit 1.15.2 — agent guide
## ipal-kit 1.16.6 — 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:
+12 -1
View File
@@ -3,7 +3,8 @@
* the real 2FA screen instead of skipping it. LOCAL / CI database only:
* pnpm payload run e2e/create-test-admin.ts
* Values come from E2E_ADMIN_EMAIL / E2E_ADMIN_PASSWORD / E2E_TOTP_SECRET (.env.example). Not a seed: seeds
* never create users (docs/seeding.md).
* never create users (docs/seeding.md). It also points e-mail sending at the tests' local mail sink
* (E2E_SMTP_PORT, default 2526).
*/
import config from '@payload-config'
import { isLocalDatabase } from '@intecion/ipal-kit/seed'
@@ -23,4 +24,14 @@ if (found.docs[0]) {
await payload.create({ collection: 'users', data: data as never, overrideAccess: true })
}
console.log(`[e2e] test admin ready: ${email}`)
// E-mail for the smoke tests goes to a local sink the test itself starts (e2e/smtp-sink.ts), so the test can
// read what the site sent — the form file as an attachment. Without the sink running, sends simply fail.
const smtpPort = Number(process.env.E2E_SMTP_PORT ?? 2526)
await payload.updateGlobal({
slug: 'site-integrations',
data: { emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpHost: '127.0.0.1', smtpPassword: 'e2e-sink', smtpPort, smtpUser: 'e2e' } as never,
overrideAccess: true,
})
console.log(`[e2e] e-mail sending points at the local sink 127.0.0.1:${smtpPort}`)
process.exit(0)
+117
View File
@@ -1,5 +1,6 @@
import { expect, type Page, test } from '@playwright/test'
import { attachmentOf, startSmtpSink } from './smtp-sink'
import { totp } from './totp'
/**
@@ -66,6 +67,89 @@ for (const l of LOCALES) {
})
}
// Files on forms (forms: { attachments: true }): e-mailed to the studio, never stored. A real browser, the real
// endpoint and a local mail sink — the file must arrive as an attachment of the staff e-mail only.
test.describe('the quote form sends a file by e-mail', () => {
const PDF = Buffer.concat([Buffer.from('%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF\n'), Buffer.alloc(200_000, 0x20)])
let sink: Awaited<ReturnType<typeof startSmtpSink>>
test.beforeAll(async () => {
sink = await startSmtpSink(Number(process.env.E2E_SMTP_PORT ?? 2526))
})
test.afterAll(async () => {
await sink.close()
})
async function fillQuote(page: Page) {
await page.goto('/en/quote')
await rejectCookies(page)
const form = page.locator('form[data-ipal="form"]').first()
await form.locator('input[name="name"]').fill('Test Smoke')
await form.locator('input[name="email"]').fill('[email protected]')
await form.locator('button[type="submit"]').click() // Next
await form.locator('input[name="scope"][value="building"]').check()
await form.locator('input[name="area"][value="s"]').check()
await form.locator('input[name="consent"]').check()
return form
}
test('a wrong file is refused at the field; a PDF arrives attached to the staff e-mail, not the customer one', async ({ page }) => {
const form = await fillQuote(page)
const input = form.locator('input[type="file"][name="attachment"]')
await expect(input).toHaveAttribute('accept', /\.pdf/)
// a type the field does not accept: the message shows at once, by the field
await input.setInputFiles({ buffer: Buffer.from('MZ'), mimeType: 'application/octet-stream', name: 'plan.exe' })
await expect(form.locator('[id$="attachment-error"]')).toContainText('The file "plan.exe" is in a format we do not accept. Choose one of: PDF, JPG, PNG.')
// keyboard: the Remove button is a real button — focus it and press Enter
await form.getByRole('button', { name: /Remove plan\.exe/ }).focus()
await page.keyboard.press('Enter')
await expect(form.locator('[data-ipal="form-files"] li')).toHaveCount(0)
// a program renamed to .pdf passes the browser check and is stopped by the server (content, not name)
await input.setInputFiles({ buffer: Buffer.concat([Buffer.from('MZ\x90\x00'), Buffer.alloc(2000)]), mimeType: 'application/pdf', name: 'plan.pdf' })
const token = form.locator('input[name="cf-turnstile-response"]')
await expect(token).not.toHaveValue('', { timeout: 15_000 })
await form.locator('button[type="submit"]').click()
// the message is at the File field, names the file, says why and what to do; nothing the visitor typed is lost
const problem = form.locator('[id$="attachment-error"]')
await expect(problem).toContainText('The file "plan.pdf" was refused', { timeout: 15_000 })
await expect(problem).toContainText('Choose another file (PDF, JPG, PNG). You can also send the form without the file.')
await expect(input).toHaveAttribute('aria-invalid', 'true')
await expect(form.locator('input[name="scope"][value="building"]')).toBeChecked()
await expect(form.locator('input[name="consent"]')).toBeChecked()
await form.getByRole('button', { name: 'Back' }).click()
await expect(form.locator('input[name="name"]')).toHaveValue('Test Smoke')
await expect(form.locator('input[name="email"]')).toHaveValue('[email protected]')
await form.locator('button[type="submit"]').click() // Next
expect(sink.messages).toHaveLength(0)
// the real file (the field takes several: remove the refused one first)
await form.getByRole('button', { name: /Remove plan\.pdf/ }).click()
await input.setInputFiles({ buffer: PDF, mimeType: 'application/pdf', name: 'Floor plan (ground).pdf' })
await expect(form.locator('[data-ipal="form-files"] li')).toContainText('Floor plan (ground).pdf')
// After a refusal the spam check renews itself (a token is single-use). The test keys always give the same
// dummy token, so there is nothing to watch for: submit until the request goes out.
let status = 0
await expect(async () => {
const posted = page.waitForResponse((r) => r.url().includes('/api/ipal/forms/submit') && r.request().method() === 'POST', { timeout: 3000 })
await form.locator('button[type="submit"]').click()
status = (await posted).status()
}).toPass({ timeout: 25_000 })
expect(status).toBe(200)
await expect(page.locator('[data-ipal="form-success"]')).toBeVisible({ timeout: 15_000 })
await expect.poll(() => sink.messages.length, { timeout: 15_000 }).toBe(2)
const staff = sink.messages.find((m) => !m.to.join().includes('[email protected]'))!
const customer = sink.messages.find((m) => m.to.join().includes('[email protected]'))!
const attached = attachmentOf(staff.data, 'Floor plan (ground).pdf')
expect(attached && Buffer.compare(attached, PDF)).toBe(0)
const text = (raw: string) => raw.replace(/=\n/g, '') // undo quoted-printable soft line breaks
expect(text(staff.data)).toContain('not checked for viruses')
expect(customer.data).not.toContain('Content-Disposition: attachment')
expect(text(customer.data)).toContain('Floor plan (ground).pdf') // the name in the summary, never the file
})
})
test('every sitemap URL answers 200 with a title, canonical, hreflang and JSON-LD', async ({ page, request }) => {
const xml = await (await request.get('/sitemap.xml')).text()
const urls = [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => new URL(m[1]).pathname)
@@ -135,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()
})
+64
View File
@@ -0,0 +1,64 @@
import { createServer, type Server } from 'node:net'
export type SinkMessage = { data: string; to: string[] }
/**
* A mail sink for the smoke tests: just enough SMTP for nodemailer to log in and deliver. It keeps every
* message in memory, so a test can read what the site really sent (recipients, attachments).
* e2e/create-test-admin.ts points Site integrations → E-mail sending at it (127.0.0.1:E2E_SMTP_PORT).
*/
export function startSmtpSink(port: number): Promise<{ close: () => Promise<void>; messages: SinkMessage[] }> {
const messages: SinkMessage[] = []
const server: Server = createServer((socket) => {
const mail: SinkMessage = { data: '', to: [] }
let inData = false
let buffer = ''
const reply = (line: string) => socket.write(`${line}\r\n`)
reply('220 localhost ESMTP smoke-sink')
socket.on('error', () => undefined)
socket.on('data', (chunk) => {
buffer += chunk.toString('latin1')
let index: number
while ((index = buffer.indexOf('\r\n')) >= 0) {
const line = buffer.slice(0, index)
buffer = buffer.slice(index + 2)
if (inData) {
if (line === '.') {
inData = false
messages.push({ ...mail, to: [...mail.to] })
reply('250 2.0.0 Ok: queued')
} else {
mail.data += `${line}\n`
}
continue
}
const command = line.toUpperCase()
if (command.startsWith('EHLO')) {socket.write('250-localhost\r\n250-AUTH PLAIN LOGIN\r\n250 8BITMIME\r\n')}
else if (command.startsWith('AUTH PLAIN')) {reply('235 2.7.0 Authentication successful')}
else if (command.startsWith('MAIL FROM:')) {reply('250 2.1.0 Ok')}
else if (command.startsWith('RCPT TO:')) {
mail.to.push(line.slice(8).trim())
reply('250 2.1.5 Ok')
} else if (command === 'DATA') {
inData = true
reply('354 End data with <CR><LF>.<CR><LF>')
} else if (command === 'QUIT') {
reply('221 2.0.0 Bye')
socket.end()
} else {reply('502 5.5.2 Command not recognized')}
}
})
})
return new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(port, '127.0.0.1', () => resolve({ close: () => new Promise((done) => server.close(() => done())), messages }))
})
}
/** The decoded bytes of the attachment named `filename` in a raw message, or null. */
export function attachmentOf(raw: string, filename: string): Buffer | null {
const at = raw.indexOf(`filename=${filename}`) >= 0 ? raw.indexOf(`filename=${filename}`) : raw.indexOf(`filename="${filename}"`)
if (at < 0) {return null}
const body = raw.slice(raw.indexOf('\n\n', at) + 2)
return Buffer.from(body.slice(0, body.indexOf('\n--')).replace(/\s+/g, ''), 'base64')
}
+92
View File
@@ -0,0 +1,92 @@
import { type Browser, expect, type Page, test } from '@playwright/test'
import { randomUUID } from 'node:crypto'
import { totp } from './totp'
/**
* The `back` link of the 2FA screens (twoFactor.safeBack, security.md). The 2FA package sends the browser to
* `back` after a valid code; ipal-kit checks the value first. A prepared link must end on the admin root:
* no script in the panel, no other site. Run against a built site with the test admin (create-test-admin.ts).
*
* Two verify attempts for the test admin here; the smoke spec makes two more (the limit is 5 in 10 minutes).
*/
const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = process.env
/** Script that would mark the page: runs only if the browser follows `back` as given. */
const SCRIPT = "javascript:void(document.title='XSS-'+document.domain)"
async function passwordOnly(browser: Browser, baseURL: string, who: { email: string; password: string }): Promise<Page> {
const context = await browser.newContext({ baseURL })
const page = await context.newPage()
await page.goto('/admin/login')
await page.fill('#field-email', who.email)
await page.fill('#field-password', who.password)
await page.click('.form-submit button')
await page.waitForURL(/(verify|setup)-totp/, { waitUntil: 'commit' })
return page
}
async function enterCode(page: Page, code: string) {
// six one-digit inputs: type the code into the first, focus moves on by itself
await page.getByRole('textbox').first().click()
await page.keyboard.type(code)
}
/** The page ended on the admin root of this site, and the marker script did not run. */
async function expectAdminRoot(page: Page, baseURL: string) {
await expect(page).toHaveURL(new RegExp(`^${baseURL.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/admin/?$`), { timeout: 20_000 })
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
expect(await page.title()).not.toContain('XSS-')
}
test('2FA screens: a prepared back link ends on the admin root', async ({ baseURL, browser }) => {
test.skip(!email || !password || !secret, 'E2E_* test admin not configured')
test.setTimeout(120_000)
const admin = { email: email!, password: password! }
const other = new URL(baseURL!)
other.hostname = other.hostname === 'localhost' ? '127.0.0.1' : 'localhost' // another origin, still this machine
// verify screen, script in `back`
const first = await passwordOnly(browser, baseURL!, admin)
await first.goto(`/admin/verify-totp?back=${encodeURIComponent(SCRIPT)}`)
await enterCode(first, totp(secret!))
await expectAdminRoot(first, baseURL!)
// two accounts that have not set TOTP up yet, made by the admin who is now fully signed in
const fresh = [0, 1].map(() => ({ email: `e2e-back-${randomUUID()}@example.com`, password: `T-${randomUUID()}` }))
const ids: string[] = []
for (const account of fresh) {
const created = await first.request.post('/api/users', { data: { ...account, roles: ['editor'] }, headers: { origin: baseURL! } })
expect(created.status()).toBe(201)
ids.push((await created.json()).doc.id)
}
try {
// verify screen, another host written with a backslash
const second = await passwordOnly(browser, baseURL!, admin)
await second.goto(`/admin/verify-totp?back=${encodeURIComponent(`/\\${other.host}/admin/login?landed=elsewhere`)}`)
await enterCode(second, totp(secret!))
await expectAdminRoot(second, baseURL!)
await second.context().close()
// setup screen, script in `back`
const third = await passwordOnly(browser, baseURL!, fresh[0])
await third.goto(`/admin/setup-totp?back=${encodeURIComponent(SCRIPT)}`)
const newSecret = await third.locator('input[type="hidden"]').evaluateAll((inputs) => inputs.map((i) => (i as HTMLInputElement).value).find((v) => /^[A-Z2-7]{16,}$/.test(v)))
expect(newSecret).toBeTruthy()
await enterCode(third, totp(newSecret!))
await expectAdminRoot(third, baseURL!)
await third.context().close()
// setup screen, an ordinary link back into the panel is still followed
const fourth = await passwordOnly(browser, baseURL!, fresh[1])
await fourth.goto(`/admin/setup-totp?back=${encodeURIComponent('/admin/collections/pages?limit=5')}`)
const fourthSecret = await fourth.locator('input[type="hidden"]').evaluateAll((inputs) => inputs.map((i) => (i as HTMLInputElement).value).find((v) => /^[A-Z2-7]{16,}$/.test(v)))
await enterCode(fourth, totp(fourthSecret!))
await expect(fourth).toHaveURL(/\/admin\/collections\/pages\?limit=5$/, { timeout: 20_000 })
await fourth.context().close()
} finally {
for (const id of ids) {await first.request.delete(`/api/users/${id}`, { headers: { origin: baseURL! } })}
await first.context().close()
}
})
+127
View File
@@ -0,0 +1,127 @@
import { type APIRequestContext, expect, type Page, test } from '@playwright/test'
import { totp } from './totp'
/**
* "2FA setup required" in a real browser: an account that has not set two-step verification up sees only the setup
* screen and gets nothing from the API; after the code it is in. Covers the first admin of a fresh site (only when
* the database has no users yet — run this file before e2e/create-test-admin.ts for that), a new editor, and the
* administrator's reset on the account page.
* E2E_BASE_URL=http://localhost:3217 pnpm exec playwright test e2e/two-factor-setup.spec.ts
*/
test.describe.configure({ mode: 'serial' })
const stamp = Date.now()
const OWNER = { email: `e2e-owner-${stamp}@example.com`, password: `owner-${stamp}-Hk29dLq` }
const EDITOR = { email: `e2e-editor-${stamp}@example.com`, password: `editor-${stamp}-Pz71mWx` }
/** The admin the later tests act as: the owner made in the first test, else the smoke-test admin. */
let admin: { email: string; password: string; secret: string } | null =
process.env.E2E_ADMIN_EMAIL && process.env.E2E_ADMIN_PASSWORD && process.env.E2E_TOTP_SECRET
? { email: process.env.E2E_ADMIN_EMAIL, password: process.env.E2E_ADMIN_PASSWORD, secret: process.env.E2E_TOTP_SECRET }
: null
let editorId: string | undefined
async function typeCode(page: Page, secret: string) {
// six one-digit inputs: type the code into the first, focus moves on by itself
await page.getByRole('textbox').first().click()
await page.keyboard.type(totp(secret))
}
async function signIn(page: Page, who: { email: string; password: string }) {
await page.goto('/admin/login')
await page.fill('#field-email', who.email)
await page.fill('#field-password', who.password)
await page.click('.form-submit button')
}
/** A fully logged-in API session (password, then the code). Payload takes the cookie only with the site's Origin. */
async function adminApi(playwright: { request: { newContext: (o: object) => Promise<APIRequestContext> } }, baseURL: string) {
const api = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL } })
expect((await api.post('/api/users/login', { data: { email: admin!.email, password: admin!.password } })).status()).toBe(200)
expect((await (await api.post('/api/verify-totp', { data: { token: totp(admin!.secret) } })).json()).ok).toBe(true)
return api
}
test('first admin of a fresh site: created, sent to 2FA setup, in after the code', async ({ baseURL, page }) => {
// With users in the database this address leads to the login screen instead.
await page.goto('/admin/create-first-user')
const firstUserForm = await page.locator('#field-confirm-password').waitFor({ timeout: 10_000 }).then(() => true, () => false)
test.skip(!firstUserForm, 'the database already has users')
// Type like a person, once the form is live: values filled in before hydration are not in the form's state.
await page.waitForLoadState('networkidle')
await page.locator('#field-email').pressSequentially(OWNER.email)
await page.locator('#field-password').pressSequentially(OWNER.password)
await page.locator('#field-confirm-password').pressSequentially(OWNER.password)
const registered = page.waitForResponse((r) => r.url().includes('/first-register') && r.request().method() === 'POST')
await page.click('.form-submit button')
expect((await registered).status()).toBe(200)
await page.waitForURL(/setup-totp/)
await expect(page.locator('#ipal-two-factor-notice')).toContainText(/Ustaw weryfikację dwuetapową do|Set up two-step verification by/)
// nothing but setup, over the API too
for (const path of ['/api/globals/site-integrations', '/api/users', '/api/pages']) {
expect((await page.request.get(path, { headers: { origin: baseURL! } })).status(), path).toBe(403)
}
const secret = await page.locator('input[name="secret"]').inputValue()
await typeCode(page, secret)
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
expect((await page.request.get('/api/globals/site-integrations', { headers: { origin: baseURL! } })).status()).toBe(200)
admin = { ...OWNER, secret }
})
test('a new editor: setup screen with the deadline, nothing else, in after the code', async ({ baseURL, page, playwright }) => {
test.skip(!admin, 'no admin to create the editor with (set E2E_* or run on a fresh database)')
const api = await adminApi(playwright, baseURL!)
const created = await api.post('/api/users', { data: { ...EDITOR, roles: ['editor'] } })
expect(created.status()).toBe(201)
editorId = String((await created.json()).doc.id)
await api.dispose()
// the brand images must load on the setup screen too (the session is refused `media` itself)
const refusedImages: string[] = []
page.on('response', (r) => {
if (r.status() === 403 && /\/api\/(media\/|ipal\/admin-icon)/.test(r.url())) {refusedImages.push(r.url())}
})
await signIn(page, EDITOR)
await page.waitForURL(/setup-totp/)
await expect(page.locator('#ipal-two-factor-notice')).toContainText(/Ustaw weryfikację dwuetapową do|Set up two-step verification by/)
for (const path of ['/api/pages', '/api/form-submissions', '/api/globals/site-settings', `/api/users/${editorId}`]) {
expect((await page.request.get(path, { headers: { origin: baseURL! } })).status(), path).toBe(403)
}
expect(refusedImages).toEqual([])
// going elsewhere in the panel leads back to setup
await page.goto('/admin/collections/pages')
await page.waitForURL(/setup-totp/)
const secret = await page.locator('input[name="secret"]').inputValue()
await typeCode(page, secret)
// back where it wanted to go, and the data opens
await page.waitForURL(/\/admin\/collections\/pages/, { timeout: 20_000 })
expect((await page.request.get('/api/pages', { headers: { origin: baseURL! } })).status()).toBe(200)
})
test('the administrator sees the status on the account and resets it; the editor must set it up again', async ({ baseURL, page, playwright }) => {
test.skip(!admin || !editorId, 'needs the editor from the previous test')
await signIn(page, admin!)
await page.waitForURL(/verify-totp|\/admin(\?|$)/, { waitUntil: 'commit' })
if (page.url().includes('verify-totp')) {await typeCode(page, admin!.secret)}
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
await page.goto(`/admin/collections/users/${editorId}`)
const status = page.locator('#ipal-two-factor-status')
await expect(status).toContainText(/Ustawiona\.|Set up\./)
page.once('dialog', (dialog) => dialog.accept())
await status.getByRole('button').click()
await expect(status).toContainText(/Nieustawiona\. Konto może ją ustawić do|Not set up\. The account can set it up until/, { timeout: 15_000 })
// the editor's password alone opens nothing again
const editor = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } })
expect((await editor.post('/api/users/login', { data: EDITOR })).status()).toBe(200)
expect((await editor.get('/api/pages')).status()).toBe(403)
await editor.dispose()
// clean up the account this file made
const api = await adminApi(playwright, baseURL!)
expect((await api.delete(`/api/users/${editorId}`)).status()).toBe(200)
await api.dispose()
})
+28 -29
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.3",
"payload": "3.90.2",
"react": "19.3.0",
"react-dom": "19.3.0",
"next": "16.4.6",
"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,17 +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",
"undici@>=7 <7.30.1": "^7.30.1"
"happy-dom@<21.0.4": "^21.0.4"
}
},
"dependenciesMeta": {
+492 -491
View File
File diff suppressed because it is too large Load Diff
+10 -4
View File
@@ -29,6 +29,7 @@ import { MetaDescriptionCheck as MetaDescriptionCheck_7568fe47d582ff15ce85d2e187
import { MetaImageComponent as MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { PreviewComponent as PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { TOTPField as TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { TwoFactorStatusField as TwoFactorStatusField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CookieScanButton as CookieScanButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { FaviconCheck as FaviconCheck_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntegrationStatusBanner as IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
@@ -39,13 +40,15 @@ import { CookieSiteCheckTab as CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c
import { AdminIcon as AdminIcon_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { AdminLogo as AdminLogo_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntecionCredit as IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { TwoFactorAlert as TwoFactorAlert_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CookieCrawlAlert as CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntegrationAlerts as IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { TotpRedirectProvider as TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { TOTPSetup as TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { TOTPVerify as TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { SafeTotpView as SafeTotpView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CookieApprovalView as CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
import { TOTPSetup as TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { TOTPVerify as TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { S3ClientUploadHandler as S3ClientUploadHandler_f97aa6c64367fa259c5bc0567239ef24 } from '@payloadcms/storage-s3/client'
/** @type import('payload').ImportMap */
@@ -81,6 +84,7 @@ export const importMap = {
"@payloadcms/plugin-seo/client#MetaImageComponent": MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#PreviewComponent": PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@clocklimited/payload-2fa/rsc#TOTPField": TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128,
"@intecion/ipal-kit/admin#TwoFactorStatusField": TwoFactorStatusField_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#CookieScanButton": CookieScanButton_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#FaviconCheck": FaviconCheck_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntegrationStatusBanner": IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23,
@@ -91,12 +95,14 @@ export const importMap = {
"@intecion/ipal-kit/admin#AdminIcon": AdminIcon_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#AdminLogo": AdminLogo_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntecionCredit": IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#TwoFactorAlert": TwoFactorAlert_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#CookieCrawlAlert": CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntegrationAlerts": IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#TotpRedirectProvider": TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23,
"@clocklimited/payload-2fa/rsc#TOTPSetup": TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128,
"@clocklimited/payload-2fa/rsc#TOTPVerify": TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128,
"@intecion/ipal-kit/admin#SafeTotpView": SafeTotpView_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#CookieApprovalView": CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23,
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1,
"@clocklimited/payload-2fa/rsc#TOTPSetup": TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128,
"@clocklimited/payload-2fa/rsc#TOTPVerify": TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128,
"@payloadcms/storage-s3/client#S3ClientUploadHandler": S3ClientUploadHandler_f97aa6c64367fa259c5bc0567239ef24
}
@@ -17,6 +17,11 @@ export const formClasses: BuilderFormClassNames = {
fields: 'grid grid-cols-12 gap-4',
form: 'grid gap-6',
formError: 'rounded-control bg-danger-surface p-3 text-danger',
file: 'block w-full text-fg file:mr-3 file:rounded-control file:border-0 file:bg-surface-muted file:px-3 file:py-2 file:text-fg-strong',
fileItem: 'flex flex-wrap items-center gap-2',
fileList: 'mt-2 grid gap-1 text-sm',
fileRemove: 'underline underline-offset-2',
help: 'mt-1 text-sm text-fg-muted',
input: control,
label: 'mb-1 block font-medium text-fg-strong',
legend: 'mb-1 font-medium text-fg-strong',
+119
View File
@@ -757,6 +757,38 @@ export interface Form {
blockName?: string | null;
blockType: 'date';
}
| {
/**
* No spaces, e.g. attachment.
*/
name: string;
label?: string | null;
/**
* Shown under the field.
*/
help?: string | null;
width?: number | null;
required?: boolean | null;
/**
* The file is sent by e-mail and is not kept on the site.
*/
allowedTypes: ('doc' | 'docx' | 'jpg' | 'odt' | 'pdf' | 'png' | 'rtf' | 'webp' | 'xls' | 'xlsx')[];
maxSizeMB?: number | null;
maxFiles?: number | null;
showWhen?: {
/**
* Key of the field it depends on.
*/
field?: string | null;
/**
* Separate with commas; leave empty for any value.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'file';
}
| {
name: string;
label?: string | null;
@@ -1260,6 +1292,7 @@ export interface User {
id: string;
totpSecret?: string | null;
hasTotp?: boolean | null;
totpSetupFrom?: string | null;
/**
* Administrators manage everything; editors manage content.
*/
@@ -1298,6 +1331,24 @@ export interface FormSubmission {
id?: string | null;
}[]
| null;
/**
* Sent by e-mail to the form recipients. The files are not kept on the site.
*/
submissionFiles?:
| {
name?: string | null;
type?: string | null;
size?: number | null;
field?: string | null;
id?: string | null;
}[]
| null;
filesDelivery?: ('sent' | 'failed') | null;
/**
* Ask the sender for the file again.
*/
filesDeliveryNote?: string | null;
attemptKey?: string | null;
updatedAt: string;
createdAt: string;
}
@@ -2026,6 +2077,7 @@ export interface MediaSelect<T extends boolean = true> {
export interface UsersSelect<T extends boolean = true> {
totpSecret?: T;
hasTotp?: T;
totpSetupFrom?: T;
roles?: T;
updatedAt?: T;
createdAt?: T;
@@ -2242,6 +2294,26 @@ export interface FormsSelect<T extends boolean = true> {
id?: T;
blockName?: T;
};
file?:
| T
| {
name?: T;
label?: T;
help?: T;
width?: T;
required?: T;
allowedTypes?: T;
maxSizeMB?: T;
maxFiles?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
radio?:
| T
| {
@@ -2335,6 +2407,18 @@ export interface FormSubmissionsSelect<T extends boolean = true> {
value?: T;
id?: T;
};
submissionFiles?:
| T
| {
name?: T;
type?: T;
size?: T;
field?: T;
id?: T;
};
filesDelivery?: T;
filesDeliveryNote?: T;
attemptKey?: T;
updatedAt?: T;
createdAt?: T;
}
@@ -2850,6 +2934,34 @@ export interface Notification {
turnstile?: string | null;
rateLimited?: string | null;
notFound?: string | null;
/**
* Use {file} for the file name and {max} for the limit in MB.
*/
fileTooLarge?: string | null;
/**
* Use {file} for the file name and {types} for the accepted types.
*/
fileType?: string | null;
/**
* For a program, an archive, macros or content that does not match; use {file} and {types}.
*/
fileRefused?: string | null;
/**
* Use {field} for the field label and {max} for the limit.
*/
fileCount?: string | null;
/**
* Shown when the file could not be sent by e-mail; use {file} for the file name.
*/
fileNotSent?: string | null;
/**
* Added to a file message when the file field is not required.
*/
fileOptional?: string | null;
/**
* Use {file} for the file name.
*/
fileRemove?: string | null;
next?: string | null;
back?: string | null;
/**
@@ -3194,6 +3306,13 @@ export interface NotificationsSelect<T extends boolean = true> {
turnstile?: T;
rateLimited?: T;
notFound?: T;
fileTooLarge?: T;
fileType?: T;
fileRefused?: T;
fileCount?: T;
fileNotSent?: T;
fileOptional?: T;
fileRemove?: T;
next?: T;
back?: T;
stepOf?: T;
+6 -1
View File
@@ -69,7 +69,12 @@ export default buildConfig({
// @starter:endif
],
},
forms: { redirectRelationships: ['pages'], emailLayout: true },
// @starter:if demo
// attachments: the Quote form takes floor plans and photos — e-mailed to the studio, never stored (forms.md "Files")
forms: { attachments: true, emailLayout: true, redirectRelationships: ['pages'] },
// @starter:else
//: forms: { redirectRelationships: ['pages'], emailLayout: true }, // files on forms: add `attachments: true` (forms.md "Files")
// @starter:endif
// @starter:if twoFactor
twoFactor: { issuer: 'Example Studio', plugin: payloadTotp },
// @starter:else
+2 -2
View File
@@ -240,8 +240,8 @@ export async function seedDemoPages(seed: Seeder, media: Record<string, string>)
{
blockType: 'richText',
content: rich(
['Wycena obejmuje zakres prac, podział na etapy, harmonogram i warunki płatności. Im więcej wiemy na starcie, tym dokładniejsza będzie: podaj lokalizację, przybliżoną powierzchnię, rodzaj budynku albo wnętrza i planowany termin rozpoczęcia. Jeśli masz rzuty, zdjęcia, mapę do celów projektowych albo wypis z planu miejscowego, wspomnij o nich w formularzu — poprosimy o pliki w odpowiedzi. Wycena jest bezpłatna i do niczego nie zobowiązuje.'],
['The quote covers the scope of work, the stages, the schedule and the payment terms. The more we know at the start, the more precise it is: tell us the location, the rough floor area, the type of building or interior and when you plan to start. If you have floor plans, photos, a survey map or an extract from the local plan, mention them in the form — we will ask for the files in our reply. The quote is free and commits you to nothing.'],
['Wycena obejmuje zakres prac, podział na etapy, harmonogram i warunki płatności. Im więcej wiemy na starcie, tym dokładniejsza będzie: podaj lokalizację, przybliżoną powierzchnię, rodzaj budynku albo wnętrza i planowany termin rozpoczęcia. Jeśli masz rzuty, zdjęcia, mapę do celów projektowych albo wypis z planu miejscowego, dołącz je w formularzu (PDF, JPG lub PNG). Wycena jest bezpłatna i do niczego nie zobowiązuje.'],
['The quote covers the scope of work, the stages, the schedule and the payment terms. The more we know at the start, the more precise it is: tell us the location, the rough floor area, the type of building or interior and when you plan to start. If you have floor plans, photos, a survey map or an extract from the local plan, attach them in the form (PDF, JPG or PNG). The quote is free and commits you to nothing.'],
),
variant: 'narrow',
},
+12
View File
@@ -84,6 +84,18 @@ export async function seedForms(seed: Seeder, notifyTo: string) {
required: true,
},
{ blockType: 'date', label: tx('Planowany start', 'Planned start'), name: 'start' },
// @starter:if demo
// A File field (forms: { attachments: true }): sent with the notification to the studio, never stored on the site.
{
allowedTypes: ['pdf', 'jpg', 'png'],
blockType: 'file',
help: tx('Rzuty, zdjęcia lub mapa: PDF, JPG lub PNG, razem do 10 MB.', 'Floor plans, photos or a map: PDF, JPG or PNG, up to 10 MB together.'),
label: tx('Załączniki (opcjonalnie)', 'Attachments (optional)'),
maxFiles: 3,
maxSizeMB: 10,
name: 'attachment',
},
// @starter:endif
{ blockType: 'message', message: rich(tx('Dane przetwarzamy wyłącznie w celu przygotowania wyceny.', 'We use your data only to prepare the quote.')) },
consent,
],
+5 -2
View File
@@ -59,8 +59,11 @@ export const DESCRIPTIONS = {
'DESIGN.md': 'the human source of the look, matching src/design/tokens.ts',
'README.md': 'how to run the reference site and what is where',
'docs/DEPLOY.md': 'the Coolify runbook: local check, app settings, MongoDB resource, env, targeted seeds, DNS, rollback',
'e2e/create-test-admin.ts': 'a test admin with a known TOTP secret (local / CI database only)',
'e2e/smoke.spec.ts': 'the smoke tests every release must pass: pages, showcase, forms, sitemap, SEO/GEO, headers, consent, 2FA',
'e2e/create-test-admin.ts': 'a test admin with a known TOTP secret, and e-mail sending pointed at the tests\' mail sink (local / CI database only)',
'e2e/two-factor-setup.spec.ts': 'browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator\'s reset on the account page',
'e2e/smoke.spec.ts': 'the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA',
'e2e/smtp-sink.ts': 'a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments)',
'e2e/two-factor-back.spec.ts': 'browser test of the 2FA screens\' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed',
'e2e/totp.ts': 'RFC 6238 code generator for the 2FA sign-in in the smoke test',
'ipal-doctor.json': 'the production domain and launch state for ipal-doctor',
'next.config.ts': 'security headers, enforced CSP, admin CSP, upload headers, images, no X-Powered-By',
+5
View File
@@ -18,8 +18,13 @@ export { CookieSiteCheckTab } from '../modules/consent/scanner/CookieSiteCheckTa
export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { SafeTotpView } from '../modules/security/totp/SafeTotpView.js'
export type { SafeTotpViewProps } from '../modules/security/totp/SafeTotpView.js'
export { TotpRedirectProvider } from '../modules/security/totp/TotpRedirectProvider.js'
export type { TotpRedirectProviderProps } from '../modules/security/totp/TotpRedirectProvider.js'
export { TwoFactorAlert } from '../modules/security/totp/TwoFactorAlert.js'
export { TwoFactorResetButton } from '../modules/security/totp/TwoFactorResetButton.js'
export { TwoFactorStatusField } from '../modules/security/totp/TwoFactorStatusField.js'
export { FaviconCheck } from '../modules/seo/FaviconCheck.js'
export type { FaviconCheckProps } from '../modules/seo/FaviconCheck.js'
export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js'
+4 -1
View File
@@ -29,11 +29,14 @@ export { ConstructionNotice } from '../modules/construction/ConstructionNotice.j
export type { ConstructionNoticeClassNames } from '../modules/construction/ConstructionNotice.js'
export { CONSTRUCTION_CLOSE_LABEL, CONSTRUCTION_CLOSE_LABEL_PL, constructionCloseLabel } from '../modules/construction/texts.js'
export type { ConstructionMode } from '../modules/construction/types.js'
export { formatFileSize } from '../modules/forms/attachments/fileTypes.js'
export { BuilderForm } from '../modules/forms/BuilderForm.js'
export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.js'
export { autoCompleteFor, fileFieldError, fileFieldRules, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.js'
export type { BuilderFile } from '../modules/forms/builderLogic.js'
export type {
BuilderField,
BuilderFileLimits,
BuilderFormAction,
BuilderFormDoc,
BuilderFormTexts,
+1 -1
View File
@@ -1,6 +1,6 @@
export { sendEmail } from '../modules/email/index.js'
export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js'
export { createSubmitAction } from '../modules/forms/createSubmitAction.js'
export { createSubmitAction, splitFormFiles } from '../modules/forms/createSubmitAction.js'
export type { SubmitActionResult } from '../modules/forms/createSubmitAction.js'
export { submitForm } from '../modules/forms/index.js'
export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js'
+32 -1
View File
@@ -59,6 +59,37 @@ export const notificationsFields: Field[] = [
formText('turnstile', { en: 'Spam check failed', pl: 'Błąd weryfikacji' }),
formText('rateLimited', { en: 'Too many attempts', pl: 'Zbyt wiele prób' }),
formText('notFound', { en: 'Form unavailable', pl: 'Formularz niedostępny' }),
{
type: 'collapsible',
admin: { initCollapsed: true },
fields: [
formText('fileTooLarge', { en: 'File too large', pl: 'Plik za duży' }, {
description: { en: 'Use {file} for the file name and {max} for the limit in MB.', pl: 'Użyj {file}, aby wstawić nazwę pliku, i {max} — limit w MB.' },
}),
formText('fileType', { en: 'Wrong file type', pl: 'Niedozwolony typ pliku' }, {
description: { en: 'Use {file} for the file name and {types} for the accepted types.', pl: 'Użyj {file}, aby wstawić nazwę pliku, i {types} — dozwolone typy.' },
}),
formText('fileRefused', { en: 'File refused', pl: 'Plik odrzucony' }, {
description: {
en: 'For a program, an archive, macros or content that does not match; use {file} and {types}.',
pl: 'Dla programu, archiwum, makr lub niezgodnej zawartości; użyj {file} i {types}.',
},
}),
formText('fileCount', { en: 'Too many files', pl: 'Za dużo plików' }, {
description: { en: 'Use {field} for the field label and {max} for the limit.', pl: 'Użyj {field}, aby wstawić etykietę pola, i {max} — limit.' },
}),
formText('fileNotSent', { en: 'File not sent', pl: 'Plik niewysłany' }, {
description: { en: 'Shown when the file could not be sent by e-mail; use {file} for the file name.', pl: 'Widoczny, gdy pliku nie udało się wysłać e-mailem; użyj {file}, aby wstawić nazwę pliku.' },
}),
formText('fileOptional', { en: 'Optional file hint', pl: 'Wskazówka: plik opcjonalny' }, {
description: { en: 'Added to a file message when the file field is not required.', pl: 'Dodawana do komunikatu o pliku, gdy pole pliku nie jest wymagane.' },
}),
formText('fileRemove', { en: 'Remove file button', pl: 'Przycisk usuwania pliku' }, {
description: { en: 'Use {file} for the file name.', pl: 'Użyj {file}, aby wstawić nazwę pliku.' },
}),
],
label: { en: 'Files', pl: 'Pliki' },
},
{
type: 'row',
fields: [
@@ -89,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.
*/
@@ -17,6 +17,7 @@ export const TestEmailButton = () => {
const { t } = useTranslation()
const text = (key: Parameters<typeof ipalT>[1], vars?: Record<string, unknown>) => ipalT(t as never, key, vars)
const [to, setTo] = useState('')
const [withFile, setWithFile] = useState(false)
const [status, setStatus] = useState<
{ kind: 'error'; msg: string } | { kind: 'idle' } | { kind: 'ok'; msg: string } | { kind: 'sending' }
>({ kind: 'idle' })
@@ -29,7 +30,7 @@ export const TestEmailButton = () => {
setStatus({ kind: 'sending' })
try {
const res = await fetch('/api/ipal/test-email', {
body: JSON.stringify({ to: to.trim() }),
body: JSON.stringify({ to: to.trim(), ...(withFile ? { attachmentMB: 10 } : {}) }),
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
@@ -69,6 +70,10 @@ export const TestEmailButton = () => {
{status.kind === 'sending' ? text('testEmailSending') : text('testEmailSend')}
</button>
</div>
<label htmlFor="ipal-test-email-file" style={{ alignItems: 'center', display: 'flex', fontSize: '.85rem', gap: '.4rem', marginTop: '.5rem' }}>
<input aria-label={text('testEmailWithFile')} checked={withFile} id="ipal-test-email-file" onChange={(e) => setWithFile(e.target.checked)} type="checkbox" />
{text('testEmailWithFile')}
</label>
{status.kind === 'ok' && (
<p style={{ color: 'var(--theme-success-500, green)', marginTop: '.5rem' }}>
✓ {status.msg}
+32 -3
View File
@@ -8,6 +8,7 @@ export {
adminOrEditor,
adminOrEditorField,
adminOrSelf,
adminOrSelfIn,
authenticated,
buildRolesField,
hasMinimumRole,
@@ -17,6 +18,7 @@ export {
requireRole,
requireRoleField,
ROLE_HIERARCHY,
staffCollectionSlugs,
userMeetsRole,
} from './modules/access/index.js'
// Concrete files, not module barrels: a barrel that also re-exports 'use client'
@@ -38,6 +40,7 @@ export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './m
export { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
export { ADMIN_META_TEXTS, adminMetaForSite, buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js'
export type { AdminMetaOptions, AgencyOption, ResolvedAdminMeta } from './modules/branding/adminMeta.js'
export { fetchPublicImage, PUBLIC_IMAGE_MAX_BYTES, publicImageDataUri, rasterImageType, siteOrigin } from './modules/branding/publicImage.js'
export {
ACCEPT_ALL_CONSENT,
buildConsentLogCollection,
@@ -172,6 +175,8 @@ export {
} from './modules/content/index.js'
export type { ArchiveEntries } from './modules/content/index.js'
export type { SearchResult } from './modules/content/index.js'
// Files on panel forms (forms.attachments): checked, e-mailed, never stored.
export { mailAttachmentLimit } from './modules/email/attachmentLimit.js'
export { graphAdapter } from './modules/email/graphAdapter.js'
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'
export { mailAdapter } from './modules/email/mailAdapter.js'
@@ -184,9 +189,13 @@ export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, ipalEnvRules } from './modules/env/index.js'
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
export type { FormAttachmentsOption, FormFileScanInput, FormFileScanResult, FormSubmitEndpointOptions } from './modules/forms/attachments/config.js'
export { buildFileBlock, fileBlock } from './modules/forms/attachments/fileBlock.js'
export { FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS } from './modules/forms/attachments/fileTypes.js'
export type { FormFileDetect, FormFileType } from './modules/forms/attachments/fileTypes.js'
export { checkboxGroupBlock, placeholderField, stepBlock, timeBlock, withPlaceholder } from './modules/forms/builderBlocks.js'
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './modules/forms/builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './modules/forms/builderTypes.js'
export type { BuilderField, BuilderFileLimits, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './modules/forms/builderTypes.js'
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
@@ -304,6 +313,7 @@ export {
parseCspReports,
totpAdminPath,
totpRedirectTarget,
UPLOAD_SECURITY_HEADERS,
withSecurityConfig,
} from './modules/security/index.js'
export type {
@@ -317,9 +327,28 @@ export type {
TotpUser,
WithSecurityConfigOptions,
} from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js'
export type { SafeBackContext, SafeBackRule, TotpViewComponent } from './modules/security/totp/safeBack.js'
export { requireSecondFactor, secondFactorPassed, twoFactorSetupDeadline, twoFactorSetupState } from './modules/security/totp/secondFactor.js'
export type { TwoFactorSetupState } from './modules/security/totp/secondFactor.js'
export { SETUP_FROM_FIELD } from './modules/security/totp/secondFactor.js'
export {
backfillSetupFrom,
buildSetupFields,
buildTwoFactorResetEndpoint,
countAccountsWithoutTotp,
DEFAULT_SETUP_WINDOW_HOURS,
resolveRequireSetup,
stampSetupFrom,
strictExempt,
TWO_FACTOR_RESET_PATH,
} from './modules/security/totp/setupRequired.js'
export type { RequireSetupOptions, TwoFactorResetOptions } from './modules/security/totp/setupRequired.js'
export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
export 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 {
@@ -365,7 +394,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
@@ -26,6 +26,8 @@ export const integrationsTexts = defineTexts({
statusWorkingSince: '{{label}}: working since {{date}}.',
// Status messages, by status code
statusEmailGraphLargeFiles:
'Microsoft Graph cannot send files of 3 MB and more here, so larger form files are limited or go over SMTP. Ask your administrator.',
statusEmailGraphUnavailable:
'Microsoft Graph is selected but not set up on the server, so e-mails go over SMTP. Ask your administrator.',
statusTurnstileBadResponse: 'Cloudflare sent an unexpected response.',
@@ -53,6 +55,7 @@ export const integrationsTexts = defineTexts({
testEmailSent: 'Test e-mail sent to {{to}}.',
testEmailSubject: 'Test e-mail from {{site}}',
testEmailSubjectGeneric: 'Test e-mail from your website',
testEmailWithFile: 'Attach a 10 MB test file',
},
pl: {
alertsHeading: 'Integracja wymaga uwagi. Witryna nadal działa.',
@@ -74,6 +77,8 @@ export const integrationsTexts = defineTexts({
statusWorking: '{{label}}: działa.',
statusWorkingSince: '{{label}}: działa od {{date}}.',
statusEmailGraphLargeFiles:
'Microsoft Graph nie może tu wysyłać plików od 3 MB, więc większe pliki z formularzy są ograniczone lub idą przez SMTP. Zapytaj administratora.',
statusEmailGraphUnavailable:
'Wybrano Microsoft Graph, ale nie jest on skonfigurowany na serwerze, więc e-maile idą przez SMTP. Zapytaj administratora.',
statusTurnstileBadResponse: 'Cloudflare zwrócił nieoczekiwaną odpowiedź.',
@@ -100,5 +105,6 @@ export const integrationsTexts = defineTexts({
testEmailSent: 'Testowy e-mail wysłano na adres {{to}}.',
testEmailSubject: 'Testowy e-mail z witryny {{site}}',
testEmailSubjectGeneric: 'Testowy e-mail z witryny',
testEmailWithFile: 'Dołącz plik testowy 10 MB',
},
})
+49
View File
@@ -0,0 +1,49 @@
import { defineTexts } from '../define.js'
/** Admin component texts — two-step verification (2FA). Placeholders use Payload's {{name}} syntax. */
export const securityTexts = defineTexts({
en: {
twoFactorAlertBlocked: 'Blocked because the time for setup has passed: {{count}}. Open the account in the user list and choose "Reopen setup".',
twoFactorAlertLink: 'Open the user list',
twoFactorAlertPending: 'Accounts without two-step verification: {{count}}. Until it is set up, such an account cannot use the panel.',
twoFactorAlertTitle: 'Two-step verification',
twoFactorReopen: 'Reopen setup',
twoFactorReset: 'Reset two-step verification',
twoFactorResetConfirm: 'This account will have to set up two-step verification again before it can use the panel. Continue?',
twoFactorResetDone: 'Done. The account can set up two-step verification now.',
twoFactorResetFailed: 'Could not reset two-step verification. Try again.',
twoFactorResetForbidden: 'Only an administrator who is fully logged in can do this.',
twoFactorSetupClosed: 'The time to set up two-step verification has passed, so this account is blocked. Ask an administrator to reopen setup for it.',
twoFactorSetupDeadline: 'Set up two-step verification by {{date}}. Until then you cannot use the panel.',
twoFactorSetupRequired: 'Set up two-step verification to use the panel.',
twoFactorStatusClosed: 'Not set up. The time for it passed on {{date}}, so the account is blocked.',
twoFactorStatusExempt: 'Not set up. This account is exempt in the site configuration.',
twoFactorStatusLabel: 'Two-step verification',
twoFactorStatusOn: 'Set up.',
twoFactorStatusOpen: 'Not set up. The account can set it up until {{date}}.',
twoFactorStatusOpenNoLimit: 'Not set up yet. The account cannot use the panel until it is.',
twoFactorTooManyAttempts: 'Too many codes were tried for this account. Wait {{minutes}} min, then enter the current code from your app.',
},
pl: {
twoFactorAlertBlocked: 'Zablokowane, bo minął czas na konfigurację: {{count}}. Otwórz konto na liście użytkowników i wybierz „Otwórz konfigurację ponownie”.',
twoFactorAlertLink: 'Otwórz listę użytkowników',
twoFactorAlertPending: 'Konta bez weryfikacji dwuetapowej: {{count}}. Dopóki nie zostanie ustawiona, takie konto nie może korzystać z panelu.',
twoFactorAlertTitle: 'Weryfikacja dwuetapowa',
twoFactorReopen: 'Otwórz konfigurację ponownie',
twoFactorReset: 'Zresetuj weryfikację dwuetapową',
twoFactorResetConfirm: 'To konto będzie musiało ponownie ustawić weryfikację dwuetapową, zanim skorzysta z panelu. Kontynuować?',
twoFactorResetDone: 'Gotowe. Konto może teraz ustawić weryfikację dwuetapową.',
twoFactorResetFailed: 'Nie udało się zresetować weryfikacji dwuetapowej. Spróbuj ponownie.',
twoFactorResetForbidden: 'Może to zrobić tylko w pełni zalogowany administrator.',
twoFactorSetupClosed: 'Czas na ustawienie weryfikacji dwuetapowej minął, więc to konto jest zablokowane. Poproś administratora o ponowne otwarcie konfiguracji.',
twoFactorSetupDeadline: 'Ustaw weryfikację dwuetapową do {{date}}. Do tego czasu nie możesz korzystać z panelu.',
twoFactorSetupRequired: 'Ustaw weryfikację dwuetapową, aby korzystać z panelu.',
twoFactorStatusClosed: 'Nieustawiona. Czas na konfigurację minął {{date}}, więc konto jest zablokowane.',
twoFactorStatusExempt: 'Nieustawiona. To konto jest zwolnione w konfiguracji strony.',
twoFactorStatusLabel: 'Weryfikacja dwuetapowa',
twoFactorStatusOn: 'Ustawiona.',
twoFactorStatusOpen: 'Nieustawiona. Konto może ją ustawić do {{date}}.',
twoFactorStatusOpenNoLimit: 'Jeszcze nieustawiona. Do tego czasu konto nie może korzystać z panelu.',
twoFactorTooManyAttempts: 'Dla tego konta wpisano zbyt wiele kodów. Odczekaj {{minutes}} min, a potem wpisz aktualny kod z aplikacji.',
},
})
+13
View File
@@ -2,6 +2,8 @@ import type { Payload } from 'payload'
import { ipalT } from '../admin-i18n/t.js'
import { settingsTexts } from '../admin-i18n/texts/settings.js'
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { publicImageDataUri, siteOrigin } from './publicImage.js'
/**
* White-label admin branding: the Payload admin panel's logo (login + nav) and
@@ -25,6 +27,8 @@ import { settingsTexts } from '../admin-i18n/texts/settings.js'
type BrandingProps = {
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
imageField?: string
/** `whiteLabel.inlineImages: false` — never fetch the image on the server for the 2FA screens. */
inlineImages?: false
/** Injected by Payload — current admin locale (object or code). */
locale?: { code?: string } | string
/** Field holding the site name. Default 'siteName'. */
@@ -33,6 +37,8 @@ type BrandingProps = {
payload?: Payload
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string
/** Injected by Payload into admin server components — the account looking at the panel. */
user?: null | Record<string, unknown>
}
type MediaLike = { url?: null | string } | null | undefined
@@ -70,6 +76,13 @@ async function loadBranding(
const image = settings[imageField] as MediaLike
const url =
image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null
// A session that still owes its 2FA code (or has not set 2FA up) is refused `media` like every
// other collection, so the browser would show a broken image on the verify / setup screens.
// Give it the picture itself, fetched as an anonymous visitor would get it; when that fails
// (media is not public), the site name is shown instead.
if (url && props.inlineImages !== false && props.user && !secondFactorPassed({ payload, user: props.user })) {
return { name, url: await publicImageDataUri(url, siteOrigin(payload.config.serverURL)) }
}
return { name, url }
} catch (error) {
console.warn('[ipal] admin branding: falling back to Payload default:', error)
+22 -3
View File
@@ -2,7 +2,9 @@ import type { Endpoint, PayloadRequest } from 'payload'
import type { AgencyOption, ResolvedAdminMeta } from './adminMeta.js'
import { UPLOAD_SECURITY_HEADERS } from '../security/buildSecurityHeaders.js'
import { ADMIN_ICON_PATH, ADMIN_META_TEXTS, ADMIN_OG_PATH } from './adminMeta.js'
import { fetchPublicImage, rasterImageType } from './publicImage.js'
/**
* The panel's link-preview image (1200×630) and icon, drawn from SiteSettings:
@@ -13,13 +15,13 @@ import { ADMIN_ICON_PATH, ADMIN_META_TEXTS, ADMIN_OG_PATH } from './adminMeta.js
* the site name, then to initials.
*/
type Fields = { iconField?: string; logoField?: string; nameField?: string; settingsSlug?: string }
type Fields = { iconField?: string; logoField?: string; nameField?: string; serveIcon?: false; settingsSlug?: string }
type Branding = { icon: null | string; logo: null | string; name: string }
const CACHE = 'public, max-age=3600, s-maxage=3600'
async function loadBranding(req: PayloadRequest, f: Required<Fields>): Promise<Branding> {
async function loadBranding(req: PayloadRequest, f: Required<Omit<Fields, 'serveIcon'>>): Promise<Branding> {
try {
const locale = req.payload.config.localization ? req.payload.config.localization.defaultLocale : undefined
const s = (await req.payload.findGlobal({ slug: f.settingsSlug as never, depth: 1, ...(locale ? { locale: locale as never } : {}), req })) as Record<string, unknown>
@@ -62,7 +64,7 @@ const initials = (name: string) =>
.join('') || 'A'
export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fields = {}): Endpoint[] {
const f: Required<Fields> = {
const f: Required<Omit<Fields, 'serveIcon'>> = {
iconField: fields.iconField ?? 'favicon',
logoField: fields.logoField ?? 'logo',
nameField: fields.nameField ?? 'siteName',
@@ -105,6 +107,23 @@ export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fi
handler: async (req) => {
const brand = await loadBranding(req, f)
if (brand.icon) {
// The picture itself, fetched the way an anonymous visitor gets it — not a redirect to the
// media file: a panel session that still owes its 2FA code is refused that file (it is
// refused every collection), and a cached redirect would send it there anyway. The answer
// is the same for everyone, so it can be cached like the redirect was.
const image = fields.serveIcon === false ? null : await fetchPublicImage(absolute(brand.icon, req), null)
// Only a bitmap is answered from here, recognised by its first bytes — never an SVG, which
// is a document that can run script in the site's origin. The headers below are the upload
// routes' (sandbox, no sniffing), but a Next project's site-wide CSP rule overrides a
// route's own header, so they are a second layer, not the protection.
const type = image ? rasterImageType(image.bytes) : null
if (image && type) {
return new Response(new Uint8Array(image.bytes), {
headers: { 'Cache-Control': CACHE, 'Content-Type': type, ...Object.fromEntries(UPLOAD_SECURITY_HEADERS.map((h) => [h.key, h.value])) },
})
}
// An SVG favicon, or not fetchable from here (too large, media is not public): the browser
// goes to the media file itself, where the upload route's own headers apply.
return new Response(null, { headers: { 'Cache-Control': CACHE, Location: absolute(brand.icon, req) }, status: 302 })
}
const ImageResponse = await imageResponse()

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