Files
ipal-kit/src/modules/security/withSecurityConfig.ts
T
Radosław SmolińskiandClaude Fable 5.2 9143c132a3 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]>
2026-11-26 11:55:26 +01:00

151 lines
6.5 KiB
TypeScript

/**
* 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 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;
* `false` leaves the config's poweredByHeader as it is.
*/
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 `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 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 withSecurityConfig(withPayload(nextConfig))
*/
export function withSecurityConfig<T extends object>(
config: T,
options: WithSecurityConfigOptions = {},
): { poweredByHeader?: boolean } & T {
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,
...(hidePoweredBy ? { poweredByHeader: false } : {}),
...(original
? {
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
},
}
: {}),
}
}