From 48b6d0eaf2383a7a9b6ad7856e2d1ece72517194 Mon Sep 17 00:00:00 2001 From: Lars Mikkelsen Date: Sat, 16 May 2020 04:59:05 -0400 Subject: [PATCH] Fix double-encoding of URLs (#182) --- index.d.ts | 2 +- index.js | 3 ++- readme.md | 2 +- test.js | 8 ++++++++ 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/index.d.ts b/index.d.ts index d378964..3546af1 100644 --- a/index.d.ts +++ b/index.d.ts @@ -33,7 +33,7 @@ declare namespace open { readonly app?: string | readonly string[]; /** - Uses `encodeURI` to encode the `target` before executing it. + Uses `URL` to encode the `target` before executing it. The use with targets that are not URLs is not recommended. diff --git a/index.js b/index.js index e741e45..67b3c29 100644 --- a/index.js +++ b/index.js @@ -3,6 +3,7 @@ const {promisify} = require('util'); const path = require('path'); const childProcess = require('child_process'); const fs = require('fs'); +const url = require('url'); const isWsl = require('is-wsl'); const isDocker = require('is-docker'); @@ -45,7 +46,7 @@ module.exports = async (target, options) => { // double-quotes through the “double-quotes on Windows caveat”, but it // can be used on any platform. if (options.url) { - target = encodeURI(target); + target = new url.URL(target).href; if (isWsl) { target = target.replace(/&/g, '^&'); diff --git a/readme.md b/readme.md index 9d947f2..4669e86 100644 --- a/readme.md +++ b/readme.md @@ -97,7 +97,7 @@ You may also pass in the app's full path. For example on WSL, this can be `/mnt/ Type: `boolean`\ Default: `false` -Uses `encodeURI` to encode the target before executing it.
+Uses `URL` to encode the target before executing it.
We do not recommend using it on targets that are not URLs. Especially useful when dealing with the [double-quotes on Windows](#double-quotes-on-windows) caveat. diff --git a/test.js b/test.js index 91af5d5..1caf538 100644 --- a/test.js +++ b/test.js @@ -78,6 +78,14 @@ test('open URL with query strings, spaces, pipes and a fragment', async () => { await open('https://sindresorhus.com/?abc=123&def=456&ghi=w|i|t|h spaces#projects'); }); +test('open URL with query strings and URL reserved characters', async () => { + await open('https://httpbin.org/get?amp=%26&colon=%3A&comma=%2C&commat=%40&dollar=%24&equals=%3D&plus=%2B&quest=%3F&semi=%3B&sol=%2F'); +}); + +test('open URL with query strings and URL reserved characters with `url` option', async () => { + await open('https://httpbin.org/get?amp=%26&colon=%3A&comma=%2C&commat=%40&dollar=%24&equals=%3D&plus=%2B&quest=%3F&semi=%3B&sol=%2F', {url: true}); +}); + if (isWsl) { test('open URL in specified Windows app given a WSL path to the app', async () => { await open('https://sindresorhus.com', {app: firefoxWslName});