diff --git a/src/main.ts b/src/main.ts index f9884ba34b..0b82a13d71 100644 --- a/src/main.ts +++ b/src/main.ts @@ -22,6 +22,7 @@ import { ROOT_DIR } from '@config/path.config'; import { gateMiddleware, initializeRuntime, shutdown, startHeartbeat } from '@licensing/runtime'; import { setDB } from '@licensing/store'; import * as Sentry from '@sentry/node'; +import { isCorsOriginAllowed } from '@utils/corsOrigin'; import { ServerUP } from '@utils/server-up'; import axios from 'axios'; import compression from 'compression'; @@ -62,10 +63,7 @@ async function bootstrap() { cors({ origin(requestOrigin, callback) { const { ORIGIN } = configService.get('CORS'); - if (ORIGIN.includes('*')) { - return callback(null, true); - } - if (ORIGIN.indexOf(requestOrigin) !== -1) { + if (isCorsOriginAllowed(ORIGIN, requestOrigin)) { return callback(null, true); } return callback(new Error('Not allowed by CORS')); diff --git a/src/utils/corsOrigin.ts b/src/utils/corsOrigin.ts new file mode 100644 index 0000000000..cd586d1ecd --- /dev/null +++ b/src/utils/corsOrigin.ts @@ -0,0 +1,9 @@ +/** + * Whether a CORS request may proceed. CORS governs browsers only: a request without an Origin header comes from a + * server, a bot or a health check, never from a cross-site page, so it is always allowed. + */ +export const isCorsOriginAllowed = (allowed: string[], requestOrigin: string | undefined): boolean => { + if (!requestOrigin) return true; + if (allowed.includes('*')) return true; + return allowed.includes(requestOrigin); +};