-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpasswordUtils.ts
81 lines (76 loc) · 3.17 KB
/
passwordUtils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import {Argv, Arguments} from "yargs";
const path = require('path');
const fs = require('fs');
const execSync = require('child_process').execSync;
const runFromArgs = (manualArgs?: string[], exitOnFail: boolean = false): string => {
return require('yargs')
.command('encryptFile', 'Encrypts a password file', (commandArgs: Argv) => {
commandArgs
.option('password', {
describe: 'The encryption password',
demandOption: true,
type: 'string'
})
.option('file', {
describe: 'The source password file to encrypt',
demandOption: true,
type: 'string',
coerce: val => path.resolve(val)
})
.option('output', {
describe: 'The target encrypted file',
type: 'string',
coerce: val => (val) ? path.resolve(val) : val
})
.check(parsedArgs => {
if (!fs.existsSync(parsedArgs.file)) throw new Error(`File ${parsedArgs.file} doesn't exist`);
return true;
});
}, args => {
const output = args.output || `${args.file}.enc`;
execSync(`openssl enc -aes-256-cbc -in "${args.file}" -out "${output}" -k ${args.password}`);
console.log(`Password file has been encrypted. Output at ${output}`);
})
.command('decryptFile', 'Decrypt a password file', (commandArgs: Argv) => {
commandArgs
.option('password', {
describe: 'The decryption password',
demandOption: true,
type: 'string'
})
.option('file', {
describe: 'The source password file to decrypt',
demandOption: true,
type: 'string',
coerce: val => path.resolve(val)
})
.option('output', {
describe: 'The target decrypted file',
type: 'string',
coerce: val => (val) ? path.resolve(val) : val
})
.check(parsedArgs => {
if (!fs.existsSync(parsedArgs.file)) throw new Error(`File ${parsedArgs.file} doesn't exist`);
return true;
});
}, args => {
let output = args.output || args.file.replace(/\.enc$/, '');
if (output === args.file) output = output + '.dec';
execSync(`openssl enc -d -aes-256-cbc -in ${args.file} -out ${output} -k ${args.password}`);
console.log(`Password file has been decrypted. Output at ${output}`);
})
.demandCommand()
.fail((msg: string, err: Error) => {
if (err) throw err;
if (exitOnFail) {
console.error(msg);
process.exit(1);
} else {
throw new Error(msg);
}
}).parse(manualArgs);
};
if (require.main === module) {
runFromArgs(process.argv, true);
}
export {runFromArgs};