-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
72 lines (66 loc) · 2.25 KB
/
cli.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
require("dotenv").config();
const {
askIntroQuestions,
askRetrievePasswordQuestions,
askSetPasswordQuestions,
askForNewMasterPassword,
OPTION_READ,
OPTION_SET,
} = require("./lib/questions");
const {
readPassword,
writePassword,
readMasterPassword,
writeMasterPassword,
} = require("./lib/passwords");
const { encrypt, decrypt, createHash, verifyHash } = require("./lib/crypto");
const { MongoClient } = require("mongodb");
const client = new MongoClient(process.env.MONGO_URL);
async function main() {
try {
await client.connect();
const database = client.db(process.env.MONGO_DB_NAME);
const originalMasterPassword = await readMasterPassword();
if (!originalMasterPassword) {
const { newMasterPassword } = await askForNewMasterPassword();
const hashedMasterPassword = createHash(newMasterPassword);
await writeMasterPassword(hashedMasterPassword);
console.log("Master Password set!");
return;
}
const { masterPassword, action } = await askIntroQuestions();
if (!verifyHash(masterPassword, originalMasterPassword)) {
console.log("Master Password is incorrect!");
return;
}
console.log("Master Password is correct!");
if (action === OPTION_READ) {
console.log("Now Get a password");
const { key } = await askRetrievePasswordQuestions();
try {
const encryptedPassword = await readPassword(key, database);
const decryptPassword = decrypt(encryptedPassword, masterPassword);
console.log(`Your ${key} password is ${decryptPassword}`);
} catch (error) {
console.error("Oops, something went wrong");
// What to do now?
}
} else if (action === OPTION_SET) {
console.log("Now Set a password");
try {
const { key, password } = await askSetPasswordQuestions();
const encryptedPassword = encrypt(password, masterPassword);
console.log(encryptedPassword);
await writePassword(key, encryptedPassword, database);
console.log(`New Password set`);
} catch (error) {
console.error("Oops, something went wrong");
// What to do now?
}
}
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
main();