hongbo-miao/hongbomiao.com

View on GitHub
api-node/src/security/middlewares/corsMiddleware.ts

Summary

Maintainability
A
0 mins
Test Coverage
import cors from 'cors';
import { RequestHandler } from 'express';
import config from '../../config';
import logger from '../../log/utils/logger';
import meter from '../../reliability/utils/meter';
import isProduction from '../../shared/utils/isProduction';

const ALLOW_LIST = isProduction() ? config.prodCORSAllowOrigins : config.devCORSAllowOrigins;

const corsMiddleware = (allowOrigins: ReadonlyArray<string> = ALLOW_LIST): RequestHandler => {
  const corsViolationCounter = meter.createCounter('corsViolationCounter', {
    description: 'Count CORS violations',
  });

  return cors({
    allowedHeaders: ['Authorization', 'Content-Type'],
    credentials: true,
    methods: ['GET', 'HEAD', 'PUT', 'POST', 'PATCH'],
    optionsSuccessStatus: 200,
    origin: (origin, callback) => {
      if (
        origin == null || // Server-to-server requests and REST tools
        allowOrigins.includes(origin)
      ) {
        callback(null, true);
      } else {
        const labels = { origin };
        corsViolationCounter.add(1, labels);
        const errMsg = `${origin} is not allowed by CORS.`;
        logger.warn({ errMsg }, 'cors');
        callback(new Error(errMsg));
      }
    },
  });
};

export default corsMiddleware;