1const t = require('tap') 2const { load: loadMockNpm } = require('../../fixtures/mock-npm') 3const MockRegistry = require('@npmcli/mock-registry') 4const nock = require('nock') 5 6const username = 'foo' 7const auth = { '//registry.npmjs.org/:_authToken': 'test-auth-token' } 8 9t.test('npm whoami', async t => { 10 const { npm, joinedOutput } = await loadMockNpm(t, { config: auth }) 11 const registry = new MockRegistry({ 12 tap: t, 13 registry: npm.config.get('registry'), 14 authorization: 'test-auth-token', 15 }) 16 registry.whoami({ username }) 17 await npm.exec('whoami', []) 18 t.equal(joinedOutput(), username, 'should print username') 19}) 20 21t.test('npm whoami --json', async t => { 22 const { npm, joinedOutput } = await loadMockNpm(t, { 23 config: { 24 json: true, 25 ...auth, 26 }, 27 }) 28 const registry = new MockRegistry({ 29 tap: t, 30 registry: npm.config.get('registry'), 31 authorization: 'test-auth-token', 32 }) 33 registry.whoami({ username }) 34 await npm.exec('whoami', []) 35 t.equal(JSON.parse(joinedOutput()), username, 'should print username') 36}) 37 38t.test('npm whoami using mTLS', async t => { 39 const { npm, joinedOutput } = await loadMockNpm(t, { config: { 40 '//registry.npmjs.org/:certfile': '/some.cert', 41 '//registry.npmjs.org/:keyfile': '/some.key', 42 } }) 43 const registry = new MockRegistry({ 44 tap: t, 45 registry: npm.config.get('registry'), 46 }) 47 registry.whoami({ username }) 48 await npm.exec('whoami', []) 49 t.equal(joinedOutput(), username, 'should print username') 50}) 51 52t.test('credentials from token', async t => { 53 const { npm, joinedOutput } = await loadMockNpm(t, { 54 config: { 55 '//registry.npmjs.org/:username': username, 56 '//registry.npmjs.org/:_password': 'hunter2', 57 }, 58 }) 59 await npm.exec('whoami', []) 60 t.equal(joinedOutput(), username, 'should print username') 61}) 62 63t.test('not logged in', async t => { 64 const { npm } = await loadMockNpm(t, { 65 config: { 66 json: true, 67 }, 68 }) 69 await t.rejects(npm.exec('whoami', []), { code: 'ENEEDAUTH' }) 70}) 71 72t.test('non-string username in response', async t => { 73 nock.disableNetConnect() 74 t.teardown(() => { 75 nock.enableNetConnect() 76 }) 77 78 const server = nock('https://registry.npmjs.org', { 79 reqheaders: { 80 authorization: 'Bearer abcd1234', 81 }, 82 }) 83 .get('/-/whoami') 84 .reply(200, { username: null }) 85 86 const { npm } = await loadMockNpm(t, { 87 config: { 88 '//registry.npmjs.org/:_authToken': 'abcd1234', 89 }, 90 }) 91 92 await t.rejects(npm.exec('whoami', []), { code: 'ENEEDAUTH' }) 93 t.ok(server.isDone()) 94}) 95