All files / server/src/middleware cors.ts

78.57% Statements 11/14
75% Branches 3/4
100% Functions 1/1
78.57% Lines 11/14

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        39x         5181x 5181x     5181x 1567x 1567x       4989x             4989x 3614x 3614x         3614x    
import { Request, Response, NextFunction } from "express";
import { logger } from "server/utils/logger";
import { config } from "shared/config";
 
export const allowCORS = (
  req: Request,
  res: Response,
  next: NextFunction,
): void => {
  const allowedOrigins = config.server().allowedCorsOrigins;
  const origin = req.headers.origin;
 
  // Same origin, no preflight CORS request
  if (!origin) {
    next();
    return;
  }
 
  // Origin not allowed
  Iif (!allowedOrigins.includes(origin)) {
    logger.warn(new Error(`CORS: Request blocked from ${origin}`));
    res.sendStatus(403);
    return;
  }
 
  // Allowed origin
  res.setHeader("Access-Control-Allow-Origin", origin);
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Content-Type, Authorization, Baggage, Sentry-Trace",
  );
 
  next();
};