@clocklimited/payload-2fa's admin provider reads the current path from an x-pathname request header. Nothing sets it on /admin (the createProxy matcher skips /admin), so the path was null: every admin page, the setup screen too, redirected to /admin/setup-totp?back=null, forever. Every new admin on a site with 2FA got stuck. ipalKit now swaps that provider for its own TotpRedirectProvider (@intecion/ipal-kit/admin, client-side): it reads the path in the browser, never redirects away from the setup/verify screens or logout, and renders nothing while redirecting. twoFactor.provider takes a project component, or false to keep the package's. totpRedirectTarget / totpAdminPath export the rules. Projects run generate:importmap. Test: test/totpRedirect.test.ts (redirect walk, provider swap). Dev app: IPAL_DEV_2FA=1 turns 2FA on. Docs: security.md, CHANGELOG (Unreleased), AGENT.md, ipal-setup/-upgrade/-debug/-reference, PROGRAMISTA item 51. Co-Authored-By: Claude Opus 5.5 <[email protected]>
502 lines
27 KiB
Markdown
502 lines
27 KiB
Markdown
# 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.
|
|
|
|
```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: 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.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 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)
|
|
|
|
```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 + 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'`.
|
|
|
|
### 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 })` — 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.
|
|
|
|
```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
|
|
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 the proven `@clocklimited/payload-2fa` (it wraps access control — TOTP is
|
|
checked before access to DATA, not only the panel UI).
|
|
|
|
### 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'
|
|
|
|
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
|
|
},
|
|
})
|
|
```
|
|
|
|
**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.
|
|
|
|
### Import map (required)
|
|
|
|
The 2FA screens and the redirect to them are admin components. After adding `twoFactor`, and after every
|
|
ipal-kit upgrade, run:
|
|
|
|
```bash
|
|
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.
|
|
|
|
### 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 the version after 1.14.1, 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 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.
|
|
|
|
### 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)
|
|
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 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) })`.
|
|
|
|
### 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.
|
|
|
|
## 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).
|
|
|
|
## 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 `[ipal] 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).
|
|
|
|
## Turn off, override, extend
|
|
|
|
- **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;
|
|
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 })`;
|
|
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.
|
|
- **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 `[ipal] twoFactor…`.
|