Files
ipal-kit/docs/security.md
T

17 KiB

security

Generic HTTP security headers (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, Cross-Origin-Opener-Policy; X-Robots-Tag on staging) as a function for next.config. CSP is DELIBERATELY left out — it depends on the project's domains, so it stays in the project.

Rule

Headers that are IDENTICAL across projects are provided once by the plugin. CSP (Content-Security-Policy) needs to know the domains of a specific project (where scripts, images, fonts and analytics load from), so it cannot be generic — it stays in the project and is added through additional.

Usage — next.config.ts

Wire the headers in next.config, NOT in the proxy — they must cover the WHOLE application (including /admin and static files), and the proxy skips those routes.

// next.config.ts
import { withPayload } from '@payloadcms/next/withPayload'
import type { NextConfig } from 'next'
import { buildSecurityHeaders } from '@intecion/ipal-kit'

const securityHeaders = buildSecurityHeaders({
  hsts: process.env.NODE_ENV === 'production',   // IMPORTANT: off in dev (http)
  additional: [
    // the project's CSP — it knows its own domains:
    // { key: 'Content-Security-Policy', value: "default-src 'self'; ..." },
  ],
})

const nextConfig: NextConfig = {
  async headers() {
    return [{ source: '/:path*', headers: securityHeaders }]
  },
}

export default withPayload(nextConfig)

Options

Option Default Role
hsts true Strict-Transport-Security (force HTTPS)
hstsMaxAge 63072000 (2 years) HSTS max-age in seconds
hstsIncludeSubDomains true HSTS on subdomains
hstsPreload false preload (only if you submit to the list)
frameOptions 'DENY' X-Frame-Options (anti-clickjacking); null = no header
referrerPolicy 'strict-origin-when-cross-origin' Referrer-Policy; null = no header
permissionsPolicy blocks camera/mic/geolocation Permissions-Policy; your own string, or null = no header
coop 'same-origin' Cross-Origin-Opener-Policy; 'same-origin-allow-popups', or false = no header
additional [] extra headers (e.g. CSP); the same key overrides

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'.

Overriding and CSP

additional with the same key OVERRIDES the default (e.g. change X-Frame-Options to SAMEORIGIN). A new key (like CSP) is added. CSP always goes through additional — the plugin does not generate it, because it depends on the project.

Why CSP stays in the project (not the plugin)

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 mechanism (additional), and the project supplies a CSP that fits it.

Instead of writing a raw CSP in every project (risk of forgetting base-uri, object-src), use buildCsp — it has hard OWASP/Lighthouse rules built in, and you turn on only the flags for what the project loads:

// next.config.ts
import { buildCsp, buildSecurityHeaders } from '@intecion/ipal-kit'

const csp = buildCsp({
  mode: 'report-only',              // start here; 'enforce' once the console is clean
  r2Url: process.env.R2_PUBLIC_URL, // R2 media → img-src
  turnstile: true,                  // challenges.cloudflare.com → script/frame/connect
  analytics: true,                  // GTM + GA
  youtube: true,                    // youtube → frame-src
  googleMaps: true,                 // Google Maps
  // extra: { 'script-src': ['https://other-script.example'] },  // extra sources
})

const securityHeaders = buildSecurityHeaders({
  hsts: process.env.NODE_ENV === 'production',
  additional: [csp],
})

Hard rules built in (always on, impossible to forget): base-uri 'self', object-src 'none', frame-ancestors 'none'. These are the ones Lighthouse/OWASP require and that are easy to miss when writing CSP by hand.

Base sources: default-src 'self', form-action 'self', script-src 'self' 'unsafe-inline' (Next / analytics), style-src 'self' 'unsafe-inline' https://fonts.googleapis.com. r2Url goes into img-src only as an absolute address (https://…); youtube also adds i.ytimg.com (the YouTubeEmbed poster); googleMaps adds *.googleapis.com, *.gstatic.com, *.google.com, *.ggpht.com, *.googleusercontent.com (iframe and Maps JS).

buildCsp does NOT add 'unsafe-eval' (it weakens CSP) — add it through extra only if a library requires it. mode defaults to 'enforce' (Content-Security-Policy); 'report-only' gives …-Report-Only — start with it when rolling out.

CSP is still "in the project" (you pick the flags for what you load), but the skeleton comes from the plugin — every project has the same hardened foundation.

