This repository has been archived by the owner on Jun 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
/
key-manager.es6
78 lines (72 loc) · 2.31 KB
/
key-manager.es6
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
import {remote} from 'electron'
import keytar from 'keytar'
/**
* A basic wrap around keytar's secure key management. Consolidates all of
* our keys under a single namespaced keymap and provides migration
* support.
*
* Consolidating this prevents a ton of key authorization popups for each
* and every key we want to access.
*/
class KeyManager {
constructor() {
/**
* NOTE: Old N1 includes a migration system that manually looks for
* the names of these keys. If you change them be sure that old N1 is
* fully deprecated or updated as well.
*/
this.SERVICE_NAME = "Nylas Mail";
if (NylasEnv.inDevMode()) {
this.SERVICE_NAME = "Nylas Mail Dev";
}
this.KEY_NAME = "Nylas Mail Keys"
this._alreadyMigrated = new Set()
}
replacePassword(keyName, newVal) {
this._try(() => {
const keys = this._getKeyHash();
keys[keyName] = newVal;
return keytar.replacePassword(this.SERVICE_NAME, this.KEY_NAME, JSON.stringify(keys))
})
}
deletePassword(keyName) {
this._try(() => {
const keys = this._getKeyHash();
delete keys[keyName];
return keytar.replacePassword(this.SERVICE_NAME, this.KEY_NAME, JSON.stringify(keys))
})
}
getPassword(keyName, {migrateFromService} = {}) {
const keys = this._getKeyHash();
if (!keys[keyName] && migrateFromService &&
!this._alreadyMigrated.has(migrateFromService)) {
const oldVal = keytar.getPassword(migrateFromService, keyName);
if (oldVal) {
this.replacePassword(keyName, oldVal)
this._alreadyMigrated.add(migrateFromService)
}
}
return keys[keyName]
}
_getKeyHash() {
const raw = keytar.getPassword(this.SERVICE_NAME, this.KEY_NAME) || "{}";
try {
return JSON.parse(raw)
} catch (err) {
return {}
}
}
_try(fn) {
const ERR_MSG = "We couldn't store your password securely! For more information, visit https://support.nylas.com/hc/en-us/articles/223790028";
try {
if (!fn()) {
remote.dialog.showErrorBox("Password Management Error", ERR_MSG)
NylasEnv.reportError(new Error(`Password Management Error: ${ERR_MSG}`))
}
} catch (err) {
remote.dialog.showErrorBox("Password Management Error", ERR_MSG)
NylasEnv.reportError(err)
}
}
}
export default new KeyManager();