Skip to content

Commit 81f6c12

Browse files
committed
fix(passport): include req.host from express@5 for ease of use in express@4
1 parent 6c42f9c commit 81f6c12

1 file changed

Lines changed: 26 additions & 1 deletion

File tree

src/passport.ts

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,29 @@ function setAuthorizationDetails(
208208
}
209209
}
210210

211+
/**
212+
* Taken from express@5 req.host implementation to get around the fact that
213+
* req.host in express@4 is not the host but hostname. Catches errors stemming
214+
* from possibly not using express and returns req.host for compatibility with
215+
* e.g. fastify-express.
216+
*/
217+
function host(req: express.Request): string | undefined {
218+
try {
219+
const trust = req.app.get('trust proxy fn')
220+
let val = req.get('x-forwarded-host')
221+
222+
if (!val || !trust(req.socket.remoteAddress, 0)) {
223+
val = req.get('host')
224+
} else if (val.indexOf(',') !== -1) {
225+
val = val.substring(0, val.indexOf(',')).trimRight()
226+
}
227+
228+
return val || undefined
229+
} catch {
230+
return req.host
231+
}
232+
}
233+
211234
export class Strategy implements passport.Strategy {
212235
/**
213236
* Name of the strategy
@@ -627,7 +650,9 @@ export class Strategy implements passport.Strategy {
627650
* are properly configured to trust them.
628651
*/
629652
currentUrl(req: express.Request): URL {
630-
return new URL(`${req.protocol}://${req.host}${req.originalUrl ?? req.url}`)
653+
return new URL(
654+
`${req.protocol}://${host(req)}${req.originalUrl ?? req.url}`,
655+
)
631656
}
632657

633658
/**

0 commit comments

Comments
 (0)