1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | 'use strict';
|
18 |
|
19 |
|
20 |
|
21 | const fs = require('fs');
|
22 | const q = require('q');
|
23 | const assert = require('assert');
|
24 | const options = require('commander');
|
25 | const crypto = require('crypto');
|
26 | const cryptoUtil = require('../lib/cryptoUtil');
|
27 | const localKeyUtil = require('../lib/localKeyUtil');
|
28 | const KEYS = require('../lib/sharedConstants').KEYS;
|
29 |
|
30 | (function run() {
|
31 | const runner = {
|
32 | run(argv) {
|
33 | let passwordPromise;
|
34 | options
|
35 | .version('4.23.0-beta.3')
|
36 | .option(
|
37 | '--length <password_length>',
|
38 | 'Length of password. Default 32.',
|
39 | 32
|
40 | )
|
41 | .option(
|
42 | '--file <path/to/file>',
|
43 | 'Location in which to store the password. Default log to console.'
|
44 | )
|
45 | .option(
|
46 | '--encrypt',
|
47 | 'Encrypt the password before writing to disk. Default false'
|
48 | )
|
49 | .parse(argv);
|
50 |
|
51 | assert.equal(Number.isNaN(options.length), false, '--length must be an integer');
|
52 |
|
53 | const password =
|
54 | crypto.randomBytes(parseInt(options.length, 10)).toString('base64').substr(0, options.length);
|
55 |
|
56 | if (options.encrypt) {
|
57 | passwordPromise = encryptPassword(password);
|
58 | } else {
|
59 | passwordPromise = q(password);
|
60 | }
|
61 |
|
62 | passwordPromise
|
63 | .then((finalPassword) => {
|
64 | if (options.file) {
|
65 | writeDataToFile(finalPassword, options.file);
|
66 | } else {
|
67 | console.log(finalPassword);
|
68 | }
|
69 | })
|
70 | .catch((err) => {
|
71 | throw (err);
|
72 | });
|
73 | }
|
74 | };
|
75 |
|
76 | function encryptPassword(password) {
|
77 | return localKeyUtil.generateAndInstallKeyPair(
|
78 | KEYS.LOCAL_PUBLIC_KEY_DIR,
|
79 | KEYS.LOCAL_PUBLIC_KEY_PATH,
|
80 | KEYS.LOCAL_PRIVATE_KEY_FOLDER,
|
81 | KEYS.LOCAL_PRIVATE_KEY
|
82 | )
|
83 | .then(() => {
|
84 | return cryptoUtil.encrypt(KEYS.LOCAL_PUBLIC_KEY_PATH, password);
|
85 | })
|
86 | .catch((err) => {
|
87 | return q.reject(err);
|
88 | });
|
89 | }
|
90 |
|
91 | function writeDataToFile(data, file) {
|
92 | const deferred = q.defer();
|
93 |
|
94 | if (fs.existsSync(file)) {
|
95 | fs.unlinkSync(file);
|
96 | }
|
97 |
|
98 | fs.writeFile(file, data, { mode: 0o400 }, (err) => {
|
99 | if (err) {
|
100 | deferred.reject(err);
|
101 | } else {
|
102 | deferred.resolve();
|
103 | }
|
104 | });
|
105 |
|
106 | return deferred.promise;
|
107 | }
|
108 |
|
109 | module.exports = runner;
|
110 |
|
111 |
|
112 |
|
113 | if (!module.parent) {
|
114 | runner.run(process.argv);
|
115 | }
|
116 | }());
|