emailengine-app 2.72.2 → 2.72.4
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/CHANGELOG.md +52 -0
- package/Gruntfile.js +4 -1
- package/data/google-crawlers.json +1 -1
- package/lib/account.js +4 -3
- package/lib/autodetect-imap-settings.js +60 -11
- package/lib/consts.js +7 -0
- package/lib/email-client/gmail-client.js +4 -1
- package/lib/email-client/imap/mailbox.js +137 -30
- package/lib/email-client/imap/subconnection.js +105 -36
- package/lib/email-client/imap-client.js +331 -165
- package/lib/email-client/outlook/graph-api.js +3 -1
- package/lib/email-client/reconnect-backoff.js +38 -0
- package/lib/export.js +3 -2
- package/lib/imap-proxy-auth.js +2 -1
- package/lib/schemas.js +14 -0
- package/lib/settings.js +42 -11
- package/lib/smtp-auth.js +2 -1
- package/lib/sub-script.js +14 -3
- package/lib/tokens.js +2 -1
- package/lib/tools.js +122 -12
- package/lib/ui-routes/account-routes.js +340 -121
- package/lib/ui-routes/admin-config-routes.js +11 -1
- package/lib/ui-routes/unsubscribe-routes.js +69 -49
- package/package.json +23 -20
- package/sbom.json +1 -1
- package/static/js/ee-client.js +198 -140
- package/static/licenses.html +63 -73
- package/translations/messages.pot +106 -96
- package/views/accounts/register/imap-server.hbs +87 -17
- package/views/partials/oauth_form.hbs +4 -4
- package/views/unsubscribe.hbs +8 -17
- package/workers/api.js +124 -53
|
@@ -126,7 +126,9 @@ async function request(context, url, method, payload, options = {}) {
|
|
|
126
126
|
|
|
127
127
|
switch (status) {
|
|
128
128
|
case 401:
|
|
129
|
-
|
|
129
|
+
// NOTE: never include `accessToken` here - this logger persists to the per-account
|
|
130
|
+
// log store (exposed via the account logs API/UI) and to Sentry (security review M3).
|
|
131
|
+
context.logger.error({ msg: 'Failed to authenticate API request', account: context.account, err });
|
|
130
132
|
throw err;
|
|
131
133
|
|
|
132
134
|
case 429:
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Shared capped exponential backoff counter for IMAP reconnection scheduling.
|
|
4
|
+
// Pure delay math - the consumers own the timers and decide when a setup
|
|
5
|
+
// counts as validated (reset()).
|
|
6
|
+
|
|
7
|
+
// Exponent clamp so the intermediate float can not blow up on a long outage;
|
|
8
|
+
// with the delay cap applied the clamp itself never changes the resulting
|
|
9
|
+
// delay for the parameter sets in use
|
|
10
|
+
const MAX_ATTEMPT_EXPONENT = 10;
|
|
11
|
+
|
|
12
|
+
class ReconnectBackoff {
|
|
13
|
+
constructor(opts) {
|
|
14
|
+
opts = opts || {};
|
|
15
|
+
this.baseDelay = opts.baseDelay || 2000; // first computed delay (before jitter)
|
|
16
|
+
this.maxDelay = opts.maxDelay || 30000;
|
|
17
|
+
this.factor = opts.factor || 1.5;
|
|
18
|
+
this.jitter = opts.jitter || 0; // random 0..jitter ms added after the cap
|
|
19
|
+
this.attempts = 0;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Returns the next scheduling delay and increments the attempt counter:
|
|
24
|
+
* min(maxDelay, baseDelay * factor^attempts) plus random jitter
|
|
25
|
+
* @returns {number} Delay in milliseconds
|
|
26
|
+
*/
|
|
27
|
+
nextDelay() {
|
|
28
|
+
const delay = Math.min(this.maxDelay, this.baseDelay * Math.pow(this.factor, Math.min(this.attempts, MAX_ATTEMPT_EXPONENT)));
|
|
29
|
+
this.attempts++;
|
|
30
|
+
return this.jitter ? delay + Math.random() * this.jitter : delay;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
reset() {
|
|
34
|
+
this.attempts = 0;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = { ReconnectBackoff };
|
package/lib/export.js
CHANGED
|
@@ -9,6 +9,7 @@ const { redis, exportQueue } = require('./db');
|
|
|
9
9
|
const settings = require('./settings');
|
|
10
10
|
const logger = require('./logger');
|
|
11
11
|
const getSecret = require('./get-secret');
|
|
12
|
+
const { escapeRedisGlob } = require('./tools');
|
|
12
13
|
|
|
13
14
|
const {
|
|
14
15
|
REDIS_PREFIX,
|
|
@@ -304,7 +305,7 @@ class Export {
|
|
|
304
305
|
const page = Number(options.page) || 0;
|
|
305
306
|
const pageSize = Number(options.pageSize) || 20;
|
|
306
307
|
|
|
307
|
-
const pattern = `${REDIS_PREFIX}exp:${account}:${EXPORT_ID_PREFIX}*`;
|
|
308
|
+
const pattern = `${REDIS_PREFIX}exp:${escapeRedisGlob(account)}:${EXPORT_ID_PREFIX}*`;
|
|
308
309
|
const keys = await scanKeys(pattern);
|
|
309
310
|
|
|
310
311
|
const exports = [];
|
|
@@ -567,7 +568,7 @@ class Export {
|
|
|
567
568
|
if (!file.startsWith(EXPORT_ID_PREFIX)) continue;
|
|
568
569
|
|
|
569
570
|
const exportId = file.split('.')[0];
|
|
570
|
-
const pattern = `${REDIS_PREFIX}exp:*:${exportId}`;
|
|
571
|
+
const pattern = `${REDIS_PREFIX}exp:*:${escapeRedisGlob(exportId)}`;
|
|
571
572
|
const keys = await scanKeys(pattern);
|
|
572
573
|
|
|
573
574
|
if (keys.length === 0) {
|
package/lib/imap-proxy-auth.js
CHANGED
|
@@ -12,6 +12,7 @@ const { Account } = require('./account');
|
|
|
12
12
|
const getSecret = require('./get-secret');
|
|
13
13
|
const { isApiBasedApp } = require('./oauth2-apps');
|
|
14
14
|
const { validateAuthToken, REASON_MESSAGES } = require('./auth-token');
|
|
15
|
+
const { constantTimeEqual } = require('./tools');
|
|
15
16
|
|
|
16
17
|
/**
|
|
17
18
|
* Builds the IMAP proxy authentication handler.
|
|
@@ -25,7 +26,7 @@ function createImapProxyAuthHandler({ call }) {
|
|
|
25
26
|
let account = auth.username;
|
|
26
27
|
|
|
27
28
|
let imapPassword = await settings.get('imapProxyServerPassword');
|
|
28
|
-
if (!imapPassword || auth.password
|
|
29
|
+
if (!imapPassword || !constantTimeEqual(auth.password, imapPassword)) {
|
|
29
30
|
// fall back to API token authentication
|
|
30
31
|
let result = await validateAuthToken({
|
|
31
32
|
password: auth.password,
|
package/lib/schemas.js
CHANGED
|
@@ -48,6 +48,19 @@ const ADDRESS_STRATEGIES = [
|
|
|
48
48
|
|
|
49
49
|
const accountIdSchema = Joi.string().empty('').trim().max(256).example('user123').description('Unique identifier for the email account');
|
|
50
50
|
|
|
51
|
+
// The service-secret-signed blob (base64url `data` + its HMAC `sig`) carried by every hosted
|
|
52
|
+
// authentication-form page. Defined once so the security-relevant field definitions cannot drift across
|
|
53
|
+
// the auth:false hosted-form endpoints. Both fields required: every issuer signs unconditionally and every
|
|
54
|
+
// template renders the sig hidden input, so a request without one is always hand-crafted. NB: the tracking
|
|
55
|
+
// endpoints (/redirect, /open.gif, /unsubscribe in workers/api.js) intentionally keep `sig` OPTIONAL at the
|
|
56
|
+
// Joi layer - their handlers fail closed on a missing/bad signature, and /unsubscribe must not turn a
|
|
57
|
+
// missing-sig request into a Joi 400 (RFC 8058 one-click wants a benign non-throwing response) - so they do
|
|
58
|
+
// NOT use this fragment.
|
|
59
|
+
const signedFormBlobFields = {
|
|
60
|
+
data: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required(),
|
|
61
|
+
sig: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required()
|
|
62
|
+
};
|
|
63
|
+
|
|
51
64
|
// All states that the account state field can expose over the API. In addition to the state
|
|
52
65
|
// machine states, 'disconnected' and 'paused' are client-level display states set by imap-client
|
|
53
66
|
const ACCOUNT_DISPLAY_STATES = [...Object.values(ACCOUNT_STATES), 'disconnected', 'paused'];
|
|
@@ -2466,6 +2479,7 @@ module.exports = {
|
|
|
2466
2479
|
responseFromAddressSchema,
|
|
2467
2480
|
emailIdSchema,
|
|
2468
2481
|
threadIdSchema,
|
|
2482
|
+
signedFormBlobFields,
|
|
2469
2483
|
outboxEntrySchema,
|
|
2470
2484
|
googleProjectIdSchema,
|
|
2471
2485
|
googleTopicNameSchema,
|
package/lib/settings.js
CHANGED
|
@@ -142,16 +142,36 @@ module.exports = {
|
|
|
142
142
|
return value;
|
|
143
143
|
},
|
|
144
144
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
value = JSON.stringify(formattedValue);
|
|
145
|
+
// Serialize an already-formatted setting value the way get()/getValue() expect it back:
|
|
146
|
+
// JSON-encoded, encrypted for ENCRYPTED_KEYS members. Every writer (set, setMulti,
|
|
147
|
+
// setIfMissing) must go through this so the encoding cannot drift between them.
|
|
148
|
+
encodeSettingValue(key, formattedValue, encryptSecret) {
|
|
149
|
+
let value = JSON.stringify(formattedValue);
|
|
150
150
|
|
|
151
151
|
if (encryptSecret && ENCRYPTED_KEYS.includes(key)) {
|
|
152
152
|
value = encrypt(value, encryptSecret);
|
|
153
153
|
}
|
|
154
154
|
|
|
155
|
+
return value;
|
|
156
|
+
},
|
|
157
|
+
|
|
158
|
+
async set(key, value) {
|
|
159
|
+
// A blank serviceSecret must never be persisted: an empty stored secret breaks HMAC
|
|
160
|
+
// signing/verification for every hosted-form and tracking link, and makes getServiceSecret()
|
|
161
|
+
// silently mint a fresh secret - invalidating every signed link already out in delivered mail.
|
|
162
|
+
// A blank value means "keep the current secret", not "clear it". Enforced here so it covers every
|
|
163
|
+
// writer that reaches set() (the /v1/settings API and the EENGINE_SETTINGS prepared config), not
|
|
164
|
+
// just the admin UI which additionally surfaces a flash. Boot-time minting (server.js) passes a
|
|
165
|
+
// non-empty random value, so it is unaffected.
|
|
166
|
+
if (key === 'serviceSecret' && (typeof value !== 'string' || !value.trim())) {
|
|
167
|
+
return 0;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const encryptSecret = await getSecret();
|
|
171
|
+
|
|
172
|
+
let formattedValue = module.exports.formatSettingValue(key, value);
|
|
173
|
+
value = module.exports.encodeSettingValue(key, formattedValue, encryptSecret);
|
|
174
|
+
|
|
155
175
|
if (/^documentStore/.test(key)) {
|
|
156
176
|
// increase version for documentStore settings
|
|
157
177
|
try {
|
|
@@ -178,19 +198,30 @@ module.exports = {
|
|
|
178
198
|
return await redis.hset(`${REDIS_PREFIX}settings`, key, value);
|
|
179
199
|
},
|
|
180
200
|
|
|
201
|
+
// Store a value only if the key does not exist yet (atomic HSETNX). Meant for one-shot
|
|
202
|
+
// initialization keys (currently the auto-generated serviceSecret) where concurrent minters
|
|
203
|
+
// must converge on a single stored value instead of overwriting each other. Skips the
|
|
204
|
+
// documentStore/openAi side effects of set() on purpose. Returns true when the value was stored.
|
|
205
|
+
async setIfMissing(key, value) {
|
|
206
|
+
const encryptSecret = await getSecret();
|
|
207
|
+
|
|
208
|
+
value = module.exports.encodeSettingValue(key, module.exports.formatSettingValue(key, value), encryptSecret);
|
|
209
|
+
|
|
210
|
+
return (await redis.hsetnx(`${REDIS_PREFIX}settings`, key, value)) === 1;
|
|
211
|
+
},
|
|
212
|
+
|
|
181
213
|
async setMulti(obj) {
|
|
182
214
|
const encryptSecret = await getSecret();
|
|
183
215
|
let docStoreUpdated = false;
|
|
184
216
|
const storeObj = {};
|
|
185
217
|
for (let key of Object.keys(obj)) {
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
if (encryptSecret && ENCRYPTED_KEYS.includes(key)) {
|
|
190
|
-
value = encrypt(value, encryptSecret);
|
|
218
|
+
// See set(): never persist a blank serviceSecret - a blank value means "keep the current one".
|
|
219
|
+
if (key === 'serviceSecret' && (typeof obj[key] !== 'string' || !obj[key].trim())) {
|
|
220
|
+
continue;
|
|
191
221
|
}
|
|
192
222
|
|
|
193
|
-
|
|
223
|
+
let formattedValue = module.exports.formatSettingValue(key, obj[key]);
|
|
224
|
+
storeObj[key] = module.exports.encodeSettingValue(key, formattedValue, encryptSecret);
|
|
194
225
|
|
|
195
226
|
if (/^documentStore/.test(key)) {
|
|
196
227
|
docStoreUpdated = true;
|
package/lib/smtp-auth.js
CHANGED
|
@@ -10,6 +10,7 @@ const { redis } = require('./db');
|
|
|
10
10
|
const { Account } = require('./account');
|
|
11
11
|
const getSecret = require('./get-secret');
|
|
12
12
|
const { validateAuthToken, REASON_MESSAGES } = require('./auth-token');
|
|
13
|
+
const { constantTimeEqual } = require('./tools');
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
16
|
* Builds the SMTP server onAuth handler.
|
|
@@ -28,7 +29,7 @@ function createSmtpAuthHandler({ accountCache, call }) {
|
|
|
28
29
|
let account = auth.username;
|
|
29
30
|
|
|
30
31
|
let smtpPassword = await settings.get('smtpServerPassword');
|
|
31
|
-
if (!smtpPassword || auth.password
|
|
32
|
+
if (!smtpPassword || !constantTimeEqual(auth.password, smtpPassword)) {
|
|
32
33
|
// fall back to API token authentication
|
|
33
34
|
let result = await validateAuthToken({
|
|
34
35
|
password: auth.password,
|
package/lib/sub-script.js
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
// SECURITY WARNING: SubScript runs operator-authored fn/map/pre-processing code through
|
|
4
|
+
// Node's `vm` module. `vm` is NOT a security sandbox - code executed here can reach the
|
|
5
|
+
// host realm (e.g. via `someHostValue.constructor.constructor('return process')()`) and
|
|
6
|
+
// therefore runs with full server privileges (process env/secrets, host modules, fs).
|
|
7
|
+
// Only trusted operators may author these scripts; never expose script authoring to
|
|
8
|
+
// untrusted principals. Replacing this with a real isolate (isolated-vm) or out-of-process
|
|
9
|
+
// execution is a tracked follow-up (see security review finding C1).
|
|
10
|
+
|
|
3
11
|
const crypto = require('crypto');
|
|
4
12
|
const vm = require('vm');
|
|
5
13
|
const logger = require('./logger');
|
|
@@ -73,9 +81,12 @@ class SubScript {
|
|
|
73
81
|
}
|
|
74
82
|
|
|
75
83
|
// Allow callers (and tests) to shorten the execution timeout, but never
|
|
76
|
-
// raise it above SUBSCRIPT_RUNTIME_TIMEOUT
|
|
77
|
-
//
|
|
78
|
-
//
|
|
84
|
+
// raise it above SUBSCRIPT_RUNTIME_TIMEOUT. A falsy override (including 0,
|
|
85
|
+
// which vm treats as "no limit") falls back to the default so the limit can
|
|
86
|
+
// never be disabled. NOTE: vm's `timeout` only interrupts SYNCHRONOUS
|
|
87
|
+
// execution - it does not bound async work, so a script that awaits (or spins
|
|
88
|
+
// the microtask queue) can still run past this limit. It is a coarse guard,
|
|
89
|
+
// not a hard ceiling (see security review finding M8).
|
|
79
90
|
let runtimeTimeout = options && options.timeout ? Math.min(options.timeout, SUBSCRIPT_RUNTIME_TIMEOUT) : SUBSCRIPT_RUNTIME_TIMEOUT;
|
|
80
91
|
|
|
81
92
|
let start = Date.now();
|
package/lib/tokens.js
CHANGED
|
@@ -5,6 +5,7 @@ const crypto = require('crypto');
|
|
|
5
5
|
const msgpack = require('msgpack5')();
|
|
6
6
|
const logger = require('./logger');
|
|
7
7
|
const { REDIS_PREFIX } = require('./consts');
|
|
8
|
+
const { constantTimeEqual } = require('./tools');
|
|
8
9
|
|
|
9
10
|
const SESS_PREFIX = 'sess_';
|
|
10
11
|
|
|
@@ -64,7 +65,7 @@ module.exports = {
|
|
|
64
65
|
|
|
65
66
|
const [storedSignature, storedAccount] = storedSignatureValue.split(':');
|
|
66
67
|
|
|
67
|
-
if (!storedSignature || storedSignature
|
|
68
|
+
if (!storedSignature || !constantTimeEqual(storedSignature, expectedSignature)) {
|
|
68
69
|
// Delete invalid tokens
|
|
69
70
|
await redis.del(key);
|
|
70
71
|
return false;
|
package/lib/tools.js
CHANGED
|
@@ -11,7 +11,7 @@ const settings = require('./settings');
|
|
|
11
11
|
const { brotliDecompress } = require('zlib');
|
|
12
12
|
const util = require('util');
|
|
13
13
|
const brotliDecompressAsync = util.promisify(brotliDecompress);
|
|
14
|
-
const { createPublicKey, createVerify, randomBytes, createHmac } = require('crypto');
|
|
14
|
+
const { createPublicKey, createVerify, randomBytes, createHmac, createHash, timingSafeEqual } = require('crypto');
|
|
15
15
|
const logger = require('./logger');
|
|
16
16
|
const Boom = require('@hapi/boom');
|
|
17
17
|
const { ImapFlow } = require('imapflow');
|
|
@@ -812,6 +812,26 @@ module.exports = {
|
|
|
812
812
|
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
|
|
813
813
|
},
|
|
814
814
|
|
|
815
|
+
// Escape Redis glob metacharacters (\ * ? [ ]) so a user-controlled identifier interpolated into
|
|
816
|
+
// a SCAN/KEYS MATCH pattern matches literally and cannot widen the match across the key namespace
|
|
817
|
+
// (security review H2). Intended wildcards in the surrounding pattern are added by the caller and
|
|
818
|
+
// are not passed through here.
|
|
819
|
+
escapeRedisGlob(value) {
|
|
820
|
+
return String(value === null || value === undefined ? '' : value).replace(/[\\*?[\]]/g, '\\$&');
|
|
821
|
+
},
|
|
822
|
+
|
|
823
|
+
// Constant-time comparison of two secret / MAC strings. Both sides are hashed to a fixed-length
|
|
824
|
+
// digest first so timingSafeEqual never sees unequal lengths (which would throw and would leak
|
|
825
|
+
// length via the exception). Returns false for null/undefined (security review L1).
|
|
826
|
+
constantTimeEqual(a, b) {
|
|
827
|
+
if (a === null || a === undefined || b === null || b === undefined) {
|
|
828
|
+
return false;
|
|
829
|
+
}
|
|
830
|
+
const ha = createHash('sha256').update(String(a)).digest();
|
|
831
|
+
const hb = createHash('sha256').update(String(b)).digest();
|
|
832
|
+
return timingSafeEqual(ha, hb);
|
|
833
|
+
},
|
|
834
|
+
|
|
815
835
|
getRendezvousScore(key, shardId) {
|
|
816
836
|
return murmurhash(`${(shardId || '').toString()}\x00${key}`);
|
|
817
837
|
},
|
|
@@ -984,6 +1004,13 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
984
1004
|
},
|
|
985
1005
|
|
|
986
1006
|
async verifyAccountInfo(redis, accountData, logger) {
|
|
1007
|
+
// By design this connects to whatever imap/smtp host it is given, with no private/loopback/
|
|
1008
|
+
// reserved-IP filtering: EmailEngine routinely talks to mail servers on any address (incl.
|
|
1009
|
+
// self-hosted boxes on RFC1918 / 127.0.0.1), and it is normally deployed as an isolated
|
|
1010
|
+
// instance with no sensitive internal services to reach. Callers that expose this to
|
|
1011
|
+
// untrusted input gate it upstream (e.g. the hosted form's signed-blob check), and network
|
|
1012
|
+
// isolation - not host filtering here - is the intended SSRF boundary. Do not add an
|
|
1013
|
+
// IP blocklist here without making it opt-in; it would break legitimate local-mail setups.
|
|
987
1014
|
let response = {};
|
|
988
1015
|
|
|
989
1016
|
let proxyUrl = await settings.get('proxyUrl');
|
|
@@ -1679,8 +1706,22 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
1679
1706
|
async getServiceSecret() {
|
|
1680
1707
|
let serviceSecret = await settings.get('serviceSecret');
|
|
1681
1708
|
if (!serviceSecret) {
|
|
1709
|
+
// Mint atomically (HSETNX): unauthenticated tracking/form requests can race to generate
|
|
1710
|
+
// a missing secret, and a plain read-then-write would let the last writer invalidate
|
|
1711
|
+
// whatever the first writer already signed. The loser adopts the winner's secret.
|
|
1682
1712
|
serviceSecret = randomBytes(16).toString('hex');
|
|
1683
|
-
await settings.
|
|
1713
|
+
let created = await settings.setIfMissing('serviceSecret', serviceSecret);
|
|
1714
|
+
if (!created) {
|
|
1715
|
+
let stored = await settings.get('serviceSecret');
|
|
1716
|
+
if (stored) {
|
|
1717
|
+
serviceSecret = stored;
|
|
1718
|
+
} else {
|
|
1719
|
+
// The field exists but reads back empty/undecryptable (e.g. explicitly blanked
|
|
1720
|
+
// via the settings API): HSETNX cannot heal it, so overwrite - same healing the
|
|
1721
|
+
// previous read-then-write implementation performed.
|
|
1722
|
+
await settings.set('serviceSecret', serviceSecret);
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1684
1725
|
}
|
|
1685
1726
|
return serviceSecret;
|
|
1686
1727
|
},
|
|
@@ -1732,26 +1773,95 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
1732
1773
|
return { data: data.toString('base64url'), signature };
|
|
1733
1774
|
},
|
|
1734
1775
|
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1776
|
+
// Fail-closed HMAC check for service-secret-signed blobs, shared by every verification site.
|
|
1777
|
+
// getServiceSecret() generates and persists a secret when missing, so verification is never
|
|
1778
|
+
// silently skipped (an empty secret would otherwise accept forged, unsigned data). Returns true
|
|
1779
|
+
// only when `sig` matches `data`.
|
|
1780
|
+
//
|
|
1781
|
+
// Reviewed compat note (accepted, do not revert to skip-when-empty): fail-closed means an install
|
|
1782
|
+
// whose stored serviceSecret is currently blank will 403 tracking/unsubscribe links in
|
|
1783
|
+
// already-delivered mail (the old code skipped verification and resolved them, which also accepted
|
|
1784
|
+
// FORGED blobs - the hole this closes). This is documented in the release notes; an operator can
|
|
1785
|
+
// restore the previous secret via the settings API to revive old links. The separate hazard of an
|
|
1786
|
+
// undecryptable-but-present secret being overwritten is PRE-EXISTING (server.js startApplication
|
|
1787
|
+
// re-mints a null-reading secret at boot, before any request), not introduced by this change - so
|
|
1788
|
+
// do not treat it as a regression of this refactor.
|
|
1789
|
+
async verifyServiceSignature(data, sig) {
|
|
1790
|
+
const serviceSecret = await module.exports.getServiceSecret();
|
|
1791
|
+
const hmac = createHmac('sha256', serviceSecret);
|
|
1792
|
+
hmac.update(data);
|
|
1793
|
+
return module.exports.constantTimeEqual(hmac.digest('base64url'), sig);
|
|
1794
|
+
},
|
|
1795
|
+
|
|
1796
|
+
// Redis key for a hosted-form single-use nonce (`n` inside the signed blob). Built in one place so
|
|
1797
|
+
// the sites that must agree on it - the consumed-nonce check below, the IMAP-arm claim
|
|
1798
|
+
// (lib/ui-routes/account-routes.js) and the OAuth callback claim (workers/api.js) - cannot drift.
|
|
1799
|
+
formNonceKey(n) {
|
|
1800
|
+
return `${REDIS_PREFIX}account:form:${n}`;
|
|
1801
|
+
},
|
|
1802
|
+
|
|
1803
|
+
// Atomically claim a hosted-form single-use nonce (SET NX). Returns true when THIS caller won the
|
|
1804
|
+
// claim, false when the key already existed (the signed URL was already used). Throws on a Redis error
|
|
1805
|
+
// - a Redis failure is NOT a consumed nonce, so callers must map it to a retryable 5xx, not a 403.
|
|
1806
|
+
// Shared by the IMAP-arm submit and the OAuth callback so the EX/NX/TTL semantics of the double-spend
|
|
1807
|
+
// guard cannot drift between the two arms; each caller keeps its own Boom 403/500 messages.
|
|
1808
|
+
async claimFormNonce(redis, n, t) {
|
|
1809
|
+
const claimed = await redis.set(module.exports.formNonceKey(n), (t || '0').toString(), 'EX', Math.floor(MAX_FORM_TTL / 1000), 'NX');
|
|
1810
|
+
return !!claimed;
|
|
1811
|
+
},
|
|
1812
|
+
|
|
1813
|
+
// Release a claimed nonce (best-effort) so the caller can let the user retry after a failed create.
|
|
1814
|
+
// Never throws - a lost release just leaves the nonce consumed for its TTL (the accepted residual of
|
|
1815
|
+
// claim-before-create). Pair with claimFormNonce.
|
|
1816
|
+
async releaseFormNonce(redis, n, logger) {
|
|
1817
|
+
const nonceKey = module.exports.formNonceKey(n);
|
|
1818
|
+
try {
|
|
1819
|
+
await redis.del(nonceKey);
|
|
1820
|
+
} catch (err) {
|
|
1821
|
+
if (logger) {
|
|
1822
|
+
logger.error({ msg: 'Failed to release claimed form nonce', nonceKey, err });
|
|
1744
1823
|
}
|
|
1745
1824
|
}
|
|
1825
|
+
},
|
|
1826
|
+
|
|
1827
|
+
async parseSignedFormData(redis, payload, gt, opts) {
|
|
1828
|
+
opts = opts || {};
|
|
1829
|
+
|
|
1830
|
+
let data = Buffer.from(payload.data, 'base64url').toString();
|
|
1831
|
+
if (!(await module.exports.verifyServiceSignature(data, payload.sig))) {
|
|
1832
|
+
let error = Boom.boomify(new Error(gt.gettext('Signature validation failed')), { statusCode: 403 });
|
|
1833
|
+
throw error;
|
|
1834
|
+
}
|
|
1746
1835
|
|
|
1747
1836
|
data = JSON.parse(data);
|
|
1748
1837
|
|
|
1838
|
+
// Connection-driving / account-creating callers (the IMAP test + server endpoints) require a
|
|
1839
|
+
// single-use nonce so a signed blob cannot be replayed. Blobs issued without n/t (the
|
|
1840
|
+
// unsubscribe and tracking links) are verified by signature only and skip this gate.
|
|
1841
|
+
// NB! this also rejects hosted-form links generated by EmailEngine before v2.39 (those blobs
|
|
1842
|
+
// carry no n/t and never expire) BY DESIGN - a never-expiring signed setup link is exactly
|
|
1843
|
+
// the vulnerability this gate closes. Do not add a legacy bypass; issue a fresh setup link
|
|
1844
|
+
// instead. Warn so support can tell a legacy link from a forgery (the HMAC check above has
|
|
1845
|
+
// already passed at this point).
|
|
1846
|
+
//
|
|
1847
|
+
// Reviewed compat note (kept deliberately, do not "fix"): only the IMAP-arm endpoints pass
|
|
1848
|
+
// requireNonce, so a pre-v2.39 link dead-ends at those POSTs after the user enters credentials -
|
|
1849
|
+
// the accepted cost of closing the replay hole; recovery is re-issuing the link. The OAuth
|
|
1850
|
+
// re-auth path (POST /accounts/new -> accountFormHandler) intentionally does NOT pass
|
|
1851
|
+
// requireNonce, so rolling-upgrade re-auth and legacy OAuth links keep working; that arm's replay
|
|
1852
|
+
// safety is the atomic nonce claim in the OAuth callback (workers/api.js), not this gate.
|
|
1853
|
+
if (opts.requireNonce && (!data.n || !data.t)) {
|
|
1854
|
+
logger.warn({ msg: 'Rejected legacy signed form blob without a nonce (pre-v2.39 setup link)', account: data.account });
|
|
1855
|
+
let error = Boom.boomify(new Error(gt.gettext('Invalid or expired account setup URL')), { statusCode: 403 });
|
|
1856
|
+
throw error;
|
|
1857
|
+
}
|
|
1858
|
+
|
|
1749
1859
|
if (data.n && data.t) {
|
|
1750
1860
|
if (data.t < Date.now() - (MAX_FORM_TTL - 60 * 1000)) {
|
|
1751
1861
|
let error = Boom.boomify(new Error(gt.gettext('Invalid or expired account setup URL')), { statusCode: 403 });
|
|
1752
1862
|
throw error;
|
|
1753
1863
|
}
|
|
1754
|
-
const nonceSeen = await redis.exists(
|
|
1864
|
+
const nonceSeen = await redis.exists(module.exports.formNonceKey(data.n));
|
|
1755
1865
|
if (nonceSeen) {
|
|
1756
1866
|
let error = Boom.boomify(new Error(gt.gettext('Invalid or expired account setup URL')), { statusCode: 403 });
|
|
1757
1867
|
throw error;
|