emailengine-app 2.84.1 → 2.84.2

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.
Files changed (93) hide show
  1. package/.dockerignore +6 -0
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +28 -0
  4. package/Dockerfile +2 -2
  5. package/bin/emailengine.js +15 -0
  6. package/data/google-crawlers.json +1 -1
  7. package/docker-compose.yml +1 -1
  8. package/lib/account/own-account-key.js +42 -0
  9. package/lib/account-assignment.js +1 -33
  10. package/lib/account.js +32 -19
  11. package/lib/add-trackers.js +11 -4
  12. package/lib/api-routes/account-routes.js +67 -14
  13. package/lib/api-routes/gateway-routes.js +9 -3
  14. package/lib/api-routes/message-routes.js +7 -1
  15. package/lib/api-routes/mint-bounds.js +11 -0
  16. package/lib/api-routes/route-helpers.js +125 -3
  17. package/lib/api-routes/submit-routes.js +4 -2
  18. package/lib/auth-token.js +23 -10
  19. package/lib/bounce-detect.js +17 -5
  20. package/lib/consts.js +34 -0
  21. package/lib/create-imap-client.js +41 -2
  22. package/lib/email-client/base-client.js +20 -10
  23. package/lib/email-client/gmail-client.js +21 -7
  24. package/lib/email-client/imap/mailbox.js +10 -4
  25. package/lib/email-client/imap/response-metrics.js +75 -0
  26. package/lib/email-client/imap-client.js +5 -2
  27. package/lib/email-client/message-builder.js +7 -2
  28. package/lib/email-client/outlook/graph-api.js +17 -2
  29. package/lib/email-client/outlook-client.js +6 -3
  30. package/lib/email-client/smtp-pool-manager.js +6 -0
  31. package/lib/encrypt.js +9 -0
  32. package/lib/export.js +3 -1
  33. package/lib/get-raw-email.js +4 -2
  34. package/lib/imap-proxy-auth.js +14 -1
  35. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  36. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  37. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  38. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  39. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  40. package/lib/mcp/listen.js +10 -1
  41. package/lib/oauth/external-account-config.js +3 -1
  42. package/lib/oauth/gmail.js +21 -48
  43. package/lib/oauth/mail-ru.js +5 -38
  44. package/lib/oauth/outlook.js +26 -44
  45. package/lib/pbkdf2-phc.js +18 -1
  46. package/lib/privileged-settings.js +6 -3
  47. package/lib/redis-scan-delete.js +15 -1
  48. package/lib/schemas.js +78 -32
  49. package/lib/settings.js +13 -1
  50. package/lib/smtp-auth.js +23 -0
  51. package/lib/tools.js +245 -56
  52. package/lib/ui-routes/account-routes.js +16 -37
  53. package/lib/ui-routes/admin-config-routes.js +10 -38
  54. package/lib/ui-routes/admin-entities-routes.js +22 -24
  55. package/lib/ui-routes/auth-routes.js +47 -24
  56. package/lib/ui-routes/connection-security-form.js +74 -0
  57. package/lib/ui-routes/form-lists.js +46 -0
  58. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  59. package/lib/ui-routes/oauth-config-routes.js +9 -18
  60. package/lib/ui-routes/sign-in-helpers.js +59 -0
  61. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  62. package/lib/utils/map-concurrent.js +36 -0
  63. package/lib/utils/network.js +28 -0
  64. package/lib/utils/provider-id.js +27 -0
  65. package/lib/utils/require-tls.js +33 -0
  66. package/lib/web-safe-html.js +5 -6
  67. package/lib/webhook-penalty.js +75 -0
  68. package/lib/webhook-routing.js +22 -2
  69. package/package.json +21 -21
  70. package/sbom.json +1 -1
  71. package/server.js +25 -14
  72. package/static/js/ace/ace.js +1 -1
  73. package/static/js/ace/mode-handlebars.js +1 -1
  74. package/static/js/ace/mode-html.js +1 -1
  75. package/static/js/ace/mode-javascript.js +1 -1
  76. package/static/js/ace/mode-markdown.js +1 -1
  77. package/static/js/ace/worker-html.js +1 -1
  78. package/static/js/ace/worker-javascript.js +1 -1
  79. package/static/js/ace/worker-json.js +1 -1
  80. package/static/js/ee-client.js +5 -0
  81. package/static/licenses.html +23 -23
  82. package/translations/messages.pot +66 -66
  83. package/views/account/security.hbs +10 -0
  84. package/views/accounts/account.hbs +11 -11
  85. package/views/accounts/edit.hbs +6 -2
  86. package/views/partials/gateway_form.hbs +3 -1
  87. package/workers/api.js +43 -3
  88. package/workers/webhooks.js +39 -3
  89. package/config/test.toml +0 -46
  90. package/install.sh +0 -428
  91. package/setup-production.sh +0 -215
  92. package/systemd/emailengine.service +0 -97
  93. package/systemd/nginx-proxy.conf +0 -77
