1
1
const fs = require ( 'fs-extra' )
2
2
const path = require ( 'path' )
3
3
4
+ const ini = require ( 'ini' )
4
5
const minimist = require ( 'minimist' )
5
6
const LRU = require ( 'lru-cache' )
6
7
@@ -154,6 +155,36 @@ class PackageManager {
154
155
return this . _registry
155
156
}
156
157
158
+ async getAuthToken ( ) {
159
+ // get npmrc (https://docs.npmjs.com/configuring-npm/npmrc.html#files)
160
+ const possibleRcPaths = [
161
+ path . resolve ( this . context , '.npmrc' ) ,
162
+ path . resolve ( require ( 'os' ) . homedir ( ) , '.npmrc' )
163
+ ]
164
+ if ( process . env . PREFIX ) {
165
+ possibleRcPaths . push ( path . resolve ( process . env . PREFIX , '/etc/npmrc' ) )
166
+ }
167
+ // there's also a '/path/to/npm/npmrc', skipped for simplicity of implementation
168
+
169
+ let npmConfig = { }
170
+ for ( const loc of possibleRcPaths ) {
171
+ if ( fs . existsSync ( loc ) ) {
172
+ // the closer config file (the one with lower index) takes higher precedence
173
+ npmConfig = Object . assign ( { } , ini . parse ( fs . readFileSync ( loc , 'utf-8' ) ) , npmConfig )
174
+ }
175
+ }
176
+
177
+ console . log ( npmConfig )
178
+ const registry = await this . getRegistry ( )
179
+ console . log ( registry )
180
+ const registryWithoutProtocol = registry
181
+ . replace ( / h t t p s ? : / , '' ) // remove leading protocol
182
+ . replace ( / ( [ ^ / ] ) $ / , '$1/' ) // ensure ending with slash
183
+ const authTokenKey = `${ registryWithoutProtocol } :_authToken`
184
+
185
+ return npmConfig [ authTokenKey ]
186
+ }
187
+
157
188
async setRegistryEnvs ( ) {
158
189
const registry = await this . getRegistry ( )
159
190
@@ -204,6 +235,7 @@ class PackageManager {
204
235
// https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md
205
236
async getMetadata ( packageName , { full = false } = { } ) {
206
237
const registry = await this . getRegistry ( )
238
+ const authToken = await this . getAuthToken ( )
207
239
208
240
const metadataKey = `${ this . bin } -${ registry } -${ packageName } `
209
241
let metadata = metadataCache . get ( metadataKey )
@@ -217,6 +249,10 @@ class PackageManager {
217
249
headers . Accept = 'application/vnd.npm.install-v1+json'
218
250
}
219
251
252
+ if ( authToken ) {
253
+ headers . Authorization = `Bearer ${ authToken } `
254
+ }
255
+
220
256
const url = `${ registry . replace ( / \/ $ / g, '' ) } /${ packageName } `
221
257
try {
222
258
metadata = ( await request . get ( url , { headers } ) ) . body
0 commit comments