Files
ipal-kit/src/modules/doctor/rules/security.ts
T
Radosław SmolińskiandClaude Opus 5.5 03f5cf1a8d Panel actions only from the site's own origin (adminSameOrigin); doctor reads serverURL from the running config
The plugin's panel actions (mail service connect / disconnect, test e-mail,
cookie scan, approval, crawl) act with the panel's login cookie and read a
text/plain body, which another origin sends without a CORS preflight; a
sibling subdomain is same-site and Payload's csrf list is empty without
serverURL. On 1.17.1 such a page reached connect with an admin's cookie
(it called the mail service). Now each refuses a request a browser marks as
coming from elsewhere (403 before anything is read), the rule of the 2FA
endpoints; only endpoints the plugin added; logged once per origin, naming
adminSameOrigin. adminSameOrigin: false / { origins } (owner's Q6).
iapl-doctor csrf-empty: the deep status reports originKnown (serverURL or
csrf in the running config, never the value) and it wins over the file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 10:46:05 +01:00

359 lines
22 KiB
TypeScript

import type { DoctorContext } from '../project.js'
import type { DoctorRule, RuleFinding } from '../types.js'
import { configFile, nextConfigFile } from '../project.js'
import { lt, stripComments } from '../util.js'
const next = (ctx: DoctorContext) => stripComments(ctx.read(nextConfigFile(ctx) ?? ''))
const cfg = (ctx: DoctorContext) => stripComments(ctx.read(configFile(ctx) ?? ''))
const isLocal = (url: string) => /^https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::|\/|$)/i.test(url)
const noindex = (html: string, robotsHeader: null | string) =>
/<meta[^>]+name=["']robots["'][^>]*content=["'][^"']*noindex/i.test(html) || /<meta[^>]+content=["'][^"']*noindex[^>]+name=["']robots["']/i.test(html) || /noindex/i.test(robotsHeader ?? '')
/** Days between two ISO dates. */
const daysBetween = (from: string, to: string) => Math.floor((Date.parse(to) - Date.parse(from)) / 86_400_000)
export const securityRules: DoctorRule[] = [
{
id: 'security-headers',
check: async (ctx) => {
const out: RuleFinding[] = []
const file = nextConfigFile(ctx)
if (!/buildSecurityHeaders\s*\(/.test(next(ctx))) {out.push({ file: file ?? 'next.config.ts', fix: 'headers(): [{ source: "/:path*", headers: buildSecurityHeaders({ csp }) }]', message: 'next.config does not use buildSecurityHeaders', severity: 'error' })}
if (ctx.live) {
const home = await ctx.live.fetch('/')
if (home.status) {
const h = home.headers
const missing = [
...(isLocal(ctx.live.url) || h.get('strict-transport-security') ? [] : ['Strict-Transport-Security']),
...(h.get('x-content-type-options') ? [] : ['X-Content-Type-Options']),
...(h.get('referrer-policy') ? [] : ['Referrer-Policy']),
...(h.get('permissions-policy') ? [] : ['Permissions-Policy']),
...(h.get('x-frame-options') || /frame-ancestors/.test(h.get('content-security-policy') ?? '') ? [] : ['X-Frame-Options / frame-ancestors']),
]
if (missing.length) {out.push({ fix: 'buildSecurityHeaders on /:path* (security.md)', message: `live / lacks ${missing.join(', ')}`, severity: 'error' })}
}
}
return out
},
docs: 'docs/security.md',
group: 'security',
source: 'static',
},
{
id: 'powered-by',
check: async (ctx) => {
const out: RuleFinding[] = []
if (!/withSecurityConfig\s*\(|poweredByHeader\s*:\s*false/.test(next(ctx))) {
out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: 'export default withSecurityConfig(withPayload(nextConfig))', message: 'X-Powered-By is not hidden (withSecurityConfig)', severity: 'error' })
}
if (ctx.live) {
for (const path of ['/', `${ctx.live.adminRoute}/login`]) {
const res = await ctx.live.fetch(path)
const value = res.headers.get('x-powered-by')
if (value) {out.push({ fix: 'withSecurityConfig (security.md → X-Powered-By)', message: `live ${path} sends X-Powered-By: ${value}`, severity: 'error' })}
}
}
return out
},
docs: 'docs/security.md',
group: 'security',
source: 'static',
},
{
// A matcher whose lookahead names api / admin / _next without ending them at "/" also skips every page whose
// first segment merely STARTS with those letters (/administracja, /apis): no locale redirect, and no CSP from the
// proxy on a single-locale site (IAWL idea 36, fixed in the documented literal in 1.17.1).
id: 'proxy-matcher',
check: (ctx) => {
const file = `${ctx.src}proxy.ts`
const code = stripComments(ctx.read(file))
const loose = [...code.matchAll(/\(\?!((?:[\w-]+\|)*[\w-]+)\|/g)].map((m) => m[1].split('|')).find((names) => names.some((n) => ['_next', 'admin', 'api'].includes(n)))
if (!loose) {return []}
return [{
file,
fix: "matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\\\..*).*)'] (i18n.md → Next matcher)",
message: `the proxy matcher skips every path that starts with ${loose.map((n) => `"${n}"`).join(', ')} (e.g. /${loose.includes('admin') ? 'administracja' : `${loose[0]}s`}), not only those folders: no locale redirect, no proxy CSP there`,
severity: 'warning',
}]
},
docs: 'docs/i18n.md',
group: 'security',
source: 'static',
},
{
id: 'client-hints',
check: async (ctx) => {
const out: RuleFinding[] = []
const code = next(ctx)
const kept = /adminClientHints\s*:\s*false/.test(code)
if (!kept && /withPayload\s*\(\s*withSecurityConfig\s*\(/.test(code)) {
out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: 'export default withSecurityConfig(withPayload(nextConfig))', message: "withSecurityConfig is inside withPayload: Payload's colour-scheme client hints go out with every page (Chrome repeats the first request of a visit)", severity: 'info' })
}
if (ctx.live && !kept) {
const res = await ctx.live.fetch('/')
if (/sec-ch-prefers-color-scheme/i.test(res.headers.get('critical-ch') ?? '')) {
out.push({ fix: 'withSecurityConfig(withPayload(nextConfig)) (security.md → Client hints)', message: 'live / sends Critical-CH: Sec-CH-Prefers-Color-Scheme (only the admin needs it)', severity: 'info' })
}
}
return out
},
docs: 'docs/security.md',
group: 'security',
source: 'static',
},
{
id: 'csp',
check: async (ctx) => {
const code = next(ctx) + stripComments(ctx.read(`${ctx.src}proxy.ts`))
if (!/\bcsp\s*[:,}]|buildCsp|Content-Security-Policy/i.test(code)) {
return [{ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: "buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report' } }) + buildAdminCspHeaders on /admin/:path*", message: 'no Content-Security-Policy', severity: 'warning' }]
}
const out: RuleFinding[] = []
if (!/buildAdminCspHeaders\s*\(/.test(code)) {out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: "{ source: '/admin/:path*', headers: buildAdminCspHeaders(csp) }", message: 'no CSP for the admin (buildAdminCspHeaders)', severity: 'warning' })}
let reportOnly = /mode\s*:\s*['"]report-only['"]/.test(code) || !/mode\s*:\s*['"]enforce['"]/.test(code)
if (ctx.live) {
for (const path of ['/', `${ctx.live.adminRoute}/login`]) {
const h = (await ctx.live.fetch(path)).headers
if (h.get('content-security-policy')) {
if (path === '/') {reportOnly = false}
} else if (h.get('content-security-policy-report-only')) {
reportOnly = true
} else {
out.push({ fix: 'security.md → ROLL OUT CSP', message: `live ${path} has no CSP header`, severity: 'warning' })
}
}
}
if (reportOnly) {
const seen = ctx.config.seen?.['csp-report-only'] ?? ctx.today
const days = daysBetween(seen, ctx.today)
out.push({
fix: "switch to mode: 'enforce' once the reports are clean (security.md → ROLL OUT CSP)",
message: `CSP is report-only (since ${seen}${days ? `, ${days} days` : ''})`,
severity: days >= 28 ? 'warning' : 'info',
})
}
return out
},
docs: 'docs/security.md',
group: 'security',
source: 'static',
},
{
id: '2fa',
check: (ctx) => {
const out: RuleFinding[] = []
const code = cfg(ctx)
const twoFactor = code.match(/twoFactor\s*:([^\n]*)/)?.[1] ?? ''
if (/\?\s*false\b|:\s*false\b|&&/.test(twoFactor) && /payloadTotp/.test(twoFactor)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor: { issuer, plugin: payloadTotp } without a switch', message: '2FA can be turned off at runtime (a condition on twoFactor)', severity: 'warning' })}
if (!/twoFactor\s*:[^\n]*payloadTotp|twoFactor\s*:\s*\{[\s\S]*?plugin\s*:\s*payloadTotp/.test(code)) {out.push({ file: configFile(ctx) ?? 'payload.config.ts', fix: "iapl({ twoFactor: { issuer: '<site>', plugin: payloadTotp } })", message: '2FA is not on (twoFactor with plugin: payloadTotp)', severity: 'error' })}
else if (!ctx.installed('@clocklimited/payload-2fa')) {out.push({ fix: 'pnpm add @clocklimited/payload-2fa', message: '@clocklimited/payload-2fa is not installed', severity: 'error' })}
if (/requireSetup\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'remove twoFactor.requireSetup: false (or record the reason in iapl-doctor.json)', message: 'twoFactor.requireSetup is off: an account that has not set 2FA up opens everything with its password alone', severity: 'warning' })}
if (/windowHours\s*:\s*(?:false|0)\b/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor.requireSetup.windowHours: 72 (the default)', message: 'no time limit for 2FA setup: an account that never sets it up can be taken over with its password at any time', severity: 'info' })}
// Postgres / SQLite: the 2FA collection has the column `totp_setup_from` (whenever 2FA is on). Without a
// migration that adds it, every query on the collection fails in production — nobody can log in.
const sqlAdapter = ['@payloadcms/db-postgres', '@payloadcms/db-vercel-postgres', '@payloadcms/db-sqlite', '@payloadcms/db-d1-sqlite'].some((name) => ctx.installed(name))
const pluginHasColumn = /totpSetupFrom/.test(ctx.read('node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js'))
if (sqlAdapter && pluginHasColumn && /payloadTotp/.test(code)) {
const dirs = [`${ctx.src}migrations`, 'migrations'].filter((dir) => ctx.exists(dir))
const files = dirs.flatMap((dir) => ctx.list(dir).filter((name) => /\.(?:ts|js|mjs|sql|json)$/.test(name)).map((name) => `${dir}/${name}`))
if (!files.some((file) => /totp_setup_from|totpSetupFrom/.test(ctx.read(file)))) {
out.push({
fix: 'pnpm payload migrate:create, commit the migration, and have it applied when the new container starts — prodMigrations in the adapter, or the start command `pnpm payload migrate && pnpm start`; not a pre-deployment command (docs/deployment.md §4.3) — in the same deploy, before the new version serves requests',
message: files.length
? 'no migration adds the 2FA column `totp_setup_from`: in production every login would answer 500 — nobody could sign in to the panel'
: 'a SQL database and no migrations folder: the 2FA column `totp_setup_from` must exist before this version runs in production (migrate:create; applied at container start — docs/deployment.md §4.3), or nobody can sign in',
severity: files.length ? 'error' : 'warning',
})
}
}
if (ctx.deep?.usersWithout2fa) {
const closed = ctx.deep.usersSetupClosed ?? 0
out.push({
fix: closed
? 'each of them signs in and sets up TOTP; for the blocked ones an admin opens the account in the panel → "Reopen setup" (or removes the account)'
: 'each of them signs in and sets up TOTP now; remove accounts nobody uses',
message: `${ctx.deep.usersWithout2fa} panel user(s) without TOTP${closed ? ` (${closed} blocked: the setup window has passed)` : ''}`,
severity: 'error',
})
}
return out
},
docs: 'docs/security.md#2fa-totp--enforced-for-every-user',
group: 'security',
source: 'static',
},
{
// Without `access` the plugin adds no roles: every account that can log in to the panel is an admin.
id: 'access-missing',
check: (ctx) => {
const code = cfg(ctx)
if (!/\b(?:iapl|ipalKit)\s*\(/.test(code)) {return []}
// `access: { authCollection | defaultRole | … }`, an empty `access: {}`, or a variable whose name says so
const set = /\baccess\s*:\s*\{\}/.test(code.replace(/\s+/g, '')) || /\baccess\s*:\s*\{[^{}]*\b(?:authCollection|defaultRole|authAccess|firstUserAdmin|staffCollections|panelRole|selfRegistration|password)\b/.test(code) || /\baccess\s*:\s*\w*[aA]ccess\w*\s*[,}]/.test(code)
return set
? []
: [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "iapl({ access: { authCollection: 'users' } }) — roles admin > editor > user; or record the reason in iapl-doctor.json", message: 'iapl has no `access` option: there are no roles, so every account that can log in to the panel is an admin', severity: 'warning' }]
},
docs: 'docs/access.md',
group: 'security',
source: 'static',
},
{
// Payload accepts the login cookie from ANY origin while its `csrf` list is empty — and it is empty
// unless `csrf` or `serverURL` is set. A page on a sibling subdomain can then act with a panel user's cookie.
// The plugin's own-origin checks (2FA verify / setup / reset, the panel actions — 1.17.2) then know the site
// only from the request's Host: behind a proxy that rewrites it, the site's own panel would be refused.
id: 'csrf-empty',
check: (ctx) => {
const fix = "serverURL: process.env.NEXT_PUBLIC_SERVER_URL (Payload then trusts that origin only; the plugin's own-origin checks know the site's address), or csrf: ['https://<site>']"
const why = 'Payload accepts the login cookie from any origin (a risk when other applications share the domain), and behind a proxy that rewrites Host the plugin cannot tell the panel\'s own requests (2FA, panel actions) from foreign ones'
// deep (the running config) wins over reading the file: serverURL may come from a spread or a helper
if (ctx.deep && typeof ctx.deep.originKnown === 'boolean') {
return ctx.deep.originKnown ? [] : [{ fix, message: `the running config has neither \`serverURL\` nor \`csrf\`: ${why}`, severity: 'warning' }]
}
const code = cfg(ctx)
if (!/buildConfig\s*\(/.test(code) || /\bcsrf\s*:/.test(code) || /\bserverURL\s*:/.test(code)) {return []}
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix, message: `neither \`serverURL\` nor \`csrf\` is set: ${why}`, severity: 'warning' }]
},
docs: 'docs/security.md',
group: 'security',
source: 'static',
},
{
// An auth collection anyone can register in. Often exactly what the project wants (customers) — said, not judged.
id: 'open-signup',
check: (ctx) =>
(ctx.deep?.openSignUp ?? []).map((slug) => ({
fix: `intended (a customer zone)? silence it with a reason in iapl-doctor.json; otherwise give "${slug}" a create rule`,
message: `sign-up is open on "${slug}": an anonymous request can create an account there`,
severity: 'info' as const,
})),
docs: 'docs/access.md',
group: 'security',
source: 'deep',
},
{
// A staff collection that an account of another auth collection (a customer, a member) may write to:
// it can create a staff account, or change a staff account's password. The plugin's default rules close
// it (accounts.adminOnlyCreate / adminOnlyWrite); this fires when they are off or a project's own rule is wider.
id: 'staff-accounts-open',
check: (ctx) =>
(ctx.deep?.staffOpenToOthers ?? []).map((entry) => {
const [slug, operation] = entry.split(':')
const what: Record<string, string> = {
create: ': it can make itself a staff account',
read: ': it can list the staff accounts (addresses, roles)',
readVersions: ': it can read the versions of staff accounts (addresses, roles)',
unlock: ': it can lift the lock after failed logins, which helps guessing a password',
update: ": it can change a staff account's password",
}
const reads = operation === 'read' || operation === 'readVersions'
const option = operation === 'create' ? 'adminOnlyCreate' : reads ? 'staffOnlyRead' : 'adminOnlyWrite'
return {
fix: `give "${slug}" an access.${operation} rule that asks for a staff account (staffCreateAccess, staffUpdateAccess('${slug}'), staffReadAccess, adminOrSelfIn('${slug}')), or drop accounts: false / accounts.${option}: false`,
message: `an account of another auth collection may ${operation} in the staff collection "${slug}"${what[operation] ?? ''}`,
severity: reads ? ('warning' as const) : ('error' as const),
}
}),
docs: 'docs/access.md',
group: 'security',
source: 'deep',
},
{
// A staff collection with role values of its own on the plugin's default rules: the plugin cannot rank
// those roles, so inside the collection every account may create an account with any role.
id: 'staff-own-roles',
check: (ctx) =>
(ctx.deep?.staffOnOwnRoles ?? []).map((slug) => ({
fix: `write "${slug}"'s own access.create / update / delete rules (and field access on its roles field) from its own roles`,
message: `the staff collection "${slug}" has role values of its own and no access rules: accounts of other collections are kept out, but inside it every account may create, change and delete accounts, with any role`,
severity: 'warning' as const,
})),
docs: 'docs/access.md',
group: 'security',
source: 'deep',
},
{
// Turnstile lets submissions through while it is misconfigured or Cloudflare fails ("degraded") — visible here.
id: 'turnstile-degraded',
check: (ctx) => {
const status = ctx.deep?.turnstile
if (!status || status.state !== 'degraded') {return []}
// "Now": the clock when the run is for today; for another date (a test, a replay) the middle of that day.
// Not the END of the day: a state that began at 23:59 would be "a day old" a minute later.
const now = ctx.today === new Date().toISOString().slice(0, 10) ? Date.now() : Date.parse(`${ctx.today}T12:00:00Z`)
const hours = status.since ? Math.floor((now - Date.parse(status.since)) / 3_600_000) : null
const long = hours !== null && hours >= 24
return [{
fix: 'Site integrations → Spam protection: both keys from the same Cloudflare widget; then send a test form',
message: `Turnstile is not checking forms (${status.code ?? 'unknown'})${status.since ? `, since ${status.since.slice(0, 16).replace('T', ' ')}` : ''}: text forms are accepted without the check and forms with files are refused (unless forms.turnstileOnConfigError says otherwise)`,
severity: long ? 'error' : 'warning',
}]
},
docs: 'docs/turnstile.md',
group: 'security',
source: 'deep',
},
{
// The secret key from the environment is deprecated: the panel is its source.
id: 'turnstile-env-key',
check: (ctx) =>
ctx.deep?.turnstileSecretFromEnv
? [{ fix: 'copy the key into Site integrations → Spam protection → Secret key, check a form, then remove TURNSTILE_SECRET_KEY from the environment (Coolify)', message: 'the Turnstile secret key comes from the TURNSTILE_SECRET_KEY environment variable (deprecated; it will be removed in a later release)', severity: 'warning' }]
: [],
docs: 'docs/turnstile.md',
group: 'security',
source: 'deep',
},
{
id: 'cookie-scanner',
check: (ctx) => {
const code = cfg(ctx)
if (!/cookieScanner\s*:/.test(code) || /cookieScanner\s*:\s*false/.test(code)) {
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: 'iapl({ cookieScanner: { crawl: true } }) + generate:importmap', message: 'the cookie scanner is off', severity: 'error' }]
}
const out: RuleFinding[] = []
if (!/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(code)) {out.push({ fix: 'cookieScanner: { crawl: true } (shared cookie-crawler service)', message: 'cookie scanner without crawl — no scheduled site check', severity: 'info' })}
if (ctx.deep?.pendingCookies) {out.push({ fix: 'Privacy → Cookies → Review and approve → Approve and add', message: `${ctx.deep.pendingCookies} cookie(s) wait for approval`, severity: 'warning' })}
return out
},
docs: 'docs/cookie-scanner.md',
group: 'security',
source: 'static',
},
{
id: 'admin-meta',
check: async (ctx) => {
const out: RuleFinding[] = []
const code = cfg(ctx)
if (lt(ctx.pluginVersion, '1.14.5')) {out.push({ message: `admin link previews (adminMeta) need IAPL ≥ 1.14.5 (installed ${ctx.pluginVersion ?? 'none'})`, severity: 'warning' })}
if (/adminMeta\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, message: 'adminMeta: false — the panel has no link preview and no noindex from the plugin', severity: 'warning' })}
if (/agency\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, message: 'agency: false — no technology credit', severity: 'warning' })}
if (ctx.live && !out.length) {
const res = await ctx.live.fetch(`${ctx.live.adminRoute}/login`)
if (res.status && res.status < 400 && !/\/api\/ipal\/admin-og/.test(res.text)) {out.push({ fix: 'adminMeta on (default) and generate:importmap', message: 'the live admin has no ipal link preview (og:image /api/ipal/admin-og)', severity: 'warning' })}
}
return out
},
docs: 'docs/white-label.md',
group: 'admin',
source: 'static',
},
{
id: 'admin-noindex',
check: async (ctx) => {
if (!ctx.live) {return []}
const path = `${ctx.live.adminRoute}/login`
const res = await ctx.live.fetch(path)
if (!res.status || res.status >= 400) {return [{ message: `live ${path} → ${res.status || res.error}`, severity: 'warning' }]}
return noindex(res.text, res.headers.get('x-robots-tag')) ? [] : [{ fix: 'adminMeta robots (default noindex, nofollow)', message: `live ${path} is not noindex`, severity: 'error' }]
},
docs: 'docs/white-label.md',
group: 'admin',
source: 'live',
},
]
export { noindex }