Security review: drafts no longer public, submissions staff-only, safe links, upload sandbox

- Fix: resolveRoute served never-published drafts by URL (Payload's find
  returns them with _status 'draft') — also via Markdown, MCP get_page and
  metadata. Drafts are dropped on every branch; `draft: true` for previews.
- Fix: getArchiveEntries listed drafts in archive pages despite its comment;
  `_status: published` is added automatically when the collection has drafts.
- form-submissions readable only by editor+ (form-builder default: any account
  of the admin collection, incl. plain users from an open sign-up); delete admin.
- Forms stay public for rendering, but the Emails tab (recipients) is hidden
  from anonymous REST reads.
- safeHref: CMS links only http(s), mailto, tel, sms, #, / — javascript:, data:
  and control-character tricks are dropped in resolveLinkHref.
- Analytics IDs validated in the panel and before reaching the browser.
- buildUploadSecurityHeaders: sandbox CSP for /api/<upload>/file/* so an
  uploaded SVG can't run script on the site's origin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-16 03:06:26 +02:00
co-authored by Claude Opus 5.5
parent ebf70d49bd
commit 9e49856611
14 changed files with 284 additions and 20 deletions
+7 -6
View File
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
import type { AnalyticsConfig } from './types.js'
import { getSiteIntegrations } from '../payload/index.js'
import { validAnalyticsId } from './idFormats.js'
/**
* Reads the public analytics / marketing tag IDs from SiteIntegrations,
@@ -12,11 +13,11 @@ import { getSiteIntegrations } from '../payload/index.js'
export async function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig> {
const integrations = await getSiteIntegrations<AnalyticsConfig>(payload)
return {
clarityProjectId: integrations.clarityProjectId ?? null,
ga4MeasurementId: integrations.ga4MeasurementId ?? null,
gtmContainerId: integrations.gtmContainerId ?? null,
linkedInPartnerId: integrations.linkedInPartnerId ?? null,
metaPixelId: integrations.metaPixelId ?? null,
tiktokPixelId: integrations.tiktokPixelId ?? null,
clarityProjectId: validAnalyticsId('clarityProjectId', integrations.clarityProjectId),
ga4MeasurementId: validAnalyticsId('ga4MeasurementId', integrations.ga4MeasurementId),
gtmContainerId: validAnalyticsId('gtmContainerId', integrations.gtmContainerId),
linkedInPartnerId: validAnalyticsId('linkedInPartnerId', integrations.linkedInPartnerId),
metaPixelId: validAnalyticsId('metaPixelId', integrations.metaPixelId),
tiktokPixelId: validAnalyticsId('tiktokPixelId', integrations.tiktokPixelId),
}
}
+28
View File
@@ -0,0 +1,28 @@
/**
* Formats of the tag IDs typed into Site Integrations. Used twice: as field
* validation in the panel (typos caught on save) and when the IDs are handed to
* the browser (getAnalyticsConfig) — a malformed value from an import or an old
* version is dropped instead of being put into a script URL.
*/
export const ANALYTICS_ID_FORMATS = {
clarityProjectId: /^[a-z0-9]{5,20}$/i,
ga4MeasurementId: /^G-[A-Z0-9]{4,20}$/,
gtmContainerId: /^GTM-[A-Z0-9]{4,12}$/,
linkedInPartnerId: /^\d{3,12}$/,
metaPixelId: /^\d{5,20}$/,
tiktokPixelId: /^[A-Z0-9]{10,30}$/i,
} as const
export type AnalyticsIdField = keyof typeof ANALYTICS_ID_FORMATS
/** The trimmed ID when it matches its format, else null. */
export function validAnalyticsId(field: AnalyticsIdField, value: unknown): null | string {
const v = typeof value === 'string' ? value.trim() : ''
return v && ANALYTICS_ID_FORMATS[field].test(v) ? v : null
}
/** Payload field `validate` for an ID field. */
export const validateAnalyticsId =
(field: AnalyticsIdField, example: string) =>
(value: null | string | undefined): string | true =>
!value?.trim() || validAnalyticsId(field, value) !== null || `Unexpected format — expected something like ${example}`
+14 -4
View File
@@ -15,6 +15,8 @@ type GetArchiveEntriesArgs = {
collection: string
/** Relationship depth. Defaults to 1 — enough for a cover image. */
depth?: number
/** Preview (draftMode): include unpublished entries and latest drafts. Default false. */
draft?: boolean
locale: string
/** 1-based. Values below 1 are clamped. */
page?: number
@@ -30,9 +32,10 @@ type GetArchiveEntriesArgs = {
/**
* Fetches one page of a collection's entries for an archive listing.
*
* Only published documents are returned when the collection has drafts enabled;
* Payload's `where` on `_status` is left to the caller, since a collection
* without drafts has no such field.
* Only published documents are returned when the collection has drafts enabled
* (the `_status` filter is added automatically — only then, since a collection
* without drafts has no such field and querying it would throw). Pass
* `draft: true` for a preview.
*
* Returns pagination facts rather than markup — the listing itself belongs to
* the client (as a block on the archive page, most likely), because how a list
@@ -41,6 +44,7 @@ type GetArchiveEntriesArgs = {
export async function getArchiveEntries<T = Record<string, unknown>>({
collection,
depth = 1,
draft = false,
locale,
page = 1,
payload,
@@ -48,14 +52,20 @@ export async function getArchiveEntries<T = Record<string, unknown>>({
sort = '-createdAt',
where,
}: GetArchiveEntriesArgs): Promise<ArchiveEntries<T>> {
const versions = payload.collections?.[collection as never]?.config?.versions as { drafts?: unknown } | false | undefined
const hasDrafts = Boolean(versions && versions.drafts)
const published = !draft && hasDrafts ? { _status: { equals: 'published' } } : undefined
const fullWhere = published && where ? { and: [published, where] } : (published ?? where)
const result = await payload.find({
collection: collection as never,
depth,
draft,
limit: perPage,
locale: locale as never,
page: Math.max(1, page),
sort,
...(where ? { where: where as never } : {}),
...(fullWhere ? { where: fullWhere as never } : {}),
})
return {
+25 -3
View File
@@ -31,6 +31,12 @@ export type ResolvedRoute =
type ResolveRouteArgs = {
content?: ContentOption
/**
* Preview (Next draftMode): return the latest draft instead of the published
* version, and resolve never-published pages. Default false — public
* requests only ever see published content.
*/
draft?: boolean
locale: string
/** Page number from the query string (?page=2). Defaults to 1. */
page?: number
@@ -72,8 +78,20 @@ type ResolveRouteArgs = {
* make canonical and hreflang ambiguous (the same entry reachable under several
* URLs).
*/
/**
* Payload's `find` returns never-published documents from the main collection
* (with `_status: 'draft'`) unless asked otherwise — public routing must drop
* them, or an unpublished page is reachable by its URL.
*/
function isPublic(doc: unknown, draft: boolean): boolean {
if (draft || !doc || typeof doc !== 'object') {return Boolean(doc)}
const status = (doc as { _status?: unknown })._status
return status === undefined || status === null || status === 'published'
}
export async function resolveRoute({
content,
draft = false,
locale,
page = 1,
pagesSlug = 'pages',
@@ -107,10 +125,11 @@ export async function resolveRoute({
id: homepageId,
collection: pagesSlug,
depth: 2,
draft,
locale: locale as never,
})
return doc ? { type: 'home', doc: doc as Record<string, unknown> } : null
return doc && isPublic(doc, draft) ? { type: 'home', doc: doc as Record<string, unknown> } : null
}
const [first, ...rest] = segments
@@ -122,6 +141,7 @@ export async function resolveRoute({
const archiveDoc = archive as ArchivePage
if (archiveDoc.slug !== first) {continue}
if (!isPublic(archiveDoc, draft)) {return null}
// /pl/artykuly → the archive page itself.
if (rest.length === 0) {
@@ -139,12 +159,13 @@ export async function resolveRoute({
const found = await payload.find({
collection: collection.slug as never,
depth: 2,
draft,
limit: 1,
locale: locale as never,
where: { slug: { equals: rest[0] } },
})
const entry = found.docs[0]
if (!entry) {return null}
if (!entry || !isPublic(entry, draft)) {return null}
return {
type: 'entry',
@@ -162,12 +183,13 @@ export async function resolveRoute({
const found = await payload.find({
collection: pagesSlug as never,
depth: 2,
draft,
limit: 1,
locale: locale as never,
where: { slug: { equals: segments.join('/') } },
})
const doc = found.docs[0]
if (!doc) {return null}
if (!doc || !isPublic(doc, draft)) {return null}
// The page assigned as 404 in System Pages must not be reachable as a normal
// 200 URL (/pl/strona-nie-znaleziona) — that's a soft-404 / duplicate. Treat
+33 -2
View File
@@ -1,11 +1,38 @@
import type { Plugin } from 'payload'
import type { Field, Plugin } from 'payload'
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { FormsOption } from './types.js'
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
type AccessArgs = { req: { user?: unknown } }
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
const submissionsCreateAccess = ({ req }: { req: { user?: unknown } }) => Boolean(req.user)
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
/**
* Submissions are visitors' personal data: editors and admins only. The
* form-builder default lets ANY account of the admin collection read them —
* including a plain 'user' from an open sign-up.
*/
const submissionsReadAccess = ({ req }: AccessArgs) => hasMinimumRole(req.user as never, 'editor')
const submissionsDeleteAccess = ({ req }: AccessArgs) => isAdmin(req.user as never)
/**
* Forms stay publicly readable (their fields render the form), but the Emails
* tab — recipient addresses, templates — is for logged-in staff only, so
* GET /api/forms doesn't hand out the company's inboxes to spammers.
*/
function hideEmails(fields: Field[]): Field[] {
return fields.map((field) =>
'name' in field && field.name === 'emails'
? ({
...field,
access: { ...(field as { access?: object }).access, read: ({ req }: AccessArgs) => Boolean(req.user) },
} as Field)
: field,
)
}
/**
* Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.
@@ -48,12 +75,16 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
labels: { plural: 'Forms', singular: 'Form' },
...forms.formOverrides,
admin: { ...group, ...forms.formOverrides?.admin },
fields: ({ defaultFields }) =>
hideEmails(forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields }) : defaultFields),
},
formSubmissionOverrides: {
labels: { plural: 'Submissions', singular: 'Submission' },
...forms.formSubmissionOverrides,
access: {
create: submissionsCreateAccess,
delete: submissionsDeleteAccess,
read: submissionsReadAccess,
...forms.formSubmissionOverrides?.access,
},
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
+1 -1
View File
@@ -1,4 +1,4 @@
export { buildLinkField, buildLinksField } from './buildLinkField.js'
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance } from './buildLinkField.js'
export { resolveLinkHref } from './resolveLinkHref.js'
export { resolveLinkHref, safeHref } from './resolveLinkHref.js'
export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'
+16 -1
View File
@@ -6,6 +6,21 @@ import { buildLocalizedPath } from '../i18n/index.js'
* Minimal shape of a link value (the project's generated `CmsLink` fits it).
* The plugin doesn't know the project's types — only this contract.
*/
/**
* Schemes a CMS link may use. The field validates this too, but data can come
* from imports, seeds or older versions — `javascript:`, `data:` and other
* schemes are dropped here so a stored link can never run script on click.
*/
const SAFE_HREF = /^(?:https?:\/\/|mailto:|tel:|sms:|#|\/(?!\/))/i
/** The URL when it's a safe link target, otherwise null (control characters — e.g. "java\tscript:" — reject it). */
export function safeHref(url: null | string | undefined): null | string {
const v = url?.trim()
// eslint-disable-next-line no-control-regex
if (!v || /[\u0000-\u001F\u007F]/.test(v)) {return null}
return SAFE_HREF.test(v) ? v : null
}
export type LinkValue = {
appearance?: null | string
file?: unknown
@@ -43,7 +58,7 @@ export function resolveLinkHref(
): null | string {
if (!link) {return null}
if (link.type === 'external') {return link.url?.trim() || null}
if (link.type === 'external') {return safeHref(link.url)}
if (link.type === 'file') {
const file = link.file
@@ -125,3 +125,30 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur
return headers
}
/**
* Headers for files served from the upload routes. Media accept `image/*`,
* which includes SVG — and an SVG opened directly from the site's own origin
* can run script (stored XSS from any account that can upload). This CSP lets
* the file display but never execute: no scripts, no plugins, sandboxed.
* Media on R2 come from another domain and are already isolated; local-disk
* media (dev, or sites without R2) need this.
*
* // next.config.ts — next to the site-wide headers
* async headers() {
* return [
* { source: '/:path*', headers: securityHeaders },
* ...buildUploadSecurityHeaders(), // default: /api/media/file/*
* ]
* }
*/
export function buildUploadSecurityHeaders({ collections = ['media'] }: { collections?: string[] } = {}): {
headers: SecurityHeader[]
source: string
}[] {
const headers: SecurityHeader[] = [
{ key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox" },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
]
return collections.map((slug) => ({ headers, source: `/api/${slug}/file/:path*` }))
}
+1 -1
View File
@@ -1,4 +1,4 @@
export { buildCsp } from './buildCsp.js'
export type { BuildCspArgs } from './buildCsp.js'
export { buildSecurityHeaders } from './buildSecurityHeaders.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './buildSecurityHeaders.js'
export type { BuildSecurityHeadersArgs, SecurityHeader, } from './buildSecurityHeaders.js'