UNPKG

2.98 kBPlain TextView Raw
1#!/usr/bin/env node
2
3'use strict'
4
5// exist-false, trusted-false : create CA
6// exist-true, trusted-false : trust CA
7// exist-true, trusted-true : all things done
8const program = require('commander');
9const color = require('colorful');
10const certMgr = require('../lib/certMgr');
11const AnyProxy = require('../proxy');
12const exec = require('child_process').exec;
13const co = require('co');
14const path = require('path');
15const inquirer = require('inquirer');
16
17program
18 .option('-c, --clear', 'clear all the tmp certificates and root CA')
19 .option('-g, --generate', 'generate a new rootCA')
20 .parse(process.argv);
21
22function openFolderOfFile(filePath) {
23 const isWin = /^win/.test(process.platform);
24 if (isWin) {
25 exec('start .', { cwd: path.dirname(filePath) });
26 } else {
27 exec(`open -R ${filePath}`);
28 }
29}
30
31function guideToGenrateCA() {
32 AnyProxy.utils.certMgr.generateRootCA((error, keyPath, crtPath) => {
33 if (!error) {
34 const certDir = path.dirname(keyPath);
35 console.log(`The cert is generated at ${certDir}. Please trust the ${color.bold('rootCA.crt')}.`);
36 // TODO: console.log('guide to install');
37 openFolderOfFile(crtPath);
38 } else {
39 console.error('failed to generate rootCA', error);
40 }
41 });
42}
43
44function guideToTrustCA() {
45 const certPath = AnyProxy.utils.certMgr.getRootCAFilePath();
46 if (certPath) {
47 // TODO: console.log('guide to install');
48 openFolderOfFile(certPath);
49 } else {
50 console.error('failed to get cert path');
51 }
52}
53
54if (program.clear) {
55 AnyProxy.utils.certMgr.clearCerts(() => {
56 console.log(color.green('done !'));
57 });
58} else if (program.generate) {
59 guideToGenrateCA();
60} else {
61 console.log('detecting CA status...');
62 co(certMgr.getCAStatus)
63 .then(status => {
64 if (!status.exist) {
65 console.log('AnyProxy CA does not exist.');
66 const questions = [{
67 type: 'confirm',
68 name: 'ifCreate',
69 message: 'Would you like to generate one ?',
70 default: true
71 }];
72 inquirer.prompt(questions).then(answers => {
73 if (answers.ifCreate) {
74 guideToGenrateCA();
75 }
76 });
77 } else if (!status.trusted) {
78 if (/^win/.test(process.platform)) {
79 console.log('AnyProxy CA exists, make sure it has been trusted');
80 } else {
81 console.log('AnyProxy CA exists, but not be trusted');
82 const questions = [{
83 type: 'confirm',
84 name: 'ifGotoTrust',
85 message: 'Would you like to open the folder and trust it ?',
86 default: true
87 }];
88 inquirer.prompt(questions).then(answers => {
89 if (answers.ifGotoTrust) {
90 guideToTrustCA();
91 }
92 });
93 }
94 // AnyProxy.utils.certMgr.clearCerts()
95 } else {
96 console.log(color.green('AnyProxy CA has already been trusted'));
97 }
98 })
99 .catch(e => {
100 console.log(e);
101 })
102}