/** 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 /** * What to do with each violation. Default: one `console.warn` line per * violation (Coolify keeps container logs — read them there). Plug in * payload.logger, Sentry or a database write here. */ onReport?: (violation: CspViolation) => Promise | void } 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, onReport = (v: CspViolation) => { console.warn( `[csp] ${v.disposition ?? 'report'} ${v.effectiveDirective ?? '?'} blocked=${v.blockedUri ?? '?'} page=${v.documentUri ?? '?'}${v.sourceFile ? ` src=${v.sourceFile}:${v.lineNumber ?? ''}` : ''}`, ) }, } = args return async (request: Request) => { const length = Number(request.headers.get('content-length') ?? 0) if (length > maxBytes) {return new Response(null, { status: 413 })} let text: string try { text = await request.text() } catch { return new Response(null, { status: 400 }) } if (text.length > maxBytes) {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, 50)) { try { await onReport(violation) } catch { // a failing sink must not turn reports into errors in the browser } } return new Response(null, { status: 204 }) } }