forked from postalsys/emailengine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encrypt.js
183 lines (157 loc) · 5.97 KB
/
encrypt.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
'use strict';
if (!process.env.EE_ENV_LOADED) {
require('dotenv').config(); // eslint-disable-line global-require
process.env.EE_ENV_LOADED = 'true';
}
try {
process.chdir(__dirname);
} catch (err) {
// ignore
}
const { redis } = require('./lib/db');
const config = require('wild-config');
const { encrypt, decrypt, parseEncryptedData } = require('./lib/encrypt');
const { encryptedKeys } = require('./lib/settings');
const getSecret = require('./lib/get-secret');
const { REDIS_PREFIX } = require('./lib/consts');
const DECRYPT_PASSWORDS = [].concat(config.decrypt || []);
async function processSecret(value, encryptSecret) {
let lastErr = false;
let decrypted = value;
for (let password of DECRYPT_PASSWORDS) {
try {
decrypted = decrypt(value, password);
if (password === encryptSecret) {
// nothing was changed
return value;
}
break;
} catch (err) {
lastErr = err;
}
}
let parsed = parseEncryptedData(decrypted);
if (parsed.format !== 'cleartext') {
// was not able to decrypt
if (encryptSecret) {
try {
decrypted = decrypt(value, encryptSecret);
// did not throw, so the value is already encrypted with the new password
return value;
} catch (err) {
// ignore
}
}
throw lastErr || new Error('Could not decrypt encrypted password');
}
if (encryptSecret) {
// encrypt
return encrypt(decrypted, encryptSecret);
}
// return plaintext
return decrypted;
}
async function main() {
console.error('EmailEngine account encryption tool');
const encryptSecret = await getSecret();
if (!encryptSecret && !DECRYPT_PASSWORDS.length) {
console.error('Usage:');
console.error(' emailengine encrypt --dbs.redis="redis://url" --service.secret="new-pass" --decrypt="old-pass"');
console.error('Where');
console.error(' --dbs.redis is a Redis configuration URL');
console.error(' --service.secret is the secret value to use for encryption.');
console.error(' Leave empty to remove encryption.');
console.error(' --decrypt is the old secret value. Not needed if current passwords are not encrypted.');
console.error(' You can set this value multiple times if accounts are enrypted with different secrets.');
return;
}
// convert settings
for (let key of encryptedKeys) {
let value = await redis.hget(`${REDIS_PREFIX}settings`, key);
if (value && typeof value === 'string') {
try {
let updated = await processSecret(value, encryptSecret);
if (updated !== value) {
await redis.hset(`${REDIS_PREFIX}settings`, key, updated);
console.log(`${key}: Updated setting value`);
}
} catch (err) {
console.error(`${key}: Failed to process setting value`);
console.error(err);
}
}
}
let updatedAccounts = 0;
let accounts = await redis.smembers(`${REDIS_PREFIX}ia:accounts`);
for (let account of accounts) {
let accountData = await redis.hgetall(`${REDIS_PREFIX}iad:${account}`);
if (!accountData) {
continue;
}
let updates = {};
let updated = false;
for (let key of ['imap', 'smtp', 'oauth2']) {
if (!accountData[key]) {
continue;
}
try {
accountData[key] = JSON.parse(accountData[key]);
} catch (err) {
console.error(`Failed to parse ${key} for ${account}`);
console.error(err);
continue;
}
if (!accountData[key]) {
continue;
}
let changes = false;
for (let subKey of ['pass', 'accessToken', 'refreshToken']) {
if (accountData[key].auth && accountData[key].auth[subKey]) {
try {
let value = await processSecret(accountData[key].auth[subKey], encryptSecret);
if (value !== accountData[key].auth[subKey]) {
accountData[key].auth[subKey] = value;
changes = true;
}
} catch (err) {
console.error(`Could not process "${key}.auth.${subKey}" for ${account}. Check decryption secrets.`);
}
}
}
for (let subKey of ['accessToken', 'refreshToken']) {
if (accountData[key] && accountData[key][subKey]) {
try {
let value = await processSecret(accountData[key][subKey], encryptSecret);
if (value !== accountData[key][subKey]) {
accountData[key][subKey] = value;
changes = true;
}
} catch (err) {
console.error(`Could not process "${key}.${subKey}" for ${account}. Check decryption secrets.`);
}
}
}
if (changes) {
updates[key] = JSON.stringify(accountData[key]);
updated = true;
}
}
if (updated) {
let result = await redis.hmset(`${REDIS_PREFIX}iad:${account}`, updates);
if (result === 'OK') {
console.log(`${account}: updated`);
} else {
console.log(`${account}: Unexpected response from DB: ${result}`);
}
updatedAccounts++;
}
}
console.log(`Updated ${updatedAccounts}/${accounts.length} accounts`);
}
main()
.then(() => process.exit(0))
.catch(err => {
console.error(err);
process.exit(1);
})
.finally();