All files / src/lib/security security-headers.ts

61.71% Statements 158/256
100% Branches 9/9
60% Functions 6/10
61.71% Lines 158/256

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 2571x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x                                                   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 1x 1x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x                                                                                                     1x 1x 1x 1x 1x                                          
/**
 * Security headers for API responses
 * Protects against common web vulnerabilities like XSS, clickjacking, MIME sniffing
 */
 
import { NextResponse, NextRequest } from "next/server";
import crypto from 'crypto';
 
interface SecurityHeadersOptions {
  origin?: string;
  allowMethods?: string[];
  allowHeaders?: string[];
}
 
interface CspConfig {
  /** Enable Content Security Policy */
  enableCsp?: boolean;
  /** CSP nonce for inline scripts */
  nonce?: string;
  /** Additional allowed script sources */
  additionalScriptSrc?: string[];
  /** Additional allowed connect sources */
  additionalConnectSrc?: string[];
  /** Additional allowed image sources */
  additionalImgSrc?: string[];
  /** Additional allowed frame sources */
  additionalFrameSrc?: string[];
  /** CSP report URI for violations */
  cspReportUri?: string;
}
 
/**
 * Generate a cryptographic nonce for CSP
 */
export function generateCspNonce(): string {
  return crypto.randomBytes(16).toString('base64');
}
 
/**
 * Build CSP directives string
 */
function buildCspDirectives(config: CspConfig): string {
  const nonce = config.nonce || generateCspNonce();
  const appDomain = process.env.NEXT_PUBLIC_APP_DOMAIN || 'localhost';

  const directives: string[] = [
    "default-src 'self'",
    `script-src 'self' 'nonce-${nonce}' https://js.stripe.com https://www.googletagmanager.com https://www.google-analytics.com ${(config.additionalScriptSrc || []).join(' ')}`.trim(),
    "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
    `img-src 'self' data: blob: https: ${(config.additionalImgSrc || []).join(' ')}`.trim(),
    "font-src 'self' https://fonts.gstatic.com",
    `connect-src 'self' https://api.stripe.com https://*.cloudinary.com https://www.google-analytics.com https://api.emailjs.com wss://${appDomain} ws://localhost:* ${(config.additionalConnectSrc || []).join(' ')}`.trim(),
    `frame-src 'self' https://js.stripe.com https://hooks.stripe.com ${(config.additionalFrameSrc || []).join(' ')}`.trim(),
    "object-src 'none'",
    "base-uri 'self'",
    "form-action 'self'",
    "frame-ancestors 'none'",
    ...(process.env.NODE_ENV === 'production' ? ['upgrade-insecure-requests'] : []),
  ];

  if (config.cspReportUri) {
    directives.push(`report-uri ${config.cspReportUri}`);
  }

  return directives.join('; ');
}
 
/**
 * Add security headers to a response
 * Headers protect against:
 * - X-XSS-Protection: Prevents reflected XSS attacks
 * - X-Content-Type-Options: Prevents MIME type sniffing
 * - X-Frame-Options: Prevents clickjacking
 * - Referrer-Policy: Controls referrer information
 * - Access-Control-Allow-Origin: CORS configuration
 *
 * @param response The NextResponse to add headers to
 * @param options Configuration options
 * @returns Response with security headers added
 */
export function addSecurityHeaders<T>(
  response: NextResponse<T>,
  options: SecurityHeadersOptions = {}
): NextResponse<T> {
  const {
    origin = process.env.NEXTAUTH_URL || "http://localhost:3000",
    allowMethods = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allowHeaders = ["Content-Type", "Authorization", "X-Requested-With"]} = options;
 
  // Prevent MIME type sniffing - tells browsers to respect content-type header
  response.headers.set("X-Content-Type-Options", "nosniff");
 
  // Prevent clickjacking attacks - only allow same-origin frame embedding
  response.headers.set("X-Frame-Options", "DENY");
 
  // Enable XSS protection in older browsers
  response.headers.set("X-XSS-Protection", "1; mode=block");
 
  // Control referrer information sent with requests
  response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
 
  // Require HTTPS for future connections (if in production)
  if (process.env.NODE_ENV === "production" && origin.startsWith("https")) {
    response.headers.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
  }
 
  // CORS headers - allow same-origin requests
  response.headers.set("Access-Control-Allow-Origin", origin);
  response.headers.set("Access-Control-Allow-Methods", allowMethods.join(", "));
  response.headers.set("Access-Control-Allow-Headers", allowHeaders.join(", "));
  response.headers.set("Access-Control-Allow-Credentials", "true");
 
  // Prevent Content Security Policy violations in certain contexts
  response.headers.set("X-Permitted-Cross-Domain-Policies", "none");
 
  return response;
}
 
