diff --git a/src/globals/SiteIntegrations/fields/analytics.ts b/src/globals/SiteIntegrations/fields/analytics.ts index ca29481..104508b 100644 --- a/src/globals/SiteIntegrations/fields/analytics.ts +++ b/src/globals/SiteIntegrations/fields/analytics.ts @@ -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'), }, ] diff --git a/src/index.ts b/src/index.ts index 97e262e..b33aced 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' diff --git a/src/modules/analytics/getAnalyticsConfig.ts b/src/modules/analytics/getAnalyticsConfig.ts index d7773d5..21b3db4 100644 --- a/src/modules/analytics/getAnalyticsConfig.ts +++ b/src/modules/analytics/getAnalyticsConfig.ts @@ -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 { const integrations = await getSiteIntegrations(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), } } diff --git a/src/modules/analytics/idFormats.ts b/src/modules/analytics/idFormats.ts new file mode 100644 index 0000000..381b7d2 --- /dev/null +++ b/src/modules/analytics/idFormats.ts @@ -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}` diff --git a/src/modules/content/getArchiveEntries.ts b/src/modules/content/getArchiveEntries.ts index a205e65..cfaa012 100644 --- a/src/modules/content/getArchiveEntries.ts +++ b/src/modules/content/getArchiveEntries.ts @@ -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>({ collection, depth = 1, + draft = false, locale, page = 1, payload, @@ -48,14 +52,20 @@ export async function getArchiveEntries>({ sort = '-createdAt', where, }: GetArchiveEntriesArgs): Promise> { + 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 { diff --git a/src/modules/content/resolveRoute.ts b/src/modules/content/resolveRoute.ts index 9fc8f6c..d7afe46 100644 --- a/src/modules/content/resolveRoute.ts +++ b/src/modules/content/resolveRoute.ts @@ -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 } : null + return doc && isPublic(doc, draft) ? { type: 'home', doc: doc as Record } : 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 diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index fc85b9e..491e812 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -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 }, diff --git a/src/modules/links/index.ts b/src/modules/links/index.ts index 3d61db6..c4af8fb 100644 --- a/src/modules/links/index.ts +++ b/src/modules/links/index.ts @@ -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' diff --git a/src/modules/links/resolveLinkHref.ts b/src/modules/links/resolveLinkHref.ts index 41a72e9..10e27c6 100644 --- a/src/modules/links/resolveLinkHref.ts +++ b/src/modules/links/resolveLinkHref.ts @@ -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 diff --git a/src/modules/security/buildSecurityHeaders.ts b/src/modules/security/buildSecurityHeaders.ts index eb0b09b..ce07735 100644 --- a/src/modules/security/buildSecurityHeaders.ts +++ b/src/modules/security/buildSecurityHeaders.ts @@ -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*` })) +} diff --git a/src/modules/security/index.ts b/src/modules/security/index.ts index 9fde34a..9ae7397 100644 --- a/src/modules/security/index.ts +++ b/src/modules/security/index.ts @@ -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' diff --git a/test/drafts.test.ts b/test/drafts.test.ts new file mode 100644 index 0000000..c1d2277 --- /dev/null +++ b/test/drafts.test.ts @@ -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) + }) +}) diff --git a/test/integration.test.ts b/test/integration.test.ts index 1828994..6c67927 100644 --- a/test/integration.test.ts +++ b/test/integration.test.ts @@ -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: 'biuro@acme.pl', subject: 'Nowe zgłoszenie' }] } as never, + }) + const anon = (await payload.findByID({ id: formId, collection: 'forms' as never, overrideAccess: false })) as Record + expect(anon.fields).toBeDefined() + expect(JSON.stringify(anon.emails ?? [])).not.toContain('biuro@acme.pl') + + const user = (await payload.create({ + collection: 'users', + data: { email: 'plain@acme.pl', password: 'Passw0rd!x' } as never, + })) as unknown as Record + 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) + }) +}) diff --git a/test/seo.test.ts b/test/seo.test.ts index f9573f1..3e89b0c 100644 --- a/test/seo.test.ts +++ b/test/seo.test.ts @@ -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:a@b.pl', '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') + }) +})