generate-pw 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +143 -54
  2. package/generate-pw.js +185 -146
  3. package/package.json +12 -2
package/README.md CHANGED
@@ -1,54 +1,143 @@
1
- # > generate-pw
2
-
3
- ### Randomly generate cryptographically-secure passwords.
4
-
5
- <a href="https://github.com/adamlui/js-utils/tree/main/generate-pw"><img height=28 src="https://img.shields.io/badge/Latest_Build-1.0.0-fc7811.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
6
-
7
- ## Installation
8
-
9
- As a **global utility**:
10
-
11
- ```
12
- npm install -g generate-pw
13
- ```
14
-
15
- As a **dev dependency**, from your project root:
16
-
17
- ```
18
- npm install -D generate-pw
19
- ```
20
-
21
- As a **runtime dependency**, from your project root:
22
-
23
- ```
24
- npm install generate-pw
25
- ```
26
-
27
- ## 💻 Command line usage
28
-
29
- The basic **global command** is:
30
-
31
- ```
32
- generate-pw
33
- ```
34
-
35
- **💡 Note:** Pass `--qty=n` where `n` is the number of passwords to generate for multiple results.
36
- <br><br>
37
-
38
- ## 🏛️ MIT License
39
-
40
- **Copyright © 2024 [Adam Lui](https://github.com/adamlui)**
41
-
42
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
43
-
44
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
45
-
46
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
47
-
48
- <br>
49
-
50
- <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
51
-
52
- <a href="https://github.com/adamlui/js-utils">**Home**</a> /
53
- <a href="https://github.com/adamlui/js-utils/discussions">Discuss</a> /
54
- <a href="#-generate-pw">Back to top ↑</a>
1
+ # > generate-pw
2
+
3
+ ### Randomly generate cryptographically-secure passwords.
4
+
5
+ <a href="#%EF%B8%8F-mit-license"><img height=28 src="https://img.shields.io/badge/License-MIT-orange.svg?logo=internetarchive&logoColor=white&labelColor=464646&style=for-the-badge"></a>
6
+ <a href="https://www.npmjs.com/package/generate-pw?activeTab=versions"><img height=28 src="https://img.shields.io/badge/Latest_Build-1.1.0-44cc11.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
7
+ <a href="https://www.npmjs.com/package/generate-pw?activeTab=code"><img height=28 src="https://img.shields.io/npm/unpacked-size/generate-pw?style=for-the-badge&logo=ebox&logoColor=white&labelColor=464646&color=blue"></a>
8
+ <a href="https://sonarcloud.io/component_measures?metric=new_vulnerabilities&id=adamlui_js-utils:generate-pw/generate-pw.js"><img height=28 src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsonarcloud.io%2Fapi%2Fmeasures%2Fcomponent%3Fcomponent%3Dadamlui_js-utils%3Agenerate-pw%2Fgenerate-pw.js%26metricKeys%3Dvulnerabilities&query=%24.component.measures.0.value&style=for-the-badge&logo=sonarcloud&logoColor=white&labelColor=464646&label=Vulnerabilities&color=gold"></a>
9
+
10
+ ## ⚡ Installation
11
+
12
+ As a **global utility**:
13
+
14
+ ```
15
+ $ npm install -g generate-pw
16
+ ```
17
+
18
+ As a **runtime dependency**, from your project root:
19
+
20
+ ```
21
+ $ npm install generate-pw
22
+ ```
23
+
24
+ ## 🔌 API usage
25
+
26
+ **generate-pw** can be imported into your app as an ECMAScript module or a CommonJS module.
27
+
28
+ #### ESM:
29
+
30
+ ```js
31
+ import * as pw from 'generate-pw';
32
+ ```
33
+
34
+ #### CJS:
35
+
36
+ ```js
37
+ const pw = require('generate-pw');
38
+ ```
39
+
40
+ ### `generatePassword([options])`
41
+
42
+ Generates **one** password if `qty` option is not given, returning a string:
43
+
44
+ ```js
45
+ const password = pw.generatePassword({ length: 11, numbers: true });
46
+ console.log(password);
47
+ // sample output: 'bAsZmsmqoQn'
48
+ ```
49
+
50
+ ...or **multiple** passwords if `qty` option is given, returning an array of strings:
51
+
52
+ ```js
53
+ const passwords = pw.generatePassword({ qty: 5, length: 8, symbols: true });
54
+ console.log(passwords);
55
+ // sample output: [ '!zSf@Q.s', '!,HT\\;m=', '?Lq&FV>^', 'gf}Y;}Ne', 'Stsx(GqE' ]
56
+ ```
57
+
58
+ **💡 Note:** If no options are passed, passwords will be 8-chars long, consisting of upper/lower cased letters.
59
+
60
+ ### `generatePasswords(qty[, options])`
61
+
62
+ Generates **multiple** passwords based on `qty` given, returning an array of strings:
63
+
64
+ ```js
65
+ const passwords = pw.generatePasswords(5, { length: 3, uppercase: false });
66
+ console.log(passwords);
67
+ // sample output: [ 'yilppxru', 'ckvkyjfp', 'zolcpyfb' ]
68
+ ```
69
+
70
+ ### Available options
71
+
72
+ Any of these can be passed into the options object for each function:
73
+
74
+ Name | Type | Description | Default Value
75
+ ------------|---------|--------------------------------------------------------------------------------|---------------
76
+ `length` | Integer | Length of password(s). | `8`
77
+ `qty`* | Integer | Number of passwords to generate. | `1`
78
+ `charset` | String | Characters to include in password(s). | ''
79
+ `exclude` | String | Characters to exclude from password(s). | ''
80
+ `numbers` | Boolean | Allow numbers in password(s). | `false`
81
+ `symbols` | Boolean | Allow symbols in password(s). | `false`
82
+ `lowercase` | Boolean | Allow lowercase letters in password(s). | `true`
83
+ `uppercase` | Boolean | Allow uppercase letters in password(s). | `true`
84
+ `strict` | Boolean | Require at least one character from each allowed character set in password(s). | `false`
85
+
86
+ ##### _*Only available in [`generatePassword([options])`](#generatepasswordoptions) since [`generatePasswords(qty[, options])`](#generatepasswordsqty-options) takes a `qty` argument_
87
+
88
+ <br>
89
+
90
+ ## 💻 Command line usage
91
+
92
+ **generate-pw** can also be used from the command line. The basic **global command** is:
93
+
94
+ ```
95
+ $ generate-pw
96
+ ```
97
+
98
+ **💡 Note:** To generate multiple results, pass `--qty=n` where `n` is the number of passwords to generate.
99
+
100
+ ### Command line options
101
+
102
+ ```
103
+ Argument options:
104
+ --length=n Generate password(s) of n length.
105
+ --qty=n Generate n password(s).
106
+ --charset=chars Only include chars in password(s).
107
+ --exclude=chars Exclude chars from password(s).
108
+
109
+ Boolean options:
110
+ -n, --include-numbers Allow numbers in password(s).
111
+ -s, --include-symbols Allow symbols in password(s).
112
+ -L, --no-lowercase Disallow lowercase letters in password(s).
113
+ -U, --no-uppercase Disallow uppercase letters in password(s).
114
+
115
+ Info commands:
116
+ -h, --help Display this help screen.
117
+ -v, --version Show version number.
118
+ ```
119
+
120
+ <br>
121
+
122
+ ## 💖 Support
123
+
124
+ Please consider [giving a GitHub ⭐](https://github.com/adamlui/js-utils) or [funding](https://github.com/sponsors/adamlui) this project if it helped you!
125
+ <br><br>
126
+
127
+ ## 🏛️ MIT License
128
+
129
+ **Copyright © 2024 [Adam Lui](https://github.com/adamlui)**
130
+
131
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
132
+
133
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
134
+
135
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
136
+
137
+ <br>
138
+
139
+ <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
140
+
141
+ <a href="https://github.com/adamlui/js-utils">**Home**</a> /
142
+ <a href="https://github.com/adamlui/js-utils/discussions">Discuss</a> /
143
+ <a href="#-generate-pw">Back to top ↑</a>
package/generate-pw.js CHANGED
@@ -1,146 +1,185 @@
1
- #!/usr/bin/env node
2
-
3
- // Import crypto.randomInt() for secure RNG
4
- const { randomInt } = require('crypto');
5
-
6
- // Init character sets
7
- const charsets = {
8
- lower: 'abcdefghijklmnopqrstuvwxyz',
9
- upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
10
- numbers: '0123456789',
11
- symbols: '!@#$%^&*()-_=+[]{}/\\|;:\'",.<>?'
12
- };
13
-
14
- // Define MAIN functions
15
-
16
- function generatePassword(options = {}) {
17
-
18
- // Init options
19
- const defaultOptions = {
20
- length: 8, // length of password
21
- qty: 1, // number of passwords to generate
22
- charset: '', // characters to include
23
- exclude: '', // characters to exclude
24
- numbers: false, // include numberChars
25
- symbols: false, // include symbolChars
26
- lowercase: true, // include lowercase letters
27
- uppercase: true, // include uppercase letters
28
- strict: false // require at least one char from each enabled set
29
- };
30
- options = { ...defaultOptions, ...options };
31
-
32
- if (options.qty > 1) { // return array of [qty] password strings
33
- const { qty, ...otherOptions } = options;
34
- return generatePasswords(qty, otherOptions);
35
-
36
- } else { // return single password string
37
-
38
- // Init password's char set
39
- let pwCharset = options.charset || ( // use passed [charset], or construct from options
40
- (options.numbers ? charsets.numbers : '')
41
- + (options.symbols ? charsets.symbols : '')
42
- + (options.lowercase ? charsets.lower : '')
43
- + (options.uppercase ? charsets.upper : '')
44
- );
45
- if (pwCharset === '') // all flags false + no charset passed
46
- pwCharset = charsets.lower + charsets.upper; // default to upper + lower
47
-
48
- // Exclude passed `exclude` chars
49
- pwCharset = pwCharset.replace(new RegExp(`[${ options.exclude }]`, 'g'), '');
50
-
51
- // Generate unstrict password
52
- let password = '';
53
- for (let i = 0; i < options.length; i++) {
54
- const randomIndex = randomInt(0, pwCharset.length);
55
- password += pwCharset.charAt(randomIndex);
56
- }
57
-
58
- // Enforce strict mode if enabled
59
- if (options.strict) {
60
- const charTypes = ['number', 'symbol', 'lower', 'upper'],
61
- requiredCharTypes = charTypes.filter(charType => options[charType + 's'] || options[charType + 'case']);
62
-
63
- // Init flags
64
- for (const charType of requiredCharTypes)
65
- global['has' + charType.charAt(0).toUpperCase() + charType.slice(1)] = false;
66
- for (let i = 0; i < password.length; i++)
67
- for (const charType of requiredCharTypes)
68
- if ((charsets[charType] || charsets[charType + 's']).includes(password.charAt(i)))
69
- global['has' + charType.charAt(0).toUpperCase() + charType.slice(1)] = true;
70
-
71
- // Modify password if necessary
72
- const maxReplacements = Math.min(password.length, requiredCharTypes.length),
73
- replacedPositions = []; let replacementCnt = 0;
74
- for (const charType of requiredCharTypes) {
75
- if (replacementCnt < maxReplacements) {
76
- if (!global['has' + charType.charAt(0).toUpperCase() + charType.slice(1)]) {
77
- let replacementPos;
78
- do replacementPos = randomInt(0, password.length); // pick random pos
79
- while (replacedPositions.includes(replacementPos)); // check if pos already replaced
80
- replacedPositions.push(replacementPos); // track new replacement pos
81
- const replacementCharSet = charsets[charType] || charsets[charType + 's']
82
- password = password.substring(0, replacementPos) // perform actual replacement
83
- + replacementCharSet.charAt(randomInt(0, replacementCharSet.length))
84
- + password.substring(replacementPos + 1);
85
- replacementCnt++;
86
- }}}
87
- }
88
-
89
- return password;
90
- }
91
- }
92
-
93
- function generatePasswords(qty, options) {
94
- qty = parseInt(qty);
95
- if (isNaN(qty)) return console.error(
96
- 'ERROR: First argument <qty> of generatePasswords() must be an integer');
97
- const passwords = [];
98
- for (let i = 0; i < qty; i++) passwords.push(generatePassword(options));
99
- return passwords;
100
- }
101
-
102
- // Export function if script was required
103
- if (require.main !== module) module.exports = { generatePassword, generatePasswords };
104
-
105
- else { // run as CLI tool
106
-
107
- // Init UI colors
108
- const nc = '\x1b[0m', // no color
109
- br = '\x1b[1;91m', // bright red
110
- bw = '\x1b[1;97m'; // bright white
111
-
112
- // Load settings from args
113
- const config = {
114
- length: parseInt(process.argv.find(arg => /^--?length/.test(arg))?.split('=')[1]) || 8,
115
- qty: parseInt(process.argv.find(arg => /^--?qu?a?n?ti?t?y=\d+$/.test(arg))?.split('=')[1]) || 1,
116
- charset: process.argv.find(arg => /^--?chars/.test(arg))?.split('=')[1] || charsets.lower + charsets.upper,
117
- excludeChars: process.argv.find(arg => /^--?exclude/.test(arg))?.split('=')[1] || '',
118
- includeNums: process.argv.some(arg => /^--?(?:n|include-?numbers?|numbers?=(?:true|1))$/.test(arg)),
119
- includeSymbols: process.argv.some(arg => /^--?(?:s|include-?symbols?|symbols?=(?:true|1))$/.test(arg)),
120
- excludeLowerChars: process.argv.some(arg =>
121
- /^--?(?:L|exclude-?lower-?(?:case)?|lower-?(?:case)?=(?:false|0))$/.test(arg)),
122
- excludeUpperChars: process.argv.some(arg =>
123
- /^--?(?:L|exclude-?upper-?(?:case)?|upper-?(?:case)?=(?:false|0))$/.test(arg)),
124
- strictMode: process.argv.some(arg => /^--?s(?:trict)?/.test(arg))
125
- };
126
-
127
- // Show VERSION number if -v or --version passed
128
- if (process.argv.some(arg => /^--?ve?r?s?i?o?n?$/.test(arg))) {
129
- console.info('v' + require('./package.json').version);
130
-
131
- } else { // run MAIN routine
132
- for (const numArgType of ['length', 'qty']) {
133
- if (config['numArgType'] < 1) {
134
- console.error(`\n${br}Error: '${ numArgType }' argument must be 1 or greater.${nc}`);
135
- process.exit(1);
136
- }}
137
- const funcOptions = {
138
- length: config.length, qty: config.qty, charset: config.charset, exclude: config.excludeChars,
139
- numbers: config.includeNums, symbols: config.includeSymbols,
140
- lowercase: !config.excludeLowerChars, uppercase: !config.excludeUpperChars,
141
- strict: config.strictMode
142
- };
143
- const pwResult = generatePassword(funcOptions);
144
- console.log('\n' + bw + ( Array.isArray(pwResult) ? pwResult.join('\n') : pwResult ) + nc);
145
- }
146
- }
1
+ #!/usr/bin/env node
2
+
3
+ // Import crypto.randomInt() for secure RNG
4
+ const { randomInt } = require('crypto');
5
+
6
+ // Init CHARACTER SETS
7
+ const charsets = {
8
+ lower: 'abcdefghijklmnopqrstuvwxyz',
9
+ upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
10
+ numbers: '0123456789',
11
+ symbols: '!@#$%^&*()-_=+[]{}/\\|;:\'",.<>?'
12
+ };
13
+
14
+ // Define MAIN functions
15
+
16
+ function generatePassword(options = {}) {
17
+
18
+ // Init options
19
+ const defaultOptions = {
20
+ length: 8, // length of password
21
+ qty: 1, // number of passwords to generate
22
+ charset: '', // characters to include
23
+ exclude: '', // characters to exclude
24
+ numbers: false, // include numberChars
25
+ symbols: false, // include symbolChars
26
+ lowercase: true, // include lowercase letters
27
+ uppercase: true, // include uppercase letters
28
+ strict: false // require at least one char from each enabled set
29
+ };
30
+ options = { ...defaultOptions, ...options };
31
+
32
+ if (options.qty > 1) { // return array of [qty] password strings
33
+ const { qty, ...otherOptions } = options;
34
+ return generatePasswords(qty, otherOptions);
35
+
36
+ } else { // return single password string
37
+
38
+ // Init password's char set
39
+ let pwCharset = options.charset || ( // use passed [charset], or construct from options
40
+ (options.numbers ? charsets.numbers : '')
41
+ + (options.symbols ? charsets.symbols : '')
42
+ + (options.lowercase ? charsets.lower : '')
43
+ + (options.uppercase ? charsets.upper : '')
44
+ );
45
+ if (pwCharset === '') // all flags false + no charset passed
46
+ pwCharset = charsets.lower + charsets.upper; // default to upper + lower
47
+
48
+ // Exclude passed `exclude` chars
49
+ pwCharset = pwCharset.replace(new RegExp(`[${ options.exclude }]`, 'g'), '');
50
+
51
+ // Generate unstrict password
52
+ let password = '';
53
+ for (let i = 0; i < options.length; i++) {
54
+ const randomIndex = randomInt(0, pwCharset.length);
55
+ password += pwCharset.charAt(randomIndex);
56
+ }
57
+
58
+ // Enforce strict mode if enabled
59
+ if (options.strict) {
60
+ const charTypes = ['number', 'symbol', 'lower', 'upper'],
61
+ requiredCharTypes = charTypes.filter(charType => options[charType + 's'] || options[charType + 'case']);
62
+
63
+ // Init flags
64
+ for (const charType of requiredCharTypes)
65
+ global['has' + charType.charAt(0).toUpperCase() + charType.slice(1)] = false;
66
+ for (let i = 0; i < password.length; i++)
67
+ for (const charType of requiredCharTypes)
68
+ if ((charsets[charType] || charsets[charType + 's']).includes(password.charAt(i)))
69
+ global['has' + charType.charAt(0).toUpperCase() + charType.slice(1)] = true;
70
+
71
+ // Modify password if necessary
72
+ const maxReplacements = Math.min(password.length, requiredCharTypes.length),
73
+ replacedPositions = []; let replacementCnt = 0;
74
+ for (const charType of requiredCharTypes) {
75
+ if (replacementCnt < maxReplacements) {
76
+ if (!global['has' + charType.charAt(0).toUpperCase() + charType.slice(1)]) {
77
+ let replacementPos;
78
+ do replacementPos = randomInt(0, password.length); // pick random pos
79
+ while (replacedPositions.includes(replacementPos)); // check if pos already replaced
80
+ replacedPositions.push(replacementPos); // track new replacement pos
81
+ const replacementCharSet = charsets[charType] || charsets[charType + 's'];
82
+ password = password.substring(0, replacementPos) // perform actual replacement
83
+ + replacementCharSet.charAt(randomInt(0, replacementCharSet.length))
84
+ + password.substring(replacementPos + 1);
85
+ replacementCnt++;
86
+ }}}
87
+ }
88
+
89
+ return password;
90
+ }
91
+ }
92
+
93
+ function generatePasswords(qty, options) {
94
+ qty = parseInt(qty);
95
+ if (isNaN(qty)) return console.error(
96
+ 'ERROR: First argument <qty> of generatePasswords() must be an integer');
97
+ const passwords = [];
98
+ for (let i = 0; i < qty; i++) passwords.push(generatePassword(options));
99
+ return passwords;
100
+ }
101
+
102
+ // EXPORT functions if script was required
103
+ if (require.main !== module) module.exports = { generatePassword, generatePasswords };
104
+
105
+ else { // run as CLI tool
106
+
107
+ // Init UI colors
108
+ const nc = '\x1b[0m', // no color
109
+ br = '\x1b[1;91m', // bright red
110
+ by = '\x1b[1;33m', // bright yellow
111
+ bw = '\x1b[1;97m'; // bright white
112
+
113
+ // Load settings from ARGS
114
+ const config = {
115
+ length: parseInt(process.argv.find(arg => /^--?length/.test(arg))?.split('=')[1]) || 8,
116
+ qty: parseInt(process.argv.find(arg => /^--?qu?a?n?ti?t?y=\d+$/.test(arg))?.split('=')[1]) || 1,
117
+ charset: process.argv.find(arg => /^--?chars/.test(arg))?.split('=')[1],
118
+ excludeChars: process.argv.find(arg => /^--?exclude=/.test(arg))?.split('=')[1] || '',
119
+ includeNums: process.argv.some(arg => /^--?(?:n|(?:include-?)?num(?:ber)?s?=?(?:true|1)?)$/.test(arg)),
120
+ includeSymbols: process.argv.some(arg => /^--?(?:s|(?:include-?)?symbols?=?(?:true|1)?)$/.test(arg)),
121
+ excludeLowerChars: process.argv.some(arg =>
122
+ /^--?(?:L|(?:exclude|disable|no)-?lower-?(?:case)?|lower-?(?:case)?=(?:false|0))$/.test(arg)),
123
+ excludeUpperChars: process.argv.some(arg =>
124
+ /^--?(?:U|(?:exclude|disable|no)-?upper-?(?:case)?|upper-?(?:case)?=(?:false|0))$/.test(arg)),
125
+ strictMode: process.argv.some(arg => /^--?s(?:trict)?(?:-?mode)?$/.test(arg))
126
+ };
127
+
128
+ // Show HELP screen if -h or --help passed
129
+ if (process.argv.some(arg => /^--?h(?:elp)?$/.test(arg))) {
130
+ printHelp(`\n${by}generate-pw [options]${nc}`);
131
+ printHelp('\nArgument options:');
132
+ printHelp(' --length=n Generate password(s) of n length.');
133
+ printHelp(' --qty=n Generate n password(s).');
134
+ printHelp(' --charset=chars Only include chars in password(s).');
135
+ printHelp(' --exclude=chars Exclude chars from password(s).');
136
+ printHelp('\nBoolean options:');
137
+ printHelp(' -n, --include-numbers Allow numbers in password(s).');
138
+ printHelp(' -s, --include-symbols Allow symbols in password(s).');
139
+ printHelp(' -L, --no-lowercase Disallow lowercase letters in password(s).');
140
+ printHelp(' -U, --no-uppercase Disallow uppercase letters in password(s).');
141
+ printHelp('\nInfo commands:');
142
+ printHelp(' -h, --help Display this help screen.');
143
+ printHelp(' -v, --version Show version number.');
144
+
145
+ // Show VERSION number if -v or --version passed
146
+ } else if (process.argv.some(arg => /^--?ve?r?s?i?o?n?$/.test(arg))) {
147
+ console.info('v' + require('./package.json').version);
148
+
149
+ } else { // run MAIN routine
150
+ for (const numArgType of ['length', 'qty'])
151
+ if (config[numArgType] < 1) return console.error(
152
+ `\n${br}Error: '${ numArgType }' argument must be 1 or greater.${nc}`);
153
+ const funcOptions = {
154
+ length: config.length, qty: config.qty, charset: config.charset, exclude: config.excludeChars,
155
+ numbers: config.includeNums, symbols: config.includeSymbols,
156
+ lowercase: !config.excludeLowerChars, uppercase: !config.excludeUpperChars,
157
+ strict: config.strictMode
158
+ };
159
+ const pwResult = generatePassword(funcOptions);
160
+ console.log('\n' + bw + ( Array.isArray(pwResult) ? pwResult.join('\n') : pwResult ) + nc);
161
+ }
162
+
163
+ function printHelp(msg) { // wrap msg + indent 2nd+ lines (for --help screen)
164
+ const terminalWidth = process.stdout.columns || 80,
165
+ indentation = 29, lines = [], words = msg.match(/\S+|\s+/g);
166
+
167
+ // Split msg into lines of appropriate lengths
168
+ let currentLine = '';
169
+ words.forEach(word => {
170
+ const lineLength = terminalWidth - ( lines.length === 0 ? 0 : indentation );
171
+ if (currentLine.length + word.length > lineLength) { // cap/store it
172
+ lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
173
+ currentLine = '';
174
+ }
175
+ currentLine += word;
176
+ });
177
+ lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
178
+
179
+ // Print formatted msg
180
+ lines.forEach((line, index) => console.info(
181
+ index === 0 ? line // print 1st line unindented
182
+ : ' '.repeat(indentation) + line // print subsequent lines indented
183
+ ));
184
+ }
185
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "generate-pw",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Randomly generate cryptographically-secure passwords.",
5
5
  "author": {
6
6
  "name": "Adam Lui",
@@ -10,8 +10,18 @@
10
10
  "homepage": "https://github.com/adamlui/js-utils",
11
11
  "license": "MIT",
12
12
  "main": "generate-pw.js",
13
+ "bin": {
14
+ "generatepw": "generate-pw.js",
15
+ "generate-pw": "generate-pw.js"
16
+ },
13
17
  "scripts": {
14
- "test": "echo \"Error: no test specified\" && exit 1"
18
+ "test": "echo \"Error: no test specified\" && exit 1",
19
+ "bump:patch": "bash utils/bump.sh patch",
20
+ "bump:minor": "bash utils/bump.sh minor",
21
+ "bump:major": "bash utils/bump.sh major",
22
+ "publish:patch": "bash utils/bump.sh patch --publish",
23
+ "publish:minor": "bash utils/bump.sh minor --publish",
24
+ "publish:major": "bash utils/bump.sh major --publish"
15
25
  },
16
26
  "repository": {
17
27
  "type": "git",