unshiftio / url-parse

Small footprint URL parser that works seamlessly across Node.js and browser environments.
http://unshift.io
MIT License
1.03k stars 104 forks source link

Incorrectly getting `@` added on href #229

Closed gita-vahdatinia closed 2 years ago

gita-vahdatinia commented 2 years ago

Hi! 👋

After the change from https://github.com/unshiftio/url-parse/pull/226 I was getting an incorrect evaluation of URLs when using toString().

Example: If I urlParseLibrary('/a/relative/path') I would get:

{
  auth: '',
  hash: '',
  host: '.',
  hostname: '.',
  href: 'https://./a/relative/path',
  origin: 'https://.',
  password: '',
  pathname: '/a/relative/path',
  port: '',
  protocol: 'https:',
  query: '',
  slashes: true,
  username: ''
}

If I set the hostname to '' I would get the href as 'https://@/a/relative/path',

{
  auth: '',
  hash: '',
  host: '',
  hostname: '',
  href: 'https://@/a/relative/path',
  origin: 'null',
  password: '',
  pathname: '/a/relative/path',
  port: '',
  protocol: 'https:',
  query: '',
  slashes: true,
  username: ''
}

Here is the diff that solved my problem:

diff --git a/node_modules/url-parse/index.js b/node_modules/url-parse/index.js
index b86c29f..f8e9252 100644
--- a/node_modules/url-parse/index.js
+++ b/node_modules/url-parse/index.js
@@ -547,7 +547,7 @@ function toString(stringify) {
     url.protocol !== 'file:' &&
     isSpecial(url.protocol) &&
     !host &&
-    url.pathname !== '/'
+    !url.pathname.startsWith('/')
   ) {
     //
     // Add back the empty userinfo, otherwise the original invalid URL
@@ -555,7 +555,6 @@ function toString(stringify) {
     //
     result += '@';
   }
-
   //
   // Trailing colon is removed from `url.host` when it is parsed. If it still
   // ends with a colon, then add back the trailing colon that was removed. This

Is this an intentional change? Please let me know Ill open PR

lpinca commented 2 years ago

It is intentional. The hostname cannot be empty if the protocol is special.

gita-vahdatinia commented 2 years ago

But why does that add a "@"? Shouldn't it throw an error and say it cant set the hostname to empty if there is a special protocol?

lpinca commented 2 years ago

See https://www.huntr.dev/bounties/83a6bc9a-b542-4a38-82cd-d995a1481155/. url-parse does not throw errors by design.

gita-vahdatinia commented 2 years ago

Okay thank you!