Payload's colour-scheme client hints go to the admin only: withSecurityConfig outside withPayload

withPayload adds Accept-CH, Critical-CH and Vary: Sec-CH-Prefers-Color-Scheme for /:path*; Critical-CH makes
Chrome repeat the first document request of a visit to a public page. As the outer wrapper, withSecurityConfig
moves the three headers to /admin/:path* (adminClientHints: { route, sources } | false). Inside withPayload
nothing changes, so an unedited site behaves as before. Exports scopeColorSchemeClientHints,
adminClientHintSources, COLOR_SCHEME_CLIENT_HINT; doctor rule client-hints (info); reference site and starter
use the new order; e2e:built and the starter gate check it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 11:55:26 +01:00
co-authored by Claude Fable 5.2
parent 2f6a81acbf
commit 9143c132a3
28 changed files with 500 additions and 59 deletions
+30
View File
@@ -493,6 +493,12 @@ describe('security and deep status', () => {
expect(rules(await doctor(root, ['security']))).toContain('csp:info')
expect(rules(await doctor(root, ['csp'], { config: { seen: { 'csp-report-only': '2026-09-01' } } }))).toEqual(['csp:warning'])
})
test('client-hints: withSecurityConfig inside withPayload is reported (info); outside, or kept on purpose, is not', async () => {
const inner = project(next('export default withPayload(\n withSecurityConfig(nextConfig))'))
expect(rules(await doctor(inner, ['client-hints']))).toEqual(['client-hints:info'])
expect(rules(await doctor(project(next('export default withSecurityConfig(withPayload(nextConfig))')), ['client-hints']))).toEqual([])
expect(rules(await doctor(project(next('export default withPayload(withSecurityConfig(nextConfig, { adminClientHints: false }))')), ['client-hints']))).toEqual([])
})
test('deep status: users without TOTP, pending cookies, stale import map, env problems', async () => {
const root = project({ ...base(), 'src/app/(payload)/admin/importMap.js': '', 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }, cookieScanner: { crawl: true }', ...installed('@clocklimited/payload-2fa', '3.0.0') })
const report = await doctor(root, ['2fa', 'cookie-scanner', 'importmap', 'env-live', 'deep-status'], {
@@ -595,6 +601,30 @@ describe('live (--url)', () => {
})
})
describe('live (--url): client hints', () => {
let server: Server
let url = ''
let headers: Record<string, string> = {}
beforeAll(async () => {
server = createServer((_req, res) => res.writeHead(200, headers).end('ok'))
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
url = `http://127.0.0.1:${(server.address() as { port: number }).port}`
})
afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())))
test('a public page that sends Critical-CH for the colour scheme is reported; without it, or kept on purpose, not', async () => {
const outer = { ...base(), 'next.config.ts': 'export default withSecurityConfig(withPayload(nextConfig))' }
headers = { 'Accept-CH': 'Sec-CH-Prefers-Color-Scheme', 'Critical-CH': 'Sec-CH-Prefers-Color-Scheme' }
expect((await doctor(project(outer), ['client-hints'], { url })).findings.map((f) => `${f.severity}: ${f.message}`)).toEqual([
'info: live / sends Critical-CH: Sec-CH-Prefers-Color-Scheme (only the admin needs it)',
])
const kept = { ...base(), 'next.config.ts': 'export default withSecurityConfig(withPayload(nextConfig), { adminClientHints: false })' }
expect((await doctor(project(kept), ['client-hints'], { url })).findings).toEqual([])
headers = {}
expect((await doctor(project(outer), ['client-hints'], { url })).findings).toEqual([])
})
})
describe('CLI', () => {
const clean = () => project({ ...base(), 'AGENTS.md': '## Project decisions\n- x\n<!-- iapl:start -->\n## IAPL 1.14.6 — agent guide\n<!-- iapl:end -->', 'CLAUDE.md': '@AGENTS.md\n' })
const cli = async (args: string[], cwd: string) => {
+98
View File
@@ -7,14 +7,17 @@ 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'
@@ -62,6 +65,101 @@ describe('withSecurityConfig (X-Powered-By)', () => {
})
})
describe('withSecurityConfig (colour-scheme client hints for the admin only)', () => {
type Rule = { headers: { key: string; value: string }[]; source: string } & Record<string, unknown>
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')