codekingpro/portable-devtools
114k
1const { read: _read } = require('read')
2const userValidate = require('npm-user-validate')
3const { log, input, META } = require('proc-log')
4
5const otpPrompt = `This command requires a one-time password (OTP) from your authenticator app.
6Enter one below. You can also pass one on the command line by appending --otp=123456.
7For more information, see:
8https://docs.npmjs.com/getting-started/using-two-factor-authentication
9Enter OTP: `
10const passwordPrompt = 'npm password: '
11const usernamePrompt = 'npm username: '
12const emailPrompt = 'email (this will be public): '
13
14// Pass options through so we can differentiate between regular and silent prompts
15const read = (options) =>
16 input.read(() => _read(options), { [META]: true, silent: options?.silent })
17
18function readOTP (msg = otpPrompt, otp, isRetry) {
19 if (isRetry && otp && /^[\d ]+$|^[A-Fa-f0-9]{64,64}$/.test(otp)) {
20 return otp.replace(/\s+/g, '')
21 }
22
23 return read({ prompt: msg, default: otp || '' })
24 .then((rOtp) => readOTP(msg, rOtp, true))
25}
26
27function readPassword (msg = passwordPrompt, password, isRetry) {
28 if (isRetry && password) {
29 return password
30 }
31
32 return read({ prompt: msg, silent: true, default: password || '' })
33 .then((rPassword) => readPassword(msg, rPassword, true))
34}
35
36function readUsername (msg = usernamePrompt, username, isRetry) {
37 if (isRetry && username) {
38 const error = userValidate.username(username)
39 if (error) {
40 log.warn(error.message)
41 } else {
42 return Promise.resolve(username.trim())
43 }
44 }
45
46 return read({ prompt: msg, default: username || '' })
47 .then((rUsername) => readUsername(msg, rUsername, true))
48}
49
50function readEmail (msg = emailPrompt, email, isRetry) {
51 if (isRetry && email) {
52 const error = userValidate.email(email)
53 if (error) {
54 log.warn(error.message)
55 } else {
56 return email.trim()
57 }
58 }
59
60 return read({ prompt: msg, default: email || '' })
61 .then((username) => readEmail(msg, username, true))
62}
63
64module.exports = {
65 otp: readOTP,
66 password: readPassword,
67 username: readUsername,
68 email: readEmail,
69}
70 