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]>
This commit is contained in:
Radosław Smoliński
2026-12-01 10:46:05 +01:00
co-authored by Claude Opus 5.5
parent 97c62f21f0
commit 03f5cf1a8d
19 changed files with 308 additions and 10 deletions
+9 -1
View File
@@ -202,11 +202,19 @@ export const securityRules: DoctorRule[] = [
{
// 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: "serverURL: process.env.NEXT_PUBLIC_SERVER_URL (Payload then trusts that origin only), or csrf: ['https://<site>']", message: 'neither `serverURL` nor `csrf` is set: Payload accepts the login cookie from any origin (a risk when other applications share the domain)', severity: 'warning' }]
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix, message: `neither \`serverURL\` nor \`csrf\` is set: ${why}`, severity: 'warning' }]
},
docs: 'docs/security.md',
group: 'security',
+3 -1
View File
@@ -111,7 +111,9 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
} catch {
staffOnOwnRoles = null
}
return { mail, node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
const { csrf, serverURL } = payload.config as { csrf?: unknown; serverURL?: unknown }
const originKnown = (typeof serverURL === 'string' && serverURL.trim() !== '') || (Array.isArray(csrf) && csrf.some((o) => typeof o === 'string' && o.trim() !== ''))
return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
}
export type DoctorEndpointOptions = {
+5
View File
@@ -99,6 +99,11 @@ export type DoctorStatus = {
node?: string
/** Auth collections whose `create` rule lets an anonymous request through (slugs only). */
openSignUp?: null | string[]
/**
* The running config has a `serverURL` (1.17.2), or a non-empty `csrf` list. Without either Payload takes the
* login cookie from any origin, and the plugin's own-origin checks know the site only from the request's host.
*/
originKnown?: boolean
pendingCookies?: null | number
plugin?: string
/**
+71
View File
@@ -0,0 +1,71 @@
import type { Config, Endpoint, PayloadRequest } from 'payload'
import { COOKIE_APPROVAL_PATH } from '../consent/scanner/approval.js'
import { COOKIE_CRAWL_PATH } from '../consent/scanner/crawl/config.js'
import { COOKIE_SCAN_PATH } from '../consent/scanner/endpoint.js'
import { RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH } from '../email/relay/constants.js'
import { reportRefusedOrigin, requestFromOwnOrigin } from './totp/sameOrigin.js'
/**
* The plugin's panel actions only from the site's own origin (`adminSameOrigin`, 1.17.2; IAWL idea 7, owner's Q6).
*
* These endpoints act with the panel's login cookie and read a body whatever its `Content-Type` says — a
* `text/plain` POST, which another origin can send without a CORS preflight. A page on a sibling subdomain is
* "same site", so the browser sends the `SameSite=Lax` cookie along, and Payload's own CSRF list is empty unless
* `serverURL` or `csrf` is set. Such a page could make a signed-in administrator disconnect the mail service,
* connect it again, send test mails, run cookie scans and crawls, or approve every waiting cookie. The rule is the
* one 2FA verify / setup / reset use (sameOrigin.ts): a request the browser marks as coming from elsewhere
* (`Origin`, else `Sec-Fetch-Site`) gets `403` before anything is read; a request with neither header (a script,
* `curl`) passes — it rides on nobody's cookie. Refusals are logged once per origin with the ways to allow it.
*/
export type AdminSameOriginOption = {
/** More origins that may call these endpoints (a panel on another domain). */
origins?: string[]
} | boolean
/** The panel actions the rule covers: method and path (relative to the API route). */
export const ADMIN_POST_ENDPOINTS: ReadonlyArray<readonly ['post', string]> = [
['post', RELAY_CONNECT_PATH],
['post', RELAY_DISCONNECT_PATH],
['post', '/ipal/test-email'],
['post', COOKIE_SCAN_PATH],
['post', COOKIE_APPROVAL_PATH],
['post', COOKIE_CRAWL_PATH],
]
const ADMIN_REFUSAL = {
docs: 'docs/security.md "Panel actions only from the site\'s own origin"',
option: 'iapl({ adminSameOrigin',
what: 'a panel action',
}
const covered = (endpoint: Pick<Endpoint, 'method' | 'path'>): boolean =>
ADMIN_POST_ENDPOINTS.some(([method, path]) => endpoint.method === method && endpoint.path === path)
/** Wraps one endpoint: `403` for a request from another origin, the endpoint's own answer otherwise. */
export function requireOwnOrigin<T extends Pick<Endpoint, 'handler'>>(endpoint: T, origins: string[] = []): T {
const handler = endpoint.handler as (req: PayloadRequest) => Promise<Response> | Response
return {
...endpoint,
handler: (async (req: PayloadRequest) => {
if (!requestFromOwnOrigin(req as never, origins)) {
reportRefusedOrigin(req as never, origins, ADMIN_REFUSAL)
return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 })
}
return handler(req)
}) as T['handler'],
}
}
/**
* Applies the rule to the covered endpoints the plugin added (`ownEndpoints`: those not in the project's config
* before iapl ran) — a project's own endpoint on the same path is left as it is.
*/
export function guardAdminEndpoints(config: Config, before: ReadonlySet<unknown>, option: AdminSameOriginOption | undefined): Config {
if (option === false) {return config}
const origins = typeof option === 'object' ? (option.origins ?? []) : []
return {
...config,
endpoints: (config.endpoints ?? []).map((e) => (!before.has(e) && covered(e) ? requireOwnOrigin(e, origins) : e)),
}
}
+13 -5
View File
@@ -89,21 +89,29 @@ const MAX_REPORTED = 50
* that origin. Without it a site behind a proxy that hides its address has a panel nobody can
* enter and a silent log. Returns true when a line was written.
*/
export function reportRefusedOrigin(req: RequestLike, extra: string[] = []): boolean {
/** What a refusal line names: the request, the option that allows an origin, and the doc section. Default: 2FA. */
export type RefusalContext = { docs: string; option: string; what: string }
const TWO_FACTOR_REFUSAL: RefusalContext = {
docs: 'docs/security.md "Verify and setup attempts only from the site\'s own origin"',
option: 'twoFactor: { sameOrigin',
what: '2FA: a code',
}
export function reportRefusedOrigin(req: RequestLike, extra: string[] = [], context: RefusalContext = TWO_FACTOR_REFUSAL): boolean {
const origin = req.headers?.get('origin')
const key = origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}`
const key = `${context.option}|${origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}`}`
if (reported.has(key) || reported.size >= MAX_REPORTED) {return false}
reported.add(key)
const { hosts, origins } = ownOrigins(req, extra)
const known = [...origins, ...[...hosts].map((h) => `host ${h}`)].join(', ') || 'none'
const how = originOf(origin)
? `If "${originOf(origin)}" is this site's own address (a reverse proxy that rewrites Host and sends no X-Forwarded-Host), set serverURL to it in the Payload config, ` +
`or pass twoFactor: { sameOrigin: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. `
`or pass ${context.option}: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. `
: 'The browser did not name an origin this site knows. '
req.payload?.logger?.warn(
`[iapl] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` +
`[iapl] ${context.what} from ${origin ? `origin "${origin}"` : `a ${key.split('|')[1]} request`} was refused${context === TWO_FACTOR_REFUSAL ? ' and not counted' : ''} — it is not one of this site's own origins (${known}). ` +
how +
'If it is a foreign page, this is the protection working. twoFactor: { sameOrigin: false } turns the check off (docs/security.md "Verify and setup attempts only from the site\'s own origin"). Said once per origin.',
`If it is a foreign page, this is the protection working. ${context.option}: false } turns the check off (${context.docs}). Said once per origin.`,
)
return true
}
+6
View File
@@ -59,6 +59,12 @@ export function assertPluginSwitches(options: Record<string, unknown>): void {
assertSwitchOrObject(name, options[name])
}
assertBooleanSwitch('indexNow', options.indexNow)
// 1.17.2: `adminSameOrigin: 0` / `'false'` must not read as off (it took the origin check off the panel actions)
assertSwitchOrObject('adminSameOrigin', options.adminSameOrigin)
const adminSameOrigin = bag(options.adminSameOrigin)
if (adminSameOrigin && adminSameOrigin.origins !== undefined && !(Array.isArray(adminSameOrigin.origins) && adminSameOrigin.origins.every((o) => typeof o === 'string'))) {
throw new Error(`${where('adminSameOrigin.origins')} must be a list of origins such as ['https://panel.example.com'] (received ${JSON.stringify(adminSameOrigin.origins)}).`)
}
// an unknown name ('IAPL') used to mean 'ipal': the scanner declared one visitor cookie while the site set another
assertOneOf('storageNames', options.storageNames, ['ipal', 'iapl'])
assertBooleanSwitch('lightbox', options.lightbox)