generate-pw 1.0.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.
package/README.md ADDED
@@ -0,0 +1,54 @@
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>
@@ -0,0 +1,9 @@
1
+ # 🏛️ MIT License
2
+
3
+ **Copyright © 2024 [Adam Lui](https://github.com/adamlui)**
4
+
5
+ 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:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ 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.
@@ -0,0 +1,5 @@
1
+ # 🛡️ Security Policy
2
+
3
+ If you find a vulnerability, please open a [draft security advisory](https://github.com/adamlui/js-utils/security/advisories/new).
4
+
5
+ Pull requests are also welcome, but for safety reasons, send an email to <adam@kudoai.com> and wait for a response before making it public.
package/generate-pw.js ADDED
@@ -0,0 +1,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 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
+ }
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "generate-pw",
3
+ "version": "1.0.0",
4
+ "description": "Randomly generate cryptographically-secure passwords.",
5
+ "author": {
6
+ "name": "Adam Lui",
7
+ "email": "adam@kudoai.com",
8
+ "url": "https://github.com/adamlui"
9
+ },
10
+ "homepage": "https://github.com/adamlui/js-utils",
11
+ "license": "MIT",
12
+ "main": "generate-pw.js",
13
+ "scripts": {
14
+ "test": "echo \"Error: no test specified\" && exit 1"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/adamlui/js-utils.git"
19
+ },
20
+ "keywords": [
21
+ "password",
22
+ "generator",
23
+ "unique",
24
+ "generate"
25
+ ],
26
+ "bugs": {
27
+ "url": "https://github.com/adamlui/js-utils/issues"
28
+ },
29
+ "funding": {
30
+ "type": "github",
31
+ "url": "https://github.com/sponsors/adamlui"
32
+ }
33
+ }