can be used as a node module

This commit is contained in:
加里
2014-08-14 10:59:49 +08:00
parent b22a8b482e
commit 978b549be7
8 changed files with 97 additions and 72 deletions

View File

@@ -4,6 +4,7 @@ var exec = require('child_process').exec,
fs = require("fs"),
os = require("os"),
color = require('colorful'),
readline = require('readline'),
asyncTask = require("async-task-mgr");
var certDir = path.join(getUserHome(),"/.anyproxy_certs/"),
@@ -60,35 +61,65 @@ function clearCerts(cb){
exec("rm *.key *.csr *.crt",{cwd : certDir},cb);
}
function isRootCAFileExists(){
var crtFile = path.join(cmdDir,"rootCA.crt"),
keyFile = path.join(cmdDir,"rootCA.key");
return (fs.existsSync(crtFile) && fs.existsSync(keyFile));
}
function checkRootCA(){
var crtFile = path.join(cmdDir,"rootCA.crt"),
keyFile = path.join(cmdDir,"rootCA.key");
if(!fs.existsSync(crtFile) || !fs.existsSync(keyFile)){
if(!isRootCAFileExists()){
console.log(color.red("can not find rootCA.crt or rootCA.key"));
process.exit(0);
console.log(color.red("you may generate one by the following methods"));
console.log(color.red("\twhen using globally : anyproxy --root"));
console.log(color.red("\twhen using as a module : require(\"anyproxy\").generateRootCA();"));
process.exit(0);
}
}
function generateRootCA(){
var spawnSteam = spawn("./gen-rootCA",['.'],{cwd:cmdDir,stdio: 'inherit'});
if(isRootCAFileExists()){
console.log(color.yellow("rootCA exists at " + certDir));
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
spawnSteam.on('close', function (code) {
if(code == 0){
console.log(color.green("rootCA generated"));
console.log("now clearing temp certs...");
clearCerts(function(){
console.log(color.green("done"));
rl.question("do you really want to generate a new one ?)(yes/NO)", function(answer) {
if(/yes/i.test(answer)){
startGenerating();
}else{
console.log("will not generate a new one");
process.exit(0);
});
}else{
console.log(color.red("fail to generate root CA"));
}
});
}
rl.close();
});
}else{
startGenerating();
}
function startGenerating(){
var spawnSteam = spawn("./gen-rootCA",['.'],{cwd:cmdDir,stdio: 'inherit'});
spawnSteam.on('close', function (code) {
if(code == 0){
console.log(color.green("rootCA generated"));
console.log(color.green(color.bold("please trust the rootCA.crt in " + cmdDir)));
clearCerts(function(){
console.log(color.green("temp certs cleared"));
process.exit(0);
});
}else{
console.log(color.red("fail to generate root CA"));
}
});
}
}
module.exports.generateRootCA = generateRootCA;
module.exports.getCertificate = getCertificate;
module.exports.createCert = createCert;
module.exports.clearCerts = clearCerts;
module.exports.generateRootCA = generateRootCA;
module.exports.getCertificate = getCertificate;
module.exports.createCert = createCert;
module.exports.clearCerts = clearCerts;
module.exports.isRootCAFileExists = isRootCAFileExists;