Skip to content

Commit

Permalink
allow requireCloudflare setting to work when hosted on fly.io (#7781)
Browse files Browse the repository at this point in the history
  • Loading branch information
chris48s authored Mar 26, 2022
1 parent 9cc950b commit ca1e774
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions core/server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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())
Expand Down

0 comments on commit ca1e774

Please sign in to comment.