diff --git a/source/request-as-event-emitter.js b/source/request-as-event-emitter.js index 3187657e8..e0f167872 100644 --- a/source/request-as-event-emitter.js +++ b/source/request-as-event-emitter.js @@ -120,9 +120,10 @@ module.exports = options => { } const bufferString = Buffer.from(response.headers.location, 'binary').toString(); - redirectUrl = (new URL(bufferString, urlLib.format(options))).toString(); try { + // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604 + redirectUrl = (new URL(bufferString, urlLib.format(options))).toString(); decodeURI(redirectUrl); } catch (error) { emitter.emit('error', error); diff --git a/test/redirects.js b/test/redirects.js index 2bbfbfea0..dbff25f95 100644 --- a/test/redirects.js +++ b/test/redirects.js @@ -110,6 +110,13 @@ test.before('setup', async () => { response.end(); }); + http.on('/invalidRedirect', (request, response) => { + response.writeHead(302, { + location: 'http://' + }); + response.end(); + }); + await http.listen(http.port); await https.listen(https.port); }); @@ -206,3 +213,8 @@ test('throws on malformed redirect URI', async t => { const error = await t.throwsAsync(got(`${http.url}/malformedRedirect`)); t.is(error.name, 'URIError'); }); + +test('throws on invalid redirect URL', async t => { + const error = await t.throwsAsync(got(`${http.url}/invalidRedirect`)); + t.is(error.code, 'ERR_INVALID_URL'); +});