From 33a60f4466706bab71f94966f62559960ca0f71c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dafydd=20Ll=C5=B7r=20Pearson?= Date: Tue, 16 Jan 2024 10:36:08 +0000 Subject: [PATCH] fix: Wrap in helper function and handle test envs --- api.planx.uk/server.ts | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/api.planx.uk/server.ts b/api.planx.uk/server.ts index 693efcb80c..8c7bd54068 100644 --- a/api.planx.uk/server.ts +++ b/api.planx.uk/server.ts @@ -3,7 +3,7 @@ import { json, urlencoded } from "body-parser"; import assert from "assert"; import cookieParser from "cookie-parser"; import cookieSession from "cookie-session"; -import cors from "cors"; +import cors, { CorsOptions } from "cors"; import express, { ErrorRequestHandler } from "express"; import noir from "pino-noir"; import pinoLogger from "express-pino-logger"; @@ -38,19 +38,24 @@ useSwaggerDocs(app); app.set("trust proxy", 1); -const CORS_ALLOWLIST = process.env.CORS_ALLOWLIST?.split(", ") || []; +const checkAllowedOrigins: CorsOptions["origin"] = (origin, callback) => { + const isTest = process.env.NODE_ENV === "test"; + const isProduction = process.env.APP_ENVIRONMENT === "production"; + const isCORSEnv = isProduction && !isTest; + + const allowList = process.env.CORS_ALLOWLIST?.split(", ") || []; + const isAllowed = origin && allowList.includes(origin); + + isCORSEnv || isAllowed + ? callback(null, true) + : callback(new Error("Not allowed by CORS")); +}; app.use( cors({ credentials: true, methods: "*", - origin: function (origin, callback) { - if (origin && CORS_ALLOWLIST.includes(origin)) { - callback(null, true); - } else { - callback(new Error("Not allowed by CORS")); - } - }, + origin: checkAllowedOrigins, allowedHeaders: [ "Accept", "Authorization",