Building CSP by hand (if you need full control)

Read the media domain from R2_PUBLIC_URL (env), do not hard-code it. Match the other sources to what the project actually loads:

// next.config.ts
const r2Url = process.env.R2_PUBLIC_URL || ''

const csp = [
  "default-src 'self'",
  // scripts: self + Turnstile (Cloudflare) + analytics (GTM/GA if you use them)
  "script-src 'self' 'unsafe-inline' https://challenges.cloudflare.com https://*.googletagmanager.com",
  // styles: self + inline (Tailwind) + Google Fonts
  "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
  // images: self + R2 media (from env!) + data:
  `img-src 'self' data: https://*.google-analytics.com https://*.googletagmanager.com ${r2Url}`.trim(),
  "font-src 'self' https://fonts.gstatic.com data:",
  // GA4: wildcards are required — EU traffic goes to region1.google-analytics.com
  "connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com",
  // frames: Turnstile (captcha widget)
  "frame-src https://challenges.cloudflare.com",
  "form-action 'self'",
  "frame-ancestors 'none'",   // replaces X-Frame-Options in modern browsers
].join('; ')

const securityHeaders = buildSecurityHeaders({
  hsts: process.env.NODE_ENV === 'production',
  additional: [{ key: 'Content-Security-Policy', value: csp }],
})

