From e987790821d1536b765ba2575f436dc9c531bd0d Mon Sep 17 00:00:00 2001 From: Glavin Wiechert Date: Tue, 11 Dec 2018 11:25:18 -0400 Subject: [PATCH] Add custom headers to tarball fetcher (#6756) * Add custom headers to tarball fetcher * Remove requestUrl argument from requestHeaders method * Load custom headers for tarball request from yarn config --- src/fetchers/tarball-fetcher.js | 34 +++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/fetchers/tarball-fetcher.js b/src/fetchers/tarball-fetcher.js index 68c625f59e..573fcc3dcd 100644 --- a/src/fetchers/tarball-fetcher.js +++ b/src/fetchers/tarball-fetcher.js @@ -6,6 +6,7 @@ import * as constants from '../constants.js'; import BaseFetcher from './base-fetcher.js'; import * as fsUtil from '../util/fs.js'; import {removePrefix} from '../util/misc.js'; +import normalizeUrl from 'normalize-url'; const crypto = require('crypto'); const path = require('path'); @@ -228,11 +229,13 @@ export default class TarballFetcher extends BaseFetcher { const registry = this.config.registries[this.registry]; try { + const headers = this.requestHeaders(); return await registry.request( this.reference, { headers: { 'Accept-Encoding': 'gzip', + ...headers, }, buffer: true, process: (req, resolve, reject) => { @@ -273,6 +276,24 @@ export default class TarballFetcher extends BaseFetcher { } } + requestHeaders(): {[string]: string} { + const registry = this.config.registries.yarn; + const config = registry.config; + const requestParts = urlParts(this.reference); + return Object.keys(config).reduce((headers, option) => { + const parts = option.split(':'); + if (parts.length === 3 && parts[1] === '_header') { + const registryParts = urlParts(parts[0]); + if (requestParts.host === registryParts.host && requestParts.path.startsWith(registryParts.path)) { + const headerName = parts[2]; + const headerValue = config[option]; + headers[headerName] = headerValue; + } + } + return headers; + }, {}); + } + _fetch(): Promise { const isFilePath = this.reference.startsWith('file:'); this.reference = removePrefix(this.reference, 'file:'); @@ -329,3 +350,16 @@ export class LocalTarballFetcher extends TarballFetcher { return this.fetchFromLocal(this.reference); } } + +type UrlParts = { + host: string, + path: string, +}; + +function urlParts(requestUrl: string): UrlParts { + const normalizedUrl = normalizeUrl(requestUrl); + const parsed = url.parse(normalizedUrl); + const host = parsed.host || ''; + const path = parsed.path || ''; + return {host, path}; +}