|
| 1 | +import isInteractive from 'is-interactive' |
| 2 | +import meow from 'meow' |
| 3 | +import ora from 'ora' |
| 4 | +import prompts from 'prompts' |
| 5 | + |
| 6 | +import { ChalkOrMarkdown } from '../../utils/chalk-markdown.js' |
| 7 | +import { AuthError, InputError } from '../../utils/errors.js' |
| 8 | +import { setupSdk } from '../../utils/sdk.js' |
| 9 | +import { getSetting, updateSetting } from '../../utils/settings.js' |
| 10 | + |
| 11 | +const description = 'Socket API login' |
| 12 | + |
| 13 | +/** @type {import('../../utils/meow-with-subcommands').CliSubcommand} */ |
| 14 | +export const login = { |
| 15 | + description, |
| 16 | + run: async (argv, importMeta, { parentName }) => { |
| 17 | + const name = parentName + ' login' |
| 18 | + const cli = meow(` |
| 19 | + Usage |
| 20 | + $ ${name} |
| 21 | +
|
| 22 | + Logs into the Socket API by prompting for an API key |
| 23 | +
|
| 24 | + Examples |
| 25 | + $ ${name} |
| 26 | + `, { |
| 27 | + argv, |
| 28 | + description, |
| 29 | + importMeta, |
| 30 | + }) |
| 31 | + |
| 32 | + if (cli.input.length) cli.showHelp() |
| 33 | + |
| 34 | + if (!isInteractive()) { |
| 35 | + throw new InputError('cannot prompt for credentials in a non-interactive shell') |
| 36 | + } |
| 37 | + const format = new ChalkOrMarkdown(false) |
| 38 | + const { apiKey } = await prompts({ |
| 39 | + type: 'password', |
| 40 | + name: 'apiKey', |
| 41 | + message: `Enter your ${format.hyperlink( |
| 42 | + 'Socket.dev API key', |
| 43 | + 'https://docs.socket.dev/docs/api-keys' |
| 44 | + )}`, |
| 45 | + }) |
| 46 | + |
| 47 | + if (!apiKey) { |
| 48 | + ora('API key not updated').warn() |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + const spinner = ora('Verifying API key...').start() |
| 53 | + |
| 54 | + const oldKey = getSetting('apiKey') |
| 55 | + updateSetting('apiKey', apiKey) |
| 56 | + try { |
| 57 | + const sdk = await setupSdk() |
| 58 | + const quota = await sdk.getQuota() |
| 59 | + if (!quota.success) throw new AuthError() |
| 60 | + spinner.succeed(`API key ${oldKey ? 'updated' : 'set'}`) |
| 61 | + } catch (e) { |
| 62 | + updateSetting('apiKey', oldKey) |
| 63 | + spinner.fail('Invalid API key') |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments