fix: searching for auth token for URL with port (#6708)

close #6354
This commit is contained in:
Zoltan Kochan
2023-06-23 12:30:04 +03:00
committed by GitHub
parent 0119ac05b7
commit 4e7afec90c
3 changed files with 22 additions and 1 deletions

View File

@@ -0,0 +1,6 @@
---
"@pnpm/network.auth-header": patch
"pnpm": patch
---
Ignore the port in the URL, while searching for authentication token in the `.npmrc` file [#6354](https://github.com/pnpm/pnpm/issues/6354).

View File

@@ -1,4 +1,5 @@
import nerfDart from 'nerf-dart'
import { URL } from 'url'
import { getAuthHeadersFromConfig } from './getAuthHeadersFromConfig'
export function createGetAuthHeaderByURI (
@@ -22,12 +23,23 @@ function getMaxParts (uris: string[]) {
}, 0)
}
function getAuthHeaderByURI (authHeaders: Record<string, string>, maxParts: number, uri: string) {
function getAuthHeaderByURI (authHeaders: Record<string, string>, maxParts: number, uri: string): string | undefined {
const nerfed = nerfDart(uri)
const parts = nerfed.split('/')
for (let i = Math.min(parts.length, maxParts) - 1; i >= 3; i--) {
const key = `${parts.slice(0, i).join('/')}/` // eslint-disable-line
if (authHeaders[key]) return authHeaders[key]
}
const urlWithoutPort = removePort(uri)
if (urlWithoutPort !== uri) {
return getAuthHeaderByURI(authHeaders, maxParts, urlWithoutPort)
}
return undefined
}
function removePort (originalUrl: string) {
const urlObj = new URL(originalUrl)
if (urlObj.port === '') return originalUrl
const newUrlObj = new URL(`${urlObj.protocol}//${urlObj.hostname}${urlObj.pathname}${urlObj.search}${urlObj.hash}`)
return newUrlObj.toString()
}

View File

@@ -5,13 +5,16 @@ test('getAuthHeaderByURI()', () => {
allSettings: {
'//reg.com/:_authToken': 'abc123',
'//reg.co/tarballs/:_authToken': 'xxx',
'//reg.gg:8888/:_authToken': '0000',
},
userSettings: {},
})
expect(getAuthHeaderByURI('https://reg.com/')).toBe('Bearer abc123')
expect(getAuthHeaderByURI('https://reg.com/foo/-/foo-1.0.0.tgz')).toBe('Bearer abc123')
expect(getAuthHeaderByURI('https://reg.com:8080/foo/-/foo-1.0.0.tgz')).toBe('Bearer abc123')
expect(getAuthHeaderByURI('https://reg.io/foo/-/foo-1.0.0.tgz')).toBe(undefined)
expect(getAuthHeaderByURI('https://reg.co/tarballs/foo/-/foo-1.0.0.tgz')).toBe('Bearer xxx')
expect(getAuthHeaderByURI('https://reg.gg:8888/foo/-/foo-1.0.0.tgz')).toBe('Bearer 0000')
})
test('returns undefined when the auth header is not found', () => {