diff --git a/lib/utils.js b/lib/utils.js index e98a6b08..18637186 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -57,6 +57,12 @@ function stripHttp1ConnectionHeaders (headers) { // issue ref: https://github.com/fastify/fast-proxy/issues/42 function buildURL (source, reqBase) { let baseOrigin = reqBase ? new URL(reqBase).href : undefined + + // To make sure we don't accidentally override the base path + if (baseOrigin && source.length > 1 && source[0] === '/' && source[1] === '/') { + source = '.' + source + } + const dest = new URL(source, reqBase) // if base is specified, source url should not override it diff --git a/test/build-url.test.js b/test/build-url.test.js index c74d4af5..6f9332bc 100644 --- a/test/build-url.test.js +++ b/test/build-url.test.js @@ -42,12 +42,19 @@ test('should handle default port in base', (t) => { t.equal(url.href, 'https://localhost/hi') }) +test('should append instead of override base', (t) => { + t.plan(2) + let url = buildURL('//10.0.0.10/hi', 'http://localhost') + t.equal(url.href, 'http://localhost//10.0.0.10/hi') + + url = buildURL('//httpbin.org/hi', 'http://localhost') + t.equal(url.href, 'http://localhost//httpbin.org/hi') +}) + const errorInputs = [ - { source: '//10.0.0.10/hi', base: 'http://localhost' }, { source: 'http://10.0.0.10/hi', base: 'http://localhost' }, { source: 'https://10.0.0.10/hi', base: 'http://localhost' }, { source: 'blah://10.0.0.10/hi', base: 'http://localhost' }, - { source: '//httpbin.org/hi', base: 'http://localhost' }, { source: 'urn:foo:bar', base: 'http://localhost' }, { source: 'http://localhost/private', base: 'http://localhost/exposed/' }, { source: 'http://localhost/exposed-extra', base: 'http://localhost/exposed' },