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:
@@ -1,5 +1,7 @@
|
||||
import type { Field } from 'payload'
|
||||
|
||||
import { validateAnalyticsId } from '../../../modules/analytics/idFormats.js'
|
||||
|
||||
/**
|
||||
* Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no
|
||||
* read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only
|
||||
@@ -13,6 +15,7 @@ export const analyticsFields: Field[] = [
|
||||
description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)',
|
||||
placeholder: 'G-XXXXXXXXXX',
|
||||
},
|
||||
validate: validateAnalyticsId('ga4MeasurementId', 'G-XXXXXXXXXX'),
|
||||
},
|
||||
{
|
||||
name: 'gtmContainerId',
|
||||
@@ -21,6 +24,7 @@ export const analyticsFields: Field[] = [
|
||||
description: 'Google Tag Manager container ID. (Google — Consent Mode)',
|
||||
placeholder: 'GTM-XXXXXXX',
|
||||
},
|
||||
validate: validateAnalyticsId('gtmContainerId', 'GTM-XXXXXXX'),
|
||||
},
|
||||
{
|
||||
name: 'metaPixelId',
|
||||
@@ -29,6 +33,7 @@ export const analyticsFields: Field[] = [
|
||||
description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.',
|
||||
placeholder: '1234567890123456',
|
||||
},
|
||||
validate: validateAnalyticsId('metaPixelId', '1234567890123456'),
|
||||
},
|
||||
{
|
||||
name: 'clarityProjectId',
|
||||
@@ -37,6 +42,7 @@ export const analyticsFields: Field[] = [
|
||||
description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.',
|
||||
placeholder: 'abcdefghij',
|
||||
},
|
||||
validate: validateAnalyticsId('clarityProjectId', 'abcdefghij'),
|
||||
},
|
||||
{
|
||||
name: 'linkedInPartnerId',
|
||||
@@ -45,6 +51,7 @@ export const analyticsFields: Field[] = [
|
||||
description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.',
|
||||
placeholder: '1234567',
|
||||
},
|
||||
validate: validateAnalyticsId('linkedInPartnerId', '1234567'),
|
||||
},
|
||||
{
|
||||
name: 'tiktokPixelId',
|
||||
@@ -53,5 +60,6 @@ export const analyticsFields: Field[] = [
|
||||
description: 'TikTok Pixel ID. Loads only after MARKETING consent.',
|
||||
placeholder: 'CXXXXXXXXXXXXXXXXXXX',
|
||||
},
|
||||
validate: validateAnalyticsId('tiktokPixelId', 'CXXXXXXXXXXXXXXXXXXX'),
|
||||
},
|
||||
]
|
||||
|
||||
+2
-2
@@ -126,7 +126,7 @@ export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
|
||||
export { resolveLocalized } from './modules/i18n/index.js'
|
||||
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js'
|
||||
export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js'
|
||||
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'
|
||||
export { buildLinkField, buildLinksField, resolveLinkHref, safeHref } from './modules/links/index.js'
|
||||
export type {
|
||||
BuildLinkFieldOptions,
|
||||
BuildLinksFieldOptions,
|
||||
@@ -153,7 +153,7 @@ export {
|
||||
|
||||
// Lexical → Markdown (pure, no React) — for AI-readable output.
|
||||
export { lexicalToMarkdown } from './modules/richtext/index.js'
|
||||
export { buildSecurityHeaders } from './modules/security/index.js'
|
||||
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './modules/security/index.js'
|
||||
export { buildCsp } from './modules/security/index.js'
|
||||
export type { BuildCspArgs } from './modules/security/index.js'
|
||||
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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}`
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,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'
|
||||
|
||||
@@ -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,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'
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/** Unpublished drafts must never be served by the public routing helpers. */
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { buildConfig, getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
|
||||
|
||||
import { resolveRoute } from '../src/modules/content/resolveRoute.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
|
||||
let payload: Payload
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildConfig({
|
||||
collections: [
|
||||
{
|
||||
slug: 'pages',
|
||||
fields: [
|
||||
{ name: 'title', type: 'text' },
|
||||
{ name: 'slug', type: 'text', localized: true },
|
||||
],
|
||||
versions: { drafts: true },
|
||||
},
|
||||
{ slug: 'posts', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }], versions: { drafts: true } },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
|
||||
],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [
|
||||
ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
content: { collections: [{ slug: 'posts' }] },
|
||||
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
||||
pages: { slug: 'pages' },
|
||||
twoFactor: false,
|
||||
}),
|
||||
],
|
||||
secret: 'drafts-test',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await payload?.destroy()
|
||||
})
|
||||
|
||||
describe('drafts', () => {
|
||||
test('a never-published draft page is not resolvable', async () => {
|
||||
await payload.create({ collection: 'pages' as never, data: { slug: 'tajne', _status: 'draft', title: 'Tajne' } as never, draft: true })
|
||||
expect(await resolveRoute({ locale: 'pl', payload, segments: ['tajne'] })).toBeNull()
|
||||
})
|
||||
|
||||
test('a published page is resolvable, and a later draft does not replace it', async () => {
|
||||
const doc = await payload.create({ collection: 'pages' as never, data: { slug: 'oferta', _status: 'published', title: 'Oferta' } as never })
|
||||
await payload.update({ id: doc.id, collection: 'pages' as never, data: { title: 'Oferta — szkic zmian' } as never, draft: true })
|
||||
const route = await resolveRoute({ locale: 'pl', payload, segments: ['oferta'] })
|
||||
expect((route?.doc as { title?: string })?.title).toBe('Oferta')
|
||||
})
|
||||
})
|
||||
|
||||
describe('archive listing', () => {
|
||||
test('lists only published entries when the collection has drafts', async () => {
|
||||
const { getArchiveEntries } = await import('../src/modules/content/getArchiveEntries.js')
|
||||
await payload.create({ collection: 'posts' as never, data: { slug: 'jawny', _status: 'published', title: 'Jawny' } as never })
|
||||
await payload.create({ collection: 'posts' as never, data: { slug: 'szkic', _status: 'draft', title: 'Szkic' } as never, draft: true })
|
||||
const list = await getArchiveEntries({ collection: 'posts', locale: 'pl', payload })
|
||||
expect(list.docs.map((d) => (d as { title: string }).title)).toEqual(['Jawny'])
|
||||
expect(list.totalDocs).toBe(1)
|
||||
const preview = await getArchiveEntries({ collection: 'posts', draft: true, locale: 'pl', payload })
|
||||
expect(preview.totalDocs).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -219,3 +219,26 @@ describe('cookie table', () => {
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('forms access', () => {
|
||||
test('anonymous REST read of a form hides its e-mail recipients; submissions are staff-only', async () => {
|
||||
await payload.update({
|
||||
id: formId,
|
||||
collection: 'forms' as never,
|
||||
data: { emails: [{ emailTo: '[email protected]', subject: 'Nowe zgłoszenie' }] } as never,
|
||||
})
|
||||
const anon = (await payload.findByID({ id: formId, collection: 'forms' as never, overrideAccess: false })) as Record<string, unknown>
|
||||
expect(anon.fields).toBeDefined()
|
||||
expect(JSON.stringify(anon.emails ?? [])).not.toContain('[email protected]')
|
||||
|
||||
const user = (await payload.create({
|
||||
collection: 'users',
|
||||
data: { email: '[email protected]', password: 'Passw0rd!x' } as never,
|
||||
})) as unknown as Record<string, unknown>
|
||||
await expect(
|
||||
payload.find({ collection: 'form-submissions' as never, overrideAccess: false, user: { ...user, collection: 'users' } as never }),
|
||||
).rejects.toThrow()
|
||||
const editor = { ...user, collection: 'users', roles: ['editor'] }
|
||||
expect((await payload.find({ collection: 'form-submissions' as never, overrideAccess: false, user: editor as never })).totalDocs).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -213,3 +213,26 @@ describe('consent storage — version and id', () => {
|
||||
expect(readConsentRecord(raw)).toBeNull() // default version 1
|
||||
})
|
||||
})
|
||||
|
||||
describe('safeHref / resolveLinkHref', () => {
|
||||
test('only safe schemes survive', async () => {
|
||||
const { resolveLinkHref, safeHref } = await import('../src/modules/links/resolveLinkHref.js')
|
||||
for (const ok of ['https://acme.pl', 'mailto:[email protected]', 'tel:+48123', '#kontakt', '/pl/o-nas']) {expect(safeHref(ok)).toBe(ok)}
|
||||
for (const bad of ['javascript:alert(1)', ' JavaScript:alert(1)', 'java\tscript:alert(1)', 'data:text/html,x', '//evil.com', 'vbscript:x', '']) {
|
||||
expect(safeHref(bad)).toBeNull()
|
||||
}
|
||||
expect(resolveLinkHref({ type: 'external', url: 'javascript:alert(1)' }, { config, locale: 'pl' })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildUploadSecurityHeaders', () => {
|
||||
test('sandboxes files served from upload routes', async () => {
|
||||
const { buildUploadSecurityHeaders } = await import('../src/modules/security/buildSecurityHeaders.js')
|
||||
const rules = buildUploadSecurityHeaders({ collections: ['media', 'documents'] })
|
||||
expect(rules.map((r) => r.source)).toEqual(['/api/media/file/:path*', '/api/documents/file/:path*'])
|
||||
const csp = rules[0].headers.find((h) => h.key === 'Content-Security-Policy')?.value ?? ''
|
||||
expect(csp).toContain('sandbox')
|
||||
expect(csp).toContain("default-src 'none'")
|
||||
expect(csp).not.toContain('script-src')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user