/**
 * Create a JSON response with security headers already applied
 * @param data The data to return
 * @param status HTTP status code
 * @param options Configuration options
 * @returns Response with security headers and data
 */
export function jsonResponseWithHeaders<T>(
  data: T,
  status: number = 200,
  options: SecurityHeadersOptions = {}
): NextResponse<T> {
  const response = NextResponse.json(data, { status });
  return addSecurityHeaders(response, options);
}
 
/**
 * Create an error JSON response with security headers
 * @param error Error message
 * @param status HTTP status code
 * @param options Configuration options
 * @returns Error response with security headers
 */
export function errorResponseWithHeaders(
  error: string,
  status: number = 500,
  options: SecurityHeadersOptions = {}
): NextResponse<{ error: string }> {
  const response = NextResponse.json({ error }, { status });
  return addSecurityHeaders(response, options);
}
 
/**
 * Security headers for different response types
 */
export const securityHeaders = {
  /**
   * Headers for public endpoints (GET requests)
   */
  public: <T>(response: NextResponse<T>): NextResponse<T> =>
    addSecurityHeaders(response, {
      allowMethods: ["GET", "OPTIONS"]}),
 
  /**
   * Headers for authenticated endpoints
   */
  authenticated: <T>(response: NextResponse<T>): NextResponse<T> =>
    addSecurityHeaders(response, {
      allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
      allowHeaders: ["Content-Type", "Authorization", "X-Requested-With"]}),
 
  /**
   * Headers for admin endpoints
   */
  admin: <T>(response: NextResponse<T>): NextResponse<T> =>
    addSecurityHeaders(response, {
      allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
      allowHeaders: ["Content-Type", "Authorization", "X-Requested-With"]}),
};
 
/**
 * Add comprehensive security headers to a response (for middleware)
 */
export function addComprehensiveSecurityHeaders(
  _request: NextRequest,
  response: NextResponse,
  cspConfig: CspConfig = {}
): NextResponse {
  const nonce = generateCspNonce();

  // CSP
  if (cspConfig.enableCsp !== false) {
    const csp = buildCspDirectives({ ...cspConfig, nonce });
    response.headers.set('Content-Security-Policy', csp);
  }

  // Prevent MIME type sniffing
  response.headers.set('X-Content-Type-Options', 'nosniff');

  // Prevent clickjacking
  response.headers.set('X-Frame-Options', 'DENY');

  // XSS Protection (legacy)
  response.headers.set('X-XSS-Protection', '1; mode=block');

  // Referrer Policy
  response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');

  // Permissions Policy
  response.headers.set(
    'Permissions-Policy',
    'camera=(), microphone=(), geolocation=(), interest-cohort=()'
  );

  // HSTS (production only)
  if (process.env.NODE_ENV === 'production') {
    response.headers.set(
      'Strict-Transport-Security',
      'max-age=31536000; includeSubDomains; preload'
    );
  }

  // DNS Prefetch
  response.headers.set('X-DNS-Prefetch-Control', 'on');

  // Cross-Origin policies
  response.headers.set('Cross-Origin-Opener-Policy', 'same-origin');

  // Store nonce for components
  response.headers.set('x-nonce', nonce);

  return response;
}
 
/**
 * Get security headers config for next.config.js
 * Returns an array of Header objects for Next.js config
 */
export function getNextConfigSecurityHeaders(): Array<{
  source: string;
  headers: Array<{ key: string; value: string }>;
}> {
  const securityHeaders = [
    { key: 'X-DNS-Prefetch-Control', value: 'on' },
    { key: 'X-Content-Type-Options', value: 'nosniff' },
    { key: 'X-Frame-Options', value: 'DENY' },
    { key: 'X-XSS-Protection', value: '1; mode=block' },
    { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
    { key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=(), interest-cohort=()' },
  ];

  return [
    {
      source: '/:path*',
      headers: securityHeaders,
    },
  ];
}