import type { NextConfig } from 'next' import { withPayload } from '@payloadcms/next/withPayload' import { describe, expect, test, vi } from 'vitest' import type { I18nConfig } from '../src/modules/i18n/types.js' import { createProxy } from '../src/modules/i18n/createProxy.js' import { adminClientHintSources, buildAdminCsp, buildAdminCspHeaders, buildCsp, buildCspHeaders, buildSecurityHeaders, COLOR_SCHEME_CLIENT_HINT, createCspNonce, createCspReportRoute, parseCspReports, scopeColorSchemeClientHints, withSecurityConfig, } from '../src/modules/security/index.js' const directive = (value: string, name: string) => value .split('; ') .find((d) => d.startsWith(`${name} `)) ?.split(' ') .slice(1) ?? null describe('withSecurityConfig (X-Powered-By)', () => { const payloadLike = { headers: [{ key: 'X-Powered-By', value: 'Next.js, Payload' }, { key: 'Vary', value: 'x' }], source: '/:path*' } test('sets poweredByHeader: false (Next and withPayload both honour it)', () => { expect(withSecurityConfig({}).poweredByHeader).toBe(false) expect(withSecurityConfig({ poweredByHeader: true }).poweredByHeader).toBe(false) }) test('strips X-Powered-By from headers() — works outside withPayload too', async () => { const config: NextConfig = withSecurityConfig({ headers: async () => [payloadLike, { headers: [{ key: 'x-powered-by', value: 'a' }], source: '/a' }] }) const rules = await config.headers!() expect(rules.flatMap((r) => r.headers.map((h) => h.key))).toEqual(['Vary']) expect(rules[0]?.source).toBe('/:path*') }) test('real withPayload: no X-Powered-By on either side of the wrapper', async () => { const keys = async (c: NextConfig) => (await c.headers!()).flatMap((r) => r.headers.map((h) => h.key.toLowerCase())) expect(await keys(withPayload({}))).toContain('x-powered-by') // the problem being fixed const inner = withPayload(withSecurityConfig({})) expect(inner.poweredByHeader).toBe(false) expect(await keys(inner)).not.toContain('x-powered-by') const outer = withSecurityConfig(withPayload({})) expect(outer.poweredByHeader).toBe(false) expect(await keys(outer)).not.toContain('x-powered-by') }) test('hidePoweredBy: false leaves the config untouched', () => { const config = { poweredByHeader: true } expect(withSecurityConfig(config, { hidePoweredBy: false })).toBe(config) }) test('keeps the rest of the config', () => { expect(withSecurityConfig({ images: { formats: ['image/avif'] } })).toMatchObject({ images: { formats: ['image/avif'] } }) }) }) describe('withSecurityConfig (colour-scheme client hints for the admin only)', () => { type Rule = { headers: { key: string; value: string }[]; source: string } & Record const HINT = /sec-ch-prefers-color-scheme/i const rulesOf = async (c: NextConfig) => (await c.headers!()) as Rule[] /** Rules that still carry the hint in any header, by source. */ const hinted = (rules: Rule[]) => rules.filter((r) => r.headers.some((h) => HINT.test(h.value))).map((r) => r.source) const header = (rule: Rule | undefined, key: string) => rule?.headers.find((h) => h.key.toLowerCase() === key)?.value const own = { headers: [{ key: 'X-Frame-Options', value: 'DENY' }, { key: 'Vary', value: 'Accept' }], source: '/:path*' } test('real withPayload sends the hints for every path: the problem being fixed', async () => { expect(hinted(await rulesOf(withPayload({})))).toEqual(['/:path*']) }) test('outside withPayload: the three headers go to the admin only, nothing else changes', async () => { const rules = await rulesOf(withSecurityConfig(withPayload({ headers: async () => [own] }))) // FAILS when the hints come back on a public route expect(hinted(rules)).toEqual(['/admin/:path*']) const admin = rules.find((r) => r.source === '/admin/:path*') expect(admin?.headers).toEqual([ { key: 'Accept-CH', value: COLOR_SCHEME_CLIENT_HINT }, { key: 'Vary', value: COLOR_SCHEME_CLIENT_HINT }, { key: 'Critical-CH', value: COLOR_SCHEME_CLIENT_HINT }, ]) // the project's own rule is untouched, and no site-wide rule is left with Accept-CH / Critical-CH / an empty Vary expect(rules[0]).toEqual(own) const siteWide = rules.filter((r) => r.source === '/:path*').flatMap((r) => r.headers.map((h) => h.key.toLowerCase())) expect(siteWide).toEqual(['x-frame-options', 'vary']) expect(rules.flatMap((r) => r.headers).filter((h) => !h.value)).toEqual([]) }) test('no rule is left without headers (Next stops the build on one)', async () => { // withPayload's rule is hints + X-Powered-By: with both taken out nothing is left of it on /:path* for (const config of [withSecurityConfig(withPayload({})), withSecurityConfig(withPayload({ headers: async () => [own] })), withSecurityConfig(withPayload({ poweredByHeader: false }))]) { const rules = await rulesOf(config) expect(rules.filter((r) => !r.headers.length)).toEqual([]) expect(hinted(rules)).toEqual(['/admin/:path*']) } expect((await rulesOf(withSecurityConfig(withPayload({})))).map((r) => r.source)).toEqual(['/admin/:path*']) }) test('inside withPayload it cannot see the rule: behaviour as before the change (an old site is not broken)', async () => { const rules = await rulesOf(withPayload(withSecurityConfig({ headers: async () => [own] }))) expect(hinted(rules)).toEqual(['/:path*']) expect(rules.flatMap((r) => r.headers.map((h) => h.key.toLowerCase()))).not.toContain('x-powered-by') }) test('route: a changed routes.admin; sources: more paths', async () => { expect(hinted(await rulesOf(withSecurityConfig(withPayload({}), { adminClientHints: { route: '/panel' } })))).toEqual(['/panel/:path*']) expect(hinted(await rulesOf(withSecurityConfig(withPayload({}), { adminClientHints: { route: 'cms/', sources: ['/preview/:path*'] } })))).toEqual(['/cms/:path*', '/preview/:path*']) expect(adminClientHintSources()).toEqual(['/admin/:path*']) // an admin at the root: every path IS the admin, the rule stays expect(adminClientHintSources('/')).toEqual(['/:path*']) expect(hinted(await rulesOf(withSecurityConfig(withPayload({}), { adminClientHints: { route: '/' } })))).toEqual(['/:path*']) }) test('adminClientHints: false restores the old behaviour; hidePoweredBy is independent', async () => { const kept = await rulesOf(withSecurityConfig(withPayload({}), { adminClientHints: false })) expect(hinted(kept)).toEqual(['/:path*']) expect(kept.flatMap((r) => r.headers.map((h) => h.key))).not.toContain('X-Powered-By') const both = await rulesOf(withSecurityConfig(withPayload({}), { hidePoweredBy: false })) expect(hinted(both)).toEqual(['/admin/:path*']) expect(both.flatMap((r) => r.headers.map((h) => h.key))).toContain('X-Powered-By') const config = withPayload({}) expect(withSecurityConfig(config, { adminClientHints: false, hidePoweredBy: false })).toBe(config) }) test('scopeColorSchemeClientHints: other tokens stay, rule options are carried, narrower rules are left alone', () => { const rules = scopeColorSchemeClientHints([ { basePath: false, has: [{ type: 'header', key: 'x' }], headers: [ { key: 'accept-ch', value: 'Sec-CH-UA, sec-ch-prefers-color-scheme' }, { key: 'Vary', value: 'RSC, Sec-CH-Prefers-Color-Scheme, Accept' }, { key: 'Critical-CH', value: 'Sec-CH-Prefers-Color-Scheme' }, { key: 'X-A', value: '1' }, ], source: '/(.*)' }, { headers: [{ key: 'Accept-CH', value: 'Sec-CH-Prefers-Color-Scheme' }], source: '/shop/:path*' }, { headers: [{ key: 'Vary', value: 'Accept-Encoding' }], source: '/:path*' }, ]) expect(rules).toEqual([ { basePath: false, has: [{ type: 'header', key: 'x' }], headers: [ { key: 'accept-ch', value: 'Sec-CH-UA' }, { key: 'Vary', value: 'RSC, Accept' }, { key: 'X-A', value: '1' }, ], source: '/(.*)' }, { headers: [{ key: 'Accept-CH', value: 'Sec-CH-Prefers-Color-Scheme' }], source: '/shop/:path*' }, { headers: [{ key: 'Vary', value: 'Accept-Encoding' }], source: '/:path*' }, { basePath: false, has: [{ type: 'header', key: 'x' }], headers: [ { key: 'accept-ch', value: 'Sec-CH-UA, sec-ch-prefers-color-scheme' }, { key: 'Vary', value: 'RSC, Sec-CH-Prefers-Color-Scheme, Accept' }, { key: 'Critical-CH', value: 'Sec-CH-Prefers-Color-Scheme' }, ], source: '/admin/:path*' }, ]) expect(header(rules.at(-1) as Rule, 'x-a')).toBeUndefined() }) }) describe('buildCsp', () => { test('mode picks the header; report-only first, enforce with one option', () => { expect(buildCsp({ mode: 'report-only' }).key).toBe('Content-Security-Policy-Report-Only') expect(buildCsp({ mode: 'enforce' }).key).toBe('Content-Security-Policy') expect(buildCsp().key).toBe('Content-Security-Policy') }) test('hard rules are always there', () => { const { value } = buildCsp({ dev: false }) expect(directive(value, 'base-uri')).toEqual(["'self'"]) expect(directive(value, 'object-src')).toEqual(["'none'"]) expect(directive(value, 'frame-ancestors')).toEqual(["'none'"]) expect(directive(value, 'script-src')).toEqual(["'self'", "'unsafe-inline'"]) }) test('dev adds unsafe-eval; production does not', () => { expect(directive(buildCsp({ dev: true }).value, 'script-src')).toContain("'unsafe-eval'") expect(directive(buildCsp({ dev: false }).value, 'script-src')).not.toContain("'unsafe-eval'") }) test('reportUri adds report-uri and report-to', () => { const { value } = buildCsp({ reportUri: '/api/csp-report' }) expect(directive(value, 'report-uri')).toEqual(['/api/csp-report']) expect(directive(value, 'report-to')).toEqual(['csp-endpoint']) expect(directive(buildCsp({ reportGroup: 'g', reportUri: '/r' }).value, 'report-to')).toEqual(['g']) }) test('nonce: nonce + strict-dynamic first in script-src; strictDynamic: false drops it', () => { const script = directive(buildCsp({ dev: false, nonce: 'abc' }).value, 'script-src') expect(script?.slice(0, 2)).toEqual(["'nonce-abc'", "'strict-dynamic'"]) expect(directive(buildCsp({ nonce: 'abc', strictDynamic: false }).value, 'script-src')).not.toContain("'strict-dynamic'") }) test('every third party the plugin loads has a flag', () => { const { value } = buildCsp({ analytics: true, clarity: true, linkedIn: true, metaPixel: true, r2Url: 'https://media.acme.pl', tiktok: true, turnstile: true, youtube: true }) const script = directive(value, 'script-src')! for (const host of ['https://*.googletagmanager.com', 'https://connect.facebook.net', 'https://snap.licdn.com', 'https://analytics.tiktok.com', 'https://*.clarity.ms', 'https://challenges.cloudflare.com']) { expect(script).toContain(host) } expect(directive(value, 'connect-src')).toEqual(expect.arrayContaining(['https://*.google-analytics.com', 'https://px.ads.linkedin.com', 'https://www.facebook.com'])) expect(directive(value, 'frame-src')).toEqual(expect.arrayContaining(['https://www.youtube-nocookie.com', 'https://challenges.cloudflare.com'])) expect(directive(value, 'img-src')).toEqual(expect.arrayContaining(['https://media.acme.pl', 'https://i.ytimg.com'])) expect(directive(value, 'media-src')).toEqual(["'self'", 'https://media.acme.pl']) }) test('site-relative r2Url is covered by self', () => { expect(directive(buildCsp({ r2Url: '/media' }).value, 'img-src')).toEqual(["'self'", 'data:', 'blob:']) }) test('extra extends any directive, override replaces or drops one', () => { const { value } = buildCsp({ extra: { 'manifest-src': ["'self'"], 'script-src': ['https://x.example'] }, override: { 'frame-ancestors': ["'self'"], 'style-src': null }, }) expect(directive(value, 'script-src')).toContain('https://x.example') expect(directive(value, 'manifest-src')).toEqual(["'self'"]) expect(directive(value, 'frame-ancestors')).toEqual(["'self'"]) expect(directive(value, 'style-src')).toBeNull() }) test('buildCspHeaders adds Reporting-Endpoints only with reportUri', () => { expect(buildCspHeaders({}).map((h) => h.key)).toEqual(['Content-Security-Policy']) expect(buildCspHeaders({ mode: 'report-only', reportUri: '/api/csp-report' })).toEqual([ expect.objectContaining({ key: 'Content-Security-Policy-Report-Only' }), { key: 'Reporting-Endpoints', value: 'csp-endpoint="/api/csp-report"' }, ]) }) }) describe('buildAdminCsp', () => { test('looser policy for Payload admin: Monaco CDN, blob workers, framed by self', () => { const { value } = buildAdminCsp({ dev: false, r2Url: 'https://media.acme.pl' }) expect(directive(value, 'script-src')).toEqual(["'self'", "'unsafe-inline'", 'https://cdn.jsdelivr.net']) expect(directive(value, 'worker-src')).toEqual(["'self'", 'blob:']) expect(directive(value, 'frame-ancestors')).toEqual(["'self'"]) expect(directive(value, 'object-src')).toEqual(["'none'"]) expect(directive(value, 'img-src')).toContain('https://media.acme.pl') }) test('extra merges with the admin sources instead of replacing them', () => { expect(directive(buildAdminCsp({ extra: { 'script-src': ['https://y.example'] } }).value, 'script-src')).toEqual( expect.arrayContaining(['https://cdn.jsdelivr.net', 'https://y.example']), ) }) test('report-only + Reporting-Endpoints', () => { expect(buildAdminCspHeaders({ mode: 'report-only', reportUri: '/r' }).map((h) => h.key)).toEqual([ 'Content-Security-Policy-Report-Only', 'Reporting-Endpoints', ]) }) }) describe('buildSecurityHeaders csp', () => { test('off by default', () => { expect(buildSecurityHeaders().some((h) => /content-security/i.test(h.key))).toBe(false) }) test('csp args add the policy and Reporting-Endpoints; additional still overrides', () => { const headers = buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report' } }) expect(headers.map((h) => h.key)).toEqual(expect.arrayContaining(['Content-Security-Policy-Report-Only', 'Reporting-Endpoints'])) const own = buildSecurityHeaders({ additional: [{ key: 'Content-Security-Policy-Report-Only', value: "default-src 'self'" }], csp: { mode: 'report-only' }, }) expect(own.filter((h) => h.key === 'Content-Security-Policy-Report-Only')).toEqual([{ key: 'Content-Security-Policy-Report-Only', value: "default-src 'self'" }]) }) }) describe('createCspReportRoute', () => { const post = (body: string, type = 'application/csp-report') => new Request('https://acme.pl/api/csp-report', { body, headers: { 'content-type': type }, method: 'POST' }) test('report-uri format', async () => { const onReport = vi.fn() const res = await createCspReportRoute({ onReport })( post(JSON.stringify({ 'csp-report': { 'blocked-uri': 'https://evil.example/x.js', 'document-uri': 'https://acme.pl/pl', 'violated-directive': 'script-src-elem' } })), ) expect(res.status).toBe(204) expect(onReport).toHaveBeenCalledWith(expect.objectContaining({ blockedUri: 'https://evil.example/x.js', effectiveDirective: 'script-src-elem' })) }) test('Reporting API format, other report types ignored', async () => { const onReport = vi.fn() await createCspReportRoute({ onReport })( post( JSON.stringify([ { type: 'csp-violation', body: { blockedURL: 'inline', disposition: 'report', documentURL: 'https://acme.pl/', effectiveDirective: 'script-src-elem' } }, { type: 'deprecation', body: {} }, ]), 'application/reports+json', ), ) expect(onReport).toHaveBeenCalledTimes(1) expect(onReport.mock.calls[0][0]).toMatchObject({ blockedUri: 'inline', disposition: 'report' }) }) test('bad JSON → 400, too big → 413, failing sink still 204', async () => { expect((await createCspReportRoute()(post('{nope'))).status).toBe(400) expect((await createCspReportRoute({ maxBytes: 10 })(post(JSON.stringify({ 'csp-report': { a: 'x'.repeat(50) } })))).status).toBe(413) const throwing = createCspReportRoute({ onReport: () => { throw new Error('x') } }) expect((await throwing(post(JSON.stringify({ 'csp-report': {} })))).status).toBe(204) }) test('parseCspReports ignores unknown shapes', () => { expect(parseCspReports(null)).toEqual([]) expect(parseCspReports({ foo: 1 })).toEqual([]) }) }) describe('createProxy csp (nonce)', () => { const config: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } type Res = { cookies: { set: () => void }; headers: Headers; init?: { request?: { headers: Headers } } } const NextResponse = { next: (init?: { request?: { headers: Headers } }): Res => ({ cookies: { set: () => {} }, headers: new Headers(), init }), redirect: (): Res => ({ cookies: { set: () => {} }, headers: new Headers() }), } const request = (path: string) => { const url = new URL(`https://acme.pl${path}`) return { cookies: { get: () => undefined }, headers: new Headers(), nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: url.search }, url: url.toString() } } test('fresh nonce per request on the request (for Next) and response, x-nonce for the layout', () => { const proxy = createProxy(config, { csp: { mode: 'report-only', reportUri: '/api/csp-report' }, NextResponse }) const a = proxy(request('/pl')) as unknown as Res const b = proxy(request('/pl')) as unknown as Res const nonce = a.init!.request!.headers.get('x-nonce')! expect(nonce).toMatch(/^[A-Z0-9+/=]{20,}$/i) expect(b.init!.request!.headers.get('x-nonce')).not.toBe(nonce) const policy = a.headers.get('Content-Security-Policy-Report-Only')! expect(policy).toContain(`'nonce-${nonce}'`) expect(a.init!.request!.headers.get('Content-Security-Policy-Report-Only')).toBe(policy) expect(a.headers.get('Reporting-Endpoints')).toBe('csp-endpoint="/api/csp-report"') }) test('no csp → no CSP headers', () => { const res = createProxy(config, { NextResponse })(request('/pl')) as unknown as Res expect(res.headers.get('Content-Security-Policy')).toBeNull() expect(res.init!.request!.headers.get('x-nonce')).toBeNull() }) test('createCspNonce is unique base64', () => { expect(createCspNonce()).not.toBe(createCspNonce()) expect(atob(createCspNonce())).toMatch(/^[0-9a-f-]{36}$/) }) })