import { clientIp, consumeRateLimit } from '../shared/rateLimit.js' import { readCappedBody } from '../shared/readCappedBody.js' /** One CSP violation, normalised from either report format. */ export type CspViolation = { blockedUri?: string disposition?: string documentUri?: string effectiveDirective?: string lineNumber?: number originalPolicy?: string sample?: string sourceFile?: string } export type CreateCspReportRouteArgs = { /** Largest accepted body in bytes; bigger requests get 413. Default 16 KB. */ maxBytes?: number /** Most violations handled from one request (a body may hold many). Default 10; the rest are dropped. */ maxReports?: number /** * What to do with each violation. Default: one `console.warn` line per * violation (Coolify keeps container logs — read them there), made by * {@link cspLogLine}: origins and paths only, no control characters, every value * capped — a report cannot write a line of its own into the log. Your own * `onReport` gets the values exactly as the browser sent them: escape them * before you log them. Plug in payload.logger, Sentry or a database write here. */ onReport?: (violation: CspViolation) => Promise | void /** * Requests per client (`clientIp`, IPv6 per /64) and window that are handled; over it the route still answers 204 * and handles nothing. Default `{ max: 60, windowMs: 60_000 }`; `false` = no limit. */ rateLimit?: { max?: number; windowMs?: number } | false } /** Longest value {@link cspLogLine} writes. */ export const CSP_LOG_VALUE_MAX = 128 /** Control characters (new lines among them) and the Unicode line separators: never in a log line. */ // eslint-disable-next-line no-control-regex const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g const clean = (value: string | undefined, max = CSP_LOG_VALUE_MAX): string => { if (!value) {return '?'} const text = value.replace(CONTROL, ' ').trim() return text.length > max ? `${text.slice(0, max)}…` : text || '?' } /** `https://cdn.x/a.js?q` → `https://cdn.x`; a keyword (`inline`, `eval`, `data`) stays as it is. */ const originOf = (value: string | undefined): string | undefined => { if (!value) {return undefined} try { const url = new URL(value) return url.origin === 'null' ? `${url.protocol}` : url.origin } catch { return value } } /** `https://site.pl/pl/o-nas?x=1#y` → `/pl/o-nas` (no query: it may hold personal data). */ const pathOf = (value: string | undefined): string | undefined => { if (!value) {return undefined} try { return new URL(value).pathname } catch { return value.split(/[?#]/)[0] } } /** `https://cdn.x/a.js?q` → `https://cdn.x/a.js`: where the script lives, without its query. */ const scriptOf = (value: string): string => { try { const url = new URL(value) return url.origin === 'null' ? url.protocol : `${url.origin}${url.pathname}` } catch { return value.split(/[?#]/)[0] } } /** * The default log line of one violation: the blocked resource's origin, the page's path, the script's origin and path * with its line — control characters removed, every value at most {@link CSP_LOG_VALUE_MAX} characters (security * audit 2026-12, F1). Use it in your own `onReport` for the same line. */ export function cspLogLine(v: CspViolation): string { const source = v.sourceFile ? scriptOf(v.sourceFile) : '' return ( `[csp] ${clean(v.disposition ?? 'report', 16)} ${clean(v.effectiveDirective, 32)} blocked=${clean(originOf(v.blockedUri))} ` + `page=${clean(pathOf(v.documentUri))}${source ? ` src=${clean(source)}:${typeof v.lineNumber === 'number' ? v.lineNumber : ''}` : ''}` ) } type Raw = Record const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined) function fromLegacy(r: Raw): CspViolation { // report-uri: { "csp-report": { "document-uri", "violated-directive", … } } return { blockedUri: str(r['blocked-uri']), disposition: str(r['disposition']), documentUri: str(r['document-uri']), effectiveDirective: str(r['effective-directive']) ?? str(r['violated-directive']), lineNumber: typeof r['line-number'] === 'number' ? r['line-number'] : undefined, originalPolicy: str(r['original-policy']), sample: str(r['script-sample']), sourceFile: str(r['source-file']), } } function fromReportingApi(b: Raw): CspViolation { // report-to: [{ type: 'csp-violation', body: { documentURL, effectiveDirective, … } }] return { blockedUri: str(b.blockedURL), disposition: str(b.disposition), documentUri: str(b.documentURL), effectiveDirective: str(b.effectiveDirective), lineNumber: typeof b.lineNumber === 'number' ? b.lineNumber : undefined, originalPolicy: str(b.originalPolicy), sample: str(b.sample), sourceFile: str(b.sourceFile), } } /** Parses a report body in either format (report-uri JSON or Reporting API array). */ export function parseCspReports(body: unknown): CspViolation[] { if (Array.isArray(body)) { return body .filter((r): r is Raw => !!r && typeof r === 'object' && (r as Raw).type === 'csp-violation') .map((r) => fromReportingApi(((r.body ?? {}) as Raw))) } if (body && typeof body === 'object' && 'csp-report' in body) { const inner = (body as Raw)['csp-report'] return inner && typeof inner === 'object' ? [fromLegacy(inner as Raw)] : [] } return [] } /** * A small collector for CSP violation reports — the `reportUri` target while * the policy runs in report-only mode. Accepts both formats browsers send * (`application/csp-report` from report-uri, `application/reports+json` from * report-to), caps the body size, always answers 204, and never stores * anything itself: by default each violation is one `console.warn` line. * * // app/api/csp-report/route.ts (outside Payload's /api/[...slug] — a fixed route wins) * import { createCspReportRoute } from '@intecion/ipal-kit' * export const POST = createCspReportRoute() * * Third-party alternative: point `reportUri` at report-uri.com, Sentry * (security endpoint) or similar, and skip this route. */ export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (request: Request) => Promise { const { maxBytes = 16 * 1024, maxReports = 10, onReport = (v: CspViolation) => { console.warn(cspLogLine(v)) }, rateLimit = {}, } = args return async (request: Request) => { if (rateLimit) { const { ok } = await consumeRateLimit({ key: clientIp(request), max: rateLimit.max ?? 60, scope: 'csp-report', windowMs: rateLimit.windowMs ?? 60_000 }) // the browser does not read the answer: 204 either way, nothing handled if (!ok) {return new Response(null, { status: 204 })} } // read only up to the cap, whether or not the browser declared the length (a chunked body has none) let text: null | string try { text = await readCappedBody(request, maxBytes) } catch { return new Response(null, { status: 400 }) } if (text === null) {return new Response(null, { status: 413 })} let body: unknown try { body = JSON.parse(text) } catch { return new Response(null, { status: 400 }) } for (const violation of parseCspReports(body).slice(0, Math.max(0, maxReports))) { try { await onReport(violation) } catch { // a failing sink must not turn reports into errors in the browser } } return new Response(null, { status: 204 }) } }