41 KiB
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 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.
// 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: no X-Powered-By (Next's and Payload's)
export default withPayload(withSecurityConfig(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 IPAL_NOINDEX=1 (staging), X-Robots-Tag: noindex, nofollow is added to every response.
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.jsunless the config sayspoweredByHeader: false. - Payload's
withPayloadswitches Next's header off and adds its ownX-Powered-By: Next.js, Payloadfor/:path*throughheaders()— also unless the config it wraps sayspoweredByHeader: 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 work:
withPayload(withSecurityConfig(nextConfig)) (recommended) or withSecurityConfig(withPayload(nextConfig)).
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).
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)
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.
// 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 + 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,/_nextand files — those keep thenext.configheaders. Do NOT also send the site CSP fromnext.configfor the frontend paths (two policies = both apply); keep only the admin rule andbuildUploadSecurityHeadersthere. - Your own proxy:
createCspNonce()+buildCsp({ nonce }), set the policy on the request headers (NextResponse.next({ request: { headers } })) and on the response, likecreateProxydoes. ConsentScript nonce,ThemeScript nonce,Analytics nonceexist for policies without'strict-dynamic'.
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:
{ 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 }) — a POST handler for reportUri. It accepts
both formats (application/csp-report from report-uri, application/reports+json from report-to),
caps the body, always answers 204, and by default logs one console.warn line per violation:
[csp] report script-src-elem blocked=https://x.example/a.js page=https://site/pl. Read them in the
Coolify app's Logs. Plug onReport into payload.logger, Sentry or a database for more.
// 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:
- Report-only —
mode: 'report-only'withreportUri. The browser REPORTS violations (console + the report route) but does NOT block — the site works as usual. Deploy it. - 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. - Fix each violation — a missing host of yours → the matching flag or
extra; noise from browser extensions (chrome-extension://,moz-extension://) → ignore. - Enforce — when the reports are clean, change
mode: 'report-only'tomode: 'enforce'(site and admin). KeepreportUri: 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):
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
# 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.openercoop: 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
TypeErrorwith 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:
// payload.config.ts
ipalKit({
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
- 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.
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 ipal-kit runs its own check, so the second
factor also covers what the package cannot see — see "What the second factor covers" below.
Dependency
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)
import { payloadTotp } from '@clocklimited/payload-2fa'
ipalKit({
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: ipal-kit'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. ipalKit runs it early, so the plugin's own globals and collections (Site settings, Site integrations,
Cookie banner, Notifications, forms, form submissions, consent records, cookie review, stats) and anything a
plugin listed after ipalKit adds were not wrapped. Up to 1.16.3 a staff password without the TOTP code
therefore read and changed them over the API. Since 1.16.4 ipal-kit closes that itself:
| Where | How |
|---|---|
| every collection and global in the config when ipalKit finishes | access wrapped with requireSecondFactor |
| collections and globals added by plugins listed after ipalKit | wrapped in ipalKit's onInit; the log line [ipal] 2FA also enforced on entities added after ipalKit: … names them |
the same after a dev hot reload, or when Payload runs with disableOnInit |
the instance's config is watched, so a swapped config is guarded the moment Payload assigns it (before any request or Local API call); as a second line an auth strategy that authenticates nobody (ipal-second-factor-guard on the 2FA collection) does the same at the start of every request |
the plugin's endpoints (/api/ipal/test-email, cookie-scan, cookie-approval, cookie-crawl, the access option of /api/ipal/doctor) |
userMeetsRole and secondFactorPassed |
the 2FA package's own endpoints (/api/setup-totp, /api/verify-totp, /api/remove-totp, /api/admin/reset-user-totp, /api/admin/remove-user-totp, any a later version adds) |
accounts of the 2FA collection only; everything except setup and verify also needs the second factor ("The 2FA package's endpoints" below) |
The order of the project's plugins array does not matter, and there is no exception by name: Payload's own
collections (in 3.94.1: payload-preferences, payload-locked-documents, payload-migrations,
payload-query-presets, payload-folders, payload-jobs, payload-kv, the global payload-jobs-stats) are
guarded like every other, and so is whatever a later Payload version or a plugin adds under any slug
(payload-mcp-api-keys, …). The job queue's own rules (jobs.access.run / queue / cancel) are guarded too:
Payload's defaults stay exactly as Payload sets them (in 3.94.1 a logged-in user for all three); a session that
owes its code is refused.
Only access.admin (may this account open the panel) is left alone: the code is entered inside the panel, and
the verify and setup screens are rendered from the session, not from any collection.
A session that still owes its code is refused everything, also what anonymous visitors may read (Site
settings, Notifications, the Cookie banner, forms): for that account the answer is 403 until the code is
entered. The public site is not affected — it reads on the server; only files the browser fetches itself with
that session's cookie (images from media) are refused, so an editor who typed the password and not yet the code
sees broken images on the site until the code is entered or they log out.
An account of the 2FA collection passes when it logged in with password and code, or uses an API key
(auth.useAPIKey), or has not set TOTP up yet (the setup screen needs that; the package behaves the same).
Everything else is refused, including a user object the check does not recognise. Accounts of other auth
collections, anonymous visitors, bearer-token routes (/api/ipal/doctor, the cookie-crawl callback, MCP) and
the Local API with overrideAccess: true (the default) are not affected.
Until an account has set TOTP up, its password alone opens everything its role allows — Site integrations with the SMTP password included. Enforced setup is a redirect in the panel; over the API such an account is an ordinary logged-in account (it has to be, or it could not set TOTP up). So: set 2FA up right after an account is created — create the account, log in as it, scan the code, in one sitting — and never leave an invited account waiting.
ipal-doctor --urlreports the number of accounts without 2FA (2fa, deep check); it must be 0.
Verify attempts are limited (twoFactor.verifyLimit). The package checks the code and never counts tries;
a six-digit code has about three right answers in a million, so whoever held the password could guess. ipalKit
counts attempts per account on POST /api/verify-totp: by default the sixth attempt within 10 minutes —
right or wrong — is refused with 429 and Retry-After, and a line goes to the log. Only a session that already
passed the password reaches the endpoint, so nobody without the password can lock an account's owner out; someone
who has the password can delay the owner's login by ten minutes at a time (and that shows in the log). Counted in
memory per server instance. verifyLimit: { max: 10, windowMinutes: 5 } changes it, verifyLimit: false turns
it off (a limiter in front of the site).
What is NOT covered — the complete list. (1) Anonymous requests: the access function decides. (2) Accounts
of other auth collections: 2FA is about one collection; such an account is not staff unless its collection is in
access.staffCollections, and then it is staff without a second factor (warning in the log at start).
(3) API keys. (4) An account that has not set TOTP up yet. (5) Entities the project opted out (below).
(6) access.admin. (7) Endpoints that are not the plugin's or the 2FA package's: your own endpoints and other
plugins' endpoints check whatever they check — add secondFactorPassed(req) to yours. (8) Server code using the
Local API with overrideAccess: true. Nothing is skipped by slug, name or prefix, and a user object the check
cannot read is refused.
Per-entity opt-out. A collection or global that may be reached with the password alone (a project decision, e.g. a health record the panel reads before the code is entered), operation by operation:
// the 2FA package's own key — it leaves the operation unwrapped, and so does ipal-kit
{ slug: 'notices', custom: { totp: { disableAccessWrapper: { read: true } } }, … }
// ipal-kit's key — the same, and it also works for entities the package never sees
{ slug: 'notices', custom: { ipal: { secondFactor: { read: false } } }, … } // or secondFactor: false = every operation
Operations: create, delete, read, readVersions, unlock, update (collections); read, readDrafts,
readVersions, update (globals). For one of the plugin's own globals set it through globalOverrides
({ notifications: { custom: { ipal: { secondFactor: { read: false } } } } }) — and note that the plugin's
staff rules (userMeetsRole) ask for the second factor themselves, so also give that operation your own
access function there. disableAccessWrapper: true passed to the package's factory turns all access
wrapping off, ipal-kit's included; the endpoints stay guarded.
The 2FA package's endpoints. The package takes req.user from whatever auth collection it comes and then
acts on the 2FA collection by id: /api/setup-totp writes the TOTP secret under the caller's id. With
numeric ids (Postgres, SQLite) an account of another auth collection could therefore set the secret of the
staff account that has the same id, and whoever knew that staff password then passed 2FA. ipalKit wraps every
endpoint the package registers: a logged-in account of another collection gets 403; remove and the admin
reset / remove endpoints also need the second factor, so a password alone cannot reset TOTP and enrol again.
This guard is on whenever 2FA is on, also with twoFactor.guard: false.
Two things follow for project code:
payload.find({ …, user, overrideAccess: false })on a plugin collection needs auserthat came frompayload.auth({ headers })(it carries how the account logged in). A user fetched withfindByIDand passed by hand is refused when it has TOTP set up.- Your own endpoints do not go through
access. Guard them:
import { requireSecondFactor, secondFactorPassed, userMeetsRole } from '@intecion/ipal-kit'
// an endpoint
handler: async (req) => {
if (!req.user || !secondFactorPassed(req)) return Response.json({ ok: false }, { status: 403 })
// or: if (!userMeetsRole(req, 'editor')) … — it includes the second-factor check
}
// an access function (collections and globals in the config are wrapped for you; this is for the rest)
access: { read: requireSecondFactor(({ req }) => isAdmin(req.user, req.payload)) }
Fails closed. At startup ipalKit checks that the injected 2FA plugin added what the check reads (the
totpSecret and hasTotp fields and the totp auth strategy on the 2FA collection). When it did not — a
package version with another shape — startup stops with [ipal] twoFactor: the injected 2FA plugin did not add …. Tested with @clocklimited/payload-2fa 3.0.0-beta.1 and 3.0.0-beta.7 (the versions in between are not run in the plugin's tests). twoFactor.guard: false switches
ipal-kit's check off and leaves the package's wrapper alone; the plugin's own data is then open to a password
without the code again, so use it only to get a site started while the package is being sorted out.
Check (replace the address and the account):
# 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
Import map (required)
The 2FA screens and the redirect to them are admin components. After adding twoFactor, and after every
ipal-kit upgrade, run:
pnpm generate:importmap
src/app/(payload)/admin/importMap.js must list @intecion/ipal-kit/admin#TotpRedirectProvider and
@clocklimited/payload-2fa/rsc#TOTPSetup / #TOTPVerify / #TOTPField. Commit the file.
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 ipal-kit 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 — | 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, ipal-kit 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 clientPropsforceSetupand the package's serverPropspluginOptions. The pure logic is exported:totpRedirectTarget({ adminRoute, forceSetup, pathname, user })returns the URL to send the user to, ornull.twoFactor.provider: false: keep the package's provider. Then a proxy must setx-pathnameon every/adminrequest, or the loop comes back.
The provider only steers the UI. Data access is still checked by the package's access wrapper.
Turning it off (DISCOURAGED)
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
- Logs in (email + password)
- On first login: redirected to TOTP Setup (
/admin/setup-totp?back=%2Fadmin, QR + secret) - Scans the QR with an app (Google Authenticator, Authy, 1Password, Microsoft Authenticator)
- Enters the code → 2FA is active, back to the page from
back - 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 can reset another user's 2FA (when they lose their phone) — through
adminManageAccess in the @clocklimited configuration. ipalKit passes it only collection,
forceSetup and issuer; pass other options by wrapping the injected factory:
plugin: (opts) => payloadTotp({ ...opts, adminManageAccess: ({ req }) => isAdmin(req.user, req.payload) }).
ipal-kit's guard on those endpoints adds the rest: the caller must be an account of the 2FA collection that has
passed the second factor itself. After a reset the account is "not set up" again — have its owner set TOTP up
at once (see the note above).
Why @clocklimited and not another one
Chosen because it wraps ACCESS CONTROL (TOTP before data access) + forceSetup (enforced for everyone). Other 2FA plugins for Payload only gate /admin navigation — a user with a password can bypass them through REST/GraphQL/Bearer. @clocklimited protects data access, not just the UI — for what is in the config when it runs; ipal-kit's own check covers the rest ("What the second factor covers").
1.9.1 — security review results
- 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 })indraftMode(). - Links from the CMS: only
http(s),mailto,tel,sms,#,/(safeHref);javascript:anddata:are rejected — also in rich text (RenderRichTextreplaces 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()innext.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
customersaccount passed the plugin's staff checks, and with its ownrolesfield alsoisAdmin,adminOnlyand the rest. Now the staff-collection check comes first everywhere: the panel's login collection,access.authCollectionandaccess.staffCollections(access.md). The injected auth collection usesadminOrSelfIn(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 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 "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.scanwhen the client needs one. The macro check for legacy.doc/.xlsis 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.allowedOriginsadds 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 "Attachments").
Access control (since the version after 1.12.3)
- Injected auth collection with roles: a
useraccount 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
collectionSlugwraps the panel login collection (admin.user, else the first auth collection), not the literal'users'. Plugin startup fails with[ipal] twoFactor…when the target is not an auth collection or differs fromadmin.user— deliberate exception:twoFactor.allowCollectionMismatch: true. - Injected auth collection with roles:
unlockis 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 byeditor+. - Full table: access.md.
Turn off, override, extend
- Verify limit:
twoFactor.verifyLimit: { max, windowMinutes }, orfalse. - 2FA check: per entity
custom.ipal.secondFactor/custom.totp.disableAccessWrapper(one operation or all);twoFactor.guard: falseturns ipal-kit's own second-factor check off everywhere (not recommended);requireSecondFactor/secondFactorPassedare exported for your own access functions and endpoints. - Turn off: headers — do not call
buildSecurityHeaders, ornull/falseper header (frameOptions,referrerPolicy,permissionsPolicy,coop),hsts: false; CSP — leave outcsp(the default); X-Powered-By hiding —withSecurityConfig(config, { hidePoweredBy: false })or do not call it; 2FA —twoFactor: false(discouraged). - Override:
additional(the same key overrides the plugin's header and thecspones),buildCsp({ extra, override, mode, strictDynamic }),buildAdminCsp({ extra, override }),createCspReportRoute({ onReport, maxBytes }); 2FA —collectionSlug,allowCollectionMismatch, your own TOTP options by wrappingplugin,provider(your own redirect component, orfalsefor the package's); access —access.authAccess,access.firstUserAdmin,globalOverrides(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. - Check:
curl -sI https://domain/pl | grep -iE "strict-transport|x-frame|referrer|permissions|cross-origin|content-security|x-powered-by"(nox-powered-by;content-security-policy-report-onlywhile rolling out); on staging alsox-robots-tag; startup with a wrongtwoFactor.collectionSlugfails with[ipal] twoFactor….