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
+22 -1
View File
@@ -45,7 +45,7 @@ export const securityRules: DoctorRule[] = [
check: async (ctx) => {
const out: RuleFinding[] = []
if (!/withSecurityConfig\s*\(|poweredByHeader\s*:\s*false/.test(next(ctx))) {
out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: 'export default withPayload(withSecurityConfig(nextConfig))', message: 'X-Powered-By is not hidden (withSecurityConfig)', severity: 'error' })
out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: 'export default withSecurityConfig(withPayload(nextConfig))', message: 'X-Powered-By is not hidden (withSecurityConfig)', severity: 'error' })
}
if (ctx.live) {
for (const path of ['/', `${ctx.live.adminRoute}/login`]) {
@@ -60,6 +60,27 @@ export const securityRules: DoctorRule[] = [
group: 'security',
source: 'static',
},
{
id: 'client-hints',
check: async (ctx) => {
const out: RuleFinding[] = []
const code = next(ctx)
const kept = /adminClientHints\s*:\s*false/.test(code)
if (!kept && /withPayload\s*\(\s*withSecurityConfig\s*\(/.test(code)) {
out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: 'export default withSecurityConfig(withPayload(nextConfig))', message: "withSecurityConfig is inside withPayload: Payload's colour-scheme client hints go out with every page (Chrome repeats the first request of a visit)", severity: 'info' })
}
if (ctx.live && !kept) {
const res = await ctx.live.fetch('/')
if (/sec-ch-prefers-color-scheme/i.test(res.headers.get('critical-ch') ?? '')) {
out.push({ fix: 'withSecurityConfig(withPayload(nextConfig)) (security.md → Client hints)', message: 'live / sends Critical-CH: Sec-CH-Prefers-Color-Scheme (only the admin needs it)', severity: 'info' })
}
}
return out
},
docs: 'docs/security.md',
group: 'security',
source: 'static',
},
{
id: 'csp',
check: async (ctx) => {
+2 -2
View File
@@ -15,5 +15,5 @@ export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRo
export { createCspNonce, CSP_NONCE_HEADER } from './cspNonce.js'
export { totpAdminPath, totpRedirectTarget } from './totp/totpRedirect.js'
export type { TotpRedirectArgs, TotpUser } from './totp/totpRedirect.js'
export { withSecurityConfig } from './withSecurityConfig.js'
export type { WithSecurityConfigOptions } from './withSecurityConfig.js'
export { adminClientHintSources, COLOR_SCHEME_CLIENT_HINT, scopeColorSchemeClientHints, withSecurityConfig } from './withSecurityConfig.js'
export type { AdminClientHintsOptions, WithSecurityConfigOptions } from './withSecurityConfig.js'
+113 -18
View File
@@ -2,13 +2,32 @@
* Minimal structural shape of a Next config — the plugin does not import `next`
* types into this helper; Next's real NextConfig satisfies it at the call site.
*/
type HeaderRule = { headers: { key: string; value: string }[] } & Record<string, unknown>
type Header = { key: string; value: string }
type HeaderRule = { headers: Header[]; source?: string } & Record<string, unknown>
type NextConfigLike = {
headers?: () => HeaderRule[] | Promise<HeaderRule[]>
poweredByHeader?: boolean
}
export type AdminClientHintsOptions = {
/** Payload's `routes.admin`. Default `/admin`. */
route?: string
/**
* More Next `source` patterns that keep the colour-scheme hint headers, besides the panel
* (for example a page of the project that reads `Sec-CH-Prefers-Color-Scheme` on the server).
*/
sources?: string[]
}
export type WithSecurityConfigOptions = {
/**
* Send Payload's colour-scheme client hint headers (`Accept-CH`, `Critical-CH`, `Vary` with
* `Sec-CH-Prefers-Color-Scheme`) for the admin panel only, not for every path. Default true.
* Works only when this wrapper is the OUTER one: `withSecurityConfig(withPayload(nextConfig))`.
* An object sets the panel's route (`route`, default `/admin`) and extra paths (`sources`);
* `false` leaves the headers where withPayload put them (every path).
*/
adminClientHints?: AdminClientHintsOptions | boolean
/**
* Remove `X-Powered-By` (Next's own "Next.js" and the "Next.js, Payload" that
* withPayload adds) — it tells scanners which software to target. Default true;
@@ -17,38 +36,114 @@ export type WithSecurityConfigOptions = {
hidePoweredBy?: boolean
}
/** The client hint Payload's admin reads to pick light or dark before the first paint. */
export const COLOR_SCHEME_CLIENT_HINT = 'Sec-CH-Prefers-Color-Scheme'
const HINT = COLOR_SCHEME_CLIENT_HINT.toLowerCase()
const HINT_HEADERS = new Set(['accept-ch', 'critical-ch', 'vary'])
/** Sources that mean "every path": the shape of the rule withPayload adds. */
const SITE_WIDE = new Set(['/(.*)', '/:path(.*)', '/:path*'])
const tokens = (value: string) => value.split(',').map((t) => t.trim()).filter(Boolean)
/**
* Next config wrapper for the security settings that are not response headers
* the project adds itself. Today: hides `X-Powered-By`.
* Next `source` patterns of the admin panel for a `routes.admin` value: `/admin` → `['/admin/:path*']`
* (`:path*` also matches `/admin` itself). An admin at the root gives `['/:path*']`.
*/
export function adminClientHintSources(route = '/admin'): string[] {
const clean = `/${route}`.replace(/\/+/g, '/').replace(/\/$/, '')
return [`${clean}/:path*`]
}
/**
* Moves the colour-scheme client hint headers of site-wide rules to the given sources.
*
* Where the header comes from: Next sends `X-Powered-By: Next.js` unless
* `poweredByHeader: false`; Payload's withPayload switches Next's off and adds
* `X-Powered-By: Next.js, Payload` through headers() — also unless the config it
* wraps says `poweredByHeader: false`. This helper sets that flag AND drops the
* header from headers() rules, so it works on either side of withPayload:
* Where they come from: Payload's withPayload appends `Accept-CH`, `Critical-CH` and `Vary`, all with the value
* `Sec-CH-Prefers-Color-Scheme`, for `/:path*`. The admin reads the hint to render the right theme on the server.
* A public page does not, yet `Critical-CH` makes Chrome repeat the first document request of a visit, and `Vary`
* splits the page in shared caches.
*
* Only site-wide rules (`/:path*`, `/(.*)`) are narrowed; a rule the project wrote for a narrower source is left
* alone. Other tokens of the three headers (another client hint, another `Vary` name) stay where they were, and
* everything else in the rule (`has`, `missing`, `basePath`, `locale`) is carried over to the new rules.
*/
export function scopeColorSchemeClientHints<R extends HeaderRule>(rules: R[], sources: string[] = adminClientHintSources()): R[] {
const keep = new Set(sources)
const out: R[] = []
const moved: R[] = []
for (const rule of rules) {
if (typeof rule.source !== 'string' || !SITE_WIDE.has(rule.source) || keep.has(rule.source)) {
out.push(rule)
continue
}
const taken: Header[] = []
const left: Header[] = []
for (const header of rule.headers) {
const all = HINT_HEADERS.has(header.key.toLowerCase()) ? tokens(header.value) : []
const rest = all.filter((t) => t.toLowerCase() !== HINT)
if (rest.length === all.length) {
left.push(header)
continue
}
taken.push(header)
if (rest.length) {left.push({ key: header.key, value: rest.join(', ') })}
}
if (!taken.length) {
out.push(rule)
continue
}
if (left.length) {out.push({ ...rule, headers: left })}
// the admin keeps the full original value: what the panel got before the change
for (const source of sources) {moved.push({ ...rule, headers: taken, source })}
}
return [...out, ...moved]
}
/**
* Next config wrapper for the security and delivery settings that are not response headers
* the project adds itself. Hides `X-Powered-By`, and keeps Payload's colour-scheme client hint
* headers on the admin panel only.
*
* Where the headers come from: Next sends `X-Powered-By: Next.js` unless `poweredByHeader: false`;
* Payload's withPayload switches Next's off and adds `X-Powered-By: Next.js, Payload` through
* headers() — also unless the config it wraps says `poweredByHeader: false`. withPayload also
* appends `Accept-CH`, `Critical-CH` and `Vary: Sec-CH-Prefers-Color-Scheme` for every path.
*
* Hiding `X-Powered-By` works on either side of withPayload. Narrowing the client hints needs
* this wrapper OUTSIDE, because only there it sees the rule withPayload adds:
*
* // next.config.ts
* import { withSecurityConfig } from '@intecion/ipal-kit'
* export default withPayload(withSecurityConfig(nextConfig))
* export default withSecurityConfig(withPayload(nextConfig))
*/
export function withSecurityConfig<T extends object>(
config: T,
options: WithSecurityConfigOptions = {},
): { poweredByHeader?: boolean } & T {
const { hidePoweredBy = true } = options
if (!hidePoweredBy) {return config}
const { adminClientHints = true, hidePoweredBy = true } = options
const original = (config as NextConfigLike).headers
const hints = adminClientHints === true ? {} : adminClientHints
if (!hidePoweredBy && !(hints && original)) {return config}
const sources = hints ? [...adminClientHintSources(hints.route), ...(hints.sources ?? [])] : []
return {
...config,
poweredByHeader: false,
...(hidePoweredBy ? { poweredByHeader: false } : {}),
...(original
? {
headers: async () =>
(await original()).map((rule) => ({
...rule,
headers: rule.headers.filter((h) => h.key.toLowerCase() !== 'x-powered-by'),
})),
headers: async () => {
let rules = await original()
if (hints) {rules = scopeColorSchemeClientHints(rules, sources)}
if (hidePoweredBy) {
rules = rules.flatMap((rule) => {
const headers = rule.headers.filter((h) => h.key.toLowerCase() !== 'x-powered-by')
if (headers.length === rule.headers.length) {return [rule]}
// Next refuses a rule with no headers ("`headers` field cannot be empty"): drop one emptied here
return headers.length ? [{ ...rule, headers }] : []
})
}
return rules
},
}
: {}),
}