1075 lines
77 KiB
Markdown
1075 lines
77 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 `IAPL_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
|
|
iapl({
|
|
i18n: i18nConfig,
|
|
adminRoute: '/its', // panel at /its instead of /admin
|
|
})
|
|
```
|
|
|
|
**`robots.txt` with a hidden panel:** the default `robots` blocks `/admin`. Do not
|
|
put `/its` there — `robots.txt` is public and would reveal the path (the panel has
|
|
`noindex` anyway). In `createContentHelpers` set `robots: { adminRoute: false }`.
|
|
|
|
### REQUIRED — move the panel folder in the project
|
|
|
|
The plugin sets `config.routes.admin`, but does NOT create files in the project's `app/`.
|
|
You must move the panel folder for the path to work:
|
|
|
|
```
|
|
# BEFORE:
|
|
app/(payload)/admin/[[...segments]]/page.tsx
|
|
app/(payload)/admin/[[...segments]]/not-found.tsx
|
|
|
|
# AFTER (folder name = adminRoute without the slash):
|
|
app/(payload)/its/[[...segments]]/page.tsx
|
|
app/(payload)/its/[[...segments]]/not-found.tsx
|
|
```
|
|
|
|
Without moving the folder: `config.routes.admin = '/its'`, but `/its` returns 404
|
|
(no file), and `/admin` does not work either (the config changed). Both must match.
|
|
|
|
### This is OBSCURITY, not SECURITY
|
|
|
|
Changing the path makes automated scans harder, but it is NOT a safeguard.
|
|
Real panel protection:
|
|
- **2FA** for every user (enforced by the plugin — section below)
|
|
- Strong passwords
|
|
- Rate limiting on login
|
|
- 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 IAPL runs its own check, so the second
|
|
factor also covers what the package cannot see — see "What the second factor covers" below.
|
|
|
|
### Dependency
|
|
|
|
```bash
|
|
pnpm add @clocklimited/[email protected]
|
|
```
|
|
Note: the package has no stable 3.0.0 yet — use a specific beta version
|
|
(or `^3.0.0-0` to allow prereleases). Plain `^3.0.0` fails with
|
|
ERR_PNPM_NO_MATCHING_VERSION.
|
|
|
|
### Configuration (payload.config.ts) — INJECT the plugin (required in Next)
|
|
|
|
```ts
|
|
import { payloadTotp } from '@clocklimited/payload-2fa'
|
|
|
|
iapl({
|
|
i18n: i18nConfig,
|
|
twoFactor: {
|
|
issuer: 'Company Name', // shown in the authenticator app
|
|
plugin: payloadTotp, // ← INJECT — see below why
|
|
// collectionSlug: 'users', // default: the panel login collection (admin.user, else the first auth collection)
|
|
// allowCollectionMismatch: true, // deliberate only: 2FA on a collection other than admin.user
|
|
// guard: false, // NOT recommended: IAPL's own check off, the package's wrapper only
|
|
},
|
|
})
|
|
```
|
|
|
|
**Why `plugin: payloadTotp` (injection):** it is the same pattern as
|
|
`NextResponse`/`revalidatePath` — the project provides the peer dependency, the plugin does NOT
|
|
import it. Up to 1.8.x the plugin did a dynamic import instead, which **Next does not
|
|
bundle** (webpack turns an import from a variable into an empty context) → the error
|
|
**"Cannot find module '@clocklimited/payload-2fa'"** in `next build` and on every
|
|
page (public ones too). The build can still go "green", because
|
|
`generateStaticParams` catches the error — the page only breaks at runtime.
|
|
|
|
**`serverExternalPackages` is NOT a workaround.** The package imports its own
|
|
`*.module.css`; once externalized it is loaded by Node, which does not know `.css` →
|
|
`ERR_UNKNOWN_FILE_EXTENSION` while collecting data for `/admin`. The only working
|
|
configuration in Next is injection, so since 1.9.0 `plugin` is **required**
|
|
(missing → a clear error at startup). The `payload …` CLI loads the same config, so it
|
|
gets the injected plugin.
|
|
|
|
The plugin sets `forceSetup: true` — every user MUST set up TOTP after
|
|
logging in. There is no per-user "on/off" option.
|
|
|
|
### What the second factor covers
|
|
|
|
The package wraps the `access` functions of the collections and globals that are in the config **at the moment
|
|
it runs**. iapl runs it early, so the plugin's own globals and collections (Site settings, Site integrations,
|
|
Cookie banner, Notifications, forms, form submissions, consent records, cookie review, stats) and anything a
|
|
plugin listed after `iapl` adds were not wrapped. **Up to 1.16.3 a staff password without the TOTP code
|
|
therefore read and changed them over the API.** Since 1.16.4 IAPL closes that itself:
|
|
|
|
| Where | How |
|
|
|---|---|
|
|
| every collection and global in the config when iapl finishes | `access` wrapped with `requireSecondFactor` |
|
|
| collections and globals added by plugins listed **after** iapl | wrapped in iapl's `onInit`; the log line `[iapl] 2FA also enforced on entities added after iapl: …` names them |
|
|
| the same after a dev hot reload, or when Payload runs with `disableOnInit` | the instance's `config` is watched, so a swapped config is guarded the moment Payload assigns it (before any request or Local API call); as a second line an auth strategy that authenticates nobody (`ipal-second-factor-guard` on the 2FA collection) does the same at the start of every request |
|
|
| the plugin's endpoints (`/api/ipal/test-email`, `cookie-scan`, `cookie-approval`, `cookie-crawl`, the `access` option of `/api/ipal/doctor`) | `userMeetsRole` and `secondFactorPassed` |
|
|
| the 2FA package's own endpoints (`/api/setup-totp`, `/api/verify-totp`, `/api/remove-totp`, `/api/admin/reset-user-totp`, `/api/admin/remove-user-totp`, any a later version adds) | accounts of the 2FA collection only; everything except setup and verify also needs the second factor ("The 2FA package's endpoints" below) |
|
|
|
|
The order of the project's `plugins` array does not matter, and **there is no exception by name**: Payload's own
|
|
collections (in 3.94.1: `payload-preferences`, `payload-locked-documents`, `payload-migrations`,
|
|
`payload-query-presets`, `payload-folders`, `payload-jobs`, `payload-kv`, the global `payload-jobs-stats`) are
|
|
guarded like every other, and so is whatever a later Payload version or a plugin adds under any slug
|
|
(`payload-mcp-api-keys`, …). The job queue's own rules (`jobs.access.run / queue / cancel`) are guarded too:
|
|
Payload's defaults stay exactly as Payload sets them (in 3.94.1 a logged-in user for all three); a session that
|
|
owes its code is refused.
|
|
Only `access.admin` (may this account open the panel) is left alone: the code is entered inside the panel, and
|
|
the verify and setup screens are rendered from the session, not from any collection.
|
|
|
|
A session that still owes its code is refused **everything**, also what anonymous visitors may read (Site
|
|
settings, Notifications, the Cookie banner, forms): for that account the answer is `403` until the code is
|
|
entered. The public site is not affected — it reads on the server; only files the browser fetches itself with
|
|
that session's cookie (images from `media`) are refused, so an editor who typed the password and not yet the code
|
|
sees broken images on the site until the code is entered or they log out.
|
|
|
|
An account of the 2FA collection passes when it logged in with **password and code**, or uses an **API key**
|
|
(`auth.useAPIKey`). An account that has **not set TOTP up yet** is refused as well ("Setup required" below; the
|
|
package alone lets it through). Everything else is refused, including a user object the check does not recognise. Accounts of other auth
|
|
collections, anonymous visitors, bearer-token routes (`/api/ipal/doctor`, the cookie-crawl callback, MCP) and
|
|
the Local API with `overrideAccess: true` (the default) are not affected.
|
|
|
|
### Setup required (`twoFactor.requireSetup`, on by default)
|
|
|
|
An account that has **not set TOTP up yet** reaches nothing at the access level — REST, GraphQL, the panel's
|
|
data, the plugin's endpoints — until it has. It gets the setup screen and `POST /api/setup-totp`, and what
|
|
Payload gives any logged-in session about itself (`/api/access`, token refresh, logout, its own panel
|
|
preferences), nothing else.
|
|
The 2FA package alone only redirects such an account inside the panel; over the API its password would open
|
|
everything its role allows.
|
|
|
|
**The setup window.** An account has **72 hours** to set TOTP up, counted from its creation or from the last
|
|
reset by an administrator. After that it is **blocked**: setup is refused too, until an administrator reopens
|
|
it. Without the window, whoever learns the password of an account that never set TOTP up could enrol their own
|
|
authenticator at any time; with it, that is possible only in the first days of the account.
|
|
|
|
| Situation | What happens |
|
|
|---|---|
|
|
| New account (also the first admin of a fresh site) | logs in → setup screen with the notice "Set up two-step verification by <date>…" → after the code, the panel |
|
|
| Not set up within the window | login still works, every request answers 403, the setup screen says the time has passed and to ask an administrator |
|
|
| Administrator reopens setup / resets a lost phone | the account's page in the panel → **Two-step verification** (sidebar) → "Reopen setup" / "Reset two-step verification"; or `POST /api/ipal/two-factor/reset` with `{ "userId": "…" }`. A new window starts |
|
|
| Administrators' overview | a notice on the dashboard: accounts without two-step verification, and how many of them are blocked; `iapl-doctor --url` reports the same as an error |
|
|
| API key (`auth.useAPIKey`) | passes, whatever the setup state |
|
|
| Seeds, scripts, the Local API with `overrideAccess` (the default) | not affected |
|
|
| Bearer-token routes (`/api/ipal/doctor`, the cookie-crawl callback), MCP | not affected (no user) |
|
|
| `twoFactor: false` | none of this exists |
|
|
|
|
**Accounts that existed before this mode** (an upgrade): their window starts at the **first start of the site
|
|
after the upgrade**, not at their creation date, so nobody is blocked the moment a site upgrades. The server log
|
|
says how many there are: `[iapl] 2FA: N existing account(s) without two-step verification. They have 72 h from
|
|
now to set it up…`. From that moment they can only set TOTP up; after 72 hours they are blocked until an
|
|
administrator reopens setup. **Before upgrading a live site, run `pnpm exec iapl-doctor --url <site>`** (accounts
|
|
without 2FA) and have those accounts set TOTP up, or remove the ones nobody uses.
|
|
|
|
That starting moment is **written once**, on each such account (`totpSetupFrom`), by the start that first finds
|
|
the account without one. Later starts, redeploys and further instances find nothing left to do (the log line
|
|
appears on that first start only), and editing the account or logging in does not move it — so a redeploy never
|
|
hands out another 72 hours. Only an administrator's reset / "Reopen setup" opens a new window. An existing
|
|
account that **has** TOTP gets no start; if its TOTP is removed later, its window starts then. On Postgres /
|
|
SQLite the migration that adds the column must run in the same deploy (see "Data" below) — the first start
|
|
after it is the one that counts.
|
|
|
|
```ts
|
|
twoFactor: {
|
|
issuer: 'Company Name',
|
|
plugin: payloadTotp,
|
|
// requireSetup: { windowHours: 24 }, // another window
|
|
// requireSetup: { windowHours: false }, // no time limit (0 works too): locked until set up, never blocked
|
|
// requireSetup: { exempt: ({ user }) => user.email === '[email protected]' }, // a service account that logs in with a password, on purpose
|
|
// requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }, // each panel part can be switched off; the lock stays
|
|
// requireSetup: false, // the 2FA package's rule: redirect in the panel, API open until setup
|
|
// who may reset / reopen. Default: a staff admin whose session entered its own TOTP code. Your function replaces
|
|
// that rule, so keep the code check in it unless you mean to let API-key / exempt admins reset:
|
|
// resetAccess: ({ req }) => req.user?._strategy === 'totp' && isAdmin(req.user, req.payload),
|
|
}
|
|
```
|
|
|
|
- **Data.** The 2FA collection gets a date field `totpSetupFrom` (hidden, written by the plugin only) **whenever
|
|
2FA is on** — also with `requireSetup: false` or `guard: false`, so that switching the mode does not change the
|
|
schema — and, with the mode on, a panel-only field `totpSetupStatus`. MongoDB: nothing to do.
|
|
**Postgres / SQLite: the migration is a required step of the same deploy.** Run `pnpm payload migrate:create`, commit the migration, and
|
|
have it applied **when the new container starts** — `prodMigrations` in the database adapter, or the start command `pnpm payload migrate && pnpm start` ([deployment.md §4.3](./deployment.md#43-database-migrations-postgres)). **Not Coolify's Pre-deployment command:** it runs in the old container, which does not have the new migration, so the new version would start without the column.
|
|
Without the column every query on the 2FA collection fails: **every login answers 500 —
|
|
administrators with 2FA included — and nobody can sign in to the panel** (the public site keeps working). The
|
|
log says `[iapl] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN …` at start;
|
|
`iapl-doctor` reports a SQL project whose migrations do not mention `totp_setup_from` (error; a warning when
|
|
there is no migrations folder at all — it cannot see a schema that is pushed some other way). Recovery: run
|
|
the migration; no data is lost.
|
|
- **`exempt` must answer `true` or `false` at once.** It runs inside access checks, which cannot wait. An
|
|
`async` function stops the site at start with a clear error; any answer other than exactly `true` (a Promise,
|
|
a string, an error) exempts nobody and is logged once. Decide from the fields on `user`. An exempt account
|
|
works on its password alone, so give it the lowest role that does its job.
|
|
- **`windowHours`** must be a number (0 or more) or `false`; anything else (`'24'`, `-1`) stops the site at start.
|
|
- **Import map.** The status field and the dashboard notice are admin components: `pnpm payload
|
|
generate:importmap` after upgrading (`TwoFactorStatusField`, `TwoFactorAlert`); `iapl-doctor` reports a map
|
|
that lacks them. Without them the panel has no "Reopen setup" button (the endpoint still works).
|
|
- **Switch a part off:** `requireSetup: { dashboardNotice: false }` (the administrators' notice),
|
|
`{ statusField: false }` (the status / reset control on the account; the endpoint stays),
|
|
`{ setupNotice: false }` (the notice on the setup screen). None of them changes who is refused. The logo and
|
|
icon fetched by the server for the 2FA screens: `whiteLabel.inlineImages: false`, `adminMeta.serveIcon: false`
|
|
([white-label.md](./white-label.md)).
|
|
- **Building blocks** (`@intecion/ipal-kit`), for a project that wires the mode itself: `buildSetupFields`,
|
|
`stampSetupFrom`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`, `countAccountsWithoutTotp`,
|
|
`resolveRequireSetup`, `strictExempt`, `SETUP_FROM_FIELD`, `TWO_FACTOR_RESET_PATH`, `DEFAULT_SETUP_WINDOW_HOURS`.
|
|
- **Per collection or global:** the opt-out below (`custom.ipal.secondFactor`) also lets an account without TOTP
|
|
in, because it takes the entity out of the second-factor check altogether.
|
|
- **Needs** IAPL's check (`twoFactor.guard`, on by default); with `guard: false` the mode is off.
|
|
- **Project code** that calls `payload.find({ …, user, overrideAccess: false })` with a user fetched by id: refused
|
|
for every account of the 2FA collection now — before, only for accounts that had TOTP set up. Take the user from
|
|
`payload.auth({ headers })`.
|
|
- **In your own code:** `twoFactorSetupState(req)` → `'set-up' | 'open' | 'closed' | 'exempt' | 'not-applicable'`,
|
|
`twoFactorSetupDeadline(req)` → `Date | null`.
|
|
- **Texts** (English and Polish; override in `i18n.translations.<lang>.ipal`): `twoFactorSetupDeadline`,
|
|
`twoFactorSetupRequired`, `twoFactorSetupClosed`, `twoFactorStatus*`, `twoFactorReopen`, `twoFactorReset*`,
|
|
`twoFactorAlert*`.
|
|
|
|
**The brand on the setup and verify screens.** A session that still owes its code is refused `media` like every
|
|
other collection, so the browser could not load the panel's logo or tab icon from it. The plugin therefore hands
|
|
such a session the picture itself — fetched on the server without any credentials, exactly as an anonymous visitor
|
|
gets it (`AdminLogo` / `AdminIcon` as a `data:` address; `GET /api/ipal/admin-icon` answers with the image
|
|
instead of a redirect when the favicon is a bitmap — never with an SVG, which keeps the redirect). Nothing is opened by this: when `media` is not publicly readable, or the file is larger
|
|
than 512 KB, the site name (or the browser's own attempt) is used instead.
|
|
|
|
**What it does not do.** Inside the window, someone who knows the password of an account that has not set TOTP up
|
|
can still set it up with their own authenticator. The real owner then cannot ("already set") and has to ask an
|
|
administrator — the takeover is visible, and the window keeps it to the first days. So still: **create the
|
|
account, hand over the password, and have the owner set 2FA up at once.**
|
|
|
|
**Check:** create an account, log in over the API with its password → `403` from `/api/users/me` and
|
|
`/api/globals/site-settings`; open the panel as that account → the setup screen with the notice; enter the code →
|
|
the panel. As an administrator open the account → "Two-step verification: Set up."
|
|
|
|
**Verify attempts are limited** (`twoFactor.verifyLimit`). The package checks the code and never counts tries;
|
|
a six-digit code has about three right answers in a million, so whoever held the password could guess. iapl
|
|
counts 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 **and in the database** (Payload's key-value store, `payload.kv` — the `payload-kv`
|
|
collection Payload itself adds; no new collection): a restart, a redeploy or a second instance does not hand out
|
|
new attempts. The higher of the two counts decides; when the database part fails, the memory count still does
|
|
(there is no "allow when the store fails" path). `verifyLimit: { max: 10, windowMinutes: 5 }` changes it,
|
|
`{ store: 'memory' }` keeps the count in this instance only, `{ keyPrefix }` names the count's key in
|
|
`payload-kv` (`<keyPrefix>:2fa-verify:<collection>:<id>`; default `ipal`, and `iapl` on a site with
|
|
`iapl({ storageNames: 'iapl' })` — one prefix per site, a change starts the running counts from zero once), `verifyLimit: false` turns it off (a limiter in
|
|
front of the site).
|
|
|
|
**Verify and setup attempts only from the site's own origin** (`twoFactor.sameOrigin`). The limit counts every
|
|
attempt of an account, so a page that can make the browser send the account's login cookie could burn the
|
|
owner's attempts and lock them out — no password needed. A sibling subdomain is such a page (`SameSite=Lax` does
|
|
not stop it, and Payload's own `csrf` list is empty unless `serverURL` or `csrf` is set). So
|
|
`POST /api/verify-totp` and `POST /api/setup-totp` refuse (`403`) a request that the browser marks as coming from
|
|
elsewhere — the `Origin` header, else `Sec-Fetch-Site` — **before it is counted**. Own origins: the host the
|
|
request came in on (`Host`, `X-Forwarded-Host`), `serverURL`, Payload's `csrf` and `cors` lists, and
|
|
`twoFactor: { …, sameOrigin: { origins: ['https://app.example.com'] } }` for a front end on another domain.
|
|
A request with neither header (a script, `curl`, a server) passes: it cannot ride on somebody's cookie.
|
|
A default port written out (`X-Forwarded-Host: site.example:443`) is the same host.
|
|
`sameOrigin: false` turns it off.
|
|
|
|
**Behind a reverse proxy that hides the site's address** — it rewrites `Host` and sends no `X-Forwarded-Host`
|
|
(nginx's plain `proxy_pass`; Traefik and Coolify keep `Host`) — and without `serverURL`, the server cannot know
|
|
its own address: the site's own verify page is refused, and **nobody can enter a code**. It is not silent: the
|
|
first refusal of every origin is logged, `[iapl] 2FA: a code from origin "https://…" was refused and not counted
|
|
— it is not one of this site's own origins (…)`, with the three ways out: set `serverURL` (the right fix, it
|
|
also fills Payload's `csrf` list), or `twoFactor: { sameOrigin: { origins: ['https://…'] } }`, or make the proxy
|
|
send `X-Forwarded-Host` (`proxy_set_header Host $host;` in nginx). `reportRefusedOrigin` is the building block. `iapl-doctor` warns (`csrf-empty`) when the config sets neither `serverURL` nor
|
|
`csrf` — Payload then accepts the login cookie from any origin.
|
|
|
|
**What is NOT covered — the complete list.** (1) Anonymous requests: the access function decides. (2) Accounts
|
|
of other auth collections: 2FA is about one collection; such an account is not staff unless its collection is in
|
|
`access.staffCollections`, and then it is staff **without** a second factor (warning in the log at start).
|
|
(3) API keys. (4) An account that has not set TOTP up yet — only with `requireSetup: false` or when the project
|
|
exempts it ("Setup required" below); by default it is refused. (5) Entities the project opted out (below).
|
|
(6) `access.admin`. (7) Endpoints that are not the plugin's or the 2FA package's: your own endpoints and other
|
|
plugins' endpoints check whatever they check — add `secondFactorPassed(req)` to yours. (8) Server code using the
|
|
Local API with `overrideAccess: true`. Nothing is skipped by slug, name or prefix, and a user object the check
|
|
cannot read is refused.
|
|
|
|
**Per-entity opt-out.** A collection or global that may be reached with the password alone (a project decision,
|
|
e.g. a health record the panel reads before the code is entered), operation by operation:
|
|
|
|
```ts
|
|
// the 2FA package's own key — it leaves the operation unwrapped, and so does IAPL
|
|
{ slug: 'notices', custom: { totp: { disableAccessWrapper: { read: true } } }, … }
|
|
// IAPL's key — the same, and it also works for entities the package never sees
|
|
{ slug: 'notices', custom: { ipal: { secondFactor: { read: false } } }, … } // or secondFactor: false = every operation
|
|
```
|
|
|
|
Operations: `create`, `delete`, `read`, `readVersions`, `unlock`, `update` (collections); `read`, `readDrafts`,
|
|
`readVersions`, `update` (globals). For one of the plugin's own globals set it through `globalOverrides`
|
|
(`{ notifications: { custom: { ipal: { secondFactor: { read: false } } } } }`) — and note that the plugin's
|
|
staff rules (`userMeetsRole`) ask for the second factor themselves, so also give that operation your own
|
|
`access` function there. `disableAccessWrapper: true` passed to the package's factory turns all access
|
|
wrapping off, IAPL's included; the endpoints stay guarded.
|
|
|
|
**The 2FA package's endpoints.** The package takes `req.user` from whatever auth collection it comes and then
|
|
acts on the 2FA collection by id: `/api/setup-totp` writes the TOTP secret under the **caller's** id. With
|
|
numeric ids (Postgres, SQLite) an account of another auth collection could therefore set the secret of the
|
|
staff account that has the same id, and whoever knew that staff password then passed 2FA. iapl wraps every
|
|
endpoint the package registers: a logged-in account of another collection gets `403`; remove and the admin
|
|
reset / remove endpoints also need the second factor, so a password alone cannot reset TOTP and enrol again.
|
|
This guard is on whenever 2FA is on, also with `twoFactor.guard: false`.
|
|
|
|
Two things follow for project code:
|
|
|
|
- `payload.find({ …, user, overrideAccess: false })` on a plugin collection needs a `user` that came from
|
|
`payload.auth({ headers })` (it carries how the account logged in). A user fetched with `findByID` and passed
|
|
by hand is refused when it has TOTP set up.
|
|
- Your own endpoints do not go through `access`. Guard them:
|
|
|
|
```ts
|
|
import { requireSecondFactor, secondFactorPassed, userMeetsRole } from '@intecion/ipal-kit'
|
|
|
|
// an endpoint
|
|
handler: async (req) => {
|
|
if (!req.user || !secondFactorPassed(req)) return Response.json({ ok: false }, { status: 403 })
|
|
// or: if (!userMeetsRole(req, 'editor')) … — it includes the second-factor check
|
|
}
|
|
// an access function (collections and globals in the config are wrapped for you; this is for the rest)
|
|
access: { read: requireSecondFactor(({ req }) => isAdmin(req.user, req.payload)) }
|
|
```
|
|
|
|
**Fails closed.** At startup iapl checks that the injected 2FA plugin added what the check reads (the
|
|
`totpSecret` and `hasTotp` fields and the `totp` auth strategy on the 2FA collection). When it did not — a
|
|
package version with another shape — startup stops with `[iapl] twoFactor: the injected 2FA plugin did not
|
|
add …`. Tested with `@clocklimited/payload-2fa` 3.0.0-beta.1 and 3.0.0-beta.7 (the versions in between are not run in the plugin's tests). `twoFactor.guard: false` switches
|
|
IAPL's check off and leaves the package's wrapper alone; the plugin's own data is then open to a password
|
|
without the code again, so use it only to get a site started while the package is being sorted out.
|
|
|
|
**Check** (replace the address and the account):
|
|
|
|
```bash
|
|
# password only, no code → 403 on all three
|
|
TOKEN=$(curl -s https://example.com/api/users/login -H 'content-type: application/json' \
|
|
-d '{"email":"[email protected]","password":"…"}' | node -pe 'JSON.parse(require("fs").readFileSync(0)).token')
|
|
for p in globals/site-integrations form-submissions users; do
|
|
curl -s -o /dev/null -w "$p %{http_code}\n" -H "Authorization: JWT $TOKEN" https://example.com/api/$p
|
|
done
|
|
```
|
|
|
|
### Import map (required)
|
|
|
|
The 2FA screens and the redirect to them are admin components. After adding `twoFactor`, and after every
|
|
IAPL upgrade, run:
|
|
|
|
```bash
|
|
pnpm generate:importmap
|
|
```
|
|
|
|
`src/app/(payload)/admin/importMap.js` must list `@intecion/ipal-kit/admin#TotpRedirectProvider`,
|
|
`@intecion/ipal-kit/admin#SafeTotpView` and `@clocklimited/payload-2fa/rsc#TOTPSetup` / `#TOTPVerify` /
|
|
`#TOTPField`. Commit the file.
|
|
|
|
### Texts of the 2FA screens (`twoFactor.texts`)
|
|
|
|
The setup and verify screens and the user field read their texts through Payload's i18n
|
|
(`totpPlugin:*`), in the user's admin language (*Account → Language*; without a choice, the
|
|
browser's language — an English browser sees English screens on a Polish site). The package's own texts are long and informal,
|
|
so IAPL merges `TOTP_TEXTS` (English and Polish, per `docs/dev/admin-ux.md`) over them, e.g.
|
|
"Two-step verification" / "Weryfikacja dwuetapowa", "Enter the 6-digit code from the app:" /
|
|
"Wpisz 6-cyfrowy kod z aplikacji:". The browser tab reads "Weryfikacja dwuetapowa — <site> | Panel"
|
|
(`TOTP_VIEW_TITLE` in the site's default language: Payload's view title is a plain string).
|
|
|
|
- **Override one text:** `i18n.translations.<lang>.totpPlugin.<key>` in your config — your keys win
|
|
over both sets.
|
|
- **Keep the package's texts:** `twoFactor: { …, texts: false }`.
|
|
- **Not translatable:** a network failure while sending the code shows the package's hardcoded
|
|
"Something went wrong" toast (rare: the server's own errors are translated).
|
|
|
|
### The redirect to the 2FA screens (`twoFactor.provider`)
|
|
|
|
The package's own admin provider decides on the server where to send the user, from an `x-pathname`
|
|
request header. Nothing sets that header on `/admin` (the `createProxy` matcher skips `/admin`), so up to
|
|
1.14.1 a user without TOTP was sent to `/admin/setup-totp?back=null`, and the setup screen redirected
|
|
to itself forever. Since 1.14.2, IAPL swaps in its own provider,
|
|
`TotpRedirectProvider`: it reads the path in the browser, never redirects away from the setup or verify
|
|
screen or from logout, and renders nothing while a redirect is pending, so the panel does not flash.
|
|
No project change is needed apart from `generate:importmap`.
|
|
|
|
- `twoFactor.provider: '@/components/MyTotp#MyTotp'` (or a `{ path, clientProps, serverProps }` object):
|
|
your own component. It gets clientProps `forceSetup` and the package's serverProps `pluginOptions`.
|
|
The pure logic is exported: `totpRedirectTarget({ adminRoute, forceSetup, pathname, user })` returns
|
|
the URL to send the user to, or `null`.
|
|
- `twoFactor.provider: false`: keep the package's provider. Then a proxy must set `x-pathname` on every
|
|
`/admin` request, or the loop comes back.
|
|
|
|
The provider only steers the UI. Data access is still checked by the package's access wrapper.
|
|
|
|
### The `back` link of the 2FA screens (`twoFactor.safeBack`)
|
|
|
|
The setup and verify screens take a `back` query value (`/admin/verify-totp?back=%2Fadmin%2Fcollections%2Fpages`)
|
|
and the 2FA package sends the browser there once the code is accepted, without looking at it. A link with
|
|
`back=javascript:…` therefore ran script in the panel, as the user who had just passed the second factor, and a
|
|
link with an outside address sent the user off the site straight after a real login step. The original package
|
|
fixed this in `payload-totp` 3.0.5 (GHSA-rffw-fq79-g3ch); `@clocklimited/payload-2fa` (beta.1 to beta.7) has not.
|
|
The panel's CSP does not stop it: the admin needs inline script.
|
|
|
|
IAPL closes it without changing the package. `SafeTotpView` (`@intecion/ipal-kit/admin`) is registered in
|
|
place of the package's four views (`setup-totp`, `verify-totp`, each with and without a leading slash). It checks
|
|
`back` on the server and renders the package's view with the checked value. The package's views stay in the
|
|
import map through `admin.dependencies`, so IAPL still never imports the package.
|
|
|
|
The rule (`safeAdminBack`, the same as upstream's): `back` is resolved the way a browser resolves it and kept
|
|
only when it stays on the site's origin, over HTTP(S), without credentials, inside the admin route
|
|
(`routes.admin`, also a custom one). Everything else gives the admin root: `javascript:` in any case or with
|
|
leading spaces, `data:`, `https://other.example`, `//other.example`, `/\other.example`, `\\other.example`,
|
|
`https:other.example`, a path outside the panel, a repeated `back`, no `back` at all. The value passed on is
|
|
always a path, never an absolute URL. An absolute `back` on the site's own origin is accepted only when the
|
|
config has `serverURL`.
|
|
|
|
- **On by default** with `twoFactor`. **After upgrading run `pnpm payload generate:importmap` and commit
|
|
`importMap.js`** — see "A stale import map" below for what happens otherwise.
|
|
- **Your own rule:** `twoFactor: { …, safeBack: (back, { adminRoute, origin }) => string }`. It gets the raw value
|
|
(`undefined` when absent or repeated) and returns where to go. Return a path on your own origin.
|
|
- **Off:** `twoFactor: { …, safeBack: false }` — the package's views exactly as it registers them. Only when a
|
|
later version of the 2FA package checks `back` itself, or something in front of the site does.
|
|
- **Building blocks:** `safeAdminBack(back, { adminRoute, origin })` and `wrapTotpViews(views, added, rule)` from
|
|
`@intecion/ipal-kit`; `SafeTotpView` from `@intecion/ipal-kit/admin` for your own 2FA view registration (give it
|
|
the serverProp `ipalTotpView: '<import-map path of the view to render>'` and list that path in
|
|
`admin.dependencies`).
|
|
|
|
**Which views are guarded.** Every view the injected 2FA factory registers on the routes `setup-totp` and
|
|
`verify-totp`, whatever stood under its keys before. The package replaces a view the project has under the keys
|
|
`SetupTOTP`, `SetupTOTPBackslash`, `VerifyTOTP` or `VerifyTOTPBackslash`, so such a view is the package's, and
|
|
guarded. The same holds when the project also lists `payloadTotp(...)` in `plugins` itself.
|
|
|
|
**Your own 2FA screen.** Two ways, both keep the check:
|
|
- Through the wrapped factory (the pattern from "Resetting 2FA"): set `views.VerifyTOTP.Component` (or `SetupTOTP`)
|
|
on the config the factory returns. IAPL puts `SafeTotpView` in front of it. A server component gets every
|
|
server prop with `searchParams.back` checked. A client component (`'use client'`) gets Payload's client props,
|
|
your `clientProps`, and `back` plus `searchParams` — both checked; read `back` from the props, not from
|
|
`useSearchParams()`, which still holds the raw query value.
|
|
- From a plugin listed after `iapl`, or under another key or route: that view is yours and is not wrapped. Use
|
|
`wrapTotpViews` or `safeAdminBack` in it. `iapl-doctor` warns when the config uses the package's own view
|
|
(`@clocklimited/payload-2fa/rsc#TOTPVerify` / `#TOTPSetup`) as a view's `Component`; the same path as the
|
|
`ipalTotpView` of `SafeTotpView`, or in `admin.dependencies`, is fine.
|
|
|
|
Wrapping views yourself, for a project that runs the 2FA package without `iapl`'s `twoFactor` (all from
|
|
`@intecion/ipal-kit`):
|
|
```ts
|
|
const before = copyViews(config.admin?.components?.views) // copies: the factory's views are then never "the same object"
|
|
config = await payloadTotp(options)({ ...config, admin: { ...config.admin, components: { ...config.admin?.components, views: before } } })
|
|
const fromPackage = changedViewKeys(before, config.admin?.components?.views ?? {}) // by object — the package replaces views under its keys
|
|
const { dependencies, views } = wrapTotpViews(config.admin?.components?.views ?? {}, (key) => fromPackage.has(key), undefined)
|
|
config.admin = { ...config.admin, components: { ...config.admin?.components, views }, dependencies: { ...config.admin?.dependencies, ...dependencies } }
|
|
```
|
|
`SAFE_TOTP_VIEW` is the wrapper's import-map path; `findImportMapFile` / `missingImportMapEntries` are the
|
|
stale-map check below (a hint from the file on disk — warn on it, never block on it).
|
|
|
|
**A stale import map (read this before upgrading a site with 2FA).** The check needs the import-map entry
|
|
`@intecion/ipal-kit/admin#SafeTotpView`. A production build made with the import map of the previous version
|
|
passes and the site starts, but Payload renders nothing for a path its map lacks: the 2FA setup and verify
|
|
screens have no code form (HTTP 200), so nobody can sign in to the panel. Payload's only trace is
|
|
`getFromImportMap: PayloadComponent not found in importMap` in the server log. Development is not affected (Payload
|
|
regenerates the map there). IAPL reports it in three places:
|
|
- **Before deploy:** `pnpm exec iapl-doctor` reports `import map lacks @intecion/ipal-kit/admin#SafeTotpView` (error).
|
|
- **At every start in production:** the log has `[iapl] The admin import map may be out of date: … was not found
|
|
in <file> …`.
|
|
- **On the screen:** a notice above the 2FA screen, "Two-step verification may not be available", with what a
|
|
developer has to run. With a really stale map the notice is all the user sees (the form is missing); it is
|
|
shown by IAPL's `TotpRedirectProvider` only — with your own `twoFactor.provider`, or `provider: false`,
|
|
there is the log line alone.
|
|
|
|
The start-up check is a guess, and is built so that a wrong guess costs a wrong notice and nothing else: it
|
|
searches the text of the `importMap.js` **on disk** where Payload looks for it (`admin.importMap.importMapFile`,
|
|
else `app/(payload)<admin route>/` or `src/app/(payload)<admin route>/` under `admin.importMap.baseDir` or the
|
|
working directory), while the map the site really uses is inside the build. The two differ when the map is
|
|
generated during the build and the running image carries the repository's file (a Dockerfile with a separate
|
|
runner stage), or when the map file re-exports or computes its entries. Then the log line and the notice appear
|
|
although the screen works — the code form stays on the page and sign-in is not affected. Turn the check off for
|
|
such a project: `twoFactor: { …, importMapCheck: false }` (no file read, no log line, no notice). A file that is
|
|
not found is not reported. Building in place (Coolify's Nixpacks) reads the same file the build used.
|
|
|
|
**Fix for a really stale map:** `pnpm payload generate:importmap`, commit `importMap.js`, rebuild, redeploy.
|
|
A second error exists for the opposite case — the wrapper is in the map but the package's view is not:
|
|
`[iapl] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` (same fix).
|
|
|
|
**Check:** log in with the password only, open
|
|
`/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F`, enter the code: you must land on `/admin`, not on
|
|
example.com. With `back=%2Fadmin%2Fcollections%2Fpages` you must land on that list.
|
|
|
|
### Turning it off (DISCOURAGED)
|
|
|
|
```ts
|
|
twoFactor: false // ONLY when the project really cannot use 2FA (rare)
|
|
```
|
|
2FA is ENFORCED by default. `false` is a deliberate opt-out — avoid it. Leaving out `twoFactor`
|
|
(even though the type marks it optional) stops startup with `twoFactor.issuer is required` — the decision must be explicit.
|
|
|
|
### How it works for the user
|
|
|
|
1. Logs in (email + password)
|
|
2. On first login: redirected to TOTP Setup (`/admin/setup-totp?back=%2Fadmin`, QR + secret), with a notice
|
|
saying until when it has to be done. Until it is done the account can do nothing else ("Setup required")
|
|
3. Scans the QR with an app (Google Authenticator, Authy, 1Password, Microsoft Authenticator)
|
|
4. Enters the code → 2FA is active, back to the page from `back`
|
|
5. Next logins: email + password + TOTP code (`/admin/verify-totp?back=…`)
|
|
|
|
**Check:** log in as a new admin. The address must end at `/admin/setup-totp?back=%2Fadmin` and the page must
|
|
show the QR code. `back=null` or a page that keeps reloading means the import map is stale (run
|
|
`pnpm generate:importmap`) or `provider: false` without an `x-pathname` header on `/admin`.
|
|
|
|
### Resetting 2FA (admin)
|
|
|
|
An admin resets another user's 2FA (a lost phone) or reopens setup for a blocked account on that account's page
|
|
in the panel: **Two-step verification** in the sidebar → "Reset two-step verification" / "Reopen setup". Behind
|
|
it: `POST /api/ipal/two-factor/reset` `{ userId }`. The account must set TOTP up again within a new window.
|
|
The endpoint comes with IAPL's own check: with `twoFactor.guard: false` it does not exist (404), and neither
|
|
does the control in the panel.
|
|
|
|
- **Who may reset.** By default a staff admin whose session has **entered its own TOTP code**. An admin on an API
|
|
key, and an admin that `requireSetup.exempt` lets work on its password, are refused: removing someone's second
|
|
factor should take one. `twoFactor.resetAccess: ({ req }) => boolean` replaces the rule; a session that still
|
|
owes its code is refused whatever the function says, and only an answer of exactly `true` allows
|
|
(`req.user._strategy` is `'totp'`, `'api-key'` or `'local-jwt'`). Example that keeps the default's strength and
|
|
narrows it to one address: `({ req }) => req.user?._strategy === 'totp' && req.user.email === 'owner@example.com'`.
|
|
`({ req }) => isAdmin(req.user, req.payload)` alone would let an API-key or exempt admin reset.
|
|
- **A reset ends the account's sessions.** Every token of that account stops working at once; its owner logs
|
|
in again with the password and sets TOTP up. This matters when the account may be in someone else's hands: a
|
|
session that had passed 2FA could otherwise enrol a new authenticator without the password (`/api/setup-totp`
|
|
asks for none). **After a suspected compromise also change the account's password** — the reset does not, and
|
|
whoever knows the password can log in and set TOTP up within the new window. With `auth.useSessions: false`
|
|
on the collection there are no sessions to end: tokens live until they expire.
|
|
- The 2FA package's own remove / reset endpoints (below) do **not** end sessions.
|
|
|
|
#### Every administrator is blocked
|
|
|
|
When no administrator can get in (each one missed the window, or the only one did), nobody can press "Reopen
|
|
setup". Two ways out, both need a deploy or shell access — which is the point: the panel alone cannot undo it.
|
|
|
|
1. **A script, no redeploy** (`pnpm payload run scripts/reopen-2fa.ts` on the server; Local API, no access
|
|
check):
|
|
```ts
|
|
import config from '@payload-config'
|
|
import { getPayload } from 'payload'
|
|
const payload = await getPayload({ config })
|
|
const { docs } = await payload.find({ collection: 'users', where: { email: { equals: '[email protected]' } } })
|
|
await payload.update({ id: docs[0].id, collection: 'users', data: { totpSetupFrom: new Date().toISOString() } })
|
|
process.exit(0)
|
|
```
|
|
The administrator then logs in and sets TOTP up within the new window, and reopens the others from the panel.
|
|
2. **No script, one redeploy each way:** set `twoFactor.requireSetup: { windowHours: false }` and deploy — the
|
|
lock stays (nothing but setup), the time limit is gone, so every blocked account can set TOTP up. When the
|
|
administrators have, put the option back and deploy again. Accounts that still have not set TOTP up are
|
|
blocked again from that moment (their start did not move).
|
|
|
|
Avoid it: at least two administrators with 2FA, and `iapl-doctor --url <site>` before an upgrade.
|
|
|
|
The 2FA package has its own reset, off unless you turn it on — through
|
|
`adminManageAccess` in the @clocklimited configuration. iapl passes it only `collection`,
|
|
`forceSetup` and `issuer`; pass other options by wrapping the injected factory:
|
|
`plugin: (opts) => payloadTotp({ ...opts, adminManageAccess: ({ req }) => isAdmin(req.user, req.payload) })`.
|
|
IAPL's guard on those endpoints adds the rest: the caller must be an account of the 2FA collection that has
|
|
passed the second factor itself. After a reset the account is "not set up" again — have its owner set TOTP up
|
|
at once (see the note above).
|
|
|
|
### Why @clocklimited and not another one
|
|
|
|
Chosen because it wraps ACCESS CONTROL (TOTP before data access) + forceSetup
|
|
(enforced for everyone). Other 2FA plugins for Payload only gate /admin
|
|
navigation — a user with a password can bypass them through REST/GraphQL/Bearer. @clocklimited protects
|
|
data access, not just the UI — for what is in the config when it runs; IAPL's own check covers the rest
|
|
("What the second factor covers").
|
|
|
|
## 1.9.1 — security review results
|
|
|
|
- Drafts that were never published are no longer publicly available (`resolveRoute`, Markdown, MCP,
|
|
metadata), nor on archive lists (`getArchiveEntries`). Preview: `resolveRoute({ draft: true })`,
|
|
`getArchiveEntries({ draft: true })` in `draftMode()`.
|
|
- Links from the CMS: only `http(s)`, `mailto`, `tel`, `sms`, `#`, `/` (`safeHref`); `javascript:` and `data:` are rejected —
|
|
also in rich text (`RenderRichText` replaces them with `#`).
|
|
- Analytics IDs are validated (in the panel and before being sent to the browser).
|
|
- Form submissions: read `editor+`; addresses from the Emails tab are not publicly visible.
|
|
- Uploads: `buildUploadSecurityHeaders()` in `next.config.ts` (an SVG cannot run a script on the site's domain).
|
|
- `users`: the plugin injects an auth collection when the project has none (roles and 2FA always attach).
|
|
|
|
## 1.16.4 — two access fixes
|
|
|
|
- **Staff checks and a second auth collection.** Roles and the "no roles field" rule counted for an account of
|
|
any auth collection — a `customers` account passed the plugin's staff checks, and with its own `roles` field
|
|
also `isAdmin`, `adminOnly` and the rest. Now the staff-collection check comes first everywhere: the panel's
|
|
login collection, `access.authCollection` and `access.staffCollections`
|
|
([access.md](./access.md#who-is-staff)). The injected auth collection uses `adminOrSelfIn(slug)`, so an
|
|
account of another collection with the same numeric id no longer counts as "self".
|
|
- **2FA and the plugin's own data.** See "What the second factor covers" above.
|
|
- **The 2FA package's endpoints** accept accounts of the 2FA collection only ("The 2FA package's endpoints").
|
|
- After upgrading: [PROGRAMISTA.md](./dev/PROGRAMISTA.md) upgrade table, and the CHANGELOG entry of that release.
|
|
|
|
## Form files (`forms.attachments`)
|
|
|
|
Files attached to a form are **never stored and cannot be downloaded**: they are checked in memory, attached to
|
|
the company e-mail and dropped. The checks, in order — origin, rate limit, declared size, concurrency guard,
|
|
honeypot, Turnstile, field validation and consent, then per file: count, name (double and refused extensions),
|
|
size while reading, content signature, container and macro checks, an optional `scan` hook — are listed in
|
|
[forms.md](./forms.md) "The security wall".
|
|
|
|
- There is **no antivirus**. The checks stop the wrong kind of file; they do not prove a file is harmless. Plug a
|
|
scanner into `forms.attachments.scan` when the client needs one. The macro check for legacy `.doc` / `.xls` is
|
|
best-effort.
|
|
- Programs, scripts, macro-enabled Office files, archives, HTML and SVG are refused unless the project lists
|
|
the extension in `allowRisky`.
|
|
- The submit endpoint (`POST /api/ipal/forms/submit`) accepts same-origin requests only
|
|
(`attachments.submit.allowedOrigins` adds others) and runs the same gates as the server action; REST creation
|
|
of submissions stays "logged-in users only".
|
|
- Microsoft Graph: files of 3 MB and more need `Mail.ReadWrite` — limit the app to the forms mailbox
|
|
([email.md](./email.md) "Attachments").
|
|
|
|
## Access control (since the version after 1.12.3)
|
|
|
|
- Injected auth collection with roles: a `user` account reads and edits only itself; only an
|
|
admin creates and deletes. Before, any logged-in account could change an admin's email/password.
|
|
- 2FA without `collectionSlug` wraps the panel login collection (`admin.user`, else the first auth
|
|
collection), not the literal `'users'`. Plugin startup fails with `[iapl] twoFactor…` when the target is not
|
|
an auth collection or differs from `admin.user` — deliberate exception: `twoFactor.allowCollectionMismatch: true`.
|
|
- Injected auth collection with roles: `unlock` is admin-only too. You can override all of it:
|
|
`access.authAccess`, `access.firstUserAdmin: false`, `globalOverrides`, `forms.formOverrides`.
|
|
- Site settings, Cookie banner, Notifications and the Forms collection: write is `editor+` only; a form's
|
|
Emails tab (recipients, BCC) is readable only by `editor+`.
|
|
- Full table: [access.md](./access.md#what-the-plugin-locks-down-by-itself).
|
|
|
|
## Stored secrets (`secrets.writeOnly`, `secrets.reenterOnChange`)
|
|
|
|
`smtpPassword` and `turnstileSecretKey` live in the Site integrations global: **the panel is their source**
|
|
(there is no env variable for the SMTP password, and the env fallback for the Turnstile secret is deprecated —
|
|
[turnstile.md](./turnstile.md)). They are **write-only**:
|
|
|
|
| Who reads | Gets |
|
|
|---|---|
|
|
| REST (`GET /api/globals/site-integrations`), GraphQL, the panel's form, versions — anything through access control, an admin included | `'********'` when a value is stored (`SECRET_MASK`), the empty value when none is |
|
|
| Server code through the Local API with access control off (the default of `payload.findGlobal`) — the mail adapter, the Turnstile check, your own server code | the real value |
|
|
| The Local API **with** access control (`overrideAccess: false` and a `user`) | `'********'` |
|
|
|
|
| A save sends | Result |
|
|
|---|---|
|
|
| nothing for the field, an empty value, `null`, or `'********'` back | the stored value is kept |
|
|
| a new value | replaces it (the answer shows `'********'`) |
|
|
| `'[[clear]]'` (`SECRET_CLEAR`) | removes it |
|
|
| a value that is not text (`false`, `0`, a list, an object) | **refused** (`400`): "Enter the value as text." |
|
|
| the server, the port or the user name **changed** (whatever the transport), and **no** new password | **refused** (`400`, on the password field): "Enter the password again…" |
|
|
|
|
In the panel the field says "A value is set. It is not shown; type a new one to replace it." and offers "Remove
|
|
the stored value".
|
|
|
|
**The SMTP password stays with the server it was saved for** (`secrets.reenterOnChange`). Hiding the value is
|
|
not enough on its own: an admin session could point `smtpHost` / `smtpPort` at a machine of its own, press
|
|
"Send test e-mail", and read the password off the connection. So a save **through access control** (the panel,
|
|
REST, GraphQL) that changes `smtpHost`, `smtpPort` or `smtpUser` while a password is stored must send the
|
|
password again — or remove it (`'[[clear]]'`, "Remove the stored value") for a server without one. **Whatever
|
|
the transport says:** "Microsoft Graph" in the panel does not mean Graph sends — the mail adapter falls back to
|
|
SMTP when Graph is not configured, and for attachments Graph cannot take. A change of `emailTransport` alone
|
|
asks for nothing. Values are compared exactly (`587` and `'587'` are the same; another letter case or a space
|
|
is a change), and a value never saved — or a `NULL` in a SQL row — counts as the field's default, so saving
|
|
the form unchanged asks for nothing. Server code — a seed, a script with the Local API and access control off
|
|
— is not asked. `iapl({ secrets: { reenterOnChange: false } })` = the stored password follows the new
|
|
server, as before.
|
|
|
|
A stolen admin session, or any way past the global's read rule, no longer yields a working mailbox password.
|
|
What it does **not** protect: the database and its backups hold the value in plain text (encryption at rest is
|
|
a separate, open question); whoever can change the config or run server code can read it; and a session that
|
|
knows nothing but may send e-mail can still **use** the mailbox through the site (send, not read). On a port
|
|
other than 465 the connection is encrypted only when the server offers STARTTLS; requiring it is a possible
|
|
later option, not part of this release.
|
|
|
|
**Versions.** The global has no versions by default. A project that turns them on
|
|
(`globalOverrides: { 'site-integrations': { versions: … } }`) stores the secret in every version — as in the
|
|
document itself — and reads of versions are masked like any read. A **restore** answers with the version
|
|
document, the fields under `version`, where field hooks do not run: the global's `afterRead` hook
|
|
`maskSecretsOnRestore` masks them there too. A restore brings back the password of that version.
|
|
|
|
- **What an existing site sees after the upgrade:** nothing to do. The stored values stay; the panel shows "a
|
|
value is set"; the API returns the mask. Code of your own that read the secret over REST / GraphQL as an admin
|
|
must read it on the server with the Local API instead.
|
|
- **Off:** `iapl({ secrets: { writeOnly: false } })` — the value is returned to whoever may read the global.
|
|
- **Your own secret fields:** `writeOnlySecret({ name: 'apiToken', type: 'text', admin: { components: { Field:
|
|
'@intecion/ipal-kit/admin#MaskedField' } } })`, or `writeOnlySecrets(fields, ['apiToken'])` for fields inside
|
|
tabs / rows / groups; the hooks `maskSecretAfterRead` / `keepSecretBeforeValidate`, `SECRET_MASK`,
|
|
`SECRET_CLEAR`, `isSecretMask`, `INTEGRATION_SECRET_FIELDS` are exported. A real secret equal to `********` or
|
|
`[[clear]]` cannot be stored.
|
|
- Bound to other fields, like the SMTP password: `writeOnlySecret(field, { boundTo: ['apiUrl'] })`, or
|
|
`writeOnlySecrets(fields, ['apiToken'], { apiToken: { boundTo: ['apiUrl'], appliesWhen: (data) => … } })`
|
|
(`WriteOnlySecretOptions`; `buildKeepSecret(options)` is the hook; `SMTP_PASSWORD_BOUND_TO` is the plugin's
|
|
list). The fields must be siblings of the secret.
|
|
- With versions on your entity: add `hooks: { afterRead: [maskSecretsOnRestore] }` to the global or the
|
|
collection (`maskWriteOnlySecrets(data, fields)` is the walker it uses).
|
|
- **Check:** as a fully signed-in admin, `GET /api/globals/site-integrations` → `"smtpPassword":"********"`; save
|
|
the form without touching the field → a test e-mail still goes out; change the server without typing the
|
|
password → the save is refused with "Enter the password again…".
|
|
|
|
## The mail service's token and its public route (`mail.relay`)
|
|
|
|
A site that sends through the Intecion Notifications Webservice (IWSN in the panel; [email.md](./email.md)) holds one secret: its own
|
|
token. What protects it, and what the new public route can and cannot do:
|
|
|
|
| | |
|
|
|---|---|
|
|
| **No key in the package** | The plugin carries the service's address and nothing else. A site gets its token by proving it is served at its host: it makes a nonce, the service calls `POST https://<host>/api/iapl/mail-relay/confirm` with the nonce and a token, and only an answer that hashes both makes the token valid |
|
|
| **Where the token is** | `payload-kv`, one entry per host (`iapl:mail-relay:site:<host>`). The collection refuses every operation through access control (`read`, `create`, `update`, `delete` are `false`) and is hidden: REST, GraphQL and the panel cannot reach it — an admin included (test: `test/mailRelayHttp.test.ts`). Server code with the Local API can, like `smtpPassword`. It is stored as it is (no encryption at rest), never logged, never sent to a browser, never part of a route's answer |
|
|
| **A database copied to another host** | both sides hold a token to its host: every request names the site (`X-Intecion-Site`) and the service refuses another host's token (`host-mismatch`); and on the site the token is stored under the host it was issued for: a copy on a staging domain neither uses nor touches production's entry (a read never deletes), and a non-public copy (a host that matches `developmentHosts` — built in: `*.dev.netscale.pl`, no env needed — or `IAPL_NOINDEX=1`) **neither enrols nor sends by itself** — with production's data it would mail real people — until an admin presses "Connect again", also when it has a token of its own (production's data copied back onto a development address). A public site is never held (launch and a domain move must work unattended), so **a copy on a host outside those patterns, without the variable, sends**; the doctor notes a public site whose database knows another host (`mail.relay.otherHosts`) |
|
|
| **A token of another site** (stored by a script, set as `relay.token`, or pasted into the access-key field — which is off unless the project sets `mail.relay.accessKeyField`) | refused: the service is asked which host the token is for before it is stored or used; a foreign one is not saved, not used, not revoked |
|
|
| **A token read from a database dump** | **works from the same server** (a staging site on the machine production runs on shares its outgoing address) — which is why the store is tied to its host, above. From another server it does not work: the service accepts a token only from the addresses the site enrolled from (IPv6: the same `/64`) and answers anything else "enrol again" — which needs the call-back to the real site. It cannot send as another site, and the limits below apply |
|
|
| **What a token can do at most** | send within the site's limits (30 an hour, 200 a day, 10 recipients, 10 MB by default) from the service's fixed address, under a sender name the service checks, with `X-Intecion-Site: <host>` on every mail. It cannot set `From`, `Return-Path` or any header, and cannot address a security alert |
|
|
| **The confirm route** | public by design, `404` with an empty body unless the body carries a nonce **this site** made in the last 5 minutes (kept as a hash, compared in constant time, single use). It stores the delivered token **beside** the one in use and never replaces a working token: a token becomes the one in use only after the service has accepted it — a `200`, or a refusal the service gives after it has checked the token; no answer, an error page or `rate-limited` prove nothing and leave both as they are. **Refused** calls are rate-limited per address (10 a minute, `mail.relay.confirmRateLimit`); the nonce is looked up first, so junk from the address the service shares with others cannot keep the site's own enrolment out. A stranger who calls it learns nothing and changes nothing |
|
|
| **Who can start an enrolment** | the server itself (a send without a token) and an admin ("Connect again"). The three state routes need the `admin` role and answer with states only |
|
|
| **A site taken over by an attacker with admin rights** | can send mail through the service under any sender name the service's check lets through, within the limits — as it could through the site's SMTP server. Intecion sees the host on every mail and can suspend the site (`relay-suspended`) |
|
|
| **Visitors** | cannot reach the service: only the server calls it. What a visitor can trigger is a form's mail (rate limit, Turnstile) and "forgot password" — limited by the site per address and per visitor (`mail.relay.accountMail`), because the service does not limit account mail per address |
|
|
| **A subject or name typed by a visitor** | line breaks, control characters, direction marks and other invisible characters are removed before the message leaves (`cleanSubject`); recipients are reduced to bare addresses; a message has no header field |
|
|
|
|
Turn off: `iapl({ mail: { relay: false } })` — no route, no outbound call, no token. Give the token up:
|
|
"Disconnect" in the panel (`disconnectRelay`), which revokes it on the service — at once when the service answers;
|
|
when it cannot be reached the site stops using the token, the panel says the disconnection is not confirmed, and
|
|
the token stays valid at the service until "Disconnect" is pressed again and answered.
|
|
|
|
## Dashboard alerts by role (`dashboardAlerts`)
|
|
|
|
The plugin's dashboard alerts read data that only some roles may read (with access control off, on the server),
|
|
so each decides who sees it. **Integration alerts** (Site integrations is admin-only): an admin sees what is
|
|
failing and the link; an editor sees "An integration needs attention. Ask an administrator to look at it."; anyone
|
|
else sees nothing. **Cookie alerts** (crawl result, cookies waiting): editors and above. A session that still owes
|
|
its second factor sees none of them. `iapl({ dashboardAlerts: { integrations: 'editor' | 'all', cookies: 'all' } })`
|
|
loosens it. **`'all'` checks nothing** — no role and no second factor: whoever the dashboard is drawn for sees
|
|
the full text, as before. The components take the same as props
|
|
(`details`, `audience`).
|
|
|
|
## Turn off, override, extend
|
|
|
|
- **Stored secrets:** `secrets: { writeOnly: false }`, `secrets: { reenterOnChange: false }`; `writeOnlySecret` /
|
|
`writeOnlySecrets` (with `boundTo`), `maskSecretsOnRestore` for your own fields.
|
|
- **2FA attempts from another origin:** `twoFactor.sameOrigin: false`, or `{ origins: [...] }`; `requestFromOwnOrigin`,
|
|
`ownOrigins` are exported. **Verify count:** `verifyLimit: { store: 'memory' }`; `buildVerifyLimit`,
|
|
`verifyLimitKey`, `clearVerifyLimits` (tests) are exported.
|
|
- **Dashboard alerts:** `dashboardAlerts: { integrations, cookies }`.
|
|
- **The mail service:** `mail: { relay: false }`; `mail.relay: { enrol: 'manual' | false, token, accountMail,
|
|
confirmRateLimit }`; `relayConfirmEndpoint`, `enrolRelay`, `disconnectRelay`, `rotateRelayToken`, `setRelayToken`
|
|
are exported ([email.md](./email.md)).
|
|
- **Verify limit:** `twoFactor.verifyLimit: { max, windowMinutes }`, or `false`.
|
|
- **`back` link check of the 2FA screens:** `twoFactor.safeBack: false`, or a function as your own rule;
|
|
`safeAdminBack`, `wrapTotpViews`, `copyViews`, `changedViewKeys`, `SAFE_TOTP_VIEW`, `SafeTotpView` are exported.
|
|
The stale import-map notice that comes with it: `twoFactor.importMapCheck: false`; its parts
|
|
(`findImportMapFile`, `missingImportMapEntries`) are exported too.
|
|
- **Setup required:** `twoFactor.requireSetup: false` (off), `{ windowHours }` (another window, `false` / `0` = none),
|
|
`{ exempt }` (a service account), `{ dashboardNotice: false }`, `{ statusField: false }`, `{ setupNotice: false }`,
|
|
`twoFactor.resetAccess` (who reopens); exported: `twoFactorSetupState`, `twoFactorSetupDeadline`,
|
|
`buildSetupFields`, `stampSetupFrom`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`,
|
|
`countAccountsWithoutTotp`, `resolveRequireSetup`, `strictExempt`, `SETUP_FROM_FIELD`.
|
|
- **2FA check:** per entity `custom.ipal.secondFactor` / `custom.totp.disableAccessWrapper` (one operation or
|
|
all); `twoFactor.guard: false` turns IAPL's own second-factor check off everywhere (not recommended);
|
|
`requireSecondFactor` / `secondFactorPassed` are exported for your own access functions and endpoints.
|
|
- **Turn off:** headers — do not call `buildSecurityHeaders`, or `null` / `false` per header (`frameOptions`,
|
|
`referrerPolicy`, `permissionsPolicy`, `coop`), `hsts: false`; CSP — leave out `csp` (the default);
|
|
X-Powered-By hiding — `withSecurityConfig(config, { hidePoweredBy: false })` or do not call it;
|
|
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 `[iapl] twoFactor…`.
|