UNPKG

3.57 kBJavaScriptView Raw
1/**
2 * Copyright 2016-2018 F5 Networks, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17'use strict';
18
19/* eslint-disable no-console */
20
21const fs = require('fs');
22const q = require('q');
23const assert = require('assert');
24const options = require('commander');
25const crypto = require('crypto');
26const cryptoUtil = require('../lib/cryptoUtil');
27const localKeyUtil = require('../lib/localKeyUtil');
28const 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 // If we're called from the command line, run
112 // This allows for test code to call us as a module
113 if (!module.parent) {
114 runner.run(process.argv);
115 }
116}());