• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict'
2const Bluebird = require('bluebird')
3const readAsync = Bluebird.promisify(require('read'))
4const userValidate = require('npm-user-validate')
5const log = require('npmlog')
6
7exports.otp = readOTP
8exports.password = readPassword
9exports.username = readUsername
10exports.email = readEmail
11
12function read (opts) {
13  return Bluebird.try(() => {
14    log.clearProgress()
15    return readAsync(opts)
16  }).finally(() => {
17    log.showProgress()
18  })
19}
20
21function readOTP (msg, otp, isRetry) {
22  if (!msg) {
23    msg = [
24      'This command requires a one-time password (OTP) from your authenticator app.',
25      'Enter one below. You can also pass one on the command line by appending --otp=123456.',
26      'For more information, see:',
27      'https://docs.npmjs.com/getting-started/using-two-factor-authentication',
28      'Enter OTP: '
29    ].join('\n')
30  }
31  if (isRetry && otp && /^[\d ]+$|^[A-Fa-f0-9]{64,64}$/.test(otp)) return otp.replace(/\s+/g, '')
32
33  return read({prompt: msg, default: otp || ''})
34    .then((otp) => readOTP(msg, otp, true))
35}
36
37function readPassword (msg, password, isRetry) {
38  if (!msg) msg = 'npm password: '
39  if (isRetry && password) return password
40
41  return read({prompt: msg, silent: true, default: password || ''})
42    .then((password) => readPassword(msg, password, true))
43}
44
45function readUsername (msg, username, opts, isRetry) {
46  if (!msg) msg = 'npm username: '
47  if (isRetry && username) {
48    const error = userValidate.username(username)
49    if (error) {
50      opts.log && opts.log.warn(error.message)
51    } else {
52      return Promise.resolve(username.trim())
53    }
54  }
55
56  return read({prompt: msg, default: username || ''})
57    .then((username) => readUsername(msg, username, opts, true))
58}
59
60function readEmail (msg, email, opts, isRetry) {
61  if (!msg) msg = 'email (this IS public): '
62  if (isRetry && email) {
63    const error = userValidate.email(email)
64    if (error) {
65      opts.log && opts.log.warn(error.message)
66    } else {
67      return email.trim()
68    }
69  }
70
71  return read({prompt: msg, default: email || ''})
72    .then((username) => readEmail(msg, username, opts, true))
73}
74