@@ -1,7 +1,15 @@
1
1
  'use strict';
2
2
 
3
3
  const packageData = require('../../package.json');
4
- const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError, parseRetryAfter } = require('../tools');
4
+ const {
5
+ formatPartialSecretKey,
6
+ formatSecretHint,
7
+ formatOAuthRequestBody,
8
+ formatOAuthResponse,
9
+ httpAgent,
10
+ formatTokenError,
11
+ parseRetryAfter
12
+ } = require('../tools');
5
13
  const crypto = require('crypto');
6
14
 
7
15
  const { fetch: fetchCmd } = require('undici');
@@ -106,7 +114,8 @@ const checkForFlags = (err, isPrincipal) => {
106
114
  continue;
107
115
  }
108
116
  activationLink = (detail.links.find(link => /Google developers console API activation/.test(link.description) && link.url) || {}).url;
109
- if (activationLink) {
117
+ // rendered as a link in the admin UI, so only an https URL is taken from the response
118
+ if (activationLink && /^https:\/\//i.test(activationLink)) {
110
119
  return {
111
120
  message: 'Please enable the Gmail API in your Google Developer Console to use this feature.',
112
121
  code: 'GMAIL_API_NOT_ENABLED',
@@ -193,43 +202,6 @@ const checkForUserFlags = err => {
193
202
  return false;
194
203
  };
195
204
 
196
- const formatFetchBody = (searchParams, logRaw) => {
197
- let entries = typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
198
- let data = Object.fromEntries(entries);
199
-
200
- if (logRaw) {
201
- return data;
202
- }
203
-
204
- for (let key of ['refresh_token', 'client_secret', 'code']) {
205
- if (data[key]) {
206
- data[key] = formatPartialSecretKey(data[key]);
207
- }
208
- }
209
-
210
- if (data.assertion) {
211
- let [payload, signature] = data.assertion.toString().split('.');
212
- data.assertion = [payload, formatPartialSecretKey(signature)].join('.');
213
- }
214
-
215
- return data;
216
- };
217
-
218
- const formatFetchResponse = (responseObj, logRaw) => {
219
- if (!responseObj || typeof responseObj !== 'object') {
220
- return responseObj;
221
- }
222
-
223
- let data = structuredClone(responseObj);
224
- for (let key of ['access_token', 'refresh_token', 'id_token']) {
225
- if (data[key]) {
226
- data[key] = logRaw ? data[key] : formatPartialSecretKey(data[key]);
227
- }
228
- }
229
-
230
- return data;
231
- };
232
-
233
205
  /**
234
206
  * The Google Workspace or Cloud organization domain an ID token belongs to, or null.
235
207
  *
@@ -454,8 +426,8 @@ class GmailOauth {
454
426
  url: requestUrl,
455
427
  success: !!res.ok,
456
428
  status: res.status,
457
- request: formatFetchBody(tokenRequest.body, this.logRaw),
458
- response: formatFetchResponse(responseJson, this.logRaw)
429
+ request: formatOAuthRequestBody(tokenRequest.body),
430
+ response: formatOAuthResponse(responseJson)
459
431
  });
460
432
  }
461
433
 
@@ -481,8 +453,9 @@ class GmailOauth {
481
453
  err.tokenRequest.response = responseJson || { error: 'Failed to parse response' };
482
454
 
483
455
  if (this.clientSecret && EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(err.tokenRequest.response?.error_description)) {
484
- // key might have been invalidated or renewed
485
- err.tokenRequest.clientSecret = formatPartialSecretKey(this.clientSecret);
456
+ // the key might have been invalidated or renewed. On the error rather than in
457
+ // tokenRequest, which the API error payload and the webhook carry verbatim
458
+ err.clientSecretHint = formatSecretHint(this.clientSecret);
486
459
  }
487
460
 
488
461
  let flag = checkForFlags(err.tokenRequest.response);
@@ -578,8 +551,8 @@ class GmailOauth {
578
551
  url: requestUrl,
579
552
  success: !!res.ok,
580
553
  status: res.status,
581
- request: formatFetchBody(url.searchParams, this.logRaw),
582
- response: formatFetchResponse(responseJson, this.logRaw)
554
+ request: formatOAuthRequestBody(url.searchParams),
555
+ response: formatOAuthResponse(responseJson)
583
556
  });
584
557
  }
585
558
 
@@ -605,8 +578,8 @@ class GmailOauth {
605
578
  err.tokenRequest.response = responseJson || { error: 'Failed to parse response' };
606
579
 
607
580
  if (this.clientSecret && EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(err.tokenRequest.response?.error_description)) {
608
- // key might have been invalidated or renewed
609
- err.tokenRequest.clientSecret = formatPartialSecretKey(this.clientSecret);
581
+ // the key might have been invalidated or renewed, see getToken()
582
+ err.clientSecretHint = formatSecretHint(this.clientSecret);
610
583
  }
611
584
 
612
585
  let flag = checkForFlags(err.tokenRequest.response, opts.isPrincipal);
@@ -684,7 +657,7 @@ class GmailOauth {
684
657
  fn: 'refreshFromMetadataServer',
685
658
  provider: this.provider,
686
659
  success: true,
687
- response: formatFetchResponse(response, this.logRaw)
660
+ response: formatOAuthResponse(response)
688
661
  });
689
662
  }
690
663
 
@@ -4,7 +4,7 @@ const packageData = require('../../package.json');
4
4
  const { fetch: fetchCmd } = require('undici');
5
5
  const { promoteCauseCode } = require('../network-errors');
6
6
  const { fetchTokenRequest } = require('./token-fetch');
7
- const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError } = require('../tools');
7
+ const { formatPartialSecretKey, formatOAuthRequestBody, formatOAuthResponse, httpAgent, formatTokenError } = require('../tools');
8
8
 
9
9
  const MAIL_RU_SCOPES = ['userinfo', 'mail.imap'];
10
10
 
@@ -19,38 +19,6 @@ const checkForFlags = err => {
19
19
  return false;
20
20
  };
21
21
 
22
- const formatFetchBody = (searchParams, logRaw) => {
23
- let entries = typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
24
- let data = Object.fromEntries(entries);
25
-
26
- if (logRaw) {
27
- return data;
28
- }
29
-
30
- for (let key of ['refresh_token', 'client_secret', 'code']) {
31
- if (data[key]) {
32
- data[key] = formatPartialSecretKey(data[key]);
33
- }
34
- }
35
-
36
- return data;
37
- };
38
-
39
- const formatFetchResponse = (responseObj, logRaw) => {
40
- if (!responseObj || typeof responseObj !== 'object') {
41
- return responseObj;
42
- }
43
-
44
- let data = structuredClone(responseObj);
45
- for (let key of ['access_token', 'refresh_token', 'id_token']) {
46
- if (data[key]) {
47
- data[key] = logRaw ? data[key] : formatPartialSecretKey(data[key]);
48
- }
49
- }
50
-
51
- return data;
52
- };
53
-
54
22
  class MailRuOauth {
55
23
  constructor(opts) {
56
24
  // The network route of the account this client acts for (see getAccountHttpRoute()). Every
@@ -62,7 +30,6 @@ class MailRuOauth {
62
30
  this.clientSecret = opts.clientSecret;
63
31
  this.redirectUrl = opts.redirectUrl;
64
32
 
65
- this.logRaw = opts.logRaw;
66
33
  this.logger = opts.logger;
67
34
 
68
35
  this.provider = 'mailRu';
@@ -148,8 +115,8 @@ class MailRuOauth {
148
115
  url: requestUrl,
149
116
  success: !!res.ok,
150
117
  status: res.status,
151
- request: formatFetchBody(tokenRequest.body, this.logRaw),
152
- response: formatFetchResponse(responseJson, this.logRaw)
118
+ request: formatOAuthRequestBody(tokenRequest.body),
119
+ response: formatOAuthResponse(responseJson)
153
120
  });
154
121
  }
155
122
 
@@ -236,8 +203,8 @@ class MailRuOauth {
236
203
  url: requestUrl,
237
204
  success: !!res.ok,
238
205
  status: res.status,
239
- request: formatFetchBody(url.searchParams, this.logRaw),
240
- response: formatFetchResponse(responseJson, this.logRaw)
206
+ request: formatOAuthRequestBody(url.searchParams),
207
+ response: formatOAuthResponse(responseJson)
241
208
  });
242
209
  }
243
210
 
@@ -1,7 +1,15 @@
1
1
  'use strict';
2
2
 
3
3
  const packageData = require('../../package.json');
4
- const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError, parseRetryAfter } = require('../tools');
4
+ const {
5
+ formatPartialSecretKey,
6
+ formatSecretHint,
7
+ formatOAuthRequestBody,
8
+ formatOAuthResponse,
9
+ httpAgent,
10
+ formatTokenError,
11
+ parseRetryAfter
12
+ } = require('../tools');
5
13
 
6
14
  const { fetch: fetchCmd } = require('undici');
7
15
  const { promoteCauseCode } = require('../network-errors');
@@ -128,37 +136,9 @@ const checkForUserFlags = err => {
128
136
  return false;
129
137
  };
130
138
 
131
- const formatFetchBody = (searchParams, logRaw) => {
132
- let entries = typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
133
- let data = Object.fromEntries(entries);
134
-
135
- if (logRaw) {
136
- return data;
137
- }
138
-
139
- for (let key of ['refresh_token', 'client_secret', 'code']) {
140
- if (data[key]) {
141
- data[key] = formatPartialSecretKey(data[key]);
142
- }
143
- }
144
-
145
- return data;
146
- };
147
-
148
- const formatFetchResponse = (responseObj, logRaw) => {
149
- if (!responseObj || typeof responseObj !== 'object') {
150
- return responseObj;
151
- }
152
-
153
- let data = structuredClone(responseObj);
154
- for (let key of ['access_token', 'refresh_token', 'id_token']) {
155
- if (data[key]) {
156
- data[key] = logRaw ? data[key] : formatPartialSecretKey(data[key]);
157
- }
158
- }
159
-
160
- return data;
161
- };
139
+ // The secrets are masked whether or not raw logging is on: EENGINE_LOG_RAW is for the protocol
140
+ // traffic, and the application's client secret and the refresh tokens of every account are not
141
+ // something a debug switch should put in the log in full
162
142
 
163
143
  class OutlookOauth {
164
144
  constructor(opts) {
@@ -177,7 +157,6 @@ class OutlookOauth {
177
157
  this.authority = opts.authority;
178
158
  this.redirectUrl = opts.redirectUrl;
179
159
 
180
- this.logRaw = opts.logRaw;
181
160
  this.logger = opts.logger;
182
161
 
183
162
  this.useClientCredentials = !!opts.useClientCredentials;
@@ -307,8 +286,8 @@ class OutlookOauth {
307
286
  url: requestUrl,
308
287
  success: !!res.ok,
309
288
  status: res.status,
310
- request: formatFetchBody(tokenRequest.body, this.logRaw),
311
- response: formatFetchResponse(responseJson, this.logRaw)
289
+ request: formatOAuthRequestBody(tokenRequest.body),
290
+ response: formatOAuthResponse(responseJson)
312
291
  });
313
292
  }
314
293
 
@@ -332,8 +311,9 @@ class OutlookOauth {
332
311
  err.tokenRequest.response = responseJson || { error: 'Failed to parse response' };
333
312
 
334
313
  if (EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(err.tokenRequest.response?.error_description)) {
335
- // key might have been invalidated or renewed
336
- err.tokenRequest.clientSecret = formatPartialSecretKey(this.clientSecret);
314
+ // the key might have been invalidated or renewed. On the error rather than in
315
+ // tokenRequest, which the API error payload and the webhook carry verbatim
316
+ err.clientSecretHint = formatSecretHint(this.clientSecret);
337
317
  }
338
318
 
339
319
  let flag = checkForFlags(err.tokenRequest.response);
@@ -412,8 +392,8 @@ class OutlookOauth {
412
392
  url: requestUrl,
413
393
  success: !!res.ok,
414
394
  status: res.status,
415
- request: formatFetchBody(url.searchParams, this.logRaw),
416
- response: formatFetchResponse(responseJson, this.logRaw)
395
+ request: formatOAuthRequestBody(url.searchParams),
396
+ response: formatOAuthResponse(responseJson)
417
397
  });
418
398
  }
419
399
 
@@ -436,8 +416,9 @@ class OutlookOauth {
436
416
  err.tokenRequest.response = responseJson || { error: 'Failed to parse response' };
437
417
 
438
418
  if (EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(err.tokenRequest.response?.error_description)) {
439
- // key might have been invalidated or renewed
440
- err.tokenRequest.clientSecret = formatPartialSecretKey(this.clientSecret);
419
+ // the key might have been invalidated or renewed. On the error rather than in
420
+ // tokenRequest, which the API error payload and the webhook carry verbatim
421
+ err.clientSecretHint = formatSecretHint(this.clientSecret);
441
422
  }
442
423
 
443
424
  let flag = checkForFlags(err.tokenRequest.response);
@@ -507,8 +488,8 @@ class OutlookOauth {
507
488
  url: requestUrl,
508
489
  success: !!res.ok,
509
490
  status: res.status,
510
- request: formatFetchBody(url.searchParams, this.logRaw),
511
- response: formatFetchResponse(responseJson, this.logRaw)
491
+ request: formatOAuthRequestBody(url.searchParams),
492
+ response: formatOAuthResponse(responseJson)
512
493
  });
513
494
  }
514
495
 
@@ -531,7 +512,8 @@ class OutlookOauth {
531
512
  err.tokenRequest.response = responseJson || { error: 'Failed to parse response' };
532
513
 
533
514
  if (EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(err.tokenRequest.response?.error_description)) {
534
- err.tokenRequest.clientSecret = formatPartialSecretKey(this.clientSecret);
515
+ // see getToken()
516
+ err.clientSecretHint = formatSecretHint(this.clientSecret);
535
517
  }
536
518
 
537
519
  let flag = checkForFlags(err.tokenRequest.response);
package/lib/pbkdf2-phc.js CHANGED
@@ -98,4 +98,21 @@ async function verify(phcString, password) {
98
98
  return crypto.timingSafeEqual(derived, expected);
99
99
  }
100
100
 
101
- module.exports = { hash, verify };
101
+ /**
102
+ * Whether a stored hash was written with weaker parameters than hash() uses today: an older
103
+ * digest, or fewer iterations. Such a hash keeps verifying (verify() honours whatever the string
104
+ * says), so the only time it can be upgraded is right after the password was checked against it.
105
+ *
106
+ * @param {string} phcString
107
+ * @returns {boolean} true when the hash should be rewritten with the current parameters
108
+ */
109
+ function needsRehash(phcString) {
110
+ let match = typeof phcString === 'string' ? PHC_RE.exec(phcString) : null;
111
+ if (!match) {
112
+ return false;
113
+ }
114
+ let [, digest, iterationsValue] = match;
115
+ return digest !== PDKDF2_DIGEST || Number(iterationsValue) < PDKDF2_ITERATIONS;
116
+ }
117
+
118
+ module.exports = { hash, verify, needsRehash };
@@ -100,9 +100,12 @@ const PRIVILEGED_SETTINGS_GROUPS = [
100
100
  keys: ['openAiAPIKey', 'openAiAPIUrl']
101
101
  },
102
102
  {
103
- // Credential-bearing (the example is an Authorization header)
104
- label: 'custom webhook headers',
105
- keys: ['webhooksCustomHeaders']
103
+ // Credential-bearing (the example is an Authorization header), and the URL they are sent
104
+ // to: a narrowed credential that cannot read the headers could still move the target to
105
+ // its own host and receive them, with every account's event bodies, on the next delivery.
106
+ // Per-account targets stay ordinary; they carry the account's own headers only
107
+ label: 'the webhook target and its custom headers',
108
+ keys: ['webhooks', 'webhooksCustomHeaders']
106
109
  },
107
110
  {
108
111
  // HTML injected into the hosted pages, where end users type mail passwords
@@ -24,7 +24,18 @@ function execBatch(pipeline) {
24
24
  });
25
25
  }
26
26
 
27
- async function redisScanDelete(redis, logger, match) {
27
+ /**
28
+ * Deletes every key matching a glob, in batches.
29
+ *
30
+ * @param {Object} redis - ioredis client
31
+ * @param {Object} logger
32
+ * @param {String} match - SCAN pattern
33
+ * @param {Function} [filter] - key => Boolean; a key the glob matched but the filter refuses is
34
+ * left alone. A glob cannot say where one id ends and the next part of the key begins, the
35
+ * filter can
36
+ * @returns {Promise<Number>} keys removed
37
+ */
38
+ async function redisScanDelete(redis, logger, match, filter) {
28
39
  return new Promise((resolve, reject) => {
29
40
  const stream = redis.scanStream({ match, count: REDIS_BATCH_DELETE_SIZE });
30
41
  let pipeline = redis.pipeline();
@@ -79,6 +90,9 @@ async function redisScanDelete(redis, logger, match) {
79
90
  }
80
91
 
81
92
  for (let ik = 0; ik < resultKeys.length; ik++) {
93
+ if (typeof filter === 'function' && !filter(resultKeys[ik])) {
94
+ continue;
95
+ }
82
96
  batchKeys.push(resultKeys[ik]);
83
97
  pipeline.del(resultKeys[ik]);
84
98
  }
package/lib/schemas.js CHANGED
@@ -34,6 +34,7 @@ function formBoolean() {
34
34
  const config = require('@zone-eu/wild-config');
35
35
  const { getByteSize, readEnvValue } = require('./tools');
36
36
  const { COLLAPSE_CLASS, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
37
+ const { PROVIDER_ID_SEGMENT } = require('./utils/provider-id');
37
38
  const { locales } = require('./translations');
38
39
  const { OAUTH_PROVIDERS } = require('./oauth2-apps');
39
40
  const { ACCOUNT_STATES } = require('./account/account-state');
@@ -686,6 +687,63 @@ const imapMaxIdleTimeSchema = Joi.number()
686
687
  .description('Restart IDLE after this many milliseconds. Also caps the polling interval for servers without IDLE support.')
687
688
  .meta({ usage: FIELD_USAGE.maxIdleTime });
688
689
 
690
+ // The `tls` object of an IMAP or SMTP configuration is merged as it is into the options the
691
+ // connection is opened with, so it names Node's TLS options and nothing else. It used to accept
692
+ // any key, which made it a second place to say where the connection goes: `path` connects to a
693
+ // Unix socket, `host` and `port` override the validated host and port, `lookup` and
694
+ // `localAddress` reroute it. The keys below are the ones that configure the TLS session itself
695
+ // (plus the client certificate for servers that ask for one).
696
+ const PEM_MAX = 64 * 1024;
697
+ const pemSchema = Joi.string().max(PEM_MAX);
698
+ const PEM_CERT_EXAMPLE = '-----BEGIN CERTIFICATE-----\nMIIB...\n-----END CERTIFICATE-----';
699
+ const PEM_KEY_EXAMPLE = '-----BEGIN PRIVATE KEY-----\nMIIE...\n-----END PRIVATE KEY-----';
700
+
701
+ // Whether a connection that starts in cleartext (`secure: false`) must upgrade with STARTTLS.
702
+ // Required unless set to false: left to chance, a server that does not advertise STARTTLS, or an
703
+ // attacker on the path who strips the advertisement, gets the password in cleartext. False is for
704
+ // a server on a trusted network that has no TLS at all. No default, so an update that does not
705
+ // mention the field keeps the stored value and a stored account without it reads as required.
706
+ function requireTlsSchema(label, base) {
707
+ return (base || Joi.boolean())
708
+ .example(true)
709
+ .description(
710
+ 'Require STARTTLS when secure is false. Defaults to true: the connection fails if the server does not offer STARTTLS or the upgrade fails. Set to false only for a server on a trusted network that has no TLS at all'
711
+ )
712
+ .label(label);
713
+ }
714
+
715
+ function tlsOptionsSchema(label, opts) {
716
+ opts = opts || {};
717
+ let rejectUnauthorized = Joi.boolean().example(true).description('Reject connections to servers with invalid TLS certificates');
718
+ if (opts.withDefaults) {
719
+ rejectUnauthorized = rejectUnauthorized.default(true);
720
+ }
721
+
722
+ return Joi.object({
723
+ rejectUnauthorized,
724
+ minVersion: Joi.string().max(256).example('TLSv1.2').description('Minimum TLS version to accept (e.g., "TLSv1.2", "TLSv1.3")'),
725
+ maxVersion: Joi.string().max(256).example('TLSv1.3').description('Maximum TLS version to accept'),
726
+ servername: Joi.string()
727
+ .max(256)
728
+ .example('imap.example.com')
729
+ .description('Server name for SNI and certificate validation, when it differs from the host'),
730
+ ciphers: Joi.string().max(1024).example('HIGH:!aNULL:!MD5').description('Cipher suite specification, in OpenSSL format'),
731
+ ca: Joi.alternatives()
732
+ .try(pemSchema.example(PEM_CERT_EXAMPLE), Joi.array().items(pemSchema.example(PEM_CERT_EXAMPLE)).max(32).example([PEM_CERT_EXAMPLE]))
733
+ .example(PEM_CERT_EXAMPLE)
734
+ .description('Trusted CA certificates in PEM format, replacing the default trust store'),
735
+ cert: pemSchema.example(PEM_CERT_EXAMPLE).description('Client certificate in PEM format, for servers that require one'),
736
+ key: pemSchema.example(PEM_KEY_EXAMPLE).description('Private key of the client certificate in PEM format'),
737
+ passphrase: Joi.string().max(1024).example('key passphrase').description('Passphrase of the client certificate private key'),
738
+ honorCipherOrder: Joi.boolean().example(false).description('Prefer the ciphers in the order given rather than the order the server lists them'),
739
+ ecdhCurve: Joi.string().max(256).example('auto').description('ECDH curve name or list for key agreement'),
740
+ sigalgs: Joi.string().max(1024).example('RSA-PSS+SHA256:ECDSA+SHA256').description('Supported signature algorithms, colon separated'),
741
+ secureOptions: Joi.number().integer().example(0).description('OpenSSL option flags, as a number')
742
+ })
743
+ .description('Advanced TLS configuration options')
744
+ .label(label);
745
+ }
746
+
689
747
  const imapSchema = {
690
748
  auth: Joi.object({
691
749
  user: Joi.string().max(256).required().example('myuser@gmail.com').description('Username or email address for IMAP authentication'),
@@ -741,13 +799,8 @@ const imapSchema = {
741
799
  .example(993)
742
800
  .description('IMAP server port (typically 993 for IMAP over TLS, 143 for STARTTLS)'),
743
801
  secure: Joi.boolean().default(false).example(true).description('Use TLS encryption for the connection (true for port 993, false for STARTTLS on port 143)'),
744
- tls: Joi.object({
745
- rejectUnauthorized: Joi.boolean().default(true).example(true).description('Reject connections to servers with invalid TLS certificates'),
746
- minVersion: Joi.string().max(256).example('TLSv1.2').description('Minimum TLS version to accept (e.g., "TLSv1.2", "TLSv1.3")')
747
- })
748
- .unknown()
749
- .description('Advanced TLS configuration options')
750
- .label('ImapTlsOptions'),
802
+ requireTLS: requireTlsSchema('ImapRequireTLS'),
803
+ tls: tlsOptionsSchema('ImapTlsOptions', { withDefaults: true }),
751
804
  // the field name deliberately matches the ImapFlow option name - the stored
752
805
  // imap object is merged verbatim into the ImapFlow connection config
753
806
  disableIMAP4rev2: Joi.boolean()
@@ -831,13 +884,8 @@ const smtpSchema = {
831
884
  .default(false)
832
885
  .example(false)
833
886
  .description('Use TLS encryption from the start (true for port 465, false for STARTTLS on ports 587/25)'),
834
- tls: Joi.object({
835
- rejectUnauthorized: Joi.boolean().default(true).example(true).description('Reject connections to servers with invalid TLS certificates'),
836
- minVersion: Joi.string().max(256).example('TLSv1.2').description('Minimum TLS version to accept (e.g., "TLSv1.2", "TLSv1.3")')
837
- })
838
- .unknown()
839
- .description('Advanced TLS configuration options')
840
- .label('SmtpTlsOptions')
887
+ requireTLS: requireTlsSchema('SmtpRequireTLS'),
888
+ tls: tlsOptionsSchema('SmtpTlsOptions', { withDefaults: true })
841
889
  };
842
890
 
843
891
  const oauth2AuthSchema = Joi.object({
@@ -950,13 +998,8 @@ const imapUpdateSchema = {
950
998
  host: Joi.string().hostname().example('imap.gmail.com').description('IMAP server hostname'),
951
999
  port: Joi.number().integer().min(1).max(65535).example(993).description('IMAP server port'),
952
1000
  secure: Joi.boolean().example(true).description('Use TLS encryption for the connection'),
953
- tls: Joi.object({
954
- rejectUnauthorized: Joi.boolean().example(true).description('Reject connections to servers with invalid TLS certificates'),
955
- minVersion: Joi.string().max(256).example('TLSv1.2').description('Minimum TLS version to accept')
956
- })
957
- .unknown()
958
- .description('Advanced TLS configuration options')
959
- .label('ImapUpdateTlsOptions'),
1001
+ requireTLS: requireTlsSchema('ImapUpdateRequireTLS'),
1002
+ tls: tlsOptionsSchema('ImapUpdateTlsOptions'),
960
1003
  disableIMAP4rev2: Joi.boolean()
961
1004
  .example(false)
962
1005
  .description('Do not use IMAP4rev2 even if the server supports it')
@@ -1011,13 +1054,8 @@ const smtpUpdateSchema = {
1011
1054
  host: Joi.string().hostname().example('smtp.gmail.com').description('SMTP server hostname'),
1012
1055
  port: Joi.number().integer().min(1).max(65535).example(587).description('SMTP server port'),
1013
1056
  secure: Joi.boolean().example(false).description('Use TLS encryption from the start'),
1014
- tls: Joi.object({
1015
- rejectUnauthorized: Joi.boolean().example(true).description('Reject connections to servers with invalid TLS certificates'),
1016
- minVersion: Joi.string().max(256).example('TLSv1.2').description('Minimum TLS version to accept')
1017
- })
1018
- .unknown()
1019
- .description('Advanced TLS configuration options')
1020
- .label('SmtpUpdateTlsOptions')
1057
+ requireTLS: requireTlsSchema('SmtpUpdateRequireTLS'),
1058
+ tls: tlsOptionsSchema('SmtpUpdateTlsOptions')
1021
1059
  };
1022
1060
 
1023
1061
  const oauth2UpdateSchema = {
@@ -1104,6 +1142,13 @@ const threadIdSchema = Joi.string()
1104
1142
  .description('Thread identifier for email conversations (when supported by the email server)')
1105
1143
  .label('MessageThreadId');
1106
1144
 
1145
+ // A provider id the caller supplies (a search by emailId or threadId, a reference threadId) is
1146
+ // interpolated into a path segment of the provider's API URL. The response schemas above report
1147
+ // whatever the provider handed out; the request-side ids below additionally have to stay inside
1148
+ // their segment, see lib/utils/provider-id.js.
1149
+ const requestEmailIdSchema = emailIdSchema.pattern(PROVIDER_ID_SEGMENT, 'provider id');
1150
+ const requestThreadIdSchema = threadIdSchema.max(256).pattern(PROVIDER_ID_SEGMENT, 'provider id');
1151
+
1107
1152
  const messageSpecialUseSchema = Joi.string()
1108
1153
  .example('\\Sent')
1109
1154
  .valid('\\Drafts', '\\Junk', '\\Sent', '\\Trash', '\\Inbox')
@@ -1543,8 +1588,8 @@ const searchSchema = Joi.object({
1543
1588
  sentBefore: Joi.date().example('2024-08-09').description('Find messages sent before this date').label('HeaderBefore'),
1544
1589
  sentSince: Joi.date().example('2022-08-09').description('Find messages sent after this date').label('HeaderSince'),
1545
1590
 
1546
- emailId: emailIdSchema,
1547
- threadId: threadIdSchema,
1591
+ emailId: requestEmailIdSchema,
1592
+ threadId: requestThreadIdSchema,
1548
1593
 
1549
1594
  header: Joi.object().description('Search specific email headers').label('Headers').unknown().example({ 'Message-ID': '<1DAF52A51E674A2@example.com>' }),
1550
1595
 
@@ -1568,7 +1613,7 @@ const searchSchema = Joi.object({
1568
1613
  .label('LabelFilter'),
1569
1614
 
1570
1615
  emailIds: Joi.array()
1571
- .items(emailIdSchema)
1616
+ .items(requestEmailIdSchema)
1572
1617
  .single()
1573
1618
  .description('List of specific email IDs to fetch')
1574
1619
  .meta({ usage: FIELD_USAGE.searchEmailIds })
@@ -2404,7 +2449,7 @@ const messageReferenceSchema = Joi.object({
2404
2449
  .example('<test123@example.com>')
2405
2450
  .description('Verify the Message-ID of the referenced email matches this value before proceeding'),
2406
2451
 
2407
- threadId: threadIdSchema.description('Gmail thread ID to attach the outgoing message to').meta({ usage: FIELD_USAGE.referenceThreadId }),
2452
+ threadId: requestThreadIdSchema.description('Gmail thread ID to attach the outgoing message to').meta({ usage: FIELD_USAGE.referenceThreadId }),
2408
2453
 
2409
2454
  documentStore: documentStoreSchema
2410
2455
  })
@@ -2717,6 +2762,7 @@ function apiResponses(description, ...statusCodes) {
2717
2762
  }
2718
2763
 
2719
2764
  module.exports = {
2765
+ requireTlsSchema,
2720
2766
  apiBoolean,
2721
2767
  formBoolean,
2722
2768
  MAX_MESSAGE_ATTACHMENTS,
package/lib/settings.js CHANGED
@@ -49,7 +49,12 @@ const AI_HANDLER_KEYS = new Set(['generateEmailSummary', 'openAiAPIKey', 'openAi
49
49
  // rotation.
50
50
  const CREDENTIAL_BEARING_URL_KEYS = ['webhooks', 'proxyUrl', 'httpProxyUrl', 'sentryDsn', 'authServer'];
51
51
  const CREDENTIAL_BEARING_HEADER_KEYS = ['webhooksCustomHeaders'];
52
- const CREDENTIAL_BEARING_KEYS = CREDENTIAL_BEARING_URL_KEYS.concat(CREDENTIAL_BEARING_HEADER_KEYS);
52
+ // The environment the operator's webhook and pre-processing scripts read: the settings page tells
53
+ // them to keep the API keys and tokens their scripts use in it. Encrypted at rest like the lists
54
+ // above; read back whole, since the page edits it as JSON, and masking is not what a free-form
55
+ // value can get. Privileged already, so a narrowed credential never sees it
56
+ const CREDENTIAL_BEARING_TEXT_KEYS = ['scriptEnv'];
57
+ const CREDENTIAL_BEARING_KEYS = CREDENTIAL_BEARING_URL_KEYS.concat(CREDENTIAL_BEARING_HEADER_KEYS, CREDENTIAL_BEARING_TEXT_KEYS);
53
58
 
54
59
  const ENCRYPTED_KEYS = SECRET_KEYS.concat(CREDENTIAL_BEARING_KEYS);
55
60
 
@@ -188,6 +193,13 @@ module.exports = {
188
193
  return await this.getValue(encryptSecret, key, value);
189
194
  },
190
195
 
196
+ // The stored string as it is in Redis, without decryption or parsing. For a caller that has
197
+ // to tell a missing value from one that is present but does not decrypt: get() answers null
198
+ // for both
199
+ async getRaw(key) {
200
+ return await redis.hget(`${REDIS_PREFIX}settings`, key);
201
+ },
202
+
191
203
  formatSettingValue(key, value) {
192
204
  switch (key) {
193
205
  case 'serviceUrl': {
package/lib/smtp-auth.js CHANGED
@@ -39,6 +39,12 @@ function createSmtpAuthHandler({ accountCache, call }) {
39
39
  if (!result.authenticated) {
40
40
  throw new Error(REASON_MESSAGES[result.reason] || 'Failed to authenticate user');
41
41
  }
42
+
43
+ // Kept on the session (in memory, never stored) so each submission can ask whether
44
+ // the token is still what it was at login: a session can stay open for as long as
45
+ // the client likes, and a token deleted or narrowed in the meantime must not keep
46
+ // sending through it
47
+ session.eeTokenAuth = { password: auth.password, account: auth.username };
42
48
  }
43
49
 
44
50
  let accountObject = new Account({ account, redis, call, secret: await getSecret() });
@@ -133,6 +139,23 @@ function createSmtpAccountResolver({ accountCache, call }) {
133
139
  }
134
140
  } else {
135
141
  accountObject = accountCache.get(session);
142
+
143
+ if (accountObject && session.eeTokenAuth) {
144
+ // The token that opened this session has to still admit it, see onAuth()
145
+ let result = await validateAuthToken({
146
+ password: session.eeTokenAuth.password,
147
+ account: session.eeTokenAuth.account,
148
+ requiredScope: 'smtp',
149
+ remoteAddress: session.remoteAddress,
150
+ recheck: true
151
+ });
152
+ if (!result.authenticated) {
153
+ accountCache.delete(session);
154
+ let err = new Error('Authentication required');
155
+ err.responseCode = 530;
156
+ throw err;
157
+ }
158
+ }
136
159
  }
137
160
 
138
161
  if (!session.eeAuthEnabled && !messageMeta.requestedAccount && !accountObject) {