From ca1e77436b88b3119187263d6bceb9d1e795eb89 Mon Sep 17 00:00:00 2001 From: chris48s Date: Sat, 26 Mar 2022 20:08:22 +0000 Subject: [PATCH] allow requireCloudflare setting to work when hosted on fly.io (#7781) --- core/server/server.js | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/core/server/server.js b/core/server/server.js index e1ed8b45044ce..e7bde6c9f3b48 100644 --- a/core/server/server.js +++ b/core/server/server.js @@ -201,6 +201,14 @@ function addHandlerAtIndex(camp, index, handlerFn) { camp.stack.splice(index, 0, handlerFn) } +function isOnHeroku() { + return !!process.env.DYNO +} + +function isOnFly() { + return !!process.env.FLY_APP_NAME +} + /** * The Server is based on the web framework Scoutcamp. It creates * an http server, sets up helpers for token persistence and monitoring. @@ -301,13 +309,19 @@ class Server { // Set `req.ip`, which is expected by `cloudflareMiddleware()`. This is set // by Express but not Scoutcamp. addHandlerAtIndex(this.camp, 0, function (req, res, next) { - // On Heroku, `req.socket.remoteAddress` is the Heroku router. However, - // the router ensures that the last item in the `X-Forwarded-For` header - // is the real origin. - // https://stackoverflow.com/a/18517550/893113 - req.ip = process.env.DYNO - ? req.headers['x-forwarded-for'].split(', ').pop() - : req.socket.remoteAddress + if (isOnHeroku()) { + // On Heroku, `req.socket.remoteAddress` is the Heroku router. However, + // the router ensures that the last item in the `X-Forwarded-For` header + // is the real origin. + // https://stackoverflow.com/a/18517550/893113 + req.ip = req.headers['x-forwarded-for'].split(', ').pop() + } else if (isOnFly()) { + // On Fly we can use the Fly-Client-IP header + // https://fly.io/docs/reference/runtime-environment/#request-headers + req.ip = req.headers['fly-client-ip'] + } else { + req.ip = req.socket.remoteAddress + } next() }) addHandlerAtIndex(this.camp, 1, cloudflareMiddleware())