Security audit fixes for 1.18.0: Markdown negotiation private + Vary: Accept (F3), public lists capped (F4), operator sort names refused (F5), CSP report log normalised and capped (F1), buildUrlField and the reference socials (F2), document locks for staff only

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 16:56:09 +01:00
co-authored by Claude Opus 5.5
parent d2f19095dc
commit e9f9947eb7
20 changed files with 677 additions and 49 deletions
+10 -5
View File
@@ -4,6 +4,7 @@ import type { PathVisibility } from '../construction/visibility.js'
import type { ContentOption } from './types.js'
import { blocksToMarkdown } from './blocksToMarkdown.js'
import { MARKDOWN_NEGOTIATED_HEADER, NEGOTIATED_CACHE_CONTROL } from './markdownNegotiation.js'
import { resolveRoute } from './resolveRoute.js'
type CreateMarkdownRendererArgs = {
@@ -126,9 +127,11 @@ export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) {
* Wraps a Markdown string in a `text/markdown` Response, or a 404 when null.
* Uses the global Response — no next/server import.
*/
export function markdownResponse(md: null | string, options: { canonical?: string } = {}): Response {
export function markdownResponse(md: null | string, options: { canonical?: string; negotiated?: boolean } = {}): Response {
// Negotiated at an HTML URL (the proxy's marker): never stored by a shared cache as that page (audit F3).
const negotiatedHeaders: Record<string, string> = options.negotiated ? { 'cache-control': NEGOTIATED_CACHE_CONTROL, vary: 'Accept' } : {}
if (md == null) {
return new Response('Not found', { headers: { 'content-type': 'text/plain' }, status: 404 })
return new Response('Not found', { headers: { 'content-type': 'text/plain', ...negotiatedHeaders }, status: 404 })
}
return new Response(md, {
headers: {
@@ -138,6 +141,7 @@ export function markdownResponse(md: null | string, options: { canonical?: strin
// index it as a duplicate — and should credit the HTML page instead.
'x-robots-tag': 'noindex',
...(options.canonical ? { link: `<${options.canonical}>; rel="canonical"` } : {}),
...negotiatedHeaders,
},
status: 200,
})
@@ -197,16 +201,17 @@ export function createMarkdownRoute(
const { getCachedPayload, isPathVisible, ...rendererArgs } = args
const render = createMarkdownRenderer(rendererArgs)
return {
GET: async (_req, { params }) => {
GET: async (req, { params }) => {
const negotiated = req.headers?.get(MARKDOWN_NEGOTIATED_HEADER) === '1'
try {
const { slug, locale } = routeOf(await params, rendererArgs.config)
if (isPathVisible) {
const multilingual = (rendererArgs.config?.locales.length ?? 0) > 1
const path = `/${[...(multilingual ? [locale] : []), ...(slug ?? [])].join('/')}`
if (!(await isPathVisible(path, locale))) {return markdownResponse(null, {})}
if (!(await isPathVisible(path, locale))) {return markdownResponse(null, { negotiated })}
}
const md = await render({ slug, locale, payload: await getCachedPayload() })
return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) })
return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug), negotiated })
} catch (err) {
console.warn('[iapl] createMarkdownRoute: render failed:', err)
return new Response('Service unavailable', { headers: { 'content-type': 'text/plain' }, status: 503 })
+1 -1
View File
@@ -5,7 +5,7 @@ export { createSearchRoute } from './createSearchRoute.js'
export { applyDraftRelations, type DraftRelations, withoutDraftRelations } from './draftRelations.js'
export { getArchiveEntries } from './getArchiveEntries.js'
export type { ArchiveEntries } from './getArchiveEntries.js'
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'
export { appendVary, MARKDOWN_NEGOTIATED_HEADER, MARKDOWN_PREFIX, markdownHref, NEGOTIATED_CACHE_CONTROL, prefersMarkdown } from './markdownNegotiation.js'
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'
export { resolveNotFoundPage } from './resolveNotFoundPage.js'
export { resolveRedirect } from './resolveRedirect.js'
@@ -13,6 +13,24 @@
/** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */
export const MARKDOWN_PREFIX = '/md'
/**
* Request header the proxy sets when it rewrites an HTML URL to the Markdown route (content negotiation). The route
* then answers {@link NEGOTIATED_CACHE_CONTROL} with `Vary: Accept`: the answer shares the page's URL, so no shared
* cache may store it (security audit 2026-12, F3). A client sending it itself only makes its own answer private.
*/
export const MARKDOWN_NEGOTIATED_HEADER = 'x-iapl-markdown-negotiated'
/** Cache-Control of a Markdown answer given at an HTML URL. */
export const NEGOTIATED_CACHE_CONTROL = 'private, no-store'
/** Adds a token to `Vary` once (case-insensitive), keeping what is there. */
export function appendVary(headers: Headers | undefined, token: string): void {
if (!headers) {return}
const current = (headers.get('vary') ?? '').split(',').map((v) => v.trim()).filter(Boolean)
if (current.some((v) => v === '*' || v.toLowerCase() === token.toLowerCase())) {return}
headers.set('vary', [...current, token].join(', '))
}
/**
* The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so
* the discovery link and the route agree.
+25 -6
View File
@@ -1,7 +1,7 @@
import type { BuildCspArgs } from '../security/buildCsp.js'
import type { I18nConfig } from './types.js'
import { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from '../content/markdownNegotiation.js'
import { appendVary, MARKDOWN_NEGOTIATED_HEADER, MARKDOWN_PREFIX, markdownHref, NEGOTIATED_CACHE_CONTROL, prefersMarkdown } from '../content/markdownNegotiation.js'
import { buildCsp, buildReportingEndpoints } from '../security/buildCsp.js'
import { createCspNonce, CSP_NONCE_HEADER } from '../security/cspNonce.js'
import { isValidLocale } from './helpers.js'
@@ -38,7 +38,7 @@ type NextResponseLike = {
next: (init?: { request?: { headers: Headers } }) => ProxyResponse
redirect: (url: string | URL) => ProxyResponse
/** Needed for `markdown` content negotiation; Next's NextResponse has it. */
rewrite?: (url: string | URL) => ProxyResponse
rewrite?: (url: string | URL, init?: { request?: { headers: Headers } }) => ProxyResponse
}
type CreateProxyOptions = {
@@ -62,8 +62,13 @@ type CreateProxyOptions = {
* sets another one. Paths under the prefix pass through untouched (no locale
* redirect — /md/pl/o-nas must not become /pl/md/pl/o-nas), and a page
* requested with `Accept: text/markdown` is rewritten to its Markdown version.
*
* The negotiated answer shares the page's URL, so it is sent `private, no-store` with `Vary: Accept` (and the
* pages under the matcher get `Vary: Accept`): a cache in front never stores the Markdown as the page (security
* audit 2026-12, F3). `/md/…` itself keeps its public caching. The object form adapts it:
* `{ prefix?: string, negotiate?: boolean }` — `negotiate: false` serves Markdown only at `/md/…`.
*/
markdown?: boolean | string
markdown?: { negotiate?: boolean; prefix?: string } | boolean | string
/** Consent policy version to require for saving the locale cookie (createLocaleMiddleware). */
policyVersion?: number
}
@@ -89,7 +94,11 @@ export function createProxy(
): (request: ProxyRequest) => ProxyResponse {
const { csp, exposeHeaders = true, markdown, NextResponse, ...mwOptions } = deps
const run = createLocaleMiddleware({ config, ...mwOptions })
const mdPrefix = markdown ? (typeof markdown === 'string' ? markdown : MARKDOWN_PREFIX).replace(/\/$/, '') : null
const mdOptions = typeof markdown === 'object' && markdown ? markdown : {}
const mdPrefix = markdown
? (typeof markdown === 'string' ? markdown : (mdOptions.prefix ?? MARKDOWN_PREFIX)).replace(/\/$/, '')
: null
const negotiate = Boolean(mdPrefix) && mdOptions.negotiate !== false
return (request: ProxyRequest): ProxyResponse => {
const { pathname } = request.nextUrl
@@ -99,8 +108,15 @@ export function createProxy(
// Markdown route; the rest gets the locale redirect first, then negotiates.
const seg = pathname.split('/').filter(Boolean)[0] ?? ''
const routable = config.locales.length === 1 || isValidLocale(seg, config)
if (routable && NextResponse.rewrite && prefersMarkdown(request.headers)) {
return NextResponse.rewrite(new URL(markdownHref(pathname, mdPrefix), request.url))
if (negotiate && routable && NextResponse.rewrite && prefersMarkdown(request.headers)) {
// The route reads the marker and answers private + Vary: Accept; the same headers on the rewrite itself
// for a route that is not the plugin's (security audit 2026-12, F3).
const mdHeaders = new Headers(request.headers)
mdHeaders.set(MARKDOWN_NEGOTIATED_HEADER, '1')
const rewritten = NextResponse.rewrite(new URL(markdownHref(pathname, mdPrefix), request.url), { request: { headers: mdHeaders } })
rewritten.headers?.set('cache-control', NEGOTIATED_CACHE_CONTROL)
appendVary(rewritten.headers, 'Accept')
return rewritten
}
}
@@ -133,6 +149,9 @@ export function createProxy(
}
}
// The same URL answers HTML or (negotiated) Markdown: say so to any cache in front.
if (negotiate && result.type !== 'redirect') {appendVary(response.headers, 'Accept')}
if (result.cookie) {
response.cookies.set(result.cookie.name, result.cookie.value, {
path: '/',
+74
View File
@@ -0,0 +1,74 @@
import type { TextField } from 'payload'
import type { AdminText } from '../admin-i18n/define.js'
import { safeHref } from './resolveLinkHref.js'
/** Schemes {@link buildUrlField} may allow besides `https:` / `http:`. */
export type UrlScheme = 'hash' | 'mailto' | 'relative' | 'sms' | 'tel'
export type BuildUrlFieldOptions = {
/** Help under the field. Default: what the field accepts. */
description?: AdminText | string
/** Panel label. Default "Address". */
label?: AdminText | string
/** Field name. Default `url`. */
name?: string
/** Anything else of Payload's text field (admin, access, hooks, localized…); wins over the defaults. */
overrides?: Partial<Omit<TextField, 'type'>>
required?: boolean
/**
* Besides `https://` and `http://`: `mailto:`, `tel:`, `sms:`, `#section`, `/a/path` on this site.
* Default none — a profile or a website. `javascript:`, `data:`, `vbscript:` and `//host` never pass.
*/
schemes?: readonly UrlScheme[]
}
const ALLOWED: Record<UrlScheme, RegExp> = {
hash: /^#/,
mailto: /^mailto:/i,
relative: /^\/(?!\/)/,
sms: /^sms:/i,
tel: /^tel:/i,
}
/** True when `value` is an address the field accepts: safe as an `href` ({@link safeHref}) and of an allowed kind. */
export function isAllowedUrl(value: null | string | undefined, schemes: readonly UrlScheme[] = []): boolean {
const safe = safeHref(value)
if (!safe) {return false}
if (/^https?:\/\/[^\s/?#]+/i.test(safe)) {return true}
return schemes.some((s) => ALLOWED[s].test(safe))
}
/**
* A text field for an address that is rendered into `href` (a profile, a website, a map link): it accepts
* `https://…` (and the schemes you list) and refuses `javascript:`, `data:` and other addresses that would run script
* when clicked (security audit 2026-12, F2). Render the stored value with `safeHref()` as well: data can come from an
* import, a seed or an older version.
*
* fields: [{ name: 'label', type: 'text' }, buildUrlField({ required: true })]
*/
export function buildUrlField(options: BuildUrlFieldOptions = {}): TextField {
const { name = 'url', description, label, overrides = {}, required, schemes = [] } = options
const { admin, ...rest } = overrides
const pl = (req?: { i18n?: { language?: string } }) => req?.i18n?.language === 'pl'
return {
name,
type: 'text',
label: label ?? { en: 'Address', pl: 'Adres' },
required,
validate: (v: null | string | undefined, { req }: { req?: { i18n?: { language?: string } } } = {}) => {
if (!v) {return required ? (pl(req) ? 'To pole jest wymagane.' : 'This field is required.') : true}
return isAllowedUrl(v, schemes) || (pl(req) ? 'Wpisz pełny adres, np. https://example.com.' : 'Enter a full address, e.g. https://example.com.')
},
...rest,
admin: {
description:
description ??
(schemes.length
? { en: 'A full address (https://…) or one of the other kinds this field allows.', pl: 'Pełny adres (https://…) albo inny rodzaj, na który pozwala to pole.' }
: { en: 'A full address, e.g. https://example.com', pl: 'Pełny adres, np. https://example.com' }),
...admin,
},
} as TextField
}
+2
View File
@@ -1,5 +1,7 @@
export { buildLinkField, buildLinksField } from './buildLinkField.js'
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance, LinkAppearanceOption } from './buildLinkField.js'
export { buildUrlField, isAllowedUrl } from './buildUrlField.js'
export type { BuildUrlFieldOptions, UrlScheme } from './buildUrlField.js'
export { resolveLinkHref, safeHref } from './resolveLinkHref.js'
export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'
export { homeSlugFrom, resolveLink, resolveNav, resolveSystemLinks } from './resolveNav.js'
+3 -6
View File
@@ -161,7 +161,6 @@ export const ATTACK_PROBES: AttackProbe[] = [
{
id: 'markdown-vary',
class: 'cache poisoning (content negotiation)',
finding: 'F3',
live: true,
run: async ({ fetch, page = '/' }) => {
const a = await fetch(page, { follow: true, headers: { accept: 'text/markdown' } })
@@ -169,7 +168,7 @@ export const ATTACK_PROBES: AttackProbe[] = [
const cc = a.headers.get('cache-control') ?? ''
const shared = /s-maxage|public/.test(cc) && !/private|no-store/.test(cc)
const vary = (a.headers.get('vary') ?? '').split(',').map((v) => v.trim().toLowerCase())
if (shared && !vary.includes('accept') && !vary.includes('*')) {return bad(`${page} answers Markdown to Accept: text/markdown with "${cc}" and no Vary: Accept: a shared cache stores it under the HTML URL`)}
if (shared && !vary.includes('accept') && !vary.includes('*')) {return bad(`${page} answers Markdown to Accept: text/markdown with "${cc}" and no Vary: Accept: a shared cache stores it under the HTML URL (IAPL 1.18.0's createProxy sends private + Vary: Accept; a proxy of your own must too)`)}
return ok('the Markdown answer at the HTML URL varies by Accept or is not shared')
},
title: 'the Markdown copy at an HTML URL cannot be cached as the page',
@@ -260,7 +259,6 @@ export const ATTACK_PROBES: AttackProbe[] = [
{
id: 'sort-operator',
class: 'injection (operators in sort)',
finding: 'F5',
live: true,
run: async ({ fetch }) => {
const problems: string[] = []
@@ -268,14 +266,13 @@ export const ATTACK_PROBES: AttackProbe[] = [
const a = await fetch(`/api/pages?sort=${sort}&limit=1&depth=0`)
if (a.status >= 500 || LEAK.test(a.text)) {problems.push(`sort=${decodeURIComponent(sort)} → ${a.status}`)}
}
return problems.length ? bad(`${problems.join('; ')}: an operator name reaches the database as a sort field (an error and a logged stack trace per request)`) : ok('operator names in sort are refused with a 4xx')
return problems.length ? bad(`${problems.join('; ')}: an operator name reaches the database as a sort field (an error and a logged stack trace per request; IAPL 1.18.0 refuses it unless refuseOperatorSort is false)`) : ok('operator names in sort are refused with a 4xx')
},
title: 'an operator name in ?sort= is refused, not passed to the database',
},
{
id: 'unbounded-list',
class: 'denial of service (unbounded queries)',
finding: 'F4',
live: true,
run: async ({ fetch }) => {
const a = await fetch('/api/pages?limit=100000&depth=50')
@@ -286,7 +283,7 @@ export const ATTACK_PROBES: AttackProbe[] = [
} catch {
return skip('not JSON')
}
return (body.limit ?? 0) > 1000 ? bad(`/api/pages?limit=100000 is honoured (limit ${body.limit}, ${a.ms} ms, ${a.text.length} bytes): one anonymous request reads a whole collection`) : ok(`limit capped at ${body.limit}`)
return (body.limit ?? 0) > 1000 ? bad(`/api/pages?limit=100000 is honoured (limit ${body.limit}, ${a.ms} ms, ${a.text.length} bytes): one anonymous request reads a whole collection (IAPL 1.18.0 caps it unless listLimit is false or the collection is excluded)`) : ok(`limit capped at ${body.limit}`)
},
title: 'a public list caps limit (and depth) so one request cannot read a whole collection',
},
+79 -6
View File
@@ -1,3 +1,4 @@
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { readCappedBody } from '../shared/readCappedBody.js'
/** One CSP violation, normalised from either report format. */
@@ -15,12 +16,79 @@ export type CspViolation = {
export type CreateCspReportRouteArgs = {
/** Largest accepted body in bytes; bigger requests get 413. Default 16 KB. */
maxBytes?: number
/** Most violations handled from one request (a body may hold many). Default 10; the rest are dropped. */
maxReports?: number
/**
* What to do with each violation. Default: one `console.warn` line per
* violation (Coolify keeps container logs — read them there). Plug in
* payload.logger, Sentry or a database write here.
* violation (Coolify keeps container logs — read them there), made by
* {@link cspLogLine}: origins and paths only, no control characters, every value
* capped — a report cannot write a line of its own into the log. Your own
* `onReport` gets the values exactly as the browser sent them: escape them
* before you log them. Plug in payload.logger, Sentry or a database write here.
*/
onReport?: (violation: CspViolation) => Promise<void> | void
/**
* Requests per client (`clientIp`, IPv6 per /64) and window that are handled; over it the route still answers 204
* and handles nothing. Default `{ max: 60, windowMs: 60_000 }`; `false` = no limit.
*/
rateLimit?: { max?: number; windowMs?: number } | false
}
/** Longest value {@link cspLogLine} writes. */
export const CSP_LOG_VALUE_MAX = 128
/** Control characters (new lines among them) and the Unicode line separators: never in a log line. */
// eslint-disable-next-line no-control-regex
const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g
const clean = (value: string | undefined, max = CSP_LOG_VALUE_MAX): string => {
if (!value) {return '?'}
const text = value.replace(CONTROL, ' ').trim()
return text.length > max ? `${text.slice(0, max)}…` : text || '?'
}
/** `https://cdn.x/a.js?q` → `https://cdn.x`; a keyword (`inline`, `eval`, `data`) stays as it is. */
const originOf = (value: string | undefined): string | undefined => {
if (!value) {return undefined}
try {
const url = new URL(value)
return url.origin === 'null' ? `${url.protocol}` : url.origin
} catch {
return value
}
}
/** `https://site.pl/pl/o-nas?x=1#y` → `/pl/o-nas` (no query: it may hold personal data). */
const pathOf = (value: string | undefined): string | undefined => {
if (!value) {return undefined}
try {
return new URL(value).pathname
} catch {
return value.split(/[?#]/)[0]
}
}
/** `https://cdn.x/a.js?q` → `https://cdn.x/a.js`: where the script lives, without its query. */
const scriptOf = (value: string): string => {
try {
const url = new URL(value)
return url.origin === 'null' ? url.protocol : `${url.origin}${url.pathname}`
} catch {
return value.split(/[?#]/)[0]
}
}
/**
* The default log line of one violation: the blocked resource's origin, the page's path, the script's origin and path
* with its line — control characters removed, every value at most {@link CSP_LOG_VALUE_MAX} characters (security
* audit 2026-12, F1). Use it in your own `onReport` for the same line.
*/
export function cspLogLine(v: CspViolation): string {
const source = v.sourceFile ? scriptOf(v.sourceFile) : ''
return (
`[csp] ${clean(v.disposition ?? 'report', 16)} ${clean(v.effectiveDirective, 32)} blocked=${clean(originOf(v.blockedUri))} ` +
`page=${clean(pathOf(v.documentUri))}${source ? ` src=${clean(source)}:${typeof v.lineNumber === 'number' ? v.lineNumber : ''}` : ''}`
)
}
type Raw = Record<string, unknown>
@@ -86,14 +154,19 @@ export function parseCspReports(body: unknown): CspViolation[] {
export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (request: Request) => Promise<Response> {
const {
maxBytes = 16 * 1024,
maxReports = 10,
onReport = (v: CspViolation) => {
console.warn(
`[csp] ${v.disposition ?? 'report'} ${v.effectiveDirective ?? '?'} blocked=${v.blockedUri ?? '?'} page=${v.documentUri ?? '?'}${v.sourceFile ? ` src=${v.sourceFile}:${v.lineNumber ?? ''}` : ''}`,
)
console.warn(cspLogLine(v))
},
rateLimit = {},
} = args
return async (request: Request) => {
if (rateLimit) {
const { ok } = await consumeRateLimit({ key: clientIp(request), max: rateLimit.max ?? 60, scope: 'csp-report', windowMs: rateLimit.windowMs ?? 60_000 })
// the browser does not read the answer: 204 either way, nothing handled
if (!ok) {return new Response(null, { status: 204 })}
}
// read only up to the cap, whether or not the browser declared the length (a chunked body has none)
let text: null | string
try {
@@ -110,7 +183,7 @@ export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (requ
return new Response(null, { status: 400 })
}
for (const violation of parseCspReports(body).slice(0, 50)) {
for (const violation of parseCspReports(body).slice(0, Math.max(0, maxReports))) {
try {
await onReport(violation)
} catch {
+1 -1
View File
@@ -10,7 +10,7 @@ export {
export type { BuildAdminCspArgs, BuildCspArgs, CspDirective, CspSources } from './buildCsp.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } from './buildSecurityHeaders.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './buildSecurityHeaders.js'
export { createCspReportRoute, parseCspReports } from './createCspReportRoute.js'
export { createCspReportRoute, CSP_LOG_VALUE_MAX, cspLogLine, parseCspReports } from './createCspReportRoute.js'
export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRoute.js'
export { createCspNonce, CSP_NONCE_HEADER } from './cspNonce.js'
export { totpAdminPath, totpRedirectTarget } from './totp/totpRedirect.js'
+136
View File
@@ -0,0 +1,136 @@
import type { Access, CollectionBeforeOperationHook, CollectionConfig, Config, PayloadRequest, SanitizedConfig } from 'payload'
import { APIError } from 'payload'
import { staffCollectionSlugs } from '../access/predicates.js'
import { secondFactorPassed } from './totp/secondFactor.js'
/**
* Guards for what a REST / GraphQL caller may ask of a collection list (security audit 2026-12, F4 and F5), and
* Payload's document locks closed to visitor accounts (the "document locks" door). Each is on by default, each can be
* turned off or adapted, and every piece is exported for a project's own use (docs/security.md "Lists and sorting").
*
* Local API calls (`req.payloadAPI === 'local'`: the frontend, seeds, the project's own code) are never touched.
*/
export type ListLimitOptions = {
/** Collections left as Payload has them (their lists take any `limit`). */
exclude?: string[]
/** Largest page a caller that is not staff gets. Default 100. */
max?: number
/** Cap staff accounts too (the panel asks for at most 100 per page itself). Default false. */
staff?: boolean
}
export const DEFAULT_LIST_LIMIT = 100
type HookArgs = Parameters<CollectionBeforeOperationHook>[0]
type ListArgs = { id?: unknown; limit?: number | string; pagination?: boolean | string; sort?: unknown }
const fromOutside = (req: PayloadRequest | undefined): boolean =>
Boolean(req) && (req as { payloadAPI?: string }).payloadAPI !== 'local'
/** True when the request's account belongs to a staff collection (any role). */
export function isStaffRequest(req: Pick<PayloadRequest, 'payload' | 'user'> | undefined): boolean {
const slug = (req?.user as { collection?: unknown } | null | undefined)?.collection
return typeof slug === 'string' && staffCollectionSlugs(req?.payload).includes(slug)
}
/**
* The list arguments with `limit` at most `max` and pagination on — what a caller that is not staff gets. Pure: the
* hook below calls it, a project's own endpoint can too.
*/
export function capListLimit<T extends ListArgs>(args: T, max: number = DEFAULT_LIST_LIMIT): T {
// REST hands the query string over as text: '100000', 'false'
const raw = typeof args.limit === 'string' && (args.limit).trim() !== '' ? Number(args.limit) : args.limit
const limit = typeof raw === 'number' && Number.isFinite(raw) ? raw : undefined
const noPages = args.pagination === false || (args.pagination as unknown) === 'false'
// pagination: false and limit 0 both mean "everything" to Payload
if (noPages || limit === 0 || (limit !== undefined && limit > max)) {
return { ...args, limit: limit && limit > 0 ? Math.min(limit, max) : max, pagination: true }
}
return args
}
/** A sort field that names a database operator (`$where`, `-$natural`, `title.$ne`): never a field of a document. */
export function isOperatorSort(sort: unknown): boolean {
const names = Array.isArray(sort) ? sort : typeof sort === 'string' ? sort.split(',') : []
return names.some((n) => typeof n === 'string' && /(?:^-?|\.)\$/.test(n.trim()))
}
/**
* The 400 for an operator sort name. Its own name so Payload logs it as one `info` line without a stack (the plugin
* sets `loggingLevels.RefusedSortError: 'info'` unless the project set it; `false` logs nothing).
*/
export class RefusedSortError extends APIError {
constructor() {
super('This sort field is not allowed.', 400, null, true)
this.name = 'RefusedSortError'
}
}
const LIST_OPERATIONS = new Set(['findVersions', 'read', 'readDistinct'])
/**
* One `beforeOperation` hook for lists from outside: refuses a database operator as a sort field with 400 (instead of
* a 500 and a logged stack trace, F5) and caps `limit` for callers that are not staff (F4). `listLimit: false` or
* `refuseOperatorSort: false` turns that half off.
*/
export function buildQueryGuardHook(options: {
listLimit?: false | ListLimitOptions
refuseOperatorSort?: boolean
}): CollectionBeforeOperationHook {
const limit = options.listLimit === false ? null : { max: DEFAULT_LIST_LIMIT, staff: false, ...options.listLimit }
const refuseSort = options.refuseOperatorSort !== false
return (({ args, collection, operation, req }: HookArgs) => {
if (!LIST_OPERATIONS.has(operation) || !fromOutside(req)) {return args}
const list = args as ListArgs
if (refuseSort && isOperatorSort(list.sort)) {
throw new RefusedSortError()
}
if (!limit || list.id != null || limit.exclude?.includes(collection.slug)) {return args}
if (!limit.staff && isStaffRequest(req)) {return args}
return capListLimit(list, limit.max)
}) as CollectionBeforeOperationHook
}
/** The hook added to every collection of the config (the project's, the plugin's, other plugins' before iapl). */
export function applyQueryGuard(
config: Config,
options: { listLimit?: false | ListLimitOptions; refuseOperatorSort?: boolean },
): Config {
if (options.listLimit === false && options.refuseOperatorSort === false) {return config}
const hook = buildQueryGuardHook(options)
return {
...config,
collections: (config.collections ?? []).map((c) => ({
...c,
hooks: { ...c.hooks, beforeOperation: [...(c.hooks?.beforeOperation ?? []), hook] },
})),
// Payload's ErrorName union knows only its own errors; the name is looked up by string at log time
loggingLevels: { ...({ RefusedSortError: 'info' } as NonNullable<Config['loggingLevels']>), ...config.loggingLevels },
}
}
/** Payload's collection of document locks ("who edits what"). */
export const LOCKED_DOCUMENTS_SLUG = 'payload-locked-documents'
/**
* Staff accounts (with their second factor, when 2FA is on) — who edits in the panel. Payload's default for its
* document locks is any signed-in account, so a visitor account (a shop's customers) could read who edits what and
* write or delete locks.
*/
export const staffOnlyLocks: Access = ({ req }) => isStaffRequest(req) && secondFactorPassed({ payload: req.payload, user: req.user })
export type LockedDocumentsAccess = Partial<Pick<NonNullable<CollectionConfig['access']>, 'create' | 'delete' | 'read' | 'update'>>
/**
* Payload adds its document-lock collection after every plugin has run, so its rules are set on the live config
* (onInit and after a dev reload). `access` keys the project gives win; the rest is {@link staffOnlyLocks}.
*/
export function applyLockedDocumentsAccess(config: Pick<SanitizedConfig, 'collections'>, access: LockedDocumentsAccess = {}): boolean {
const locks = config.collections?.find((c) => c.slug === LOCKED_DOCUMENTS_SLUG)
if (!locks) {return false}
locks.access = { ...locks.access, create: staffOnlyLocks, delete: staffOnlyLocks, read: staffOnlyLocks, update: staffOnlyLocks, ...access }
return true
}