-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·95 lines (81 loc) · 2.38 KB
/
index.js
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const process = require('process');
const readline = require('readline');
const joi = require('@hapi/joi');
const meow = require('meow');
const randomNumber = require('random-number-csprng');
const cli = meow(
`
Usage
$ diceware <length> (default: 5)
Options
--separator, -s Words separator (default: " ")
--list, -l Word list ("beale", "cs", "en"; default: "en")
Examples
$ diceware 4 -s "."
bonsai.camper.frequent.power
$ diceware --list cs --separator "@"
1925@poprvé@přitom@upjatý@úporně@zázemí
`,
{
flags: {
separator: {
type: 'string',
alias: 's',
},
list: {
type: 'string',
alias: 'l',
},
},
},
);
const schemaInput = joi.number().integer().min(1).max(7776).default(6).label('Passphrase length');
const schemaFlags = joi.object({
separator: joi.string().default(' ').label('Separator'),
list: joi.string().equal('beale', 'cs', 'en').default('en').label('List'),
});
let passphraseLength, flags;
try {
passphraseLength = joi.attempt(cli.input?.[0], schemaInput);
flags = joi.attempt(cli.flags, schemaFlags);
} catch ({ message }) {
console.error(message);
process.exit(1);
}
const createRandomCode = length => async () => {
const numbersPromise = [...Array(length)].map(() => randomNumber(1, 6));
const number = await Promise.all(numbersPromise);
return number.join('');
};
const codesPromises = [...Array(passphraseLength)].map(createRandomCode(5));
(async () => {
const codes = await Promise.all(codesPromises);
const listFilePath = path.resolve(__dirname, 'lists', `${flags.list}.txt`);
const readStream = fs.createReadStream(listFilePath, 'utf8');
const lineReader = readline.createInterface({ input: readStream });
let diceware = [...Array(codes.length)];
let wordsCount = 0;
lineReader
.on('line', line => {
if (wordsCount >= passphraseLength) {
lineReader.close();
return;
}
const [code, word] = line.split(/\s+/);
const codeIndex = codes.indexOf(code);
if (codeIndex !== -1) {
diceware[codeIndex] = word;
wordsCount++;
}
})
.on('close', () => {
console.log(diceware.join(flags.separator));
})
.on('error', error => {
throw new Error(error);
});
})();