import { open } from '@miniu/utils'; import path from 'path'; import { createKey, matchKey, convertKey } from '../service/keytool'; import { pick, defaultTo } from 'lodash'; import { readFile } from '../utils/fs.promise'; import postLog from '../service/post.log'; import logger from '../utils/logger'; import { getUploadKeyLink } from '../utils/util'; import { setCliConfig } from '../service/config'; function uploadKey() { // 默认浏览器打开 open(getUploadKeyLink()); } async function genkey(options) { const action = 'KEY_CREATE'; try { postLog({ action, }); const scheme = options.scheme || 'pkcs8'; const keyNamePub = scheme + '-public-pem'; const keyNamePri = scheme + '-private-pem'; const pubPath = defaultTo(options.pubPath, path.resolve(keyNamePub)); const priPath = defaultTo(options.priPath, path.resolve(keyNamePri)); const { privateKey, publicKey } = await createKey({ type: options.type, scheme, pubPath, priPath, }); if (options.write) { setCliConfig({ privateKey: privateKey, }); } console.log('已生成应用私钥:'); console.log(privateKey); console.log('已生成应用公钥:'); console.log(publicKey); console.log('公钥已保存到:', pubPath); console.log('私钥已保存到:', priPath); } catch (e) { logger.error(e, { action, }); } } async function matchKeyAction(options) { const action = 'KEY_MATCH'; try { postLog({ action, }); const [publicKey, privateKey] = await Promise.all([ readFile(options.pubPath, { encoding: 'utf8', }), readFile(options.priPath, { encoding: 'utf8', }), ]); const success = matchKey({ publicKey, privateKey, }); if (success) { logger.log('密钥匹配!'); } else { logger.warn('密钥不匹配!'); } } catch (e) { logger.error(e, { action, }); } } async function convertKeyAction(options) { const action = 'KEY_CONVERT'; try { postLog({ action, }); const params = pick(options, ['scheme', 'priPath']); await convertKey(params); } catch (e) { logger.error(e, { action, }); } } /** * 密钥操作 */ export default function registerKeyCommand(program) { const KEY_SCHEME = /^pkcs(1|8)?$/; const KEY_TYPE = /^rsa2?$/; const child = program.command('key').description('密钥相关操作'); child .command('create') .description('生成密钥') .option('-t, --type [type]', '密钥类型(rsa2/rsa)', KEY_TYPE, 'rsa2') .option('-s, --scheme [scheme]', '密钥格式(pkcs8/pkcs1)', KEY_SCHEME, 'pkcs8') .option('-w, --write [write]', '写入工具配置') .option('--pub-path [pubPath]', '公钥保存地址') .option('--pri-path [priPath]', '私钥保存地址') .action(genkey); child.command('upload').description('上传密钥').action(uploadKey); child .command('match') .description('密钥匹配检测') .requiredOption('--pub-path ', '公钥地址') .requiredOption('--pri-path ', '私钥地址') .action(matchKeyAction); child .command('convert') .description('密钥转换') .option('-s, --scheme [scheme]', '需要转成的目标密钥格式(pkcs8/pkcs1)', KEY_SCHEME, 'pkcs8') .requiredOption('--pri-path ', '私钥地址') .action(convertKeyAction); }