Merge claude/security-b-content-state-cc308e: sizes before work, one link rule, no stand-in locale, strict switches, write-only secrets cannot be queried

AGENT.md conflict: the 2FA rows from A, the stored-secrets row from B (its check answers 400 QueryError, not 403).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 21:43:03 +01:00
co-authored by Claude Opus 5.5
40 changed files with 1148 additions and 72 deletions
+2
View File
@@ -56,6 +56,8 @@ export function buildSiteIntegrations({
// nothing through the API; admins read/edit in the panel and via Local API.
// Without roles (no `access` option) every logged-in account is admin.
read: ({ req }) => userMeetsRole(req, 'admin'),
// With versions on (globalOverrides), Payload lets every signed-in account list them unless told otherwise.
readVersions: ({ req }) => userMeetsRole(req, 'admin'),
update: ({ req }) => userMeetsRole(req, 'admin'),
},
admin: {
+5
View File
@@ -15,6 +15,7 @@ export {
injectRoles,
isAdmin,
isEditor,
readPublished,
requireRole,
requireRoleField,
ROLE_HIERARCHY,
@@ -203,6 +204,8 @@ export {
createMarkdownRoute,
createSearchRoute,
getArchiveEntries,
isSiteLocale,
limitQuery,
listContent,
MARKDOWN_PREFIX,
markdownHref,
@@ -212,6 +215,7 @@ export {
resolveNotFoundPage,
resolveRedirect,
resolveRoute,
SEARCH_QUERY_LIMIT,
searchContent,
} from './modules/content/index.js'
export type { ArchiveEntries } from './modules/content/index.js'
@@ -417,6 +421,7 @@ export {
maskWriteOnlySecrets,
SECRET_CLEAR,
SECRET_MASK,
secretReadAccess,
SMTP_PASSWORD_BOUND_TO,
writeOnlySecret,
writeOnlySecrets,
+29 -8
View File
@@ -3,6 +3,7 @@ import type { Access, FieldAccess } from 'payload'
import type { Role } from './types.js'
import { hasMinimumRole, isAdmin } from './predicates.js'
import { ROLE_HIERARCHY } from './types.js'
/**
* Collection-level access (returns boolean | Where).
@@ -15,10 +16,23 @@ export const adminOrEditor: Access = ({ req }) => hasMinimumRole(req.user, 'edit
export const authenticated: Access = ({ req: { user } }) => Boolean(user)
/** Requires at least the given role. */
export const requireRole =
(minimum: Role): Access =>
({ req }) =>
hasMinimumRole(req.user, minimum, req.payload)
export const requireRole = (minimum: Role): Access => {
assertKnownRole('requireRole', minimum)
return ({ req }) => hasMinimumRole(req.user, minimum, req.payload)
}
/**
* Read rule for a collection with drafts: staff of `minimum` role or higher (default editor) read everything,
* drafts and versions included; everybody else (visitors, plain `user` accounts, a session that still owes its
* second factor) reads published documents only — by id, in lists, with `?draft=true` and over GraphQL. Payload's
* open `read: () => true` answers `?draft=true` with the draft itself (IAWL idea 23).
*
* access: { read: readPublished(), readVersions: readPublished() }
*/
export const readPublished = (minimum: Role = 'editor'): Access => {
assertKnownRole('readPublished', minimum)
return ({ req }) => (hasMinimumRole(req.user, minimum, req.payload) ? true : { _status: { equals: 'published' } })
}
/**
* Admins see all; others are constrained to their own document.
@@ -59,7 +73,14 @@ export const adminOnlyField: FieldAccess = ({ req }) => isAdmin(req.user, req.pa
export const adminOrEditorField: FieldAccess = ({ req }) => hasMinimumRole(req.user, 'editor', req.payload)
/** Requires at least the given role, for field-level access. */
export const requireRoleField =
(minimum: Role): FieldAccess =>
({ req }) =>
hasMinimumRole(req.user, minimum, req.payload)
export const requireRoleField = (minimum: Role): FieldAccess => {
assertKnownRole('requireRoleField', minimum)
return ({ req }) => hasMinimumRole(req.user, minimum, req.payload)
}
/** A role name the plugin does not know fails where the rule is written, not silently at every request. */
function assertKnownRole(where: string, role: unknown): void {
if (typeof role !== 'string' || !(ROLE_HIERARCHY as readonly string[]).includes(role)) {
throw new Error(`[iapl] ${where}(${JSON.stringify(role)}): the role must be one of ${ROLE_HIERARCHY.map((r) => `'${r}'`).join(', ')}.`)
}
}
+1
View File
@@ -6,6 +6,7 @@ export {
adminOrSelf,
adminOrSelfIn,
authenticated,
readPublished,
requireRole,
requireRoleField,
} from './access.js'
+6 -2
View File
@@ -123,7 +123,9 @@ function highestRoleIndex(user: MaybeUser): number {
*/
export function hasMinimumRole(user: MaybeUser, minimum: Role, payload?: MaybePayload): boolean {
if (!isStaffAccount(user, payload)) {return false}
return highestRoleIndex(user) >= ROLE_HIERARCHY.indexOf(minimum)
// a role name the plugin does not know ('Admin', 'admins') is met by nobody (it used to be met by everybody)
const needed = ROLE_HIERARCHY.indexOf(minimum)
return needed >= 0 && highestRoleIndex(user) >= needed
}
/** True if the user is a staff account with the admin role. */
@@ -158,7 +160,9 @@ export function userMeetsRole({ payload, user }: { payload?: BasePayload; user?:
const slug = (user as { collection?: unknown }).collection
if (typeof slug !== 'string' || !staffCollectionSlugs(payload).includes(slug)) {return false}
if (!secondFactorPassed({ payload, user })) {return false}
if (highestRoleIndex(user as MaybeUser) >= ROLE_HIERARCHY.indexOf(minimum)) {return true}
const needed = ROLE_HIERARCHY.indexOf(minimum)
if (needed < 0) {return false} // an unknown role name is met by nobody
if (highestRoleIndex(user as MaybeUser) >= needed) {return true}
const collection = payload?.collections?.[slug as never]?.config
const fields = (collection?.flattenedFields ?? collection?.fields) as Array<{ name?: string }> | undefined
if (!fields) {return false}
+4 -29
View File
@@ -5,6 +5,7 @@ import type { CollectionOverride } from '../shared/collectionOverride.js'
import { userMeetsRole } from '../access/predicates.js'
import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { readCappedBody as readCapped } from '../shared/readCappedBody.js'
import { CONSENT_CATEGORIES } from './categories.js'
import { CONSENT_CATEGORY_LABELS } from './categoryLabels.js'
import { CONSENT_VERSION } from './storage.js'
@@ -89,35 +90,9 @@ const missingTableLogged = new WeakSet<object>()
/** Largest body the endpoint reads. A decision is about 200 bytes; anything near this is not one. */
export const CONSENT_LOG_MAX_BYTES = 4096
/**
* The request body as text, or null when it is larger than `max` bytes: a declared `content-length` over the cap
* is refused before anything is read, and the stream is read only up to the cap (a body without a length, or with
* a false one, cannot make the server hold more).
*/
export async function readCappedBody(request: Request, max: number = CONSENT_LOG_MAX_BYTES): Promise<null | string> {
const declared = Number(request.headers.get('content-length'))
if (Number.isFinite(declared) && declared > max) {return null}
if (!request.body) {return ''}
const reader = request.body.getReader()
const chunks: Uint8Array[] = []
let size = 0
for (;;) {
const { done, value } = await reader.read()
if (done) {break}
size += value.byteLength
if (size > max) {
await reader.cancel().catch(() => {})
return null
}
chunks.push(value)
}
const all = new Uint8Array(size)
let at = 0
for (const chunk of chunks) {
all.set(chunk, at)
at += chunk.byteLength
}
return new TextDecoder().decode(all)
/** The request body as text, or null when it is larger than `max` bytes (shared/readCappedBody.ts). */
export function readCappedBody(request: Request, max: number = CONSENT_LOG_MAX_BYTES): Promise<null | string> {
return readCapped(request, max)
}
/** Cookie Settings → Policy version per Payload instance, cached for a minute. */
+8 -2
View File
@@ -4,6 +4,7 @@ import type { I18nConfig } from '../i18n/index.js'
import type { ClientIpOptions } from '../shared/rateLimit.js'
import { pathOf, type PathVisibility } from '../construction/visibility.js'
import { isValidLocale } from '../i18n/index.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
import { searchContent } from './searchContent.js'
@@ -22,6 +23,8 @@ type CreateSearchRouteArgs = {
homeSlug?: Record<string, string> | string
/** Hide pages the site hides (construction mode) — pass `isPathVisible` from createContentHelpers. */
isPathVisible?: PathVisibility
/** How much of `q` reaches the database (searchContent). Default `{ length: 200, words: 10 }`; `false` = all of it. */
queryLimit?: { length?: number; words?: number } | false
/**
* Per-IP limit (in memory per instance, or the store from setRateLimitStore). Default { max: 120, windowMs: 60_000 }.
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
@@ -52,7 +55,7 @@ type CreateSearchRouteArgs = {
* Uses the global Request/Response — no next/server import.
*/
export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise<Response> {
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, isPathVisible, settingsSlug, summaryField } = args
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, isPathVisible, queryLimit, settingsSlug, summaryField } = args
// 120/min: a debounced search-as-you-type box stays well under it; a scraper doesn't.
const rl = args.rateLimit === false ? null : { max: 120, windowMs: 60_000, ...args.rateLimit }
@@ -65,7 +68,9 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) =
}
const url = new URL(req.url)
const query = url.searchParams.get('q')?.trim() ?? ''
const locale = url.searchParams.get('locale') ?? undefined
// one locale for the search, the visibility check and the answer: a code the site does not have is the default
const asked = url.searchParams.get('locale')
const locale = asked && isValidLocale(asked, config) ? asked : undefined
const limitParam = url.searchParams.get('limit')
const limit = limitParam ? Number(limitParam) : defaultLimit
@@ -87,6 +92,7 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) =
locale,
payload,
query,
queryLimit,
settingsSlug,
summaryField,
})
+2 -2
View File
@@ -8,9 +8,9 @@ export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegoti
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'
export { resolveNotFoundPage } from './resolveNotFoundPage.js'
export { resolveRedirect } from './resolveRedirect.js'
export { resolveRoute } from './resolveRoute.js'
export { isSiteLocale, resolveRoute } from './resolveRoute.js'
export type { ResolvedRoute } from './resolveRoute.js'
export { listContent, searchContent } from './searchContent.js'
export { limitQuery, listContent, SEARCH_QUERY_LIMIT, searchContent } from './searchContent.js'
export type { SearchResult } from './searchContent.js'
export type { ContentCollectionOption, ContentOption } from './types.js'
export { archiveFieldName } from './types.js'
+4 -1
View File
@@ -1,5 +1,7 @@
import type { BasePayload } from 'payload'
import { isPublishedDoc } from './resolveRoute.js'
type ResolveNotFoundPageArgs = {
locale: string
/** Client's Pages collection slug. Defaults to 'pages'. */
@@ -49,7 +51,8 @@ export async function resolveNotFoundPage({
depth: 2,
locale: locale as never,
})
return (doc as null | Record<string, unknown>) ?? null
// a page never published (or unpublished) is a draft: the built-in view, not its text (IAWL idea 23)
return isPublishedDoc(doc) ? (doc as Record<string, unknown>) : null
} catch (error) {
console.warn('[iapl] resolveNotFoundPage: falling back to built-in 404 view:', error)
return null
+13
View File
@@ -89,6 +89,16 @@ function isPublic(doc: unknown, draft: boolean): boolean {
return status === undefined || status === null || status === 'published'
}
/** True for a document a visitor may be shown: published, or from a collection without drafts. */
export const isPublishedDoc = (doc: unknown): boolean => isPublic(doc, false)
/** True when `locale` is one of the site's locale codes (always true on a site without localization). */
export function isSiteLocale(payload: { config?: { localization?: unknown } }, locale: unknown): boolean {
const localization = payload.config?.localization as { localeCodes?: string[] } | false | undefined
if (!localization || !Array.isArray(localization.localeCodes)) {return true}
return typeof locale === 'string' && localization.localeCodes.includes(locale)
}
export async function resolveRoute({
content,
draft = false,
@@ -100,6 +110,9 @@ export async function resolveRoute({
settings: preloaded,
settingsSlug = 'site-settings',
}: ResolveRouteArgs): Promise<null | ResolvedRoute> {
// No stand-in locale: a code the site does not have (`xx`, `all`, `*` from a URL that went past the proxy, the
// Markdown route) is "not found" — never the default locale's page shown under another code (IAWL idea 25).
if (!isSiteLocale(payload, locale)) {return null}
const settings =
preloaded ??
((await payload.findGlobal({
+23 -1
View File
@@ -28,6 +28,11 @@ type SearchContentArgs = {
payload: BasePayload
/** Keywords. */
query: string
/**
* How much of the query reaches the database: `{ length: 200, words: 10 }` by default — every word is one more
* `LIKE` on two columns, and the text comes from a stranger. `false` = the whole query, as before 1.17.1.
*/
queryLimit?: { length?: number; words?: number } | false
/** SiteSettings global — the assigned 404 page is left out (unlistedPageIds). Default 'site-settings'. */
settingsSlug?: string
/**
@@ -58,6 +63,22 @@ type PageRow = {
* Degrades to [] (never throws) when the collection's fields aren't queryable —
* same guard class as the drafts/_status lesson.
*/
/** Default share of a search query that reaches the database (searchContent `queryLimit`). */
export const SEARCH_QUERY_LIMIT = { length: 200, words: 10 } as const
/** The query as searched: trimmed, then cut to `limit` words and characters (whole words where it can). */
export function limitQuery(query: string, limit: SearchContentArgs['queryLimit'] = SEARCH_QUERY_LIMIT): string {
const q = query.trim()
if (limit === false) {return q}
const length = limit.length ?? SEARCH_QUERY_LIMIT.length
const words = limit.words ?? SEARCH_QUERY_LIMIT.words
const kept = q.split(/\s+/).slice(0, Math.max(1, words)).join(' ')
if (kept.length <= length) {return kept}
const cut = kept.slice(0, length)
const space = cut.lastIndexOf(' ')
return (space > 0 ? cut.slice(0, space) : cut).trim()
}
export async function searchContent({
baseUrl,
collection = 'pages',
@@ -67,10 +88,11 @@ export async function searchContent({
locale,
payload,
query,
queryLimit,
settingsSlug,
summaryField,
}: SearchContentArgs): Promise<SearchResult[]> {
const q = query.trim()
const q = limitQuery(query, queryLimit)
if (!q) {return []}
const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config)
+9 -4
View File
@@ -3,6 +3,7 @@ import type { Endpoint, PayloadRequest } from 'payload'
import type { RelayOptions } from './options.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../../shared/rateLimit.js'
import { readCappedBody } from '../../shared/readCappedBody.js'
import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS } from './constants.js'
import { sha256Hex, takeNonce, writeRelayCandidate } from './store.js'
@@ -14,13 +15,17 @@ const MAX_BODY = 2048
const notFound = () => new Response(null, { headers: { 'cache-control': 'no-store' }, status: 404 })
async function readBody(req: PayloadRequest): Promise<unknown> {
const length = Number(req.headers.get('content-length') ?? 0)
if (length > MAX_BODY) {return null}
try {
// read only up to the cap, whether or not the call declares its length (a chunked body has none)
const text = (req as unknown as Request).body ? await readCappedBody(req as unknown as Request, MAX_BODY) : null
if (text !== null) {return JSON.parse(text) as unknown}
if ((req as unknown as Request).body) {return null}
// a request without a stream (a double in a test, a body Payload already read)
if (Number(req.headers.get('content-length') ?? 0) > MAX_BODY) {return null}
const read = (req as { text?: () => Promise<string> }).text
if (typeof read !== 'function') {return (await req.json?.()) as unknown}
const text = await read.call(req)
return text.length <= MAX_BODY ? (JSON.parse(text) as unknown) : null
const whole = await read.call(req)
return whole.length <= MAX_BODY ? (JSON.parse(whole) as unknown) : null
} catch {
return null
}
+3 -1
View File
@@ -24,6 +24,7 @@ import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
import { isPublishedDoc } from '../content/resolveRoute.js'
import { archiveFieldName } from '../content/types.js'
import { createHealthRoute } from '../health/createHealthRoute.js'
import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw, resolveSystemLinks } from '../links/resolveNav.js'
@@ -414,7 +415,8 @@ export function createContentHelpers({
depth: 2,
locale: locale as never,
})
return (doc as null | Record<string, unknown>) ?? null
// a page never published (or unpublished) is a draft: the built-in view, not its text (IAWL idea 23)
return isPublishedDoc(doc) ? (doc as Record<string, unknown>) : null
} catch {
return null // DB unreachable (container build) or page deleted — fallback view
}
+8 -1
View File
@@ -11,6 +11,7 @@ import { getDefaultLocale, isValidLocale } from '../i18n/index.js'
import { readSiteMetaConfig } from '../seo/readSiteMetaConfig.js'
import { collectSiteIndex } from '../seo/siteIndex.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
import { readCappedBody } from '../shared/readCappedBody.js'
/**
* A read-only MCP (Model Context Protocol) server for the client site, as a Next
@@ -66,6 +67,8 @@ export type CreateMcpRouteArgs = {
isPathVisible?: PathVisibility
/** Max messages in one JSON-RPC batch. Default 10. */
maxBatch?: number
/** Largest request body read, in bytes; a larger one gets `413` before it is parsed. Default 65536 (64 KiB). */
maxBytes?: number
/**
* Per-IP limit on JSON-RPC messages (a batch counts every message) (in memory per instance, or the store from setRateLimitStore). Default { max: 60, windowMs: 60_000 }.
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
@@ -104,6 +107,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
getCachedPayload,
isPathVisible,
maxBatch = 10,
maxBytes = 64 * 1024,
serverName = 'ipal-site',
serverVersion = '1.0.0',
settingsSlug = 'site-settings',
@@ -321,7 +325,10 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
async function POST(req: Request): Promise<Response> {
let body: unknown
try {
body = await req.json()
// read only up to the cap, declared length or not: a stranger's body is measured before it is parsed
const text = req.body ? await readCappedBody(req, maxBytes) : ''
if (text === null) {return Response.json(rpcError(null, -32600, `Request too large (max ${maxBytes} bytes)`), { status: 413 })}
body = JSON.parse(text)
} catch {
return Response.json(rpcError(null, -32700, 'Parse error'), { status: 400 })
}
+5 -1
View File
@@ -1,5 +1,7 @@
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
import { safeHref } from '../links/resolveLinkHref.js'
/**
* Converts a Payload Lexical richText value to Markdown — a small, dependency-
* free walker over the serialized node tree. Self-contained on purpose: it does
@@ -53,12 +55,14 @@ function inline(nodes: unknown): string {
out += '\n'
} else if (type === 'link') {
const fields = (node.fields ?? {}) as Record<string, unknown>
const url =
const raw =
typeof fields.url === 'string'
? fields.url
: typeof (fields.doc as Record<string, unknown>)?.value === 'string'
? ((fields.doc as Record<string, unknown>).value as string)
: ''
// the same rule as <RenderRichText> and <CMSLink>: a `javascript:` / `data:` target is dropped, the label stays
const url = raw && (typeof fields.url === 'string' ? safeHref(raw) : raw)
const label = inline(node.children)
out += url ? `[${label}](${url})` : label
} else if (node.children) {
+3 -1
View File
@@ -30,7 +30,9 @@ function walk(value: unknown): unknown {
const node = value as LexicalNode
let result: LexicalNode = node
if ((node.type === 'link' || node.type === 'autolink') && node.fields && node.fields.linkType !== 'internal') {
// Whatever the linkType: Payload's autolink converter prints `fields.url` even on an "internal" one, and a
// project's internalDocToHref may fall back to it — one check for every stored link URL.
if ((node.type === 'link' || node.type === 'autolink') && node.fields) {
const url = typeof node.fields.url === 'string' ? node.fields.url : ''
if (url && safeHref(url) === null) {result = { ...node, fields: { ...node.fields, url: '#' } }}
}
+23 -2
View File
@@ -1,4 +1,4 @@
import type { CollectionAfterReadHook, Field, FieldHook, GlobalAfterReadHook } from 'payload'
import type { CollectionAfterReadHook, Field, FieldAccess, FieldHook, GlobalAfterReadHook } from 'payload'
import { ValidationError } from 'payload'
@@ -130,11 +130,32 @@ export function buildKeepSecret({ appliesWhen, boundTo = [] }: WriteOnlySecretOp
*/
export const keepSecretBeforeValidate: FieldHook = buildKeepSecret()
/** Adds the two hooks to a field (a text field as a rule). The field's own hooks stay, and run around them. */
/**
* The field `read` rule of a write-only secret: a document may be read (the value comes back masked), a query may
* not name the field. A `where` / `sort` on the field answers by the stored value — `like: "Zq"` gives a count —
* so it would read the secret back one character at a time (review B-R1). Payload checks a query's fields with
* permissions built WITHOUT a document and asks rules that depend on one to deny then; the panel's edit and create
* views always pass the document (a global's stored data, a collection's `{ _status: 'draft', … }`), so the field
* stays visible and editable there. The field's own `read` rule, if any, still decides for a document.
*/
export function secretReadAccess(own?: FieldAccess): FieldAccess {
return (args) => {
const { data, doc, siblingData } = args as { data?: unknown; doc?: unknown; siblingData?: unknown }
if (doc === undefined && data === undefined && siblingData === undefined) {return false}
return own ? own(args) : true
}
}
/**
* Adds the two hooks to a field (a text field as a rule), and a `read` rule that keeps it out of queries
* (`secretReadAccess`). The field's own hooks stay, and run around them; its own `access` is kept.
*/
export function writeOnlySecret<F extends Field>(field: F, options: WriteOnlySecretOptions = {}): F {
const own = (field as { hooks?: { afterRead?: FieldHook[]; beforeValidate?: FieldHook[] } }).hooks ?? {}
const access = (field as { access?: { create?: FieldAccess; read?: FieldAccess; update?: FieldAccess } }).access
return {
...field,
access: { ...access, read: secretReadAccess(access?.read) },
custom: { ...(field as { custom?: Record<string, unknown> }).custom, ipalWriteOnly: true },
hooks: {
...own,
+23
View File
@@ -1,5 +1,7 @@
import type { SecurityHeader } from './buildSecurityHeaders.js'
import { assertBooleanSwitch, assertOneOf } from '../shared/switches.js'
export type CspDirective =
| 'base-uri'
| 'child-src'
@@ -76,6 +78,26 @@ export type BuildCspArgs = {
export const DEFAULT_CSP_REPORT_GROUP = 'csp-endpoint'
/** Header name for the mode — the request header Next reads the nonce from is the same. */
/**
* A CSP option the policy cannot read fails at start (IAWL idea 21): `dev: 'false'` used to add 'unsafe-eval' in
* production, and a string in `extra` / `override` was spread into single characters (a lone `*` is a wildcard).
*/
function assertCspArgs(args: BuildCspArgs): void {
assertBooleanSwitch('buildCsp.dev', args.dev)
assertBooleanSwitch('buildCsp.strictDynamic', (args as { strictDynamic?: unknown }).strictDynamic)
assertOneOf('buildCsp.mode', args.mode, ['enforce', 'report-only'])
for (const [key, list] of [['extra', args.extra], ['override', args.override]] as const) {
if (list === undefined) {continue}
if (!list || typeof list !== 'object' || Array.isArray(list)) {throw new Error(`[iapl] buildCsp.${key} must be an object of directive → array of sources.`)}
for (const [dir, values] of Object.entries(list as Record<string, unknown>)) {
if (values === undefined || (key === 'override' && values === null)) {continue}
if (!Array.isArray(values) || values.some((v) => typeof v !== 'string')) {
throw new Error(`[iapl] buildCsp.${key}['${dir}'] must be an array of sources, e.g. ['https://cdn.example.com'] (received ${JSON.stringify(values)}).`)
}
}
}
}
export function cspHeaderKey(mode: BuildCspArgs['mode'] = 'enforce'): string {
return mode === 'report-only' ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy'
}
@@ -106,6 +128,7 @@ export function cspHeaderKey(mode: BuildCspArgs['mode'] = 'enforce'): string {
* missing sources via `extra`, THEN switch to 'enforce'. See docs/security.md.
*/
export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string } {
assertCspArgs(args)
const {
analytics,
clarity,
@@ -1,6 +1,7 @@
import type { BuildCspArgs } from './buildCsp.js'
import { isSiteNoindex } from '../seo/siteNoindex.js'
import { assertBooleanSwitch, assertNumberSwitch, assertOneOf } from '../shared/switches.js'
import { buildCspHeaders } from './buildCsp.js'
/**
@@ -82,6 +83,18 @@ export type BuildSecurityHeadersArgs = {
* }
*/
export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): SecurityHeader[] {
// A value the browser would not understand fails at start instead of being sent (IAWL idea 21): `hsts: null`
// dropped HSTS, `hstsMaxAge: 'abc'` and `frameOptions: 'false'` produced headers browsers ignore.
for (const name of ['hsts', 'hstsIncludeSubDomains', 'hstsPreload'] as const) {assertBooleanSwitch(`buildSecurityHeaders.${name}`, args[name])}
assertNumberSwitch('buildSecurityHeaders.hstsMaxAge', args.hstsMaxAge, { min: 0 })
if (args.frameOptions !== null) {assertOneOf('buildSecurityHeaders.frameOptions', args.frameOptions, ['DENY', 'SAMEORIGIN'])}
if (args.coop !== false) {assertOneOf('buildSecurityHeaders.coop', args.coop, ['same-origin', 'same-origin-allow-popups', 'noopener-allow-popups', 'unsafe-none'])}
for (const name of ['permissionsPolicy', 'referrerPolicy'] as const) {
const v = args[name] as unknown
if (v !== undefined && v !== null && (typeof v !== 'string' || !v.trim() || v === 'false')) {
throw new Error(`[iapl] buildSecurityHeaders.${name} must be a header value or null (received ${JSON.stringify(v)}).`)
}
}
const {
additional = [],
coop = 'same-origin',
+6 -5
View File
@@ -1,3 +1,5 @@
import { readCappedBody } from '../shared/readCappedBody.js'
/** One CSP violation, normalised from either report format. */
export type CspViolation = {
blockedUri?: string
@@ -92,15 +94,14 @@ export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (requ
} = args
return async (request: Request) => {
const length = Number(request.headers.get('content-length') ?? 0)
if (length > maxBytes) {return new Response(null, { status: 413 })}
let text: string
// read only up to the cap, whether or not the browser declared the length (a chunked body has none)
let text: null | string
try {
text = await request.text()
text = await readCappedBody(request, maxBytes)
} catch {
return new Response(null, { status: 400 })
}
if (text.length > maxBytes) {return new Response(null, { status: 413 })}
if (text === null) {return new Response(null, { status: 413 })}
let body: unknown
try {
+4
View File
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
import type { SeedTarget } from './values.js'
import { readEnv } from '../shared/envName.js'
import { assertBooleanSwitch, assertSwitchOrObject } from '../shared/switches.js'
import { activeSeedExitGuard } from './exitGuard.js'
import { isLocalDatabase, seedDatabaseUrl } from './guard.js'
import {
@@ -197,7 +198,10 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
const dryRun = options.dryRun ?? (process.argv.includes('--dry-run') || env.SEED_DRY_RUN === '1')
const update = options.update ?? env.SEED_UPDATE === '1'
const force = update && (options.force ?? env.SEED_FORCE === '1')
// `guard: 0` used to drop the production guard, `allowFull: 'false'` to allow a full seed (IAWL idea 21)
assertSwitchOrObject('seed guard', options.guard, { allowTrue: false })
const guard = options.guard === false ? false : (options.guard ?? {})
if (guard) {for (const name of ['allowFull', 'allowProdUpdate', 'production'] as const) {assertBooleanSwitch(`seed guard.${name}`, (guard as Record<string, unknown>)[name])}}
const label = options.label ?? '[seed]'
const log = options.log ?? defaultLog
const hashField = options.editCheck?.hashField ?? defaultHashField()
+2 -1
View File
@@ -13,7 +13,8 @@ export function mdToPlain(md: string): string {
/** Truncate at a word boundary, adding an ellipsis when cut. */
export function truncate(text: string, max: number): string {
if (text.length <= max) {return text}
const slice = text.slice(0, max)
// one place kept for the "…": the result is never longer than `max` (a field's maxLength, a summary limit)
const slice = text.slice(0, Math.max(0, max - 1))
const lastSpace = slice.lastIndexOf(' ')
return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`
}
+32
View File
@@ -0,0 +1,32 @@
/**
* One rule for every body the plugin reads from strangers (IAWL idea 1: count the size before the work).
*
* The request body as text, or null when it is larger than `max` bytes: a declared `content-length` over the cap
* is refused before anything is read, and the stream is read only up to the cap (a body without a length, or with
* a false one, cannot make the server hold more).
*/
export async function readCappedBody(request: Request, max: number): Promise<null | string> {
const declared = Number(request.headers.get('content-length'))
if (Number.isFinite(declared) && declared > max) {return null}
if (!request.body) {return ''}
const reader = request.body.getReader()
const chunks: Uint8Array[] = []
let size = 0
for (;;) {
const { done, value } = await reader.read()
if (done) {break}
size += value.byteLength
if (size > max) {
await reader.cancel().catch(() => {})
return null
}
chunks.push(value)
}
const all = new Uint8Array(size)
let at = 0
for (const chunk of chunks) {
all.set(chunk, at)
at += chunk.byteLength
}
return new TextDecoder().decode(all)
}
+117
View File
@@ -0,0 +1,117 @@
/**
* IAWL idea 21: a switch must never read a value nobody understands as "off" or "open".
*
* A JavaScript config is not type-checked, so `accounts: 0`, `stats: 'false'` or
* `consentLog: { retentionDays: null }` reach the plugin as they are. Where such a value would switch a
* protection off, widen who sees something, or switch an opt-in feature (a public endpoint) on, the plugin stops
* at start with a message that names the option — like `twoFactor.requireSetup.windowHours` since 1.16.6.
* Real values (`true`, `false`, an object, a number in range, a known name) are unchanged.
*
* Exported so a project (or another plugin) can check its own switches the same way.
*/
const where = (path: string) => `[iapl] ${path}`
/** Throws unless `value` is `undefined`, `true` or `false`. */
export function assertBooleanSwitch(path: string, value: unknown): void {
if (value === undefined || typeof value === 'boolean') {return}
throw new Error(`${where(path)} must be true or false (received ${JSON.stringify(value)}). A string such as "false" is not read as off.`)
}
/** Throws unless `value` is `undefined`, `true`, `false` or an object (the option's settings). */
export function assertSwitchOrObject(path: string, value: unknown, { allowTrue = true }: { allowTrue?: boolean } = {}): void {
if (value === undefined || value === false || (allowTrue && value === true)) {return}
if (value && typeof value === 'object' && !Array.isArray(value)) {return}
const allowed = allowTrue ? 'true, false or an object' : 'false or an object'
throw new Error(`${where(path)} must be ${allowed} (received ${JSON.stringify(value)}). A value like 0, "" or "false" is not read as off.`)
}
/** Throws unless `value` is `undefined` or a finite number that is at least `min` (above it when `exclusive`). */
export function assertNumberSwitch(path: string, value: unknown, { exclusive = false, min }: { exclusive?: boolean; min: number }): void {
if (value === undefined) {return}
if (typeof value === 'number' && Number.isFinite(value) && (exclusive ? value > min : value >= min)) {return}
throw new Error(`${where(path)} must be a number ${exclusive ? 'above' : 'of at least'} ${min} (received ${JSON.stringify(value)}).`)
}
/** Throws unless `value` is `undefined` or one of `allowed`. */
export function assertOneOf(path: string, value: unknown, allowed: readonly string[]): void {
if (value === undefined || (typeof value === 'string' && allowed.includes(value))) {return}
throw new Error(`${where(path)} must be one of ${allowed.map((a) => `"${a}"`).join(', ')} (received ${JSON.stringify(value)}).`)
}
type Bag = Record<string, unknown> | undefined
const bag = (value: unknown): Bag => (value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined)
/**
* The plugin options whose nonsense values used to read as off or open. Called by iapl() before anything is built.
* Each line names what a bad value did before 1.17.1.
*/
export function assertPluginSwitches(options: Record<string, unknown>): void {
// `accounts: 0` / `''` dropped every account rule (staff-only reads, admin-only writes, the panel role,
// the password rule, the closed first-user route).
assertSwitchOrObject('accounts', options.accounts, { allowTrue: false })
// Opt-in features that add public endpoints or outbound calls: `'false'` switched them ON.
for (const name of ['cookieScanner', 'stats', 'consentLog', 'adminMeta', 'whiteLabel'] as const) {
assertSwitchOrObject(name, options[name])
}
assertBooleanSwitch('indexNow', options.indexNow)
// 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)
assertBooleanSwitch('enabled', options.enabled)
const forms = bag(options.forms)
if (forms) {assertSwitchOrObject('forms.attachments', forms.attachments)}
// `maxPerMinute: 'off'` / `null` / `{}` turned the upload endpoint's limit off; only 0 is documented as off.
const submit = bag(bag(forms?.attachments)?.submit)
if (submit) {
assertNumberSwitch('forms.attachments.submit.maxPerMinute', submit.maxPerMinute, { min: 0 })
assertNumberSwitch('forms.attachments.submit.timeoutMs', submit.timeoutMs, { min: 0 })
assertNumberSwitch('forms.attachments.submit.idleTimeoutMs', submit.idleTimeoutMs, { min: 0 })
}
const scanner = bag(options.cookieScanner)
if (scanner) {assertSwitchOrObject('cookieScanner.crawl', scanner.crawl)}
// `'false'` accepted a 2FA target that is not the admin collection (panel users without 2FA).
const twoFactor = bag(options.twoFactor)
if (twoFactor) {assertBooleanSwitch('twoFactor.allowCollectionMismatch', twoFactor.allowCollectionMismatch)}
// `null` / `0` / a negative number purged every proof of consent once a day.
const consentLog = bag(options.consentLog)
if (consentLog) {assertNumberSwitch('consentLog.retentionDays', consentLog.retentionDays, { exclusive: true, min: 0 })}
// `robots.index: 'false'` / `0` / `null` took the noindex off the admin panel.
const adminMeta = bag(options.adminMeta)
const robots = bag(adminMeta?.robots)
if (robots) {
assertBooleanSwitch('adminMeta.robots.index', robots.index)
assertBooleanSwitch('adminMeta.robots.follow', robots.follow)
}
// An unknown role name ('Admin', 'admins') showed the failure details to every staff account.
const alerts = bag(options.dashboardAlerts)
if (alerts) {
assertOneOf('dashboardAlerts.integrations', alerts.integrations, ['admin', 'editor', 'all'])
assertOneOf('dashboardAlerts.cookies', alerts.cookies, ['editor', 'all'])
}
// A window of 0 minutes (or 0 ms) is a limit that never fills.
const mail = bag(options.mail)
if (mail) {assertSwitchOrObject('mail.relay', mail.relay)}
const relay = bag(mail?.relay)
if (relay) {
const accountMail = relay.accountMail
if (accountMail !== false && accountMail !== undefined) {
const limits = bag(accountMail)
if (!limits) {throw new Error(`${where('mail.relay.accountMail')} must be false or an object (received ${JSON.stringify(accountMail)}).`)}
assertNumberSwitch('mail.relay.accountMail.windowMinutes', limits.windowMinutes, { exclusive: true, min: 0 })
assertNumberSwitch('mail.relay.accountMail.perAddress', limits.perAddress, { min: 1 })
assertNumberSwitch('mail.relay.accountMail.perVisitor', limits.perVisitor, { min: 1 })
}
const confirm = bag(relay.confirmRateLimit)
if (confirm) {
assertNumberSwitch('mail.relay.confirmRateLimit.windowMs', confirm.windowMs, { exclusive: true, min: 0 })
assertNumberSwitch('mail.relay.confirmRateLimit.max', confirm.max, { min: 1 })
}
}
}
+8 -1
View File
@@ -6,6 +6,7 @@ import { gpcFromHeaders, resolveConsent } from '../consent/gpc.js'
import { CONSENT_COOKIE, CONSENT_VERSION, readConsentRecord } from '../consent/storage.js'
import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { readCappedBody } from '../shared/readCappedBody.js'
import { STATS_SLUG } from './collection.js'
import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath, VISITOR_ID_PATTERN } from './parse.js'
import { visitKey } from './visitKey.js'
@@ -46,6 +47,9 @@ function readCookie(header: null | string, name: string): string | undefined {
* version — the server checks, it doesn't take the browser's word for it.
* Logged-in panel users, bots and prefetches aren't counted.
*/
/** Largest page-view body the endpoint reads (a path of 300 characters, a referrer, a locale, an id). */
export const STATS_MAX_BYTES = 4096
export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Warsaw' }: StatsOptions = {}): Endpoint {
return {
handler: async (req: PayloadRequest) => {
@@ -63,7 +67,10 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars
let body: { l?: unknown; p?: unknown; r?: unknown; v?: unknown }
try {
body = (await request.json()) as typeof body
// a page view is about 200 bytes: read no more than STATS_MAX_BYTES of whatever is sent
const text = request.body ? await readCappedBody(request, STATS_MAX_BYTES) : null
if (text === null) {return done}
body = JSON.parse(text) as typeof body
} catch {
return done
}
+3
View File
@@ -67,6 +67,7 @@ import { searchSettingsFields } from './modules/seo/searchSettings.js'
import { migrateTitleSeparator } from './modules/seo/titleSeparator.js'
import { applyCollectionOverride } from './modules/shared/collectionOverride.js'
import { assertDevelopmentHosts } from './modules/shared/developmentHosts.js'
import { assertPluginSwitches } from './modules/shared/switches.js'
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
import { visitorCookieFor } from './modules/stats/visitorCookie.js'
@@ -101,6 +102,8 @@ const TOTP_REDIRECT_PROVIDER = '@intecion/ipal-kit/admin#TotpRedirectProvider'
export const iapl = (options: IaplOptions): Plugin => {
// Validate eagerly — fail fast before Payload boots
validateI18nConfig(options.i18n)
// a switch never reads a value nobody understands as off or open (IAWL idea 21)
assertPluginSwitches(options as unknown as Record<string, unknown>)
return async (incomingConfig: Config): Promise<Config> => {
const config = await transform(incomingConfig)