|
| 1 | +/** |
| 2 | + * Security headers configuration |
| 3 | + */ |
| 4 | +export interface SecurityHeadersConfig { |
| 5 | + /** Enforce HTTPS via HSTS */ |
| 6 | + enforceHttps?: boolean; |
| 7 | + /** Custom CSP directives */ |
| 8 | + customCsp?: Record<string, string | string[]>; |
| 9 | + /** Environment mode */ |
| 10 | + environment?: "development" | "production"; |
| 11 | +} |
| 12 | + |
| 13 | +/** |
| 14 | + * Get security headers for HTTP responses |
| 15 | + * Protects against clickjacking, XSS, MIME confusion, and other attacks |
| 16 | + */ |
| 17 | +export function getSecurityHeaders( |
| 18 | + config: SecurityHeadersConfig = {} |
| 19 | +): Record<string, string> { |
| 20 | + const { |
| 21 | + enforceHttps = true, |
| 22 | + customCsp = {}, |
| 23 | + environment = "production", |
| 24 | + } = config; |
| 25 | + |
| 26 | + // Base CSP configuration |
| 27 | + const baseCsp = { |
| 28 | + "default-src": "'self'", |
| 29 | + "script-src": "'self' 'unsafe-inline' 'unsafe-eval' https://static.cloudflareinsights.com", // React/Vite compatibility + Cloudflare Insights |
| 30 | + "style-src": "'self' 'unsafe-inline'", // Tailwind/CSS-in-JS support |
| 31 | + "img-src": "'self' data: https:", |
| 32 | + "font-src": "'self' data:", |
| 33 | + "connect-src": "'self' https://api.dafthunk.com", // Allow API connections |
| 34 | + "frame-src": "'self' https://www.youtube.com", // Allow self-iframes and YouTube embeds |
| 35 | + "frame-ancestors": "'none'", // Prevents clickjacking |
| 36 | + "base-uri": "'self'", |
| 37 | + "form-action": "'self'", |
| 38 | + "object-src": "'none'", |
| 39 | + "upgrade-insecure-requests": true, |
| 40 | + }; |
| 41 | + |
| 42 | + const mergedCsp = { ...baseCsp, ...customCsp }; |
| 43 | + |
| 44 | + // Convert to CSP string |
| 45 | + const cspString = Object.entries(mergedCsp) |
| 46 | + .map(([directive, value]) => { |
| 47 | + if (typeof value === "boolean") { |
| 48 | + return value ? directive : ""; |
| 49 | + } |
| 50 | + const valueStr = Array.isArray(value) ? value.join(" ") : value; |
| 51 | + return `${directive} ${valueStr}`; |
| 52 | + }) |
| 53 | + .filter(Boolean) |
| 54 | + .join("; "); |
| 55 | + |
| 56 | + const headers: Record<string, string> = { |
| 57 | + "X-Frame-Options": "DENY", // Clickjacking protection |
| 58 | + "Content-Security-Policy": cspString, |
| 59 | + "X-Content-Type-Options": "nosniff", // MIME protection |
| 60 | + "Referrer-Policy": "strict-origin-when-cross-origin", |
| 61 | + "X-XSS-Protection": "1; mode=block", // Legacy XSS protection |
| 62 | + }; |
| 63 | + |
| 64 | + // Add HSTS in production only |
| 65 | + if (enforceHttps && environment === "production") { |
| 66 | + headers["Strict-Transport-Security"] = |
| 67 | + "max-age=31536000; includeSubDomains; preload"; |
| 68 | + } |
| 69 | + |
| 70 | + return headers; |
| 71 | +} |
| 72 | + |
| 73 | +/** Apply security headers to Express response */ |
| 74 | +export function applySecurityHeaders( |
| 75 | + res: { set: (headers: Record<string, string>) => void }, |
| 76 | + config?: SecurityHeadersConfig |
| 77 | +): void { |
| 78 | + const headers = getSecurityHeaders(config); |
| 79 | + res.set(headers); |
| 80 | +} |
| 81 | + |
| 82 | +/** Apply security headers to Web API Response */ |
| 83 | +export function applySecurityHeadersToResponse( |
| 84 | + response: Response, |
| 85 | + config?: SecurityHeadersConfig |
| 86 | +): Response { |
| 87 | + const headers = getSecurityHeaders(config); |
| 88 | + |
| 89 | + const newHeaders = new Headers(response.headers); |
| 90 | + Object.entries(headers).forEach(([key, value]) => { |
| 91 | + newHeaders.set(key, value); |
| 92 | + }); |
| 93 | + |
| 94 | + return new Response(response.body, { |
| 95 | + status: response.status, |
| 96 | + statusText: response.statusText, |
| 97 | + headers: newHeaders, |
| 98 | + }); |
| 99 | +} |
| 100 | + |
| 101 | +/** Check if response should have security headers (HTML and error responses) */ |
| 102 | +export function shouldApplySecurityHeaders( |
| 103 | + contentType?: string | null, |
| 104 | + statusCode?: number |
| 105 | +): boolean { |
| 106 | + if (!contentType && statusCode && statusCode >= 400) { |
| 107 | + return true; // Error responses |
| 108 | + } |
| 109 | + |
| 110 | + if (contentType?.includes("text/html")) { |
| 111 | + return true; |
| 112 | + } |
| 113 | + |
| 114 | + return false; |
| 115 | +} |
0 commit comments