import fs from 'fs'; import os from 'os'; import path from 'path'; import { getNpmRegistryOptions } from './getNpmRegistryOptions'; jest.mock('./log'); const cert = (body: string) => `-----BEGIN CERTIFICATE-----\n${body}\n-----END CERTIFICATE-----`; // How an inline ca is written in an .npmrc: one quoted line with \n escapes const inlineCa = (body: string) => JSON.stringify(cert(body)); describe('getNpmRegistryOptions', () => { const originalEnv = process.env; const originalCwd = process.cwd(); let dir: string; const write = (name: string, contents: string) => { const file = path.join(dir, name); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, contents); return file; }; beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'alks-npmrc-')); process.env = {}; // Keep the tests away from the real user and global npm config process.env.npm_config_userconfig = path.join(dir, 'user.npmrc'); process.env.npm_config_globalconfig = path.join(dir, 'global.npmrc'); }); afterEach(() => { process.chdir(originalCwd); process.env = originalEnv; fs.rmSync(dir, { recursive: true, force: true }); }); describe('registry', () => { it('is left unset when nothing configures one, so npm’s own default applies', () => { expect(getNpmRegistryOptions()).not.toHaveProperty('registry'); }); it('comes from the user config', () => { write('user.npmrc', 'registry=https://user.example.com/npm/'); expect(getNpmRegistryOptions().registry).toBe( 'https://user.example.com/npm/' ); }); it('comes from the global config', () => { write('global.npmrc', 'registry=https://global.example.com/npm/'); expect(getNpmRegistryOptions().registry).toBe( 'https://global.example.com/npm/' ); }); it('comes from the environment', () => { process.env.npm_config_registry = 'https://env.example.com/npm/'; expect(getNpmRegistryOptions().registry).toBe( 'https://env.example.com/npm/' ); }); it('prefers environment over user over global', () => { write('global.npmrc', 'registry=https://global.example.com/'); write('user.npmrc', 'registry=https://user.example.com/'); expect(getNpmRegistryOptions().registry).toBe( 'https://user.example.com/' ); process.env.NPM_CONFIG_REGISTRY = 'https://env.example.com/'; expect(getNpmRegistryOptions().registry).toBe('https://env.example.com/'); }); it('finds the global config under the configured prefix', () => { delete process.env.npm_config_globalconfig; process.env.npm_config_prefix = path.join(dir, 'prefix'); write('prefix/etc/npmrc', 'registry=https://prefixed.example.com/'); expect(getNpmRegistryOptions().registry).toBe( 'https://prefixed.example.com/' ); }); it('expands environment variables in config values and keys', () => { process.env.ARTIFACTORY_HOST = 'artifactory.example.com'; process.env.ARTIFACTORY_TOKEN = 'tok-from-env'; write( 'user.npmrc', [ 'registry=https://${ARTIFACTORY_HOST}/api/npm/npm-remote/', '//${ARTIFACTORY_HOST}/api/npm/npm-remote/:_authToken=${ARTIFACTORY_TOKEN}', ].join('\n') ); expect(getNpmRegistryOptions()).toMatchObject({ registry: 'https://artifactory.example.com/api/npm/npm-remote/', '//artifactory.example.com/api/npm/npm-remote/:_authToken': 'tok-from-env', }); }); // Expected values are what @npmcli/config's env-replace returns for the // same input it.each([ ['expands an unset ${VAR?} to an empty string', 'a${UNSET?}b', 'ab'], ['expands a set ${VAR?} to its value', 'a${SET_VAR?}b', 'aval-from-envb'], ['keeps an escaped ${VAR} literal', 'a\\${SET_VAR}b', 'a${SET_VAR}b'], // The .npmrc parser consumes one level of backslash before expansion, so // `\\\\` in the file is the `\\` that env-replace sees [ 'keeps a literal backslash and expands the variable after it', 'a\\\\\\\\${SET_VAR}b', 'a\\val-from-envb', ], [ 'treats a file-level escaped backslash before ${VAR} as an escape', 'a\\\\${SET_VAR}b', 'a${SET_VAR}b', ], ])('%s', (_label, raw, expected) => { process.env.SET_VAR = 'val-from-env'; write('user.npmrc', `//host.example.com/:_authToken=${raw}`); expect(getNpmRegistryOptions()).toMatchObject({ '//host.example.com/:_authToken': expected, }); }); it('leaves a variable that is not set as written, as npm does', () => { write('user.npmrc', '//host.example.com/:_authToken=${NOT_SET_ANYWHERE}'); expect(getNpmRegistryOptions()).toMatchObject({ '//host.example.com/:_authToken': '${NOT_SET_ANYWHERE}', }); }); }); describe('credentials', () => { it('takes the login stored for each registry from the user and global configs', () => { write( 'global.npmrc', [ '//global.example.com/:_authToken=global-token', '//shared.example.com/:_authToken=global-shared', ].join('\n') ); write( 'user.npmrc', [ '//user.example.com/npm/:_auth=dXNlcjpwdw==', '//shared.example.com/:_authToken=user-shared', ].join('\n') ); expect(getNpmRegistryOptions()).toMatchObject({ '//global.example.com/:_authToken': 'global-token', '//user.example.com/npm/:_auth': 'dXNlcjpwdw==', '//shared.example.com/:_authToken': 'user-shared', }); }); it('does not pass along unrelated settings', () => { write('user.npmrc', 'cache=/somewhere\nfund=false\nsave-exact=true'); expect(Object.keys(getNpmRegistryOptions())).toEqual([]); }); }); describe('unreadable config', () => { it('is not treated as an absent npmrc: a user config that is a directory throws', () => { fs.mkdirSync(process.env.npm_config_userconfig as string); expect(() => getNpmRegistryOptions()).toThrow(/EISDIR/); }); it('names the file it could not read', () => { fs.mkdirSync(process.env.npm_config_userconfig as string); expect(() => getNpmRegistryOptions()).toThrow( new RegExp( (process.env.npm_config_userconfig as string).replace( /[.*+?^${}()|[\]\\]/g, '\\$&' ) ) ); }); it('does not repeat the path when the read error already names it', () => { const file = process.env.npm_config_userconfig as string; const readFileSync = jest .spyOn(fs, 'readFileSync') .mockImplementation(() => { throw new Error(`EACCES: permission denied, open '${file}'`); }); try { expect(() => getNpmRegistryOptions()).toThrow( `EACCES: permission denied, open '${file}'` ); let message = ''; try { getNpmRegistryOptions(); } catch (err) { message = (err as Error).message; } expect(message.split(file).length - 1).toBe(1); } finally { readFileSync.mockRestore(); } }); it('names a cafile that could not be read', () => { const cafile = path.join(dir, 'ca-dir'); fs.mkdirSync(cafile); write('user.npmrc', `cafile=${cafile}`); expect(() => getNpmRegistryOptions()).toThrow(/EISDIR/); expect(() => getNpmRegistryOptions()).toThrow(/ca-dir/); }); it('treats a missing npmrc as benign', () => { expect(() => getNpmRegistryOptions()).not.toThrow(); }); }); describe('project .npmrc', () => { it('changes neither the registry nor the credentials', () => { write('user.npmrc', 'registry=https://user.example.com/'); const project = path.join(dir, 'project'); write( 'project/.npmrc', [ 'registry=https://evil.example.com/', '//evil.example.com/:_authToken=stolen', 'cafile=/evil/ca.pem', 'strict-ssl=false', 'proxy=http://evil.example.com:3128', ].join('\n') ); process.chdir(project); expect(getNpmRegistryOptions()).toEqual({ registry: 'https://user.example.com/', }); }); it('is ignored when the user config would otherwise be the default ~/.npmrc location', () => { delete process.env.npm_config_userconfig; process.env.HOME = path.join(dir, 'home'); write('home/.npmrc', 'registry=https://home.example.com/'); write('project/.npmrc', 'registry=https://evil.example.com/'); process.chdir(path.join(dir, 'project')); expect(getNpmRegistryOptions().registry).toBe( 'https://home.example.com/' ); }); }); describe('TLS', () => { it('reads the certificates in cafile into ca, which npm-registry-fetch would not', () => { const bundle = write( 'corp-ca.pem', `${cert('AAAA')}\r\n${cert('BBBB')}\r\n` ); write('user.npmrc', `cafile=${bundle}`); expect(getNpmRegistryOptions().ca).toEqual([cert('AAAA'), cert('BBBB')]); }); it('ignores a cafile that does not exist, as npm does', () => { write('user.npmrc', `cafile=${path.join(dir, 'missing.pem')}`); expect(getNpmRegistryOptions()).not.toHaveProperty('ca'); }); it('passes an inline ca through, with cafile taking precedence when readable', () => { write('user.npmrc', `ca=${inlineCa('INLINE')}`); expect(getNpmRegistryOptions().ca).toBe(cert('INLINE')); const bundle = write('corp-ca.pem', cert('FILE')); write('user.npmrc', `ca=${inlineCa('INLINE')}\ncafile=${bundle}`); expect(getNpmRegistryOptions().ca).toEqual([cert('FILE')]); }); it.each([ ['false', false], ['true', true], ])('honors strict-ssl=%s', (value, expected) => { write('user.npmrc', `strict-ssl=${value}`); expect(getNpmRegistryOptions().strictSSL).toBe(expected); }); it('honors strict-ssl from the environment', () => { process.env.npm_config_strict_ssl = 'false'; expect(getNpmRegistryOptions().strictSSL).toBe(false); }); }); describe('proxy', () => { it('passes proxy, https-proxy and noproxy through', () => { write( 'user.npmrc', [ 'proxy=http://proxy.example.com:3128', 'https-proxy=http://secure-proxy.example.com:3128', 'noproxy=localhost,.internal.example.com', ].join('\n') ); expect(getNpmRegistryOptions()).toEqual({ proxy: 'http://proxy.example.com:3128', httpsProxy: 'http://secure-proxy.example.com:3128', noProxy: 'localhost,.internal.example.com', }); }); it('takes proxy settings from the environment', () => { process.env.npm_config_https_proxy = 'http://env-proxy.example.com:3128'; expect(getNpmRegistryOptions().httpsProxy).toBe( 'http://env-proxy.example.com:3128' ); }); }); });