// Security headers added to every page and API response (see src/start.ts).
//
// Scripts: each request gets a fresh random nonce. TanStack Start puts it on every script it
// renders (hydration data, scroll restoration, module entry), so script-src has no 'unsafe-inline':
// an injected <script> or inline event handler without the nonce is blocked by the browser.
// Everything else is locked down: no third-party scripts, no plugins, no framing, no <base>
// hijacking, and forms can only post back to this site.
// Styles: Google Fonts CSS plus inline style attributes used by charts and toasts.
// Images: https: so Google profile pictures show in the header and admin console.
// Payment (Moolre) and Google sign-in are full-page redirects, which CSP doesn't restrict.
function contentSecurityPolicy(nonce: string) {
  return [
    "default-src 'self'",
    `script-src 'self' 'nonce-${nonce}'`,
    "script-src-attr 'none'",
    "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
    "font-src 'self' data: https://fonts.gstatic.com",
    "img-src 'self' data: blob: https:",
    "connect-src 'self'",
    "media-src 'self' blob: data:",
    "worker-src 'self' blob:",
    "manifest-src 'self'",
    "object-src 'none'",
    "base-uri 'self'",
    "form-action 'self'",
    "frame-src 'none'",
    "frame-ancestors 'none'",
    'upgrade-insecure-requests',
  ].join('; ')
}

export const SECURITY_HEADERS: Record<string, string> = {
  'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
  'X-Content-Type-Options': 'nosniff',
  'X-Frame-Options': 'DENY',
  'Referrer-Policy': 'strict-origin-when-cross-origin',
  'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=(), interest-cohort=()',
  'Cross-Origin-Opener-Policy': 'same-origin-allow-popups',
}

export function createNonce(): string {
  const bytes = crypto.getRandomValues(new Uint8Array(16))
  return btoa(String.fromCharCode(...bytes))
}

export function withSecurityHeaders(response: Response, nonce: string): Response {
  const headers = { ...SECURITY_HEADERS, 'Content-Security-Policy': contentSecurityPolicy(nonce) }
  try {
    for (const [name, value] of Object.entries(headers)) response.headers.set(name, value)
    return response
  } catch {
    // Some responses (e.g. Response.redirect) have immutable headers; copy them instead.
    const copy = new Response(response.body, response)
    for (const [name, value] of Object.entries(headers)) copy.headers.set(name, value)
    return copy
  }
}
