diff --git a/lib/utils/otplease.js b/lib/utils/otplease.js index 566c24ef2e293..83985b6bc170d 100644 --- a/lib/utils/otplease.js +++ b/lib/utils/otplease.js @@ -1,17 +1,17 @@ -const readUserInfo = require('./read-user-info.js') - -module.exports = otplease async function otplease (opts, fn) { try { - await fn(opts) + return await fn(opts) } catch (err) { + const readUserInfo = require('./read-user-info.js') if (err.code !== 'EOTP' && (err.code !== 'E401' || !/one-time pass/.test(err.body))) { throw err } else if (!process.stdin.isTTY || !process.stdout.isTTY) { throw err } else { const otp = await readUserInfo.otp('This operation requires a one-time password.\nEnter OTP:') - return fn({ ...opts, otp }) + return await fn({ ...opts, otp }) } } } + +module.exports = otplease diff --git a/test/lib/utils/otplease.js b/test/lib/utils/otplease.js index b3711965c2c9c..025084ab4f2c5 100644 --- a/test/lib/utils/otplease.js +++ b/test/lib/utils/otplease.js @@ -1,4 +1,5 @@ const t = require('tap') +const mockGlobals = require('../../fixtures/mock-globals') const readUserInfo = { otp: async () => '1234', @@ -8,6 +9,27 @@ const otplease = t.mock('../../../lib/utils/otplease.js', { '../../../lib/utils/read-user-info.js': readUserInfo, }) +t.test('returns function results on success', async (t) => { + const fn = () => 'test string' + const result = await otplease({}, fn) + t.equal('test string', result) +}) + +t.test('returns function results on otp success', async (t) => { + mockGlobals(t, { + 'process.stdin': { isTTY: true }, + 'process.stdout': { isTTY: true }, + }) + const fn = ({ otp }) => { + if (otp) { + return 'success' + } + throw Object.assign(new Error('nope'), { code: 'EOTP' }) + } + const result = await otplease({}, fn) + t.equal('success', result) +}) + t.test('prompts for otp for EOTP', async (t) => { const stdinTTY = process.stdin.isTTY const stdoutTTY = process.stdout.isTTY