From 1decf6cc02ca83fe4065314b7f06707be384c1f0 Mon Sep 17 00:00:00 2001 From: Markus Tacker Date: Fri, 10 Sep 2021 00:02:28 +0200 Subject: [PATCH] fix: ensure Access-Control-Allow-Origin has no trailing slash --- src/server/dev.ts | 3 ++- src/server/feat/backend.ts | 5 +++-- src/server/prod.ts | 13 ++++++++++--- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/server/dev.ts b/src/server/dev.ts index 8a40e92da..176f6b08f 100644 --- a/src/server/dev.ts +++ b/src/server/dev.ts @@ -14,13 +14,14 @@ import EventEmitter from 'events' import { backend } from './feat/backend' import { startExpressServer } from './feat/express' import { setUp as setUpEmails } from './feat/emails' +import { URL } from 'url' const omnibus = new EventEmitter() const app = backend({ omnibus, cookieSecret: process.env.COOKIE_SECRET ?? v4(), - origin: process.env.CLIENT_URL || 'http://localhost:8080', + origin: new URL(process.env.CLIENT_URL || 'http://localhost:8080'), }) startExpressServer(app) diff --git a/src/server/feat/backend.ts b/src/server/feat/backend.ts index 8880e8904..cf2bee3c7 100644 --- a/src/server/feat/backend.ts +++ b/src/server/feat/backend.ts @@ -5,6 +5,7 @@ import cors from 'cors' import EventEmitter from 'events' import express, { Express } from 'express' import passport from 'passport' +import { URL } from 'url' import { cookieAuthStrategy } from '../../authenticateRequest' import login from '../../routes/login' import getProfile from '../../routes/me' @@ -22,7 +23,7 @@ export const backend = ({ origin, }: { omnibus: EventEmitter - origin: string + origin: URL cookieSecret: string }): Express => { const app = express() @@ -36,7 +37,7 @@ export const backend = ({ app.use( cors({ - origin, + origin: `${origin.protocol}//${origin.host}`, credentials: true, }), ) diff --git a/src/server/prod.ts b/src/server/prod.ts index c25ba3fa3..7e1368b12 100644 --- a/src/server/prod.ts +++ b/src/server/prod.ts @@ -12,6 +12,7 @@ import EventEmitter from 'events' import { backend } from './feat/backend' import { startExpressServer } from './feat/express' import { setUp as setUpEmails } from './feat/emails' +import { URL } from 'url' const omnibus = new EventEmitter() @@ -21,9 +22,15 @@ if (cookieSecret === undefined || cookieSecret.length === 0) { cookieSecret = v4() } -const origin = process.env.ORIGIN -if (origin === undefined || !/^http/.test(origin)) { - console.error(`Must set ORIGIN!`) +let origin: URL +try { + origin = new URL(process.env.ORIGIN ?? '') +} catch (err) { + console.error( + `Must set ORIGIN, current value is not a URL: "${process.env.ORIGIN}": ${ + (err as Error).message + }!`, + ) process.exit(1) }