Match the sources to the project: Google Maps (https://maps.googleapis.com, https://*.google.com), other embeds, other analytics. Anything you do not list will be blocked.

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. Reporting first — use the key Content-Security-Policy-Report-Only (not Content-Security-Policy). The browser REPORTS violations in the console but does NOT block — the site works as usual.
    additional: [{ key: 'Content-Security-Policy-Report-Only', value: csp }]
    
  2. Open the site → DevTools → Console → look for "Content Security Policy" violations. Each violation = a missing domain. Add it to the matching CSP directive.
  3. Go through the whole site — home page, forms (Turnstile!), gallery (R2 images), pages with maps/embeds. Collect every violation.
  4. Only when the console is clean → change the key to Content-Security-Policy (enforcing). Now CSP protects without breaking anything.

Checking headers in production

# check which headers actually go out:
curl -sI https://<DOMAIN>/pl | grep -i "strict-transport\|content-type-options\|referrer\|content-security\|x-frame"

If HSTS/nosniff/Referrer are there but CSP is missing → add CSP (above). 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 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.

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:

// payload.config.ts
ipalKit({
  i18n: i18nConfig,
  adminRoute: '/its',   // panel at /its instead of /admin
})

robots.txt with a hidden panel: the default robots blocks /admin. Do not put /its there — robots.txt is public and would reveal the path (the panel has noindex anyway). In createContentHelpers set robots: { adminRoute: false }.

REQUIRED — move the panel folder in the project

The plugin sets config.routes.admin, but does NOT create files in the project's app/. You must move the panel folder for the path to work:

# BEFORE:
app/(payload)/admin/[[...segments]]/page.tsx
app/(payload)/admin/[[...segments]]/not-found.tsx

# AFTER (folder name = adminRoute without the slash):
app/(payload)/its/[[...segments]]/page.tsx
app/(payload)/its/[[...segments]]/not-found.tsx

Without moving the folder: config.routes.admin = '/its', but /its returns 404 (no file), and /admin does not work either (the config changed). Both must match.

This is OBSCURITY, not SECURITY

Changing the path makes automated scans harder, but it is NOT a safeguard. Real panel protection:

  • 2FA for every user (enforced by the plugin — section below)
  • Strong passwords
  • Rate limiting on login
  • IP allowlist (if the panel is for the team only)
  • buildSecurityHeaders (headers)

/admin → /its is a layer (it filters out dumb bots), not a lock. Treat it as an addition to real safeguards, not a replacement for them.

2FA (TOTP) — ENFORCED for every user

The plugin enforces two-factor authentication (TOTP) for ALL panel users — with no way to turn it off per user. Every project gets it automatically. It uses the proven @clocklimited/payload-2fa (it wraps access control — TOTP is checked before access to DATA, not only the panel UI).

Dependency

pnpm add @clocklimited/[email protected]

Note: the package has no stable 3.0.0 yet — use a specific beta version (or ^3.0.0-0 to allow prereleases). Plain ^3.0.0 fails with ERR_PNPM_NO_MATCHING_VERSION.

Configuration (payload.config.ts) — INJECT the plugin (required in Next)

import { payloadTotp } from '@clocklimited/payload-2fa'

ipalKit({
  i18n: i18nConfig,
  twoFactor: {
    issuer: 'Company Name',   // shown in the authenticator app
    plugin: payloadTotp,      // ← INJECT — see below why
    // collectionSlug: 'users',          // default: the panel login collection (admin.user, else the first auth collection)
    // allowCollectionMismatch: true,    // deliberate only: 2FA on a collection other than admin.user
  },
})

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.

Turning it off (DISCOURAGED)

twoFactor: false   // ONLY when the project really cannot use 2FA (rare)

2FA is ENFORCED by default. false is a deliberate opt-out — avoid it. Leaving out twoFactor (even though the type marks it optional) stops startup with twoFactor.issuer is required — the decision must be explicit.

How it works for the user

  1. Logs in (email + password)
  2. On first login: redirected to TOTP Setup (QR + secret)
  3. Scans the QR with an app (Google Authenticator, Authy, 1Password, Microsoft Authenticator)
  4. Enters the code → 2FA is active
  5. Next logins: email + password + TOTP code

Resetting 2FA (admin)

An admin can reset another user's 2FA (when they lose their phone) — through adminManageAccess in the @clocklimited configuration. ipalKit passes it only collection, forceSetup and issuer; pass other options by wrapping the injected factory: plugin: (opts) => payloadTotp({ ...opts, adminManageAccess: ({ req }) => isAdmin(req.user) }).

Why @clocklimited and not another one

Chosen because it wraps ACCESS CONTROL (TOTP before data access) + forceSetup (enforced for everyone). Other 2FA plugins for Payload only gate /admin navigation — a user with a password can bypass them through REST/GraphQL/Bearer. @clocklimited protects data access, not just the UI.

1.9.1 — security review results

  • Drafts that were never published are no longer publicly available (resolveRoute, Markdown, MCP, metadata), nor on archive lists (getArchiveEntries). Preview: resolveRoute({ draft: true }), getArchiveEntries({ draft: true }) in draftMode().
  • Links from the CMS: only http(s), mailto, tel, sms, #, / (safeHref); javascript: and data: are rejected — also in rich text (RenderRichText replaces them with #).
  • Analytics IDs are validated (in the panel and before being sent to the browser).
  • Form submissions: read editor+; addresses from the Emails tab are not publicly visible.
  • Uploads: buildUploadSecurityHeaders() in next.config.ts (an SVG cannot run a script on the site's domain).
  • users: the plugin injects an auth collection when the project has none (roles and 2FA always attach).

Access control (since the version after 1.12.3)

  • Injected auth collection with roles: a user account reads and edits only itself; only an admin creates and deletes. Before, any logged-in account could change an admin's email/password.
  • 2FA without collectionSlug wraps the panel login collection (admin.user, else the first auth collection), not the literal 'users'. Plugin startup fails with [ipal] twoFactor… when the target is not an auth collection or differs from admin.user — deliberate exception: twoFactor.allowCollectionMismatch: true.
  • Injected auth collection with roles: unlock is admin-only too. You can override all of it: access.authAccess, access.firstUserAdmin: false, globalOverrides, forms.formOverrides.
  • Site settings, Cookie banner, Notifications and the Forms collection: write is editor+ only; a form's Emails tab (recipients, BCC) is readable only by editor+.
  • Full table: access.md.

Turn off, override, extend

  • Turn off: headers — do not call buildSecurityHeaders, or null / false per header (frameOptions, referrerPolicy, permissionsPolicy, coop), hsts: false; 2FA — twoFactor: false (discouraged).
  • Override: additional (the same key overrides the plugin's header), buildCsp({ extra }), mode; 2FA — collectionSlug, allowCollectionMismatch, your own TOTP options by wrapping plugin; access — access.authAccess, access.firstUserAdmin, globalOverrides (access.md).
  • Extend: buildCsp, buildUploadSecurityHeaders({ collections }) for your own upload collections.
  • Check: curl -sI https://domain/ | grep -iE "strict-transport|x-frame|referrer|permissions|cross-origin|content-security"; on staging also x-robots-tag; startup with a wrong twoFactor.collectionSlug fails with [ipal] twoFactor….