From ea186d34df48018d2f2f45dccd287f3bea6b2463 Mon Sep 17 00:00:00 2001 From: Manuel Roth Date: Wed, 1 Feb 2023 02:35:16 +0100 Subject: [PATCH] fix: support for `X-Forwarded-Host` http header (#733) * fix: fix support for overriding hostname by setting X-Forwarded-Host http header Signed-off-by: Manuel Roth * fix: improve getUrlObject Signed-off-by: Manuel Roth * Add documentation for getUrlObject function Co-authored-by: Vinayak Kulkarni <19776877+vinayakkulkarni@users.noreply.github.com> * Simplify getPublicUrl function Co-authored-by: Vinayak Kulkarni <19776877+vinayakkulkarni@users.noreply.github.com> * Remove variable Co-authored-by: Vinayak Kulkarni <19776877+vinayakkulkarni@users.noreply.github.com> * Use urlObject directly Co-authored-by: Vinayak Kulkarni <19776877+vinayakkulkarni@users.noreply.github.com> * fix: small fix Signed-off-by: Manuel Roth --------- Signed-off-by: Manuel Roth Co-authored-by: Vinayak Kulkarni <19776877+vinayakkulkarni@users.noreply.github.com> --- src/utils.js | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/utils.js b/src/utils.js index 4a46eca..bc27540 100644 --- a/src/utils.js +++ b/src/utils.js @@ -6,19 +6,35 @@ import fs from 'node:fs'; import clone from 'clone'; import glyphCompose from '@mapbox/glyph-pbf-composite'; -export const getPublicUrl = (publicUrl, req) => - publicUrl || `${req.protocol}://${req.headers.host}/`; +/** + * Generate new URL object + * @params {object} req - Express request + * @returns {URL} object + **/ +const getUrlObject = (req) => { + const urlObject = new URL(`${req.protocol}://${req.headers.host}/`); + // support overriding hostname by sending X-Forwarded-Host http header + urlObject.hostname = req.hostname; + return urlObject; +}; + +export const getPublicUrl = (publicUrl, req) => { + if (publicUrl) { + return publicUrl; + } + return getUrlObject(req).toString(); +}; export const getTileUrls = (req, domains, path, format, publicUrl, aliases) => { + const urlObject = getUrlObject(req); if (domains) { if (domains.constructor === String && domains.length > 0) { domains = domains.split(','); } - const host = req.headers.host; - const hostParts = host.split('.'); + const hostParts = urlObject.host.split('.'); const relativeSubdomainsUsable = hostParts.length > 1 && - !/^([0-9]{1,3}\.){3}[0-9]{1,3}(\:[0-9]+)?$/.test(host); + !/^([0-9]{1,3}\.){3}[0-9]{1,3}(\:[0-9]+)?$/.test(urlObject.host); const newDomains = []; for (const domain of domains) { if (domain.indexOf('*') !== -1) { @@ -34,7 +50,7 @@ export const getTileUrls = (req, domains, path, format, publicUrl, aliases) => { domains = newDomains; } if (!domains || domains.length == 0) { - domains = [req.headers.host]; + domains = [urlObject.host]; } const queryParams = [];