Files
ipal-kit/docs/security.md
T

1539 lines
120 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# security
Generic HTTP security headers (HSTS, X-Frame-Options, nosniff,
Referrer-Policy, Permissions-Policy, Cross-Origin-Opener-Policy; `X-Robots-Tag` on staging)
as a function for `next.config`, `withSecurityConfig` to hide `X-Powered-By` and to keep Payload's colour-scheme
client hint headers on the admin panel only, and an opt-in
Content-Security-Policy (`buildCsp`, report-only first, a separate admin policy, optional nonces and a
report collector).
## Rule
Headers that are IDENTICAL across projects are provided once by the plugin and are on by default. CSP
(Content-Security-Policy) needs to know the domains of a specific project (where scripts, images, fonts
and analytics load from), so it is OFF until the project turns on the `buildCsp` flags for what it
loads — through `buildSecurityHeaders({ csp })`, or its own policy through `additional`.
## Usage — next.config.ts
Wire the headers in `next.config`, NOT in the proxy — they must cover the WHOLE
application (including `/admin` and static files), and the proxy skips those routes.
```ts
// next.config.ts
import { withPayload } from '@payloadcms/next/withPayload'
import type { NextConfig } from 'next'
import { buildAdminCspHeaders, buildSecurityHeaders, buildUploadSecurityHeaders, withSecurityConfig } from '@intecion/ipal-kit'
const prod = process.env.NODE_ENV === 'production'
const csp = { mode: 'report-only', reportUri: '/api/csp-report' } as const // later: mode 'enforce'
const securityHeaders = buildSecurityHeaders({
hsts: prod, // IMPORTANT: off in dev (http)
csp: { ...csp, r2Url: process.env.R2_PUBLIC_URL, analytics: true, turnstile: true },
})
const nextConfig: NextConfig = {
async headers() {
return [
{ source: '/:path*', headers: securityHeaders },
{ source: '/admin/:path*', headers: buildAdminCspHeaders({ ...csp, r2Url: process.env.R2_PUBLIC_URL }) },
...buildUploadSecurityHeaders(),
]
},
}
// withSecurityConfig OUTSIDE withPayload: no X-Powered-By (Next's and Payload's), and Payload's colour-scheme
// client hints (Accept-CH, Critical-CH, Vary) for the admin only, not for every page
export default withSecurityConfig(withPayload(nextConfig))
```
## Options
| Option | Default | Role |
|---|---|---|
| `hsts` | `true` | Strict-Transport-Security (force HTTPS) |
| `hstsMaxAge` | `63072000` (2 years) | HSTS max-age in seconds |
| `hstsIncludeSubDomains` | `true` | HSTS on subdomains |
| `hstsPreload` | `false` | preload (only if you submit to the list) |
| `frameOptions` | `'DENY'` | X-Frame-Options (anti-clickjacking); `null` = no header |
| `referrerPolicy` | `'strict-origin-when-cross-origin'` | Referrer-Policy; `null` = no header |
| `permissionsPolicy` | blocks camera/mic/geolocation | Permissions-Policy; your own string, or `null` = no header |
| `coop` | `'same-origin'` | Cross-Origin-Opener-Policy; `'same-origin-allow-popups'`, or `false` = no header |
| `csp` | `false` | `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`) |
| `additional` | `[]` | extra headers; the same key overrides (also the `csp` ones) |
With `IAPL_NOINDEX=1` (staging), `X-Robots-Tag: noindex, nofollow` is added to every response.
**A value the browser would not understand fails at start (1.17.1).** `hsts`, `hstsIncludeSubDomains` and
`hstsPreload` take `true` / `false`, `hstsMaxAge` a number of seconds, `frameOptions` `'DENY'` / `'SAMEORIGIN'` /
`null`, `coop` a COOP value or `false`, `referrerPolicy` / `permissionsPolicy` a header value or `null`. Before,
`hsts: null` dropped HSTS and `hstsMaxAge: 'abc'` or `frameOptions: 'false'` sent a header the browser ignores.
`buildCsp` the same way: `dev` and `strictDynamic` are booleans (`dev: 'false'` used to add `'unsafe-eval'` in
production), `mode` is `'enforce'` / `'report-only'`, and every `extra` / `override` value is an array of sources
(a string was spread into single characters — a lone `*` among them is a wildcard).
## Switches are read strictly (1.17.1)
A JavaScript config is not type-checked. A plugin option whose nonsense value used to switch a protection off,
widen who sees something, or switch an opt-in feature (a public endpoint) on, now stops the start with a message
naming the option — like `twoFactor.requireSetup.windowHours` since 1.16.6. Real values work as before.
| Option | Refused now | What it did before |
|---|---|---|
| `accounts` | `0`, `''`, anything not `false` / an object | `0` or `''` dropped every account rule |
| `cookieScanner`, `stats`, `consentLog`, `adminMeta`, `whiteLabel`, `forms.attachments`, `cookieScanner.crawl`, `mail.relay` | a string, a number, `null` | `'false'` switched an opt-in feature on (or was ignored) |
| `indexNow`, `lightbox`, `enabled`, `twoFactor.allowCollectionMismatch` | anything but `true` / `false` | `'false'` meant on — for the mismatch: panel users without 2FA |
| `consentLog.retentionDays` | not a number above 0 | `null`, `0` or a negative number purged every proof of consent daily |
| `adminMeta.robots.index` / `.follow` | anything but `true` / `false` | `'false'`, `0` or `null` took the noindex off the panel |
| `dashboardAlerts.integrations` / `.cookies` | a name outside `'admin' / 'editor' / 'all'` (`'editor' / 'all'`) | an unknown name showed the details to every staff account |
| `mail.relay.accountMail.windowMinutes`, `mail.relay.confirmRateLimit.windowMs` | not a number above 0 | a window of 0 is a limit that never fills |
| `mail.relay.accountMail.perAddress` / `.perVisitor`, `confirmRateLimit.max` | not a number of at least 1 | — |
| `forms.attachments.submit.maxPerMinute`, `.timeoutMs`, `.idleTimeoutMs` | not a number of at least 0 (`0` = off, as documented) | `'off'`, `null` or `{}` turned the limit off |
| `storageNames` | anything but `'ipal'` / `'iapl'` | an unknown name meant `'ipal'` |
| seed `guard` (`createSeeder`) | `0`, `''`; `allowFull` / `allowProdUpdate` / `production` not booleans | `guard: 0` dropped the production guard; `allowFull: 'false'` allowed a full seed |
Role names are strict too: `requireRole`, `requireRoleField` and `readPublished` throw on a name outside
`ROLE_HIERARCHY`, and `hasMinimumRole` / `userMeetsRole` answer `false` for one (before, every staff account met it).
**Uploads:** `buildUploadSecurityHeaders({ collections = ['media'] })` returns `headers()` rules for
`/api/<collection>/file/*` (sandbox, no scripts) — an SVG from local disk cannot run a script on the site's
domain. Wire it alongside: `[{ source: '/:path*', headers: securityHeaders }, ...buildUploadSecurityHeaders()]`.
## TRAP — HSTS in dev
HSTS over HTTP on localhost can lock the browser into HTTPS for localhost.
ALWAYS turn it off in dev: `hsts: process.env.NODE_ENV === 'production'`.
## X-Powered-By — hide it (`withSecurityConfig`)
A response header `X-Powered-By: Next.js, Payload` tells scanners which software (and which known
advisories) to try. Audits flag it. Where it comes from:
- **Next.js** sends `X-Powered-By: Next.js` unless the config says `poweredByHeader: false`.
- **Payload's `withPayload`** switches Next's header off and adds its own `X-Powered-By: Next.js, Payload`
for `/:path*` through `headers()` — also unless the config it wraps says `poweredByHeader: false`.
Payload's REST/GraphQL handlers add nothing of their own.
`withSecurityConfig(nextConfig, { hidePoweredBy = true })` sets `poweredByHeader: false` AND drops any
`X-Powered-By` entry from `headers()` rules, so both orders hide the header:
`withSecurityConfig(withPayload(nextConfig))` (recommended: the only order that also narrows the client hints,
next section) or `withPayload(withSecurityConfig(nextConfig))` (the order of sites made before 1.17.0).
Turn off: `withSecurityConfig(nextConfig, { hidePoweredBy: false })`, or do not call it. Without the helper,
`poweredByHeader: false` in the config passed to `withPayload` has the same effect.
Check: `curl -sI https://<DOMAIN>/pl | grep -i x-powered-by` prints nothing. Behind Coolify the proxy
(Traefik or Caddy) adds no `X-Powered-By`; if the header comes back in production, look for a
"Custom labels" header middleware in the Coolify app, or a Cloudflare Transform Rule.
Keep the software updated as well — hiding the header does not remove the advisories (the minimum safe
Next.js is listed in the agent guide, §4).
## Client hints — the admin only (`withSecurityConfig`)
**The problem.** Payload's `withPayload` adds three response headers for **every** path (`/:path*`):
`Accept-CH: Sec-CH-Prefers-Color-Scheme`, `Critical-CH: Sec-CH-Prefers-Color-Scheme` and
`Vary: Sec-CH-Prefers-Color-Scheme`. The admin panel needs them: with the hint in the request it renders light or
dark on the server, so the panel does not flash on its first paint. A public page does not read the hint, yet
`Critical-CH` tells Chrome to **repeat the first document request of a visit** with the hint added — one wasted
round trip on every first page view (two requests for `/pl` in the server log; about 600 ms in a mobile Lighthouse
run of a client site, where it shows as a repeated navigation under "Avoid multiple page redirects"). Route
handlers and static files also get `Vary: Sec-CH-Prefers-Color-Scheme`, which splits them in a shared cache.
Neither `withPayload` nor the proxy has an option for it, and a proxy cannot remove a header that `next.config` set.
**The fix.** `withSecurityConfig` as the **outer** wrapper moves the three headers to the panel's routes:
```ts
export default withSecurityConfig(withPayload(nextConfig)) // /admin/:path* only (the default)
```
| Option | Default | Role |
|---|---|---|
| `adminClientHints` | `true` | `true`: the hint headers only for `/admin/:path*`. `false`: leave them on every path (the behaviour before 1.17.0) |
| `adminClientHints.route` | `'/admin'` | Payload's `routes.admin` when the panel has another address: `{ route: '/its' }` |
| `adminClientHints.sources` | `[]` | more Next `source` patterns that keep the headers, e.g. `['/preview/:path*']` for a page of your own that reads `Sec-CH-Prefers-Color-Scheme` on the server |
- **The order matters.** Only the outer wrapper sees the rule `withPayload` adds. `withPayload(withSecurityConfig(…))`
— the order of every site made before 1.17.0 — still builds and still hides `X-Powered-By`, but the hints stay on
every path, as before. Swap the two names (one line); nothing else changes. `iapl-doctor` rule `client-hints`
(info) reports the old order, and with `--url` a public page that still sends `Critical-CH`.
- **What is moved.** Only the token `Sec-CH-Prefers-Color-Scheme` in `Accept-CH`, `Critical-CH` and `Vary` of a
site-wide rule (`/:path*`, `/(.*)`). Other tokens stay (another client hint, another `Vary` name), other headers
of the rule stay (CSP, HSTS, …), and a rule you wrote for a narrower source is left alone. `/admin/:path*` gets
the headers exactly as `withPayload` wrote them. Next's own `Vary` for pages (`rsc, next-router-state-tree, …`)
is not touched.
- **The panel works as before**: on its first request Chrome learns the hint from `/admin` and repeats that one
request, the panel paints in the browser's scheme with no flash; a theme chosen in the account (the
`payload-theme` cookie) still wins.
- **Building blocks:** `scopeColorSchemeClientHints(rules, sources?)` (the same narrowing for a `headers()` array
of your own), `adminClientHintSources(route?)`, `COLOR_SCHEME_CLIENT_HINT`.
Check (a production build): `curl -sI localhost:3000/pl | grep -iE 'accept-ch|critical-ch'` prints nothing;
`curl -sI localhost:3000/admin/login | grep -iE 'accept-ch|critical-ch'` prints both. In Chrome, a first visit to a
public page in a fresh profile shows one document request.
## Content-Security-Policy
### Why CSP is opt-in
HSTS, nosniff and Referrer-Policy are IDENTICAL for every project → the plugin
generates them. CSP lists the SPECIFIC domains the project loads from (its R2,
analytics, Turnstile, fonts). A generic CSP would be either too loose (`*` =
useless) or would break the site. So the plugin provides the hardened skeleton and one flag per
integration it ships (`buildCsp`), and the project turns on what it uses.
### buildCsp — CSP generator (recommended over writing it by hand)
```ts
import { buildCsp } from '@intecion/ipal-kit'
const csp = buildCsp({
mode: 'report-only', // start here; 'enforce' once the reports are clean
reportUri: '/api/csp-report', // where browsers send violations (createCspReportRoute)
r2Url: process.env.R2_PUBLIC_URL, // R2 media → img-src, media-src
turnstile: true, // Cloudflare Turnstile
analytics: true, // GA4 / GTM
metaPixel: true, linkedIn: true, tiktok: true, clarity: true, // the pixels the plugin loads
youtube: true, // YouTubeEmbed
googleMaps: true, // Google Maps
// extra: { 'script-src': ['https://other-script.example'] }, // add sources to any directive
// override: { 'frame-ancestors': ["'self'"], 'style-src': null }, // replace / drop a directive
})
// → { key: 'Content-Security-Policy-Report-Only', value: "default-src 'self'; …" }
```
`buildCspHeaders(args)` returns `[csp, Reporting-Endpoints]` (the second only with `reportUri`);
`buildSecurityHeaders({ csp: args })` does the same inside the site-wide list.
**Hard rules built in** (always on unless you `override` them): `base-uri 'self'`,
`object-src 'none'`, `frame-ancestors 'none'`, `form-action 'self'`.
**What each flag allows** — the plugin's own components need exactly these:
| Flag | Plugin part | Sources |
|---|---|---|
| (always) | Next, Tailwind, next/font, `ThemeScript`, `JsonLdGraph`, consent banner, lightbox, `MediaPreconnect` | `'self'`, `'unsafe-inline'` (script, style), `data:`/`blob:` images, Google Fonts |
| `r2Url` | media on R2 | the URL → `img-src`, `media-src` (a site-relative `/media` is already `'self'`) |
| `analytics` | `Analytics` GA4 / GTM | `script-src *.googletagmanager.com`; `connect-src`/`img-src` `*.google-analytics.com`, `*.analytics.google.com`, `*.googletagmanager.com`, `*.g.doubleclick.net`, `www.google.com` |
| `metaPixel` | `loadMetaPixel`, fbevents via `ConsentScript` | `connect.facebook.net` (script, connect), `www.facebook.com` (connect, img, frame) |
| `linkedIn` | `loadLinkedIn` | `snap.licdn.com` (script); `px.ads.linkedin.com`, `px4.ads.linkedin.com`, `www.linkedin.com` (connect, img) |
| `tiktok` | `loadTikTok` | `analytics.tiktok.com` (script, connect, img) |
| `clarity` | `loadClarity` | `*.clarity.ms` (script, connect, img), `c.bing.com` (img) |
| `turnstile` | `Turnstile` | `challenges.cloudflare.com` (script, frame, connect) |
| `youtube` | `YouTubeEmbed` | `www.youtube.com`, `www.youtube-nocookie.com` (frame), `i.ytimg.com` (img) |
| `googleMaps` | Maps iframe / Maps JS | `*.googleapis.com`, `*.gstatic.com`, `*.google.com`, `*.ggpht.com`, `*.googleusercontent.com`, `blob:` workers |
| `dev` | `next dev` | `'unsafe-eval'` (React dev tooling). Default `process.env.NODE_ENV === 'development'` |
Plausible or another script through `ConsentScript` → add its host with `extra`. GTM tags you add in
the GTM panel (Hotjar, Ads…) load their own hosts → add them with `extra` as the reports show them.
**Why `'unsafe-inline'` stays without a nonce.** Next streams the page's RSC payload in inline
`<script>` tags (`self.__next_f.push(…)`) that differ per page and per render — a static header cannot
list their hashes, and static/ISR HTML cannot carry a per-request nonce. So a header-only CSP keeps
`'unsafe-inline'` in `script-src`; it still blocks every script from a host you did not list, `<object>`,
`<base>` hijacking, framing and form posts to other sites. `style-src 'unsafe-inline'` stays in every mode:
React, Next and the plugin set inline `style` attributes, which a nonce cannot cover. `buildCsp` never adds
`'unsafe-eval'` in production.
### Nonces (stricter; dynamic pages only)
Next adds a per-request nonce to its own scripts when the request carries a CSP header with
`'nonce-…'` (enforcing or report-only). `createProxy(i18nConfig, { NextResponse, csp: { … } })` does it:
a fresh nonce per request, the policy on the request (for Next) and the response, and the nonce as the
`x-nonce` request header. The policy then gets `'nonce-…' 'strict-dynamic'`: scripts the nonced Next
bootstrap loads (the plugin's analytics, pixels, Turnstile) are trusted, and CSP3 browsers ignore the
host list and `'unsafe-inline'` (both stay as a fallback for old browsers). `strictDynamic: false`
keeps host-based checks.
```ts
// proxy.ts
export const proxy = createProxy(i18nConfig, {
NextResponse, markdown: true,
csp: { mode: 'report-only', reportUri: '/api/csp-report', analytics: true, r2Url: process.env.R2_PUBLIC_URL },
})
// app/(frontend)/[locale]/layout.tsx
import { headers } from 'next/headers'
const nonce = (await headers()).get('x-nonce') // CSP_NONCE_HEADER
<SiteProviders shell={shell} theme nonce={nonce}>… // ThemeScript, the banner's first-paint script + GA4/GTM tag get the nonce
```
Costs and rules:
- Reading `headers()` makes every page under the proxy matcher **dynamic** — no ISR, no static HTML, a
render per request. That is why nonces are opt-in; ISR sites keep the header-only policy.
- The proxy matcher skips `/api`, `/admin`, `/_next` and files — those keep the `next.config` headers. Do
NOT also send the site CSP from `next.config` for the frontend paths (two policies = both apply); keep
only the admin rule and `buildUploadSecurityHeaders` there.
- Your own proxy: `createCspNonce()` + `buildCsp({ nonce })`, set the policy on the request headers
(`NextResponse.next({ request: { headers } })`) and on the response, like `createProxy` does.
- `ConsentScript nonce`, `ThemeScript nonce`, `Analytics nonce` exist for policies without `'strict-dynamic'`.
- The cookie banner's first-paint script (consent.md → "First paint") is inline, so under a nonce policy it needs the nonce with or without `'strict-dynamic'`: `SiteProviders nonce` passes it (`ConsentProvider nonce` / `CookieBanner nonce` by hand). Refused, the banner appears after hydration.
### Payload admin — its own, looser policy
The admin (`/admin`, or your `adminRoute`) is a large client app the project does not control: inline
scripts and styles, the Monaco code editor loaded from `cdn.jsdelivr.net` with `blob:` workers, image
previews from any `https:` host, and the Live Preview iframe (`frame-src 'self'`). `buildAdminCsp(args)` /
`buildAdminCspHeaders(args)` give that policy with the same hard rules, `frame-ancestors 'self'`, and the
same `mode`, `reportUri`, `extra`, `override`. Put its rule AFTER the site-wide one — Next uses the
last matching rule for the same header key:
```ts
{ source: '/:path*', headers: securityHeaders },
{ source: '/admin/:path*', headers: buildAdminCspHeaders({ mode: 'report-only', reportUri: '/api/csp-report' }) },
```
With a custom `adminRoute` (e.g. `/its`), use that path in `source`.
### Collecting reports
`createCspReportRoute({ onReport?, maxBytes = 16384, maxReports = 10, rateLimit })` — a `POST` handler for
`reportUri`. It accepts both formats (`application/csp-report` from `report-uri`, `application/reports+json` from
`report-to`), caps the body (a larger one → `413`; since 1.17.1 the stream is read only up to `maxBytes`, also when
the browser sends no `content-length`), always answers `204`, and by default logs one `console.warn` line per
violation: `[csp] report script-src-elem blocked=https://x.example page=/pl src=https://site/_next/a.js:3`. Read them
in the Coolify app's **Logs**. Plug `onReport` into `payload.logger`, Sentry or a database for more.
**What the default line holds (1.18.0, security audit F1).** Anyone can post a report, so its strings never reach the
log as sent: the blocked resource is reduced to its origin (`inline`, `eval` stay), the page to its path (no query — it
may hold an e-mail address), the script to origin and path; control characters and line separators are removed and
every value is cut at `CSP_LOG_VALUE_MAX` (128) — a report cannot write a forged line of its own. One request handles
at most `maxReports` (10) violations, and one client (`clientIp`, IPv6 per /64) at most 60 requests a minute
(`rateLimit: { max, windowMs }`; `false` = no limit); over it the route answers `204` and handles nothing. A project's
own `onReport` still gets every value exactly as the browser sent it — escape it before you log it, or call
`cspLogLine(violation)` for the plugin's line. **What changes for an existing site:** the log lines show origins and
paths instead of full URLs (a log parser that read full URLs must adapt), and at most 10 violations per request reach
`onReport` (was 50: `maxReports: 50` keeps it).
```ts
// app/api/csp-report/route.ts (a fixed route wins over Payload's /api/[...slug])
import { createCspReportRoute } from '@intecion/ipal-kit'
export const POST = createCspReportRoute()
```
Third-party option: point `reportUri` at a collector (report-uri.com, Sentry's security endpoint,
uriports) and skip the route. `parseCspReports(body)` normalises both formats for your own handler.
### ROLL OUT CSP CAREFULLY — Report-Only first
A CSP that is too strict **breaks the site** (blocks scripts/styles/images). NEVER deploy
an enforcing CSP blindly. The safe method:
1. **Report-only** — `mode: 'report-only'` with `reportUri`. The browser REPORTS violations (console +
the report route) but does NOT block — the site works as usual. Deploy it.
2. **Read the reports** — DevTools → Console ("Content Security Policy" / "[Report Only]") on every page
type, and the `[csp]` lines in the Coolify logs (real visitors, other browsers). Go through the whole
site — home page, forms (Turnstile!), gallery (R2 images), embeds, cookie banner accept (analytics and
pixels load only after consent), the admin. Give it a few days of real traffic.
3. **Fix each violation** — a missing host of yours → the matching flag or `extra`; noise from browser
extensions (`chrome-extension://`, `moz-extension://`) → ignore.
4. **Enforce** — when the reports are clean, change `mode: 'report-only'` to `mode: 'enforce'` (site and
admin). Keep `reportUri`: enforced violations keep being reported. Check the pages once more.
### Building CSP by hand (if you need full control)
Pass your own string through `additional` (same key overrides `csp`):
```ts
const securityHeaders = buildSecurityHeaders({
hsts: process.env.NODE_ENV === 'production',
additional: [{ key: 'Content-Security-Policy-Report-Only', value: "default-src 'self'; base-uri 'self'; object-src 'none'; …" }],
})
```
Read the media domain from `R2_PUBLIC_URL` (env), do not hard-code it. Anything you do not list will be
blocked once enforced.
### Checking headers in production
```bash
# check which headers actually go out:
curl -sI https://<DOMAIN>/pl | grep -iE "strict-transport|content-type-options|referrer|content-security|reporting-endpoints|x-frame|x-powered-by"
```
Expected: HSTS, nosniff, Referrer, `content-security-policy-report-only` (or `content-security-policy`
after enforcing), and NO `x-powered-by`. If ALL of them are missing despite buildSecurityHeaders in the
config → check that `headers()` is wired and that Cloudflare (if it sits in front of the app) does not
filter headers.
> Cloudflare / Coolify note: if CF sits in front of the app, it may override/filter
> headers. Then set them in CF as well (Transform Rules → Modify Response Header),
> or make sure CF passes the origin's headers through. Coolify's proxy passes the app's headers
> through unchanged; a header middleware added in the app's "Custom labels" can add or drop them.
## COOP (Cross-Origin-Opener-Policy) — on by default
buildSecurityHeaders sends `Cross-Origin-Opener-Policy: same-origin` by default —
it isolates the browsing context (protection against XS-Leaks / Spectre and
window.opener leaks). It is a universal header, so it is on automatically.
- Default `same-origin` (the safest)
- `coop: 'same-origin-allow-popups'` — if you open OAuth/payment popups
that need window.opener
- `coop: false` — turn it off (rarely needed)
## Trusted Types — do NOT roll out (for now)
Do NOT enforce `require-trusted-types-for 'script'`. Why:
- The Lighthouse audit is "Not scored" (informational/experimental in Chromium)
- Enforcing it without a complete policy engine in Next/React causes a `TypeError`
with third-party scripts that manipulate the DOM with strings (Turnstile, GA)
- The security gain does not outweigh the risk of breaking the site
Leave Trusted Types out of CSP until Next/React support it natively.
## Changing the admin panel path (/admin → /its)
Hides the panel from bots that scan well-known paths (`/admin`, `/wp-admin`).
The plugin sets the path through the `adminRoute` option:
```ts
// payload.config.ts
iapl({
i18n: i18nConfig,
adminRoute: '/its', // panel at /its instead of /admin
})
```
**`robots.txt` with a hidden panel:** the default `robots` blocks `/admin`. Do not
put `/its` there — `robots.txt` is public and would reveal the path (the panel has
`noindex` anyway). In `createContentHelpers` set `robots: { adminRoute: false }`.
### REQUIRED — move the panel folder in the project
The plugin sets `config.routes.admin`, but does NOT create files in the project's `app/`.
You must move the panel folder for the path to work:
```
# BEFORE:
app/(payload)/admin/[[...segments]]/page.tsx
app/(payload)/admin/[[...segments]]/not-found.tsx
# AFTER (folder name = adminRoute without the slash):
app/(payload)/its/[[...segments]]/page.tsx
app/(payload)/its/[[...segments]]/not-found.tsx
```
Without moving the folder: `config.routes.admin = '/its'`, but `/its` returns 404
(no file), and `/admin` does not work either (the config changed). Both must match.
### This is OBSCURITY, not SECURITY
Changing the path makes automated scans harder, but it is NOT a safeguard.
Real panel protection:
- **2FA** for every user (enforced by the plugin — section below)
- Strong passwords
- Rate limiting on login — failed staff sign-ins per IP and address (`accounts.signInLimit`, 1.18.0), staff sign-in
only from the site's own origin (`accounts.signInSameOrigin`), the current password for one's own e-mail / password
change (`accounts.confirmOwnChanges`) — [access.md](./access.md)
- IP allowlist (if the panel is for the team only)
- buildSecurityHeaders (headers)
`/admin → /its` is a layer (it filters out dumb bots), not a lock. Treat it as an
addition to real safeguards, not a replacement for them.
## Panel actions only from the site's own origin (`adminSameOrigin`, 1.17.2)
The plugin's panel actions act with the panel's login cookie and read their body whatever its `Content-Type`
says: `POST /api/iapl/mail-relay/connect` and `/disconnect` (the mail service), `/api/ipal/test-email`,
`/api/ipal/cookie-scan`, `/api/ipal/cookie-approval`, `/api/ipal/cookie-crawl`. A `text/plain` POST needs no CORS
preflight, a page on a sibling subdomain is "same site" (the browser sends the `SameSite=Lax` cookie), and
Payload's own CSRF list is empty unless `serverURL` or `csrf` is set. So before 1.17.2 such a page could make a
signed-in administrator disconnect the mail service, send test mails, run scans and crawls, or approve every
waiting cookie. Now each of them refuses (`403`, before anything is read) a request a browser marks as coming
from elsewhere — the same rule as the 2FA endpoints: the `Origin` header, else `Sec-Fetch-Site`. Own origins: the
host the request came in on (`Host`, `X-Forwarded-Host`), `serverURL`, Payload's `csrf` and `cors` lists, and
`adminSameOrigin.origins`. A request with neither header (a script, `curl`, a server) passes: it rides on nobody's
cookie. The panel's own buttons are on the site's origin and are not affected. A project's own endpoint on one of
these paths is left as it is. The 2FA endpoints keep their own switch (`twoFactor.sameOrigin`).
```ts
iapl({
// adminSameOrigin: { origins: ['https://panel.example.com'] }, // the panel served from another origin
// adminSameOrigin: false, // no check (as before 1.17.2)
})
```
- **Behind a proxy that rewrites `Host`** and sends no `X-Forwarded-Host`, without `serverURL`, the site's own
panel buttons are refused. It is not silent: the first refusal of each origin is logged
(`[iapl] a panel action from origin "…" was refused … pass iapl({ adminSameOrigin: { origins: [...] } })`), and
`iapl-doctor` warns when the running config has neither `serverURL` nor `csrf` (`csrf-empty`). Set
`serverURL: process.env.NEXT_PUBLIC_SERVER_URL`.
- **Any other value** than `true`, `false` or an object with `origins` (a list of strings) stops the start.
- **Building blocks:** `requireOwnOrigin(endpoint, origins?)` for an endpoint of your own,
`guardAdminEndpoints(config, projectEndpoints, option)`, `ADMIN_POST_ENDPOINTS` (the list), and the 2FA ones:
`requestFromOwnOrigin`, `ownOrigins`, `reportRefusedOrigin(req, origins?, { what, option, docs }?)`.
- **Check:** `curl -X POST <site>/api/ipal/test-email -H 'Origin: https://other.example' -H 'Content-Type: text/plain'
-b <admin cookies> -d '{"to":"a@example.com"}'` → `403`; "Send test e-mail" in the panel still works.
## 2FA (TOTP) — ENFORCED for every user
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 `@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 IAPL runs its own check, so the second
factor also covers what the package cannot see — see "What the second factor covers" below.
### Dependency
```bash
pnpm add @clocklimited/[email protected]
```
Note: the package has no stable 3.0.0 yet — use a specific beta version
(or `^3.0.0-0` to allow prereleases). Plain `^3.0.0` fails with
ERR_PNPM_NO_MATCHING_VERSION.
### Configuration (payload.config.ts) — INJECT the plugin (required in Next)
```ts
import { payloadTotp } from '@clocklimited/payload-2fa'
iapl({
i18n: i18nConfig,
twoFactor: {
issuer: 'Company Name', // shown in the authenticator app
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: IAPL's own check off, the package's wrapper only
},
})
```
**Why `plugin: payloadTotp` (injection):** it is the same pattern as
`NextResponse`/`revalidatePath` — the project provides the peer dependency, the plugin does NOT
import it. Up to 1.8.x the plugin did a dynamic import instead, which **Next does not
bundle** (webpack turns an import from a variable into an empty context) → the error
**"Cannot find module '@clocklimited/payload-2fa'"** in `next build` and on every
page (public ones too). The build can still go "green", because
`generateStaticParams` catches the error — the page only breaks at runtime.
**`serverExternalPackages` is NOT a workaround.** The package imports its own
`*.module.css`; once externalized it is loaded by Node, which does not know `.css` →
`ERR_UNKNOWN_FILE_EXTENSION` while collecting data for `/admin`. The only working
configuration in Next is injection, so since 1.9.0 `plugin` is **required**
(missing → a clear error at startup). The `payload …` CLI loads the same config, so it
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**. iapl 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 `iapl` 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 IAPL closes that itself:
| Where | How |
|---|---|
| every collection and global in the config when iapl finishes | `access` wrapped with `requireSecondFactor` |
| collections and globals added by plugins listed **after** iapl | wrapped in iapl's `onInit`; the log line `[iapl] 2FA also enforced on entities added after iapl: …` 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; `iapl-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: `[iapl] 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 iapl-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.serviceAccount === true }, // a service account that logs in with a password, on purpose (the field: below)
// 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 `[iapl] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN …` at start;
`iapl-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.
- **Decide `exempt` from a field only an administrator can write — not from the e-mail address.** Every account
may change its own e-mail (REST, GraphQL and the account page, with no password asked), so an e-mail list
(`user.email === 'it@example.com'`, a list of addresses) lets an editor rename itself into it, and an admin's
later reset of that account's TOTP would leave it on its password alone. An account also cannot be told apart
from an address that does not exist yet. A checkbox that only admins can set:
```ts
import { adminOnlyField } from '@intecion/ipal-kit'
// in the 2FA collection's fields:
{ name: 'serviceAccount', type: 'checkbox', defaultValue: false, access: { create: adminOnlyField, update: adminOnlyField } },
// twoFactor.requireSetup:
{ exempt: ({ user }) => user.serviceAccount === true }
```
On Postgres / SQLite the new field is a column: a migration in the same deploy. A project that keeps an e-mail
list makes the e-mail field admin-only too (`access: { update: adminOnlyField }` on `email`) — then no account
changes its own address. **Check:** as an editor, `PATCH /api/users/<own id>` with `{ "serviceAccount": true }`
→ the value stays `false`.
- **`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`); `iapl-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** IAPL'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. iapl
counts **wrong codes** per account on `POST /api/verify-totp`: by default, after **five wrong codes within 10
minutes** the next attempt — right or wrong — is refused with `429` and `Retry-After`, and a line goes to the log.
An attempt takes its place before the code is compared, so a burst of parallel guesses cannot slip under the limit,
and a right code gives its place back: an account that logs in correctly many times (an office sharing one login,
several devices) is never refused (since 1.17.1; before, every attempt counted, right or wrong, so the sixth correct
login in the window was refused). While other attempts of the same account are still being checked, a new one that
only they hold out gets `429` with `Retry-After: 2` and "try again in a moment" instead of the long wait; an attempt
that never ends counts as wrong. 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 **and in the database** (Payload's key-value store, `payload.kv` — the `payload-kv`
collection Payload itself adds; no new collection): a restart, a redeploy or a second instance does not hand out
new attempts. The higher of the two counts decides; when the database part fails, the memory count still does
(there is no "allow when the store fails" path). `verifyLimit: { max: 10, windowMinutes: 5 }` changes it,
`{ store: 'memory' }` keeps the count in this instance only, `{ keyPrefix }` names the count's key in
`payload-kv` (`<keyPrefix>:2fa-verify:<collection>:<id>`; default `ipal`, and `iapl` on a site with
`iapl({ storageNames: 'iapl' })` — one prefix per site, a change starts the running counts from zero once), `verifyLimit: false` turns it off (a limiter in
front of the site).
**Verify and setup attempts only from the site's own origin** (`twoFactor.sameOrigin`). The limit counts every
attempt of an account, so a page that can make the browser send the account's login cookie could burn the
owner's attempts and lock them out — no password needed. A sibling subdomain is such a page (`SameSite=Lax` does
not stop it, and Payload's own `csrf` list is empty unless `serverURL` or `csrf` is set). So
`POST /api/verify-totp` and `POST /api/setup-totp` refuse (`403`) a request that the browser marks as coming from
elsewhere — the `Origin` header, else `Sec-Fetch-Site` — **before it is counted**. Own origins: the host the
request came in on (`Host`, `X-Forwarded-Host`), `serverURL`, Payload's `csrf` and `cors` lists, and
`twoFactor: { …, sameOrigin: { origins: ['https://app.example.com'] } }` for a front end on another domain.
A request with neither header (a script, `curl`, a server) passes: it cannot ride on somebody's cookie.
A default port written out (`X-Forwarded-Host: site.example:443`) is the same host.
**The admin's reset** (`POST /api/ipal/two-factor/reset`, "Reset two-step verification" / "Reopen setup") follows
the same rule since 1.17.1: it reads a `text/plain` body, which a foreign page can send without a CORS preflight,
so before a page on a sibling subdomain could reset any account's TOTP and end its sessions with an admin's
cookie. The panel's own button is on the site's origin and is not affected.
`sameOrigin: false` turns it off (verify, setup and the reset).
**Behind a reverse proxy that hides the site's address** — it rewrites `Host` and sends no `X-Forwarded-Host`
(nginx's plain `proxy_pass`; Traefik and Coolify keep `Host`) — and without `serverURL`, the server cannot know
its own address: the site's own verify page is refused, and **nobody can enter a code**. It is not silent: the
first refusal of every origin is logged, `[iapl] 2FA: a code from origin "https://…" was refused and not counted
— it is not one of this site's own origins (…)`, with the three ways out: set `serverURL` (the right fix, it
also fills Payload's `csrf` list), or `twoFactor: { sameOrigin: { origins: ['https://…'] } }`, or make the proxy
send `X-Forwarded-Host` (`proxy_set_header Host $host;` in nginx). `reportRefusedOrigin` is the building block. `iapl-doctor` warns (`csrf-empty`) when the config sets neither `serverURL` nor
`csrf` — Payload then accepts the login cookie from any origin.
**What is NOT covered — the complete list.** (1) Anonymous requests: the access function decides. (2) Accounts
of other auth collections: 2FA is about one collection; such an account is not staff unless its collection is in
`access.staffCollections`, and then it is staff **without** a second factor (warning in the log at start).
(3) API keys. (4) An account that has not set TOTP up yet — 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 IAPL
{ slug: 'notices', custom: { totp: { disableAccessWrapper: { read: true } } }, … }
// IAPL'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, IAPL'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. iapl 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 iapl 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 `[iapl] 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
IAPL'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":"[email protected]","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
```
### Set-up confirmed by e-mail (`twoFactor.confirmByEmail`, 1.18.0)
**Why.** Inside an account's setup window the password alone used to be enough to enrol an authenticator — so
whoever learned the password (phishing, a reused password) could enrol THEIR OWN app first: they were in with full
rights, and the owner was locked out. The window opens for every existing account at the first start after an
upgrade to 1.16.6 or later, for every new account, and after every reset (security audit 2026-12, finding F0).
**What happens now (on by default):**
1. The person scans the code and types it on the setup screen (`POST /api/setup-totp`). IAPL checks the code like
the 2FA package does, but **does not turn the factor on**: it keeps the secret aside (payload-kv), sends a link
to the **account's own e-mail address**, and gives this browser a random cookie (`<cookiePrefix>-iapl-enrol`,
HttpOnly). The screen says where the link went (`p…@example.com`); after a reload a notice shows it too.
2. Opening the link (`GET /api/iapl/two-factor/confirm?u=…&t=…`) shows a page with one button — a mail scanner that
opens links changes nothing. The button posts it back.
3. The POST checks: the link's token (stored as a hash; single use; **30 minutes**), that no newer set-up replaced it,
the site's own origin, and — `sameBrowser`, on by default — the cookie of the browser that scanned the code. Then
the factor is written, **every session of the account ends**, and nobody is signed in: the person signs in again
with the password and the code.
- Until then the account stays in its setup state: nothing but the setup screen, as before. The window keeps running.
- A new set-up (scanning again) replaces a waiting one; its link stops working. At most **5 confirmation mails per
account and hour** (`429` after that).
- The link is made from Payload's `serverURL` (`NEXT_PUBLIC_SERVER_URL`), never from the request's `Host`; without
`serverURL` no link is made (logged).
- Why the same browser: someone with the password who starts a set-up gets the link sent to the OWNER, who may open
it thinking it is theirs. With `sameBrowser` that click is refused ("open this link in the browser where you scanned
the code"); the mail also says "if it was not you, do not open the link: someone knows your password".
**Notices.** The account's address gets a mail whenever its factor is turned on (with who confirmed it, when an
administrator did), changed, or removed / reset (with the administrator's address) — whatever path wrote it: the
setup screen, the package's remove and admin endpoints, IAPL's reset, the Local API. Mails never carry the secret.
They go in the language of the panel's fallback language (`i18n.fallbackLanguage`), as kind `account` (the link) or
`security-alert` (notices) through the site's mail (the mail service or SMTP, [email.md](./email.md)).
**When mail does not work** (no sending method chosen, the mail service still pending, SMTP incomplete, or no mail
transport at all) nobody is locked out, and the doctor says it loudly:
- the person's screen says the e-mail could not be sent and to ask an administrator;
- the **link is written to the server log** (one `[iapl] 2FA: … Link (valid 30 min, single use): …` line; Coolify →
Logs) — for the team that runs the site. With `sameBrowser` it still works only in the browser that scanned the
code (the person at the keyboard opens what the team reads out to them). A fresh site's first administrator, who
has no mail yet, finishes this way;
- an **administrator** who is fully signed in (password and code) opens the account page and chooses **"Confirm the
waiting set-up"** (`POST /api/iapl/two-factor/confirm-pending { userId }`; same rule as the reset: `resetAccess`,
own origin) — only after checking with the person, outside the panel, that they started it;
- `iapl-doctor --deep` (or `--url` with `IAPL_DOCTOR_TOKEN`): rule `2fa-enrolment-mail` — **error** while mail does
not work, and the number of set-ups waiting.
**What to do on a site:** make sure e-mail works BEFORE people set up two-step verification (Site integrations →
E-mail sending → "Send a test e-mail"); after an upgrade, tell the staff that the set-up now ends with a link in their
mailbox. Nothing to wire: the endpoints and hooks come with `twoFactor`, the import map does not change.
**Options** — `twoFactor.confirmByEmail`:
| Option | Default | Role |
|---|---|---|
| (the whole) | on | `false` = the 2FA package's behaviour: the code alone turns the factor on (no link, no notices) |
| `linkMinutes` | `30` | how long a link works (1–1440) |
| `sameBrowser` | `true` | the link works only in the browser that scanned the code; `false` = any browser (weaker: the owner can confirm an attacker's set-up by clicking) |
| `adminConfirm` | `true` | an administrator can confirm a waiting set-up from the account page |
| `logLinkWhenMailFails` | `true` | write the link to the server log when the mail cannot be sent |
| `notices` | `true` | notice mails on enrolment, change, removal / reset |
| `maxMailsPerHour` | `5` | confirmation mails per account and hour |
A value that is not understood stops the start (like every switch since 1.17.1). **Building blocks** (exported):
`startEnrolment`, `buildEnrolmentEndpoints`, `buildTotpNoticeHooks`, `sendTwoFactorNotice`, `verifyTotpCode`,
`readPendingEnrolment`, `pendingEnrolmentInfo`, `dropPendingEnrolment`, `countPendingEnrolments`,
`pendingEnrolmentKey`, `mailConfigured`, `resolveConfirmByEmail`, `ENROL_CONFIRM_PATH`, `ENROL_ADMIN_CONFIRM_PATH`.
**Verify:** a new editor signs in, scans the code → the screen says "we sent a link to e…@…" and
`curl -s -o /dev/null -w '%{http_code}' -b <its cookies> <site>/api/globals/site-integrations` is still `403`; the
mail arrives; opened in another browser it answers "open this link in the browser where you scanned the code"; in the
same browser → "Two-step verification is on", then sign-in with password and code works and the mailbox has the
"turned on" notice. The built reference site runs this in `e2e/two-factor-enrolment.spec.ts` (`pnpm e2e:built`).
### Import map (required)
The 2FA screens and the redirect to them are admin components. After adding `twoFactor`, and after every
IAPL upgrade, run:
```bash
pnpm generate:importmap
```
`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`)
The setup and verify screens and the user field read their texts through Payload's i18n
(`totpPlugin:*`), in the user's admin language (*Account → Language*; without a choice, the
browser's language — an English browser sees English screens on a Polish site). The package's own texts are long and informal,
so IAPL merges `TOTP_TEXTS` (English and Polish, per `docs/dev/admin-ux.md`) over them, e.g.
"Two-step verification" / "Weryfikacja dwuetapowa", "Enter the 6-digit code from the app:" /
"Wpisz 6-cyfrowy kod z aplikacji:". The browser tab reads "Weryfikacja dwuetapowa — <site> | Panel"
(`TOTP_VIEW_TITLE` in the site's default language: Payload's view title is a plain string).
- **Override one text:** `i18n.translations.<lang>.totpPlugin.<key>` in your config — your keys win
over both sets.
- **Keep the package's texts:** `twoFactor: { …, texts: false }`.
- **Not translatable:** a network failure while sending the code shows the package's hardcoded
"Something went wrong" toast (rare: the server's own errors are translated).
### The redirect to the 2FA screens (`twoFactor.provider`)
The package's own admin provider decides on the server where to send the user, from an `x-pathname`
request header. Nothing sets that header on `/admin` (the `createProxy` matcher skips `/admin`), so up to
1.14.1 a user without TOTP was sent to `/admin/setup-totp?back=null`, and the setup screen redirected
to itself forever. Since 1.14.2, IAPL swaps in its own provider,
`TotpRedirectProvider`: it reads the path in the browser, never redirects away from the setup or verify
screen or from logout, and renders nothing while a redirect is pending, so the panel does not flash.
No project change is needed apart from `generate:importmap`.
- `twoFactor.provider: '@/components/MyTotp#MyTotp'` (or a `{ path, clientProps, serverProps }` object):
your own component. It gets clientProps `forceSetup` and the package's serverProps `pluginOptions`.
The pure logic is exported: `totpRedirectTarget({ adminRoute, forceSetup, pathname, user })` returns
the URL to send the user to, or `null`.
- `twoFactor.provider: false`: keep the package's provider. Then a proxy must set `x-pathname` on every
`/admin` request, or the loop comes back.
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.
IAPL 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 IAPL 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. IAPL 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 `iapl`, or under another key or route: that view is yours and is not wrapped. Use
`wrapTotpViews` or `safeAdminBack` in it. `iapl-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 `iapl`'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). IAPL reports it in three places:
- **Before deploy:** `pnpm exec iapl-doctor` reports `import map lacks @intecion/ipal-kit/admin#SafeTotpView` (error).
- **At every start in production:** the log has `[iapl] 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 IAPL'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:
`[iapl] 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
twoFactor: false // ONLY when the project really cannot use 2FA (rare)
```
2FA is ENFORCED by default. `false` is a deliberate opt-out — avoid it. Leaving out `twoFactor`
(even though the type marks it optional) stops startup with `twoFactor.issuer is required` — the decision must be explicit.
### 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), 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=…`)
**Check:** log in as a new admin. The address must end at `/admin/setup-totp?back=%2Fadmin` and the page must
show the QR code. `back=null` or a page that keeps reloading means the import map is stale (run
`pnpm generate:importmap`) or `provider: false` without an `x-pathname` header on `/admin`.
### Resetting 2FA (admin)
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 IAPL'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 === 'owner@example.com'`.
`({ 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: '[email protected]' } } })
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 `iapl-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. iapl passes it only `collection`,
`forceSetup` and `issuer`; pass other options by wrapping the injected factory:
`plugin: (opts) => payloadTotp({ ...opts, adminManageAccess: ({ req }) => isAdmin(req.user, req.payload) })`.
IAPL'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 — for what is in the config when it runs; IAPL's own check covers the rest
("What the second factor covers").
## 1.9.1 — security review results
- Drafts that were never published are no longer publicly available (`resolveRoute`, Markdown, MCP,
metadata), nor on archive lists (`getArchiveEntries`). Preview: `resolveRoute({ draft: true })`,
`getArchiveEntries({ draft: true })` in `draftMode()`.
- Links from the CMS: only `http(s)`, `mailto`, `tel`, `sms`, `#`, `/` (`safeHref`); `javascript:` and `data:` are rejected —
also in rich text (`RenderRichText` replaces them with `#`).
- Analytics IDs are validated (in the panel and before being sent to the browser).
- Form submissions: read `editor+`; addresses from the Emails tab are not publicly visible.
- 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
admin creates and deletes. Before, any logged-in account could change an admin's email/password.
- 2FA without `collectionSlug` wraps the panel login collection (`admin.user`, else the first auth
collection), not the literal `'users'`. Plugin startup fails with `[iapl] twoFactor…` when the target is not
an auth collection or differs from `admin.user` — deliberate exception: `twoFactor.allowCollectionMismatch: true`.
- Injected auth collection with roles: `unlock` is admin-only too. You can override all of it:
`access.authAccess`, `access.firstUserAdmin: false`, `globalOverrides`, `forms.formOverrides`.
- Site settings, Cookie banner, Notifications and the Forms collection: write is `editor+` only; a form's
Emails tab (recipients, BCC) is readable only by `editor+`.
- Full table: [access.md](./access.md#what-the-plugin-locks-down-by-itself).
## Stored secrets (`secrets.writeOnly`, `secrets.reenterOnChange`)
`smtpPassword` and `turnstileSecretKey` live in the Site integrations global: **the panel is their source**
(there is no env variable for the SMTP password, and the env fallback for the Turnstile secret is deprecated —
[turnstile.md](./turnstile.md)). They are **write-only**:
| Who reads | Gets |
|---|---|
| REST (`GET /api/globals/site-integrations`), GraphQL, the panel's form, versions — anything through access control, an admin included | `'********'` when a value is stored (`SECRET_MASK`), the empty value when none is |
| Server code through the Local API with access control off (the default of `payload.findGlobal`) — the mail adapter, the Turnstile check, your own server code | the real value |
| The Local API **with** access control (`overrideAccess: false` and a `user`) | `'********'` |
| A save sends | Result |
|---|---|
| nothing for the field, an empty value, `null`, or `'********'` back | the stored value is kept |
| a new value | replaces it (the answer shows `'********'`) |
| `'[[clear]]'` (`SECRET_CLEAR`) | removes it |
| a value that is not text (`false`, `0`, a list, an object) | **refused** (`400`): "Enter the value as text." |
| the server, the port or the user name **changed** (whatever the transport), and **no** new password | **refused** (`400`, on the password field): "Enter the password again…" |
In the panel the field says "A value is set. It is not shown; type a new one to replace it." and offers "Remove
the stored value".
**The SMTP password stays with the server it was saved for** (`secrets.reenterOnChange`). Hiding the value is
not enough on its own: an admin session could point `smtpHost` / `smtpPort` at a machine of its own, press
"Send test e-mail", and read the password off the connection. So a save **through access control** (the panel,
REST, GraphQL) that changes `smtpHost`, `smtpPort` or `smtpUser` while a password is stored must send the
password again — or remove it (`'[[clear]]'`, "Remove the stored value") for a server without one. **Whatever
the sending method says:** with "Microsoft Graph" chosen the SMTP server is still used for attachments Graph cannot
take (and, on a site nobody has chosen a method for, when Graph is not configured). A change of the sending method
alone asks for nothing. Values are compared exactly (`587` and `'587'` are the same; another letter case or a space
is a change), and a value never saved — or a `NULL` in a SQL row — counts as the field's default, so saving
the form unchanged asks for nothing. Server code — a seed, a script with the Local API and access control off
— is not asked. `iapl({ secrets: { reenterOnChange: false } })` = the stored password follows the new
server, as before.
A stolen admin session, or any way past the global's read rule, no longer yields a working mailbox password.
What it does **not** protect: the database and its backups hold the value in plain text (encryption at rest is
a separate, open question); whoever can change the config or run server code can read it; and a session that
knows nothing but may send e-mail can still **use** the mailbox through the site (send, not read). On a port
other than 465 the connection is encrypted only when the server offers STARTTLS; requiring it is a possible
later option, not part of this release.
**Versions.** The global has no versions by default. A project that turns them on
(`globalOverrides: { 'site-integrations': { versions: … } }`) stores the secret in every version — as in the
document itself — and reads of versions are masked like any read. Since 1.17.1 the versions are read by the same
people as the global (`readVersions`: admin): Payload's own default lets every signed-in account list them, an
editor or a plain `user` account included, with the server, user name and status texts. Your own rule:
`globalOverrides: { 'site-integrations': { access: { readVersions: … } } }`. A **restore** answers with the version
document, the fields under `version`, where field hooks do not run: the global's `afterRead` hook
`maskSecretsOnRestore` masks them there too. A restore brings back the password of that version.
- **What an existing site sees after the upgrade:** nothing to do. The stored values stay; the panel shows "a
value is set"; the API returns the mask. Code of your own that read the secret over REST / GraphQL as an admin
must read it on the server with the Local API instead.
- **Off:** `iapl({ secrets: { writeOnly: false } })` — the value is returned to whoever may read the global.
- **A query cannot name a secret (1.17.1).** A `where` or `sort` on a write-only field answers by the stored value
(`where[version.smtpPassword][like]=Zq` gave a count), so an admin could read the secret back one character at a
time. `writeOnlySecret` now gives the field a `read` rule, `secretReadAccess`, that refuses a query naming it —
REST and GraphQL, `like` / `equals` / `exists` / `sort`, on the document and its versions (an error, no count) — while
every read of a document still answers the mask and the panel shows and saves the field as before. Payload checks a
query's fields without a document and asks rules that depend on one to deny then; the panel always passes the
document. The field's own `access.read` is kept and decides for a document. Not in collection list columns or
list filters. Server code with `overrideAccess` (the Local API) may still query it.
- **Your own secret fields:** `writeOnlySecret({ name: 'apiToken', type: 'text', admin: { components: { Field:
'@intecion/ipal-kit/admin#MaskedField' } } })`, or `writeOnlySecrets(fields, ['apiToken'])` for fields inside
tabs / rows / groups; the hooks `maskSecretAfterRead` / `keepSecretBeforeValidate`, `SECRET_MASK`,
`SECRET_CLEAR`, `isSecretMask`, `INTEGRATION_SECRET_FIELDS` are exported. A real secret equal to `********` or
`[[clear]]` cannot be stored.
- Bound to other fields, like the SMTP password: `writeOnlySecret(field, { boundTo: ['apiUrl'] })`, or
`writeOnlySecrets(fields, ['apiToken'], { apiToken: { boundTo: ['apiUrl'], appliesWhen: (data) => … } })`
(`WriteOnlySecretOptions`; `buildKeepSecret(options)` is the hook; `SMTP_PASSWORD_BOUND_TO` is the plugin's
list). The fields must be siblings of the secret.
- With versions on your entity: add `hooks: { afterRead: [maskSecretsOnRestore] }` to the global or the
collection (`maskWriteOnlySecrets(data, fields)` is the walker it uses).
- **Check:** as a fully signed-in admin, `GET /api/globals/site-integrations` → `"smtpPassword":"********"`; save
the form without touching the field → a test e-mail still goes out; change the server without typing the
password → the save is refused with "Enter the password again…".
## The mail service's token and its public route (`mail.relay`)
A site that sends through the Intecion Notifications Webservice (IWSN in the panel; [email.md](./email.md)) holds one secret: its own
token. What protects it, and what the new public route can and cannot do:
| | |
|---|---|
| **No key in the package** | The plugin carries the service's address and nothing else. A site gets its token by proving it is served at its host: it makes a nonce, the service calls `POST https://<host>/api/iapl/mail-relay/confirm` with the nonce and a token, and only an answer that hashes both makes the token valid |
| **Where the token is** | `payload-kv`, one entry per host (`iapl:mail-relay:site:<host>`). The collection refuses every operation through access control (`read`, `create`, `update`, `delete` are `false`) and is hidden: REST, GraphQL and the panel cannot reach it — an admin included (test: `test/mailRelayHttp.test.ts`). Server code with the Local API can, like `smtpPassword`. It is stored as it is (no encryption at rest), never logged, never sent to a browser, never part of a route's answer |
| **A database copied to another host** | both sides hold a token to its host: every request names the site (`X-Intecion-Site`) and the service refuses another host's token (`host-mismatch`); and on the site the token is stored under the host it was issued for: a copy on a staging domain neither uses nor touches production's entry (a read never deletes), and a non-public copy (a host that matches `developmentHosts` — built in: `*.dev.netscale.pl`, no env needed — or `IAPL_NOINDEX=1`) **neither enrols nor sends by itself** — with production's data it would mail real people — until an admin presses "Connect again", also when it has a token of its own (production's data copied back onto a development address). A public site is never held (launch and a domain move must work unattended), so **a copy on a host outside those patterns, without the variable, sends**; the doctor notes a public site whose database knows another host (`mail.relay.otherHosts`) |
| **A token of another site** (stored by a script, set as `relay.token`, or pasted into the access-key field — which is off unless the project sets `mail.relay.accessKeyField`) | refused: the service is asked which host the token is for before it is stored or used; a foreign one is not saved, not used, not revoked |
| **A token read from a database dump** | **works from the same server** (a staging site on the machine production runs on shares its outgoing address) — which is why the store is tied to its host, above. From another server it does not work: the service accepts a token only from the addresses the site enrolled from (IPv6: the same `/64`) and answers anything else "enrol again" — which needs the call-back to the real site. It cannot send as another site, and the limits below apply |
| **What a token can do at most** | send within the site's limits (30 an hour, 200 a day, 10 recipients, 10 MB by default) from the service's fixed address, under a sender name the service checks, with `X-Intecion-Site: <host>` on every mail. It cannot set `From`, `Return-Path` or any header, and cannot address a security alert |
| **The confirm route** | public by design, `404` with an empty body unless the body carries a nonce **this site** made in the last 5 minutes (kept as a hash, compared in constant time, single use). It stores the delivered token **beside** the one in use and never replaces a working token: a token becomes the one in use only after the service has accepted it — a `200`, or a refusal the service gives after it has checked the token; no answer, an error page or `rate-limited` prove nothing and leave both as they are. **Refused** calls are rate-limited per address (10 a minute, `mail.relay.confirmRateLimit`); the nonce is looked up first, so junk from the address the service shares with others cannot keep the site's own enrolment out. A stranger who calls it learns nothing and changes nothing |
| **Who can start an enrolment** | the server itself (a send without a token) and an admin ("Connect again"). The three state routes need the `admin` role and answer with states only |
| **A site taken over by an attacker with admin rights** | can send mail through the service under any sender name the service's check lets through, within the limits — as it could through the site's SMTP server. Intecion sees the host on every mail and can suspend the site (`relay-suspended`) |
| **Visitors** | cannot reach the service: only the server calls it. What a visitor can trigger is a form's mail (rate limit, Turnstile) and "forgot password" — limited by the site per address and per visitor (`mail.relay.accountMail`), because the service does not limit account mail per address |
| **A subject or name typed by a visitor** | line breaks, control characters, direction marks and other invisible characters are removed before the message leaves (`cleanSubject`); recipients are reduced to bare addresses; a message has no header field |
Turn off: `iapl({ mail: { relay: false } })` — no route, no outbound call, no token. Give the token up:
"Disconnect" in the panel (`disconnectRelay`), which revokes it on the service — at once when the service answers;
when it cannot be reached the site stops using the token, the panel says the disconnection is not confirmed, and
the token stays valid at the service until "Disconnect" is pressed again and answered.
## Dashboard alerts by role (`dashboardAlerts`)
The plugin's dashboard alerts read data that only some roles may read (with access control off, on the server),
so each decides who sees it. **Integration alerts** (Site integrations is admin-only): an admin sees what is
failing and the link; an editor sees "An integration needs attention. Ask an administrator to look at it."; anyone
else sees nothing. **Cookie alerts** (crawl result, cookies waiting): editors and above. A session that still owes
its second factor sees none of them. `iapl({ dashboardAlerts: { integrations: 'editor' | 'all', cookies: 'all' } })`
loosens it. **`'all'` checks nothing** — no role and no second factor: whoever the dashboard is drawn for sees
the full text, as before. The components take the same as props
(`details`, `audience`).
## Closed doors from outside (`closed-doors.spec`)
Access rules are tested from OUTSIDE, on a **production build** (`pnpm build && pnpm start`): some doors behave
differently outside production (Payload's GraphQL playground and introspection), and a bundler renames every
function (a rule told apart by its name was skipped there in 1.16.7). The test asks every door that must stay closed
as three callers and fails when one opens:
- **anonymous** — no session;
- **customer** — an account of a visitor login collection (a shop, a member zone), if the site has one;
- **editor** — a staff account with the role `editor`, signed in with the second factor.
**In a project:** copy `.agents/skills/iapl-audit/resources/closed-doors.spec.template.ts` to
`tests/closed-doors.spec.ts`, set the test accounts' variables (the file's header: `E2E_CUSTOMER_*`, `E2E_EDITOR_*`,
local or staging database only) and add the project's own doors to `DOORS`: each names who it is closed for and,
where 401 / 403 / 404 is not the whole story, what a closed answer looks like. A write door is asked with a body
that changes nothing when it is open (a document id that does not exist, `{}`): an open door then answers 404 or
400 instead of 403. Run it before every release and after every Payload / IAPL upgrade. Verify: the run lists one
test per door and caller; temporarily set a collection's `read: () => true` where a door says closed and the test
fails.
**In the plugin repository** it is `reference/e2e/closed-doors.ts` (the doors) and `closed-doors.spec.ts`, run by
`pnpm e2e:built` after a webpack and a Turbopack build; the customer is the late-staff fixture's self-signing-up
`e2e-visitors` collection, the editor `e2e/create-test-admin.ts`'s `…-editor@` account. A door that is still open
for a caller while the owner decides is listed under `openFor` and asserted OPEN (`test.fail`): the day somebody
closes it, the run says "passed unexpectedly" and the entry moves to `closedFor`.
## Routes nobody has judged (`routes:check`)
A Payload, plugin or project change can add a public route without anybody noticing (IAWL idea 34). `routes:check`
lists every door a built config opens — each REST route of every collection, global and root endpoint (Payload's
own and the plugin's), each GraphQL query and mutation, each Next route file with its methods — and compares the list
with a committed snapshot in which **every entry carries one line saying who may use it and why**. It fails on a
route that is not in the snapshot and on an entry without a reason (or one that still says `TODO`); routes that went
away are listed, not failed. The list comes from the config only, never from the database, so it is the same on
MongoDB, Postgres and SQLite.
**In a project:** copy `.agents/skills/iapl-audit/resources/routes.template.ts` to `tests/routes.ts`; `pnpm payload
run tests/routes.ts update` writes `tests/routes.snapshot.json` with an empty reason per route; write the reasons
(the reference site's `e2e/routes.snapshot.json` in the plugin repository shows the style), commit, and run
`pnpm payload run tests/routes.ts` in CI. After an upgrade: `update` again, judge the new entries, review the diff.
(`payload run` drops `--flags`, so the word is `update`.) Building blocks, for a test of your own:
`listPublicRoutes(config, { graphqlSchema, routeFiles })`, `listNextRouteFiles`, `compareRouteSnapshot`,
`updateRouteSnapshot` (`@intecion/ipal-kit`) and `runRouteCheck` (`@intecion/ipal-kit/doctor`, Node only). Verify: add
a root endpoint to the config and the check names it as "not judged".
**In the plugin repository:** `pnpm routes:check` (`--update` after a Payload upgrade) on the reference site, also
the first step of `pnpm e2e:built`; the test fixtures are switched off for it.
## Payload's job queue (`jobsRunAccess`, 1.17.2)
Payload runs its queue over HTTP at `GET /api/payload-jobs/run` and `/api/payload-jobs/handle-schedules`, checked by
`jobs.access.run`. Payload's default is **any signed-in account of any auth collection** — a shop's customer could
run the queue whenever they like. Since 1.17.2, when the project writes **no** `jobs.access.run`, iapl sets: an
**admin signed in with the second factor** (an admin's API key counts), or **`Authorization: Bearer <CRON_SECRET>`**
(16+ characters, compared in constant time). It is set even when the config has no `jobs` (Payload turns the queue on
by itself for scheduled publishing). A route that does not exist (no tasks, no workflows) stays 404.
**A project with jobs keeps its cron working** — check which of these it uses:
- jobs run **in-process** (`jobs.autoRun`, `pnpm payload jobs:run`, `payload.jobs.run()` in code): nothing changes;
- a **Coolify scheduled task** (or any cron) that calls the run route: set `CRON_SECRET` in the app's environment and
in the task, and send the header —
`curl -fsS -H "Authorization: Bearer $CRON_SECRET" "$NEXT_PUBLIC_SERVER_URL/api/payload-jobs/run"`;
- a cron that signs in with an **admin's API key**: works as before; with a **non-admin** account's key: switch to
`CRON_SECRET`, or write your own rule;
- the project's **own** `jobs.access.run`: always wins, nothing changes.
At start, when the queue is on, the rule is iapl's and `CRON_SECRET` is missing or short, the log says so in one
line. Overrides: `iapl({ jobsRunAccess: false })` keeps Payload's default; `{ secretVar: 'MY_VAR' }` reads another
variable; `jobsRunAccess()` is exported to reuse in a rule of your own. Verify: without the header
`/api/payload-jobs/run` answers 401, with it 200 (the closed-doors spec does both on the built reference site).
## Visitor accounts (customers, members) and Payload's default write rules
Payload fills every missing access rule with **"any signed-in account"** — an account of a visitor login collection
included. The plugin narrows its own collections and globals and the staff accounts; **your** collections and
globals are yours to rule. On a site that has (or may get) a visitor login collection, give every collection
`create` / `update` / `delete` and every global `update` a rule of its own — the reference site and every new site
from `iapl create` do (`adminOrEditor`, since 1.17.2). `iapl-doctor --url` (deep) lists what such an account may
write (`visitor-writes`, warning), checked by behaviour: it asks every rule with a stand-in visitor account. Payload's
own `payload-locked-documents` (who edits which document) is for staff accounts only since 1.18.0 (`lockedDocuments`,
"Lists and sorting" below). Verify: the doctor shows no `visitor-writes` finding, and the closed-doors spec's customer
gets 403 on every write door.
## Lists and sorting (`listLimit`, `refuseOperatorSort`, `lockedDocuments`, 1.18.0)
Three defaults for what a caller from outside (REST, GraphQL) may ask of a collection. The Local API — the frontend,
seeds, the project's own code (`req.payloadAPI === 'local'`) — is never touched.
- **`listLimit` (security audit F4).** A list (`find`, versions, distinct values) asked by a caller that is not staff
gets at most **100** documents per request; `pagination=false` and `limit=0` become one page of 100. Before, one
anonymous `GET /api/posts?limit=100000&depth=10` read a whole collection with its relations. Staff accounts (any
role) are not capped — the panel asks for at most 100 per page itself. Adapt: `listLimit: { max: 250 }`,
`{ exclude: ['products'] }` (that collection as Payload has it), `{ staff: true }` (staff capped too);
`listLimit: false` = Payload's behaviour. **What changes for an existing site:** a client-side script that reads more
than 100 documents anonymously over REST or GraphQL now gets the first 100 and `hasNextPage: true` — page through
(`page=2`) or raise `max`.
- **`refuseOperatorSort` (security audit F5).** A `sort` that names a database operator (`?sort=$where`, `-$natural`,
`title.$ne`) answers **400** "This sort field is not allowed." for everyone, staff too — before, MongoDB got it and
the request ended in a 500 with a stack trace in the log. The refusal is logged as one `info` line
(`RefusedSortError`; `loggingLevels: { RefusedSortError: false }` in the Payload config hides it). A field name sorts
as before. `refuseOperatorSort: false` = Payload's behaviour. Reported upstream to Payload (the MongoDB adapter).
- **`lockedDocuments`.** Payload's document locks ("who edits what", `payload-locked-documents`) run on Payload's
default — any signed-in account — so a visitor account (a shop's customer) could read who edits which document and
write or delete locks. Since 1.18.0 they are for staff accounts only, with the second factor when 2FA is on
(`staffOnlyLocks`). The panel works as before. Payload adds this collection after every plugin has run, so the
rule is set on the live config (at start and after a dev reload). Your own rule per operation:
`lockedDocuments: { access: { read: myRule } }` (the others stay staff only); `lockedDocuments: false` = Payload's
default.
Both hooks are added to every collection in the config when iapl runs — the project's, the plugin's and those of
plugins listed before iapl. A collection a plugin listed **after** iapl adds has neither: put
`buildQueryGuardHook({ listLimit, refuseOperatorSort })` into its `hooks.beforeOperation`, or list iapl last.
Exported: `buildQueryGuardHook`, `applyQueryGuard`, `capListLimit`, `isOperatorSort`, `isStaffRequest`,
`isQueryGuardHook` / `QUERY_GUARD_MARK` (to tell the hook apart when you count a collection's hooks),
`RefusedSortError`, `DEFAULT_LIST_LIMIT`, `applyLockedDocumentsAccess`, `staffOnlyLocks`, `LOCKED_DOCUMENTS_SLUG`.
Verify: `curl -s 'https://<domain>/api/pages?limit=100000' | jq .limit` → `100`;
`curl -s -o /dev/null -w '%{http_code}' 'https://<domain>/api/pages?sort=%24where'` → `400`; the closed-doors spec's
customer gets 403 on `/api/payload-locked-documents`; `iapl-doctor --url … --only live-probes` passes
`unbounded-list` and `sort-operator`.
## Addresses rendered into `href` (`buildUrlField`, 1.18.0)
A text field whose value goes into `<a href>` (a social profile, a website, a map link) must refuse `javascript:`,
`data:` and `vbscript:` — an editor's link would otherwise run script as whoever clicks it on the public site, an
admin included (security audit F2: the reference site's Company → Profiles was a plain text field).
`buildUrlField({ name?, label?, required?, schemes?, description?, overrides? })` is that field: `https://` and
`http://` pass, plus the kinds you list in `schemes` (`mailto`, `tel`, `sms`, `hash`, `relative`); protocol-relative
`//host` never passes. `isAllowedUrl(value, schemes)` is the same check for your own code. Render the stored value
through `safeHref()` as well — an import, a seed or an older version may hold anything. The reference site and every
new site from `iapl create` use both (`src/globals/Company.ts`, `Footer.tsx`, the `sameAs` of the JSON-LD).
**For an existing site:** nothing changes by itself; replace `{ name: 'url', type: 'text' }` in your own globals with
`buildUrlField()` (no schema change: still a text column) and wrap the render in `safeHref`. Verify: entering
`javascript:alert(1)` in the field shows "Enter a full address" and nothing is saved.
## Access callbacks (`cookieScanner.access`, the doctor's `access`)
A project's callback says who may use the cookie scanner's endpoints or read the doctor's status. Today any truthy
answer lets the request in: `({ req }) => req.user` returns an account object and passes, and so does a function
that returns `'no'` or `{}`. **From the next minor version (1.19.0) only `true` allows** — like
`twoFactor.requireSetup.resetAccess` already does. Since 1.18.0 the first answer that is not a boolean is reported
once per option in the server log:
`[iapl] cookieScanner.access returned an object, not true or false. It is still read as allowed; …`.
Return a boolean: `({ req }) => Boolean(req.user)`, `({ req }) => isAdmin(req.user, req.payload)`. One function reads
every answer: `accessAllowed(option, answer)` (exported). The second factor is checked before the callback, as before.
## Threat list (security audit 2026-12)
What most often hits Payload / Next.js / Node sites, ranked by how often it appeared in the advisories of the last three
years (Dec 2023 – Dec 2026: 71 for `next`, 9 for React Server Components, 58 for `payload` / `@payloadcms/*`, 147 in the
usual transitive dependencies; GitHub Security Advisories, NVD) and by what it costs a client site. OWASP Top 10:2025
and ASVS 5.0 name the categories. Each row says where IAPL covers it and which suite checks it.
| # | Class | Seen in | IAPL covers it with | Checked by |
|---|---|---|---|---|
| 1 | Denial of service (body size, ReDoS, Server Actions, image optimizer, unbounded lists, GraphQL) | 27 core + 46 deps; Next GHSA-p3m5-59mp-jv5r (Server Actions, Oct 2026) | body caps on every public plugin route (`readCappedBody`), MCP batch cap, rate limits; Payload `maxDepth`; public lists capped at 100 (`listLimit`, audit F4, 1.18.0) | probes `body-size`, `unbounded-list`; per-class tests |
| 2 | Access control (REST / GraphQL / Local API `overrideAccess`, drafts, versions, field access) | 17 Payload (A01) | account rules, `readPublished`, 2FA wrapper, jobs rule, `visitor-writes` | closed-doors spec, `routes:check`, probes `rest-where`, `graphql`; rules `code-override-access`, `code-local-api-user` |
| 3 | Cache poisoning and cross-user leaks (ISR, RSC, CDN, host headers) | 18 Next (CVE-2024-46982 …) | no host header read for URLs (`NEXT_PUBLIC_SERVER_URL`), `no-store` on personal answers; the negotiated Markdown at an HTML URL is `private, no-store` + `Vary: Accept` (audit F3, 1.18.0) | probes `host-header`, `markdown-vary`, `rsc-vary` |
| 4 | Remote code execution (RSC Flight, `use cache`, image optimizer + libvips/librsvg) | 10 core (React2Shell CVE-2025-55182, GHSA-2464-fhr4-w9xw, GHSA-673q-mjm6-r5xr, GHSA-xqc2-xf4c-x3h3) | minimum Next / sharp in AGENT.md §4; no `eval` | `deps-audit`, `code-eval` |
| 5 | Information disclosure (errors, source maps, secrets in bundles and files) | 14 core | no stack traces in plugin answers, write-only secrets, no manifest in `.next/static` | probes `error-leak`, `bundle-secrets`, `secret-files`; rule `code-public-secret` |
| 6 | SSRF (Server Actions Host header, middleware redirects, image optimizer, URL uploads) | 9 core (CVE-2024-34351, CVE-2025-57822) | `buildImagesConfig` (listed hosts only), `safeFetch` for brand images, the crawl only of the site's own URL | probe `image-optimizer`; rule `code-ssrf` |
| 7 | Authentication and session (JWT after logout, fixation, 2FA bypass, enumeration, CSRF) | 8 + 3 (CVE-2025-4643, CVE-2025-4644) | 2FA enforced and wrapped around plugin entities, own-origin checks, `serverURL` for Payload's CSRF list, verify limit | spec "attack probes with a session" (CSRF, cookie flags), 2FA specs |
| 8 | XSS (rich text, links, JSON-LD, SVG uploads, `dangerouslySetInnerHTML`) | 7 core + 39 deps (dompurify, sanitize-html) | `RenderRichText` / `safeHref` drop `javascript:`, `buildUrlField` refuses it on save (audit F2), `JsonLdGraph` escapes `<`, upload CSP `sandbox`, CSP | per-class tests; rule `code-inner-html`; `config-dangerous` (`dangerouslyAllowSVG`) |
| 9 | Middleware / proxy bypass (`x-middleware-subrequest`, path normalisation) | 7 Next (CVE-2025-29927) | the plugin makes NO access decision in the proxy (locale and CSP nonce only); matcher ends at `/` | probe `middleware-subrequest`; doctor `proxy-matcher` |
| 10 | Injection (NoSQL operators, `$where`, SQL in raw queries, CRLF, logs) | 5 Payload + 16 deps (mongoose CVE-2024-53900, CVE-2025-23061) | no `where` from request input in plugin routes; typed values in queries; operator names in `sort` refused (`refuseOperatorSort`, audit F5); CSP report log lines normalised and capped (audit F1); both 1.18.0 | probes `login-operators`, `sort-operator`; rule `code-raw-where`; per-class tests |
| 11 | Supply chain (npm worms: Shai-Hulud 2025, chalk/debug 2025, Mini Shai-Hulud 2026) | 13 incidents | exact pins of the plugin's own deps, lockfile, `pnpm.overrides` advice (AGENT.md §4 item 12) | `deps-audit` (doctor), `pnpm security:gate` |
| 12 | Open redirect | 1 Payload | `safeAdminBack`, `adminPathFromReferer`, locale redirect keeps the host | probe `open-redirect`; rule `code-open-redirect` |
| 13 | Security headers and CSP | — (misconfiguration, A02) | `buildSecurityHeaders`, `buildCsp`, `withSecurityConfig` | probe `headers-everywhere`; doctor `security-headers`, `csp`, `config-dangerous` |
## Security suites
Four suites, each runnable by a project on its own site. The plugin repository runs all of them before a release.
| Suite | In a project | In the plugin repository |
|---|---|---|
| **Static rules** over the project's own code and config | `pnpm exec iapl-doctor --only security` (rules `code-patterns`, `config-dangerous`) | `test/securityPatterns.test.ts`: every hit in `src/`, `bin/`, `scripts/` and the reference site must be judged in `test/security-patterns.allow.json` (one reason per file and rule; a new place or a higher count fails) |
| **Per-class tests** of the building blocks | — (the plugin's own) | `test/securityClasses.test.ts`: XSS payloads into JSON-LD, first-paint scripts, links, rich text, sitemap; open redirects; prototype pollution; log injection; body and batch caps; cache poisoning |
| **HTTP attack probes** against a running site | live: `pnpm exec iapl-doctor --url https://<domain> --only live-probes` (changes nothing); local / staging: `.agents/skills/iapl-audit/resources/attack-probes.spec.template.ts` → `tests/attack-probes.spec.ts` | `reference/e2e/attack-probes.spec.ts` in `pnpm e2e:built`, after a webpack and a Turbopack production build, beside the closed-doors spec |
| **Dependency audit** | the doctor's `deps-audit` (`pnpm audit --prod`, error on high / critical) | `pnpm security:gate` (also in `prepublishOnly`): `pnpm audit --prod` with no high / critical, then the two vitest suites; `--zap <url>` adds an OWASP ZAP baseline scan when the image `ghcr.io/zaproxy/zaproxy:stable` is already on the machine (offline; never pulled by the script) |
**Static rules** (`code-*`, one finding per rule and file, seeds / migrations / scripts / tests left out where the
rule is about requests):
| Rule | Severity | Finds |
|---|---|---|
| `code-inner-html` | error | `dangerouslySetInnerHTML` / `innerHTML` / `insertAdjacentHTML` / `document.write` with a value no sanitizer passed; JSON in a `<script>` without `.replace(/</g, '\\u003c')` (use `JsonLdGraph`) |
| `code-eval` | error | `eval`, `new Function`, `vm.run*`, `setTimeout("…")` |
| `code-shell` | error (warning offline) | `exec` / `execSync` with a template string |
| `code-public-secret` | error | a `NEXT_PUBLIC_…SECRET / PASSWORD / TOKEN / PRIVATE / DATABASE…` name; a server secret read in a `'use client'` file |
| `code-override-access` | warning | `overrideAccess: true` in code a request reaches |
| `code-local-api-user` | warning | `payload.find({ user })` without `overrideAccess: false` — Payload then IGNORES the user's rules |
| `code-raw-where` | error | `where:` taken from `req.query`, a body, `searchParams` or `JSON.parse` |
| `code-open-redirect` | warning | `redirect()` / `NextResponse.redirect()` to an address from the request (`?next=`, `?redirect=`) |
| `code-ssrf` | warning | a server-side `fetch()` of an address from the request |
| `config-dangerous` | error / warning | `dangerouslyAllowSVG` without `contentSecurityPolicy`, `remotePatterns` `**`, `serverActions.allowedOrigins` `*`, public source maps; `cors: '*'`, `debug: true`, GraphQL introspection or playground on in production, `maxDepth` above 20 |
A place that is correct on purpose: `// iapl-security-ok: <why>` on the same line or the line above. A whole file or
folder: `iapl-doctor.json` → `"rules": { "code-override-access": { "files": ["src/lib/admin/**"], "off": true, "reason": "…" } }`.
Verify: add `eval(x)` to a page and `pnpm exec iapl-doctor --only code-patterns` reports `code-eval` with the line.
**Attack probes** (`ATTACK_PROBES` in `@intecion/ipal-kit/doctor`; each answers on status codes and headers, a 500 is
never "closed"): `secret-files`, `bundle-secrets` (with the spec: also the site's own secret values), `middleware-subrequest`,
`open-redirect`, `host-header`, `markdown-vary`, `rsc-vary`, `login-operators`, `sort-operator`, `rest-where`, `graphql`,
`error-leak`, `unbounded-list`, `image-optimizer`, `headers-everywhere`, `methods`, `body-size` (spec only: 8 MB
bodies). The spec adds, with a signed-in editor: the session cookie is `HttpOnly` and `SameSite`, and from another
origin the same cookie neither reads `/api/users/me`, writes a global, nor runs a GraphQL mutation. A probe tied to an
open audit finding carries `finding` and is expected to fail (`test.fail`) until the fix lands; every finding of the
2026-12 audit is fixed in 1.18.0, so none carries it now. Your own probe: an object `{ id, class, title, live, run(ctx) }`
in the template's `EXTRA`. Verify: run the doctor with `--url` against `pnpm start` of a fresh starter site — no
`live-probes` finding. A site that turned a fix off (`listLimit: false`, `refuseOperatorSort: false`,
`markdown: { negotiate }` with a proxy of its own) gets that probe's finding back: silence it in `iapl-doctor.json`
with the reason.
## Turn off, override, extend
- **Stored secrets:** `secrets: { writeOnly: false }`, `secrets: { reenterOnChange: false }`; `writeOnlySecret` /
`writeOnlySecrets` (with `boundTo`), `maskSecretsOnRestore` for your own fields.
- **2FA attempts from another origin:** `twoFactor.sameOrigin: false`, or `{ origins: [...] }`; `requestFromOwnOrigin`,
`ownOrigins` are exported. **Verify count:** `verifyLimit: { store: 'memory' }`; `buildVerifyLimit`,
`verifyLimitKey`, `clearVerifyLimits` (tests) are exported. A project that wires `buildVerifyLimit` into an
endpoint of its own calls `limit.settle(req, correct)` after its check (a right code gives its place back;
without it every attempt stays counted, as before 1.17.1).
- **Dashboard alerts:** `dashboardAlerts: { integrations, cookies }`.
- **The mail service:** `mail: { relay: false }`; `mail.relay: { enrol: 'manual' | false, token, accountMail,
confirmRateLimit }`; `relayConfirmEndpoint`, `enrolRelay`, `disconnectRelay`, `rotateRelayToken`, `setRelayToken`
are exported ([email.md](./email.md)).
- **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.
- **Lists and sorting:** `listLimit: false` or `{ max, staff, exclude }`; `refuseOperatorSort: false`;
`lockedDocuments: false` or `{ access }`; the hooks and rules above for collections added after iapl.
- **Markdown negotiation:** `createProxy(…, { markdown: { negotiate: false } })` (Markdown only at `/md/…`);
`MARKDOWN_NEGOTIATED_HEADER`, `NEGOTIATED_CACHE_CONTROL`, `appendVary` for your own proxy ([content.md](./content.md)).
- **CSP report log:** `createCspReportRoute({ maxReports, rateLimit: false | { max, windowMs }, onReport })`;
`cspLogLine` for the plugin's line in your own sink.
- **Addresses in `href`:** `buildUrlField({ schemes, overrides })`, `isAllowedUrl`, `safeHref`.
- **Set-up confirmed by e-mail:** `twoFactor.confirmByEmail: false` (off), or `{ linkMinutes, sameBrowser, adminConfirm,
logLinkWhenMailFails, notices, maxMailsPerHour }`; the building blocks above.
- **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 IAPL'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;
client hints for the admin only — `withSecurityConfig(config, { adminClientHints: false })` (hints on every path
again), `{ adminClientHints: { route, sources } }` (another panel address, more paths);
2FA — `twoFactor: false` (discouraged).
- **Override:** `additional` (the same key overrides the plugin's header and the `csp` ones),
`buildCsp({ extra, override, mode, strictDynamic })`, `buildAdminCsp({ extra, override })`,
`createCspReportRoute({ onReport, maxBytes, maxReports, rateLimit })`;
2FA — `collectionSlug`, `allowCollectionMismatch`, your own TOTP options by wrapping `plugin`,
`provider` (your own redirect component, or `false` for the package's);
access — `access.authAccess`, `access.firstUserAdmin`, `globalOverrides` ([access.md](./access.md)).
- **Extend:** `totpRedirectTarget` / `totpAdminPath` (2FA redirect rules) for your own provider;
`buildCsp` / `buildCspHeaders` / `buildReportingEndpoints` / `cspHeaderKey` /
`parseCspReports` / `createCspNonce` (`CSP_NONCE_HEADER`, `DEFAULT_CSP_REPORT_GROUP`) for your own proxy
or collector; `buildUploadSecurityHeaders({ collections })` for your own upload collections.
- **Security suites:** `iapl-doctor --skip code-patterns,config-dangerous,live-probes`, or one rule per file / folder in
`iapl-doctor.json`; the building blocks `ATTACK_PROBES`, `runAttackProbes`, `createProbeContext`, `scanCode`,
`scanConfigs` (`@intecion/ipal-kit/doctor`) for your own CI.
- **Check:** `curl -sI https://domain/pl | grep -iE "strict-transport|x-frame|referrer|permissions|cross-origin|content-security|x-powered-by"`
(no `x-powered-by`; `content-security-policy-report-only` while rolling out);
on staging also `x-robots-tag`; startup with a wrong `twoFactor.collectionSlug` fails with `[iapl] twoFactor…`.