Files
ipal-kit/src/modules/security/buildSecurityHeaders.ts
T
Radosław SmolińskiandClaude Fable 5.2 0a4f001797 IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:24:21 +01:00

189 lines
7.2 KiB
TypeScript

import type { BuildCspArgs } from './buildCsp.js'
import { isSiteNoindex } from '../seo/siteNoindex.js'
import { buildCspHeaders } from './buildCsp.js'
/**
* A single HTTP header, in the shape Next.js next.config headers() expects.
*/
export type SecurityHeader = { key: string; value: string }
export type BuildSecurityHeadersArgs = {
/**
* Extra headers to append or override. Same-key entries replace the default
* (and the `csp` headers), so a hand-written Content-Security-Policy fits here too.
*/
additional?: SecurityHeader[]
/**
* Cross-Origin-Opener-Policy. Default 'same-origin' — isolates the browsing
* context so a malicious page can't hold a window.opener reference (protects
* against XS-Leaks / Spectre-class attacks). Project-independent, so it's a
* default. Use 'same-origin-allow-popups' if you open OAuth/payment popups
* that need window.opener; false to omit.
*/
coop?: 'same-origin' | 'same-origin-allow-popups' | false
/**
* Content-Security-Policy from buildCsp args — off by default, because a CSP
* lists the project's own domains. With `reportUri` the Reporting-Endpoints
* header is added too. Roll-out: `mode: 'report-only'` first, read the
* reports, then `mode: 'enforce'` (the only change). See docs/security.md.
*/
csp?: BuildCspArgs | false
/**
* X-Frame-Options value. 'DENY' (default) blocks all framing; 'SAMEORIGIN'
* allows same-origin framing. Note: CSP frame-ancestors supersedes this in
* modern browsers, but X-Frame-Options is kept for older ones. Set to null
* to omit (e.g. if you set frame-ancestors in your project CSP).
*/
frameOptions?: 'DENY' | 'SAMEORIGIN' | null
/**
* Enable HSTS (Strict-Transport-Security). Only takes effect over HTTPS, and
* tells browsers to force HTTPS for `maxAge` seconds. Default true. Turn OFF
* in local/dev over plain HTTP, or you may lock the browser to https on
* localhost. Set the env guard in your next.config (see docs).
*/
hsts?: boolean
/** Add includeSubDomains to HSTS. Default true. */
hstsIncludeSubDomains?: boolean
/** HSTS max-age in seconds. Default 63072000 (2 years), the common baseline. */
hstsMaxAge?: number
/** Add preload to HSTS (only if you'll submit to the preload list). Default false. */
hstsPreload?: boolean
/**
* Permissions-Policy. Default disables camera, microphone, geolocation. Pass
* your own string to override, or null to omit.
*/
permissionsPolicy?: null | string
/** Referrer-Policy. Default 'strict-origin-when-cross-origin' (browser default, explicit). */
referrerPolicy?: null | string
}
/**
* Builds the generic, project-independent security headers every site should
* send: HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy,
* Permissions-Policy. These are identical across projects, so the plugin owns
* the boilerplate; the client spreads the result into next.config's headers().
*
* Content-Security-Policy is opt-in: a useful CSP enumerates the exact domains
* a project loads from (its CDN, analytics, embeds), so the project turns on the
* buildCsp flags it needs through `csp` (or passes its own via `additional`).
*
* @example
* // next.config.ts
* import { buildSecurityHeaders } from '@intecion/ipal-kit'
* const securityHeaders = buildSecurityHeaders({
* hsts: process.env.NODE_ENV === 'production', // off in dev over http
* csp: { mode: 'report-only', reportUri: '/api/csp-report', analytics: true },
* })
* const nextConfig = {
* async headers() {
* return [{ source: '/:path*', headers: securityHeaders }]
* },
* }
*/
export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): SecurityHeader[] {
const {
additional = [],
coop = 'same-origin',
csp = false,
frameOptions = 'DENY',
hsts = true,
hstsIncludeSubDomains = true,
hstsMaxAge = 63072000,
hstsPreload = false,
permissionsPolicy = 'camera=(), microphone=(), geolocation=()',
referrerPolicy = 'strict-origin-when-cross-origin',
} = args
const headers: SecurityHeader[] = []
if (hsts) {
const parts = [`max-age=${hstsMaxAge}`]
if (hstsIncludeSubDomains) {parts.push('includeSubDomains')}
if (hstsPreload) {parts.push('preload')}
headers.push({ key: 'Strict-Transport-Security', value: parts.join('; ') })
}
if (frameOptions) {
headers.push({ key: 'X-Frame-Options', value: frameOptions })
}
// Prevents MIME-type sniffing — always safe, no project specifics.
headers.push({ key: 'X-Content-Type-Options', value: 'nosniff' })
if (referrerPolicy) {
headers.push({ key: 'Referrer-Policy', value: referrerPolicy })
}
if (permissionsPolicy) {
headers.push({ key: 'Permissions-Policy', value: permissionsPolicy })
}
// COOP — isolates the browsing context (XS-Leaks / Spectre protection).
if (coop) {
headers.push({ key: 'Cross-Origin-Opener-Policy', value: coop })
}
// Staging / preview (IAPL_NOINDEX=1): keep every response out of search engines.
if (isSiteNoindex()) {
headers.push({ key: 'X-Robots-Tag', value: 'noindex, nofollow' })
}
if (csp) {headers.push(...buildCspHeaders(csp))}
// Merge additional: same-key entries override the defaults above.
for (const extra of additional) {
const i = headers.findIndex((h) => h.key.toLowerCase() === extra.key.toLowerCase())
if (i >= 0) {headers[i] = extra}
else {headers.push(extra)}
}
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({
adminIcon = '/api/ipal/admin-icon',
collections = ['media'],
}: {
/**
* Path of the plugin's panel icon endpoint, which answers with the favicon's bytes. It only ever
* answers with a bitmap; the rule is a second layer. Another API route: `'/cms-api/ipal/admin-icon'`;
* `false` = no rule.
*/
adminIcon?: false | string
collections?: string[]
} = {}): {
headers: SecurityHeader[]
source: string
}[] {
return [
...collections.map((slug) => ({ headers: [...UPLOAD_SECURITY_HEADERS], source: `/api/${slug}/file/:path*` })),
...(adminIcon ? [{ headers: [...UPLOAD_SECURITY_HEADERS], source: adminIcon }] : []),
]
}
/**
* The headers themselves: for any response that carries the bytes of an uploaded file from the
* site's own origin (the upload routes above; the plugin's `/api/ipal/admin-icon`; a route of yours).
*/
export const UPLOAD_SECURITY_HEADERS: readonly 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' },
]