Skip to content

Commit

Permalink
[fix] Readd the empty userinfo to url.href (#226)
Browse files Browse the repository at this point in the history
If the userinfo is present but empty, the parsed host is also empty, and
`url.pathname` is not `'/'`, then readd the empty userinfo to `url.href`,
otherwise the original invalid URL might be transformed into a valid one
with `url.pathname` as host.
  • Loading branch information
lpinca committed Feb 16, 2022
1 parent 88df234 commit ef45a13
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
11 changes: 11 additions & 0 deletions index.js
Expand Up @@ -539,6 +539,17 @@ function toString(stringify) {
} else if (url.password) {
result += ':'+ url.password;
result += '@';
} else if (
url.protocol !== 'file:' &&
isSpecial(url.protocol) &&
!url.host &&
url.pathname !== '/'
) {
//
// Add back the empty userinfo, otherwise the original invalid URL
// might be transformed into a valid one with `url.pathname` as host.
//
result += '@';
}

result += url.host + url.pathname;
Expand Down
59 changes: 59 additions & 0 deletions test/test.js
Expand Up @@ -771,6 +771,65 @@ describe('url-parse', function () {
assume(parsed.pathname).equals('/');
assume(parsed.href).equals('http://user%40:pas%3As%40@www.example.com/');
});

it('adds @ to href if auth and host are empty', function () {
var parsed, i = 0;
var urls = [
'http:@/127.0.0.1',
'http::@/127.0.0.1',
'http:/@/127.0.0.1',
'http:/:@/127.0.0.1',
'http://@/127.0.0.1',
'http://:@/127.0.0.1',
'http:///@/127.0.0.1',
'http:///:@/127.0.0.1'
];

for (; i < urls.length; i++) {
parsed = parse(urls[i]);

assume(parsed.protocol).equals('http:');
assume(parsed.auth).equals('');
assume(parsed.username).equals('');
assume(parsed.password).equals('');
assume(parsed.host).equals('');
assume(parsed.hostname).equals('');
assume(parsed.pathname).equals('/127.0.0.1');
assume(parsed.origin).equals('null');
assume(parsed.href).equals('http://@/127.0.0.1');
assume(parsed.toString()).equals('http://@/127.0.0.1');
}

urls = [
'http:@/',
'http:@',
'http::@/',
'http::@',
'http:/@/',
'http:/@',
'http:/:@/',
'http:/:@',
'http://@/',
'http://@',
'http://:@/',
'http://:@'
];

for (i = 0; i < urls.length; i++) {
parsed = parse(urls[i]);

assume(parsed.protocol).equals('http:');
assume(parsed.auth).equals('');
assume(parsed.username).equals('');
assume(parsed.password).equals('');
assume(parsed.host).equals('');
assume(parsed.hostname).equals('');
assume(parsed.pathname).equals('/');
assume(parsed.origin).equals('null');
assume(parsed.href).equals('http:///');
assume(parsed.toString()).equals('http:///');
}
});
});

it('accepts multiple ???', function () {
Expand Down

0 comments on commit ef45a13

Please sign in to comment.