Staff check (userMeetsRole): the 'no roles field = every account passes' rule applied to the account's own collection, so an account of a second auth collection (customers) passed every staff check. It now applies only to staff collections: the panel's login collection plus the new access.staffCollections. The injected auth collection uses the new adminOrSelfIn(slug), so an account of another collection with the same numeric id is not 'self'. 2FA: @clocklimited/payload-2fa wraps the collections and globals present when it runs; ipalKit's own globals and collections were added later and stayed unwrapped, so a password without the TOTP code opened them over REST and GraphQL. ipal-kit now has its own second-factor check (secondFactorPassed / requireSecondFactor): applied to every collection and global at the end of ipalKit, again in onInit for entities added by plugins listed after it, and inside userMeetsRole and the endpoints that take a project access function. It fails closed: an unrecognised user shape is refused, and startup stops when the injected 2FA plugin lacks the parts the check reads (twoFactor.guard: false opts out). Tests through real HTTP requests (REST and GraphQL) against Payload's route handlers, plus the reference smoke test. Docs, agent guide, skills and the reference skills copy updated; changelog entry without a version. Co-Authored-By: Claude Fable 5.2 <[email protected]>
613 lines
34 KiB
Markdown
613 lines
34 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 `@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
|
|
|
|
```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
|
|
// 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 the release after 1.16.3 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 plugin's endpoints (`/api/ipal/test-email`, `cookie-scan`, `cookie-approval`, `cookie-crawl`, the `access` option of `/api/ipal/doctor`) | `userMeetsRole` and `secondFactorPassed` |
|
|
|
|
The order of the project's `plugins` array does not matter. Payload's own collections (`payload-preferences`,
|
|
`payload-locked-documents`, …) and `access.admin` (may this account open the panel) are left alone: the code is
|
|
entered inside the panel.
|
|
|
|
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.
|
|
|
|
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)) }
|
|
```
|
|
|
|
**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 …`. Supported: `@clocklimited/payload-2fa` 3.0.0-beta.1 to beta.7. `twoFactor.guard: false` switches
|
|
ipal-kit's check off and leaves the package's wrapper alone; the plugin's own data is then open to a password
|
|
without the code again, so use it only to get a site started while the package is being sorted out.
|
|
|
|
**Check** (replace the address and the account):
|
|
|
|
```bash
|
|
# password only, no code → 403 on all three
|
|
TOKEN=$(curl -s https://example.com/api/users/login -H 'content-type: application/json' \
|
|
-d '{"email":"[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:
|
|
|
|
```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.
|
|
|
|
### 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 — <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, 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 — 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 })` 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).
|
|
|
|
## The release after 1.16.3 — two access fixes
|
|
|
|
- **Staff checks and a second auth collection.** `userMeetsRole` treated an account of any auth collection
|
|
without a `roles` field as staff — a `customers` account passed every check of the plugin, admin ones
|
|
included. Now only accounts of a staff collection can pass: the panel's login collection plus
|
|
`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.
|
|
- 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 `[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
|
|
|
|
- **2FA check:** `twoFactor.guard: false` turns ipal-kit's own second-factor check off (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;
|
|
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…`.
|