import type { NextConfig } from "next"; const s3Host = process.env.S3_ENDPOINT ? new URL(process.env.S3_ENDPOINT).hostname : ""; // Derive the Clerk frontend API host from the publishable key so the // CSP allowlist always matches the active environment. // Clerk key format is: // pk_test_- -> .clerk.accounts.dev // pk_live_- -> .clerk.services // The slug itself may contain hyphens and digits, so the suffix is // only the final dash-group. The regex greedily captures the slug. function clerkFrontendApiHost(): string | null { const key = process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY; if (!key) return null; const m = key.match(/^pk_(test|live)_(.+?)-([a-z0-9]+)$/i); if (!m) return null; const slug = m[2].toLowerCase(); return m[1].toLowerCase() === "test" ? `${slug}.clerk.accounts.dev` : `${slug}.clerk.services`; } const clerkFapiHost = clerkFrontendApiHost(); const csp = [ "default-src 'self'", // Clerk user avatars are served from img.clerk.com; S3 hosts are // also allowed for memorial uploads. data:/blob: for in-app previews. "img-src 'self' data: blob: https://img.clerk.com https:", "font-src 'self' data:", "style-src 'self' 'unsafe-inline'", // script-src: must include the Clerk FAPI host because Clerk JS is // loaded from /npm/@clerk/clerk-js@/dist/clerk.browser.js "script-src 'self' 'unsafe-inline' 'unsafe-eval'" + (clerkFapiHost ? ` https://${clerkFapiHost}` : ""), // connect-src: Clerk JS talks to for all session calls. "connect-src 'self' https://api.clerk.com" + (clerkFapiHost ? ` https://${clerkFapiHost} wss://${clerkFapiHost}` : ""), "frame-ancestors 'self'", ].join("; "); const securityHeaders = [ { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" }, { key: "X-Frame-Options", value: "SAMEORIGIN" }, { key: "X-Content-Type-Options", value: "nosniff" }, { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" }, { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" }, { key: "Content-Security-Policy", value: csp }, ]; const nextConfig: NextConfig = { output: "standalone", poweredByHeader: false, compress: true, images: { remotePatterns: [ { protocol: "https", hostname: "img.clerk.com" }, ...(s3Host ? [{ protocol: "https", hostname: s3Host }] : []), ] as NonNullable["remotePatterns"]>, }, async headers() { return [ { source: "/:path*", headers: securityHeaders, }, ]; }, }; export default nextConfig;