Skip to content

Commit

Permalink
fix: explicitly allow npm help to open file:/// man pages
Browse files Browse the repository at this point in the history
PR-URL: #4026
Credit: @wraithgar
Close: #4026
Reviewed-by: @isaacs
  • Loading branch information
wraithgar committed Nov 10, 2021
1 parent 7887fb3 commit cd6d3a9
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 7 deletions.
2 changes: 1 addition & 1 deletion lib/commands/help.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ class Help extends BaseCommand {
break

case 'browser':
await openUrl(this.npm, this.htmlMan(man), 'help available at the following URL')
await openUrl(this.npm, this.htmlMan(man), 'help available at the following URL', true)
return

default:
Expand Down
16 changes: 10 additions & 6 deletions lib/utils/open-url.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const opener = require('opener')
const { URL } = require('url')

// attempt to open URL in web-browser, print address otherwise:
const open = async (npm, url, errMsg) => {
const open = async (npm, url, errMsg, isFile) => {
url = encodeURI(url)
const browser = npm.config.get('browser')

Expand All @@ -24,12 +24,16 @@ const open = async (npm, url, errMsg) => {
return
}

try {
if (!/^https?:$/.test(new URL(url).protocol)) {
throw new Error()
// We pass this in as true from the help command so we know we don't have to
// check the protocol
if (!isFile) {
try {
if (!/^https?:$/.test(new URL(url).protocol)) {
throw new Error()
}
} catch (_) {
throw new Error('Invalid URL: ' + url)
}
} catch (_) {
throw new Error('Invalid URL: ' + url)
}

const command = browser === true ? null : browser
Expand Down
12 changes: 12 additions & 0 deletions test/lib/utils/open-url.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,18 @@ t.test('returns error for file url', async t => {
t.same(OUTPUT, [], 'printed no output')
})

t.test('file url allowed if explicitly asked for', async t => {
t.teardown(() => {
openerUrl = null
openerOpts = null
OUTPUT.length = 0
})
await openUrl(npm, 'file:///man/page/npm-install', 'npm home', true)
t.equal(openerUrl, 'file:///man/page/npm-install', 'opened the given url')
t.same(openerOpts, { command: null }, 'passed command as null (the default)')
t.same(OUTPUT, [], 'printed no output')
})

t.test('returns error for non-parseable url', async t => {
t.teardown(() => {
openerUrl = null
Expand Down

0 comments on commit cd6d3a9

Please sign in to comment.