emailengine-app 2.84.1 → 2.85.0

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 (147) hide show
  1. package/.dockerignore +6 -0
  2. package/.ncurc.js +5 -3
  3. package/.prettierignore +5 -1
  4. package/.prettierrc.js +2 -0
  5. package/.release-please-manifest.json +1 -1
  6. package/CHANGELOG.md +61 -0
  7. package/Dockerfile +8 -2
  8. package/README.md +1 -1
  9. package/bin/emailengine.js +444 -403
  10. package/copy-static-files.sh +39 -14
  11. package/data/google-crawlers.json +1 -1
  12. package/data/public_suffix_list.dat +16562 -0
  13. package/docker-compose.yml +1 -1
  14. package/eslint.config.js +81 -99
  15. package/lib/account/own-account-key.js +42 -0
  16. package/lib/account-assignment.js +1 -33
  17. package/lib/account.js +68 -24
  18. package/lib/add-trackers.js +11 -4
  19. package/lib/api-reference/format.js +4 -3
  20. package/lib/api-routes/account-routes.js +244 -26
  21. package/lib/api-routes/blocklist-routes.js +23 -2
  22. package/lib/api-routes/delivery-test-routes.js +26 -3
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +37 -5
  25. package/lib/api-routes/mailbox-routes.js +41 -2
  26. package/lib/api-routes/message-routes.js +104 -4
  27. package/lib/api-routes/mint-bounds.js +11 -0
  28. package/lib/api-routes/oauth2-app-routes.js +48 -15
  29. package/lib/api-routes/outbox-routes.js +45 -11
  30. package/lib/api-routes/permission-map.js +12 -1
  31. package/lib/api-routes/route-helpers.js +125 -3
  32. package/lib/api-routes/settings-routes.js +23 -2
  33. package/lib/api-routes/submit-routes.js +338 -309
  34. package/lib/api-routes/template-routes.js +38 -2
  35. package/lib/api-routes/token-routes.js +142 -96
  36. package/lib/api-routes/webhook-route-routes.js +13 -2
  37. package/lib/auth-token.js +23 -10
  38. package/lib/bounce-detect.js +414 -210
  39. package/lib/consts.js +39 -4
  40. package/lib/create-imap-client.js +41 -2
  41. package/lib/email-client/base-client.js +30 -41
  42. package/lib/email-client/gmail-client.js +30 -18
  43. package/lib/email-client/imap/mailbox.js +13 -23
  44. package/lib/email-client/imap/response-metrics.js +75 -0
  45. package/lib/email-client/imap/subconnection.js +1 -1
  46. package/lib/email-client/imap-client.js +6 -3
  47. package/lib/email-client/message-builder.js +7 -2
  48. package/lib/email-client/notification-handler.js +1 -2
  49. package/lib/email-client/outlook/graph-api.js +17 -2
  50. package/lib/email-client/outlook-client.js +6 -3
  51. package/lib/email-client/smtp-pool-manager.js +6 -0
  52. package/lib/encrypt.js +9 -0
  53. package/lib/export.js +3 -1
  54. package/lib/gateway.js +2 -3
  55. package/lib/get-raw-email.js +4 -2
  56. package/lib/hapi-request-logger.js +107 -0
  57. package/lib/imap-proxy-auth.js +14 -1
  58. package/lib/imapproxy/imap-core/README.md +6 -5
  59. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  60. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  61. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  62. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  63. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  64. package/lib/mcp/listen.js +10 -1
  65. package/lib/mcp/tools.js +37 -8
  66. package/lib/notify-attachments.js +17 -0
  67. package/lib/oauth/external-account-config.js +3 -1
  68. package/lib/oauth/gmail.js +21 -48
  69. package/lib/oauth/mail-ru.js +5 -38
  70. package/lib/oauth/outlook-mailbox.js +35 -0
  71. package/lib/oauth/outlook.js +26 -44
  72. package/lib/oauth/state.js +24 -0
  73. package/lib/oauth2-apps.js +1 -1
  74. package/lib/pbkdf2-phc.js +19 -2
  75. package/lib/privileged-settings.js +6 -3
  76. package/lib/redis-scan-delete.js +15 -1
  77. package/lib/schemas.js +79 -33
  78. package/lib/settings.js +13 -1
  79. package/lib/smtp-auth.js +23 -0
  80. package/lib/sso.js +1 -1
  81. package/lib/swagger-options.js +1 -1
  82. package/lib/thread-diagnostics.js +46 -0
  83. package/lib/timezones.js +109 -0
  84. package/lib/token-permission-view.js +3 -3
  85. package/lib/tools.js +285 -66
  86. package/lib/totp.js +2 -5
  87. package/lib/translations.js +1 -2
  88. package/lib/ui-routes/account-routes.js +491 -491
  89. package/lib/ui-routes/account-setup.js +99 -0
  90. package/lib/ui-routes/admin-config-routes.js +98 -48
  91. package/lib/ui-routes/admin-entities-routes.js +113 -31
  92. package/lib/ui-routes/auth-routes.js +137 -62
  93. package/lib/ui-routes/connection-security-form.js +74 -0
  94. package/lib/ui-routes/form-lists.js +46 -0
  95. package/lib/ui-routes/internals-routes.js +5 -0
  96. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  97. package/lib/ui-routes/oauth-config-routes.js +133 -100
  98. package/lib/ui-routes/route-helpers.js +19 -3
  99. package/lib/ui-routes/sign-in-helpers.js +59 -0
  100. package/lib/ui-routes/tls-config-routes.js +58 -15
  101. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  102. package/lib/utils/back-off.js +82 -0
  103. package/lib/utils/map-concurrent.js +36 -0
  104. package/lib/utils/murmurhash3.js +66 -0
  105. package/lib/utils/network.js +28 -0
  106. package/lib/utils/provider-id.js +27 -0
  107. package/lib/utils/public-suffix.js +122 -0
  108. package/lib/utils/random-id.js +26 -0
  109. package/lib/utils/require-tls.js +33 -0
  110. package/lib/utils/version.js +74 -0
  111. package/lib/web-safe-html.js +5 -6
  112. package/lib/webhook-penalty.js +75 -0
  113. package/lib/webhook-routing.js +49 -2
  114. package/lib/webhooks.js +41 -6
  115. package/package.json +37 -39
  116. package/sbom.json +7980 -1
  117. package/server.js +659 -455
  118. package/static/js/ace/ace.js +1 -1
  119. package/static/js/ace/mode-handlebars.js +1 -1
  120. package/static/js/ace/mode-html.js +1 -1
  121. package/static/js/ace/mode-javascript.js +1 -1
  122. package/static/js/ace/mode-markdown.js +1 -1
  123. package/static/js/ace/worker-html.js +1 -1
  124. package/static/js/ace/worker-javascript.js +1 -1
  125. package/static/js/ace/worker-json.js +1 -1
  126. package/static/js/ee-client.js +5 -0
  127. package/static/licenses.html +191 -1016
  128. package/translations/messages.pot +70 -71
  129. package/views/account/security.hbs +10 -0
  130. package/views/accounts/account.hbs +11 -11
  131. package/views/accounts/edit.hbs +6 -2
  132. package/views/config/ai.hbs +1 -1
  133. package/views/config/security.hbs +2 -2
  134. package/views/config/service.hbs +3 -0
  135. package/views/internals/index.hbs +8 -0
  136. package/views/partials/gateway_form.hbs +3 -1
  137. package/views/partials/webhook_form.hbs +1 -1
  138. package/views/suppression-lists/index.hbs +1 -1
  139. package/workers/api.js +780 -585
  140. package/workers/export.js +1 -1
  141. package/workers/submit.js +1 -1
  142. package/workers/webhooks.js +54 -34
  143. package/config/test.toml +0 -46
  144. package/install.sh +0 -428
  145. package/setup-production.sh +0 -215
  146. package/systemd/emailengine.service +0 -97
  147. package/systemd/nginx-proxy.conf +0 -77
package/lib/consts.js CHANGED
@@ -117,6 +117,12 @@ module.exports = {
117
117
 
118
118
  LOGIN_PERIOD_TTL: 30 * 24 * 3600 * 1000,
119
119
 
120
+ // How long an admin session cookie is honoured after it was issued, whatever the browser
121
+ // does with it. The sealed cookie carries no expiry of its own, so without this a cookie
122
+ // captured once stayed valid until the next password change. Same length as the "remember
123
+ // me" cookie lifetime, so that option keeps meaning what it says
124
+ ADMIN_SESSION_MAX_AGE: 30 * 24 * 3600 * 1000,
125
+
120
126
  DEFAULT_PAGE_SIZE: 20,
121
127
 
122
128
  // Max POST payload size for message upload requests. NB! Does not apply for all routes
@@ -277,10 +283,35 @@ module.exports = {
277
283
 
278
284
  // How many times to retry an email sending before it is considered as failing
279
285
  DEFAULT_DELIVERY_ATTEMPTS: 10,
286
+ // The most a caller may ask for, through the API or the X-EE-Delivery-Attempts header of a
287
+ // stored draft or SMTP submission
288
+ MAX_DELIVERY_ATTEMPTS: 100,
289
+
290
+ // A mail merge turns one submit call into one queued message per entry, each a copy of the
291
+ // message with its attachments; the list is bounded and the copies are queued a few at a time
292
+ MAX_MAIL_MERGE_ENTRIES: 1000,
293
+ MAIL_MERGE_CONCURRENCY: 10,
280
294
 
281
295
  // fixed boundary to prevent downloading attachments that are too large
282
296
  MAX_ALLOWED_DOWNLOAD_SIZE: 250 * 1024 * 1024, // 250 MB
283
297
 
298
+ // How much of a suspected bounce or delivery report is fetched for parsing. The report and
299
+ // its delivery-status part come first and are small; what follows is the returned original,
300
+ // which the parse does not need and which a sender can make as large as the server allows
301
+ MAX_BOUNCE_DOWNLOAD_SIZE: 20 * 1024 * 1024, // 20 MB
302
+
303
+ // Bounds on what one IMAP server response may make a worker buffer, passed to every ImapFlow
304
+ // client (lib/create-imap-client.js). ImapFlow's own defaults are sized for one client talking
305
+ // to one trusted server (1 GB per line and literal, 2 GB per response); a worker here serves
306
+ // many accounts, and one hostile or broken server must not take them all down with it. The
307
+ // literal cap sits above MAX_ALLOWED_DOWNLOAD_SIZE, since a whole-message download is one
308
+ // literal, and the response cap leaves room for a multi-part FETCH and its framing. The line
309
+ // cap covers responses without a literal, where the largest legitimate one is a SEARCH
310
+ // result (a million UIDs is about 8 MB).
311
+ IMAP_MAX_LINE_LENGTH: 32 * 1024 * 1024, // 32 MB
312
+ IMAP_MAX_LITERAL_SIZE: 256 * 1024 * 1024, // 256 MB
313
+ IMAP_MAX_RESPONSE_SIZE: 512 * 1024 * 1024, // 512 MB
314
+
284
315
  // while we do require a valid cert, the passing requirements are extremely low
285
316
  TLS_DEFAULTS: {
286
317
  minVersion: (process.env.EENGINE_TLS_MIN_VERSION || '').toString().trim() || 'TLSv1',
@@ -417,6 +448,9 @@ module.exports = {
417
448
  'ETIMEDOUT',
418
449
  'ECONNRESET',
419
450
  'ECONNREFUSED',
451
+ // no route to the host, such as an IPv6 address on a host without IPv6 connectivity
452
+ 'ENETUNREACH',
453
+ 'EHOSTUNREACH',
420
454
  'UND_ERR_SOCKET',
421
455
  'UND_ERR_CONNECT_TIMEOUT',
422
456
  'UND_ERR_HEADERS_TIMEOUT',
@@ -438,10 +472,11 @@ module.exports = {
438
472
  // credential frame - without these a failed validation writes plaintext passwords, OAuth2
439
473
  // client secrets and access tokens into the log, the per-account log store and Sentry.
440
474
  // `req.query.access_token` is here because the api-token scheme accepts the credential as a
441
- // query argument, and hapi-pino logs the parsed query object with every request - so a client
442
- // using that form wrote a live token into this instance's own request log. The serialized
443
- // `req.url` is the pathname only (pino-std-serializers reports `req.path`), so the credential
444
- // reaches the log through the query object and nowhere else.
475
+ // query argument, and the request logger (lib/hapi-request-logger.js) logs the parsed query
476
+ // object with every request - so a client using that form wrote a live token into this
477
+ // instance's own request log. The serialized `req.url` is the pathname only
478
+ // (pino-std-serializers reports `req.path`), so the credential reaches the log through the
479
+ // query object and nowhere else.
445
480
  REDACTED_LOG_KEYS: [
446
481
  'req.headers.authorization',
447
482
  'req.headers.cookie',
@@ -10,15 +10,54 @@
10
10
  // every FETCH would fail on such a host. EmailEngine never reads that id (new messages are
11
11
  // deduplicated on emailId or Message-ID, and the value only appears in a log line), so the
12
12
  // algorithm is free to differ from ImapFlow's default on every installation.
13
+ //
14
+ // maxLineLength, maxLiteralSize, maxResponseSize: what one server response may make the worker
15
+ // buffer. ImapFlow's defaults (1 GB, 1 GB, 2 GB) assume one trusted server; a worker here serves
16
+ // many accounts, so a hostile or broken server answering one of them must not exhaust the memory
17
+ // of all of them. The values are in lib/consts.js with the reasoning.
18
+ //
19
+ // doSTARTTLS: a cleartext connection (`secure: false`) upgrades with STARTTLS and must succeed at
20
+ // it. Left unset, ImapFlow upgrades only when the server advertises STARTTLS and otherwise logs a
21
+ // warning and continues in cleartext, LOGIN included, which is what an on-path attacker who strips
22
+ // the capability gets. The account-level `requireTLS: false` is the opt-out for a server on a
23
+ // trusted network that has no TLS at all, and it leaves doSTARTTLS unset rather than false: the
24
+ // connection still upgrades when the server offers STARTTLS, the same as an SMTP transport with
25
+ // requireTLS off (lib/utils/require-tls.js). `requireTLS` is EmailEngine's field, not ImapFlow's,
26
+ // so it is consumed here. A connection that is `secure: true` from the start is not affected.
13
27
 
14
28
  const { ImapFlow } = require('imapflow');
29
+ const { IMAP_MAX_LINE_LENGTH, IMAP_MAX_LITERAL_SIZE, IMAP_MAX_RESPONSE_SIZE } = require('./consts');
30
+
31
+ /**
32
+ * Turns EmailEngine's connection configuration into ImapFlow options.
33
+ *
34
+ * @param {Object} config - Connection options, applied over the defaults
35
+ * @returns {Object} the options ImapFlow is constructed with
36
+ */
37
+ function imapClientOptions(config) {
38
+ let { requireTLS, ...options } = config || {};
39
+
40
+ options = {
41
+ idHashAlgorithm: 'sha256',
42
+ maxLineLength: IMAP_MAX_LINE_LENGTH,
43
+ maxLiteralSize: IMAP_MAX_LITERAL_SIZE,
44
+ maxResponseSize: IMAP_MAX_RESPONSE_SIZE,
45
+ ...options
46
+ };
47
+
48
+ if (!options.secure && options.doSTARTTLS === undefined && requireTLS !== false) {
49
+ options.doSTARTTLS = true;
50
+ }
51
+
52
+ return options;
53
+ }
15
54
 
16
55
  /**
17
56
  * @param {Object} config - Connection options, applied over the defaults
18
57
  * @returns {ImapFlow}
19
58
  */
20
59
  function createImapClient(config) {
21
- return new ImapFlow({ idHashAlgorithm: 'sha256', ...config });
60
+ return new ImapFlow(imapClientOptions(config));
22
61
  }
23
62
 
24
- module.exports = { createImapClient };
63
+ module.exports = { createImapClient, imapClientOptions };
@@ -26,6 +26,7 @@ const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS }
26
26
  const { parseCalendarEvent, sortCalendarAttachments, CALENDAR_CONTENT_TYPES } = require('../calendar-event');
27
27
  const { llmPreProcess, summaryFetchHeaders, summaryProvider } = require('../llm-pre-process');
28
28
  const { notificationHeaderFields, narrowHeaders } = require('../utils/header-map');
29
+ const { mapConcurrent } = require('../utils/map-concurrent');
29
30
  const { oauth2Apps } = require('../oauth2-apps');
30
31
  const { Account } = require('../account');
31
32
  const { removeBcc } = require('../get-raw-email');
@@ -57,6 +58,7 @@ const {
57
58
  collectCidReferences,
58
59
  embedCidImages
59
60
  } = require('../tools');
61
+ const { withinNotifyAttachmentSize } = require('../notify-attachments');
60
62
 
61
63
  // Import application constants
62
64
  const {
@@ -71,6 +73,7 @@ const {
71
73
  DEFAULT_DOWNLOAD_CHUNK_SIZE,
72
74
  EMAIL_COMPLAINT_NOTIFY,
73
75
  MAX_INLINE_ATTACHMENT_SIZE,
76
+ MAIL_MERGE_CONCURRENCY,
74
77
  DEFAULT_MAX_IMAP_AUTH_FAILURE_TIME,
75
78
  AUTH_FAILURE_DISABLED_FIELD,
76
79
  LAST_ERROR_EVENT_FIELD,
@@ -1553,7 +1556,9 @@ class BaseClient {
1553
1556
  return null;
1554
1557
  }
1555
1558
 
1556
- const idempotencyKeyName = objName ? `${objName}/${idempotencyKey}` : idempotencyKey;
1559
+ // The account id is percent-encoded so the separator cannot occur in it: `a/b` + `c` and
1560
+ // `a` + `b/c` used to be the same key, and the cached dry-run preview of one leaked to the other
1561
+ const idempotencyKeyName = objName ? `${encodeURIComponent(objName)}/${idempotencyKey}` : idempotencyKey;
1557
1562
 
1558
1563
  // check last 24-48 hours, so probably will return 2 keys, at rare cases 1
1559
1564
  const { bucketKeys } = getDateBuckets(1 * 24 * 3600);
@@ -1781,10 +1786,10 @@ class BaseClient {
1781
1786
  delete data.messageId;
1782
1787
  delete data.to;
1783
1788
 
1784
- let messageProcessors = [];
1785
-
1786
- // Create individual messages for each recipient
1787
- for (let mailMergeEntry of mailMergeList) {
1789
+ // Queued a few at a time rather than all at once: every entry is a copy of the message,
1790
+ // attachments included, and a long list queued in parallel held every copy in memory and
1791
+ // every Redis write in flight together
1792
+ let queueEntry = async mailMergeEntry => {
1788
1793
  let messageCopy = structuredClone(data);
1789
1794
  if (messageCopy.sendAt) {
1790
1795
  // date values do not survive JSON based copying
@@ -1806,15 +1811,21 @@ class BaseClient {
1806
1811
  messageCopy.render.params = mailMergeEntry.params;
1807
1812
  }
1808
1813
 
1809
- messageProcessors.push(this.queueMessageEntry(messageCopy, meta, licenseInfo, connectionOptions));
1810
- }
1814
+ return await this.queueMessageEntry(messageCopy, meta, licenseInfo, connectionOptions);
1815
+ };
1816
+
1817
+ // every entry is attempted and reports its own outcome, so the pool never stops early
1818
+ let results = await mapConcurrent(mailMergeList, MAIL_MERGE_CONCURRENCY, async mailMergeEntry => {
1819
+ try {
1820
+ return { status: 'fulfilled', value: await queueEntry(mailMergeEntry) };
1821
+ } catch (reason) {
1822
+ return { status: 'rejected', reason };
1823
+ }
1824
+ });
1811
1825
 
1812
1826
  let response = {
1813
1827
  mailMerge: []
1814
1828
  };
1815
-
1816
- // Process all messages in parallel
1817
- let results = await Promise.allSettled(messageProcessors);
1818
1829
  for (let i = 0; i < mailMergeList.length; i++) {
1819
1830
  let mailMergeEntry = mailMergeList[i];
1820
1831
  let resultEntry = results[i];
@@ -1915,8 +1926,8 @@ class BaseClient {
1915
1926
 
1916
1927
  try {
1917
1928
  referencedMessage = await retryOnTransientError(
1918
- async () => {
1919
- return await this.getMessage(
1929
+ async () =>
1930
+ await this.getMessage(
1920
1931
  data.reference.message,
1921
1932
  {
1922
1933
  fields: !extendedData
@@ -1930,8 +1941,7 @@ class BaseClient {
1930
1941
  textType: extendedData ? '*' : false
1931
1942
  },
1932
1943
  connectionOptions
1933
- );
1934
- },
1944
+ ),
1935
1945
  {
1936
1946
  maxAttempts: 3,
1937
1947
  baseDelay: 1000,
@@ -2310,8 +2320,8 @@ class BaseClient {
2310
2320
 
2311
2321
  try {
2312
2322
  referencedMessage = await retryOnTransientError(
2313
- async () => {
2314
- return await this.getMessage(
2323
+ async () =>
2324
+ await this.getMessage(
2315
2325
  data.reference.message,
2316
2326
  {
2317
2327
  fields: !extendedData
@@ -2325,8 +2335,7 @@ class BaseClient {
2325
2335
  textType: extendedData ? '*' : false
2326
2336
  },
2327
2337
  connectionOptions
2328
- );
2329
- },
2338
+ ),
2330
2339
  {
2331
2340
  maxAttempts: 3,
2332
2341
  baseDelay: 1000,
@@ -3126,7 +3135,7 @@ class BaseClient {
3126
3135
  let notifyAttachmentSize = await settings.get('notifyAttachmentSize');
3127
3136
  if (notifyAttachments && messageData.attachments?.length) {
3128
3137
  for (let attachment of messageData.attachments || []) {
3129
- if (notifyAttachmentSize && attachment.encodedSize && attachment.encodedSize > notifyAttachmentSize) {
3138
+ if (!withinNotifyAttachmentSize(attachment, notifyAttachmentSize)) {
3130
3139
  // skip large attachments
3131
3140
  continue;
3132
3141
  }
@@ -3140,26 +3149,6 @@ class BaseClient {
3140
3149
  }
3141
3150
  }
3142
3151
 
3143
- // Fetch inline attachments referenced in HTML
3144
- if (messageData.attachments && messageData.attachments.length && messageData.text && messageData.text.html) {
3145
- // fetch inline attachments
3146
- let cidReferences = collectCidReferences(messageData.text.html);
3147
- for (let attachment of messageData.attachments) {
3148
- if (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE) {
3149
- // skip large attachments
3150
- continue;
3151
- }
3152
-
3153
- if (!attachment.content && attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
3154
- try {
3155
- attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
3156
- } catch (err) {
3157
- this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
3158
- }
3159
- }
3160
- }
3161
- }
3162
-
3163
3152
  // Fetch and process calendar events if needed
3164
3153
  let notifyCalendarEvents = await settings.get('notifyCalendarEvents');
3165
3154
  if (notifyCalendarEvents && messageData.attachments && messageData.attachments.length) {
@@ -3278,8 +3267,8 @@ class BaseClient {
3278
3267
  for (let attachment of messageData.attachments) {
3279
3268
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
3280
3269
  if (contentId && cidReferences.has(contentId)) {
3281
- // An attachment the earlier inline pass already loaded is embedded as is; the
3282
- // same size cap applies to anything downloaded here
3270
+ // An attachment notifyAttachments already loaded is embedded as is; anything
3271
+ // downloaded here is capped at the inline image size
3283
3272
  if (!attachment.content && !(attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE)) {
3284
3273
  try {
3285
3274
  attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
@@ -9,6 +9,7 @@ const addressparser = require('nodemailer/lib/addressparser');
9
9
  const libmime = require('libmime');
10
10
  const he = require('he');
11
11
  const { BaseClient, metricsMeta } = require('./base-client');
12
+ const { isSafePathSegment } = require('../utils/provider-id');
12
13
  const { isTransientCredentialError } = require('./credential-errors');
13
14
  const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
14
15
  const { emitChangeEvent, toCamelCase, collectCidReferences, embedCidImages, truncateTextContents, readEnvValue } = require('../tools');
@@ -421,18 +422,16 @@ class GmailClient extends BaseClient {
421
422
  })
422
423
  };
423
424
  }
424
- } else {
425
+ } else if (profileRes.emailAddress && accountData.oauth2.auth?.user !== profileRes.emailAddress) {
425
426
  // Extract email from profile for full access accounts
426
- if (profileRes.emailAddress && accountData.oauth2.auth?.user !== profileRes.emailAddress) {
427
- updates._oldOAuth2User = accountData.oauth2.auth?.user; // needed for cleanups
428
- updates.oauth2 = {
429
- partial: true,
430
- auth: Object.assign(accountData.oauth2.auth || {}, {
431
- // update username
432
- user: profileRes.emailAddress
433
- })
434
- };
435
- }
427
+ updates._oldOAuth2User = accountData.oauth2.auth?.user; // needed for cleanups
428
+ updates.oauth2 = {
429
+ partial: true,
430
+ auth: Object.assign(accountData.oauth2.auth || {}, {
431
+ // update username
432
+ user: profileRes.emailAddress
433
+ })
434
+ };
436
435
  }
437
436
 
438
437
  // Detect and store user locale (only for full access accounts)
@@ -773,7 +772,7 @@ class GmailClient extends BaseClient {
773
772
  if (query.search.emailId) {
774
773
  // Return only a single matching email
775
774
 
776
- let messageEntry = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${query.search.emailId}`, 'get', {
775
+ let messageEntry = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${encodeURIComponent(query.search.emailId)}`, 'get', {
777
776
  format: 'full'
778
777
  });
779
778
 
@@ -796,9 +795,13 @@ class GmailClient extends BaseClient {
796
795
 
797
796
  if (query.search.threadId) {
798
797
  // Threading is a special case - fetch entire thread
799
- let threadListingResult = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/threads/${query.search.threadId}`, 'get', {
800
- format: 'full'
801
- });
798
+ let threadListingResult = await this.request(
799
+ `${GMAIL_API_BASE}/gmail/v1/users/me/threads/${encodeURIComponent(query.search.threadId)}`,
800
+ 'get',
801
+ {
802
+ format: 'full'
803
+ }
804
+ );
802
805
 
803
806
  let messageCount = threadListingResult?.messages?.length || 0;
804
807
  let currentPage = pageCursor.currentPage();
@@ -1447,7 +1450,7 @@ class GmailClient extends BaseClient {
1447
1450
  // Decode text part references
1448
1451
  const [emailId, textParts] = this.unpackApiId(
1449
1452
  textId,
1450
- parts => parts.length >= 2 && Array.isArray(parts[1]) && Array.isArray(parts[1][0]) && Array.isArray(parts[1][1])
1453
+ parts => parts.length >= 2 && isSafePathSegment(parts[0]) && Array.isArray(parts[1]) && Array.isArray(parts[1][0]) && Array.isArray(parts[1][1])
1451
1454
  );
1452
1455
 
1453
1456
  const bodyParts = new Map();
@@ -2710,12 +2713,21 @@ class GmailClient extends BaseClient {
2710
2713
  */
2711
2714
  async getAttachmentContent(attachmentId, options) {
2712
2715
  options = options || {};
2713
- const [emailId, contentType, disposition, filename, id] = this.unpackApiId(attachmentId, parts => parts.length >= 5);
2716
+ // The message and attachment parts become path segments of the API URL, so a part that
2717
+ // would leave its segment is an invalid id rather than a request for a different resource
2718
+ const [emailId, contentType, disposition, filename, id] = this.unpackApiId(
2719
+ attachmentId,
2720
+ parts => parts.length >= 5 && isSafePathSegment(parts[0]) && isSafePathSegment(parts[4])
2721
+ );
2714
2722
 
2715
2723
  await this.prepare();
2716
2724
 
2717
2725
  const requestQuery = {};
2718
- const result = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${emailId}/attachments/${id}`, 'get', requestQuery);
2726
+ const result = await this.request(
2727
+ `${GMAIL_API_BASE}/gmail/v1/users/me/messages/${encodeURIComponent(emailId)}/attachments/${encodeURIComponent(id)}`,
2728
+ 'get',
2729
+ requestQuery
2730
+ );
2719
2731
 
2720
2732
  const content = result?.data ? Buffer.from(result?.data, 'base64url') : null;
2721
2733
 
@@ -16,6 +16,7 @@ const {
16
16
  embedCidImages
17
17
  } = require('../../tools');
18
18
  const { samePath } = require('../../utils/mailbox-path');
19
+ const { withinNotifyAttachmentSize } = require('../../notify-attachments');
19
20
  const { connectionNotAvailableError } = require('./connection-errors');
20
21
  const msgpack = require('../../msgpack');
21
22
  const he = require('he');
@@ -45,6 +46,7 @@ const {
45
46
  REDIS_PREFIX,
46
47
  MAX_INLINE_ATTACHMENT_SIZE,
47
48
  MAX_ALLOWED_DOWNLOAD_SIZE,
49
+ MAX_BOUNCE_DOWNLOAD_SIZE,
48
50
  TRANSIENT_NETWORK_CODES,
49
51
  CONNECTION_CLOSING_CODES,
50
52
  PHANTOM_SELECT_FAIL_THRESHOLD,
@@ -1340,10 +1342,13 @@ class Mailbox {
1340
1342
  if (this.connection.mightBeDSNResponse(messageInfo)) {
1341
1343
  let sourceStream;
1342
1344
  try {
1345
+ // A delivery report is small and its status part comes first, so the download is
1346
+ // cut well below the general cap: the rest is the returned original, which the
1347
+ // parse does not need and which a sender can make as large as the server allows
1343
1348
  ({ content: sourceStream } = await this.requireImapClient().download(messageInfo.uid, false, {
1344
1349
  uid: true,
1345
1350
  chunkSize: options.chunkSize,
1346
- maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
1351
+ maxBytes: MAX_BOUNCE_DOWNLOAD_SIZE
1347
1352
  }));
1348
1353
 
1349
1354
  // No content means the message was expunged after it was detected (a server-side
@@ -1382,7 +1387,7 @@ class Mailbox {
1382
1387
  let result = await this.requireImapClient().download(messageInfo.uid, false, {
1383
1388
  uid: true,
1384
1389
  chunkSize: options.chunkSize,
1385
- maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
1390
+ maxBytes: MAX_BOUNCE_DOWNLOAD_SIZE
1386
1391
  });
1387
1392
  content = result.content;
1388
1393
  }
@@ -1501,7 +1506,7 @@ class Mailbox {
1501
1506
  let notifyAttachmentSize = await settings.get('notifyAttachmentSize');
1502
1507
  if (notifyAttachments && messageInfo.attachments?.length) {
1503
1508
  for (let attachment of messageInfo.attachments || []) {
1504
- if (notifyAttachmentSize && attachment.encodedSize && attachment.encodedSize > notifyAttachmentSize) {
1509
+ if (!withinNotifyAttachmentSize(attachment, notifyAttachmentSize)) {
1505
1510
  // skip large attachments
1506
1511
  continue;
1507
1512
  }
@@ -1511,23 +1516,6 @@ class Mailbox {
1511
1516
  }
1512
1517
  }
1513
1518
 
1514
- // Fetch inline attachments referenced in HTML
1515
- if (messageInfo.attachments?.length && messageInfo.text?.html) {
1516
- // fetch inline attachments
1517
- let cidReferences = collectCidReferences(messageInfo.text.html);
1518
- for (let attachment of messageInfo.attachments || []) {
1519
- if (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE) {
1520
- // skip large attachments
1521
- continue;
1522
- }
1523
-
1524
- // Check if attachment is referenced by Content-ID in HTML
1525
- if (!attachment.content && attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
1526
- await this.loadAttachmentContent(messageInfo, attachment, options);
1527
- }
1528
- }
1529
- }
1530
-
1531
1519
  // Fetch and process calendar events if needed
1532
1520
  let notifyCalendarEvents = await settings.get('notifyCalendarEvents');
1533
1521
  if (notifyCalendarEvents && messageInfo.attachments && messageInfo.attachments.length) {
@@ -1656,7 +1644,7 @@ class Mailbox {
1656
1644
  });
1657
1645
 
1658
1646
  if (attachment.content || (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE)) {
1659
- // already downloaded in a previous step, or skipped there as too large to inline
1647
+ // already loaded by notifyAttachments, or too large to inline
1660
1648
  continue;
1661
1649
  }
1662
1650
 
@@ -1679,7 +1667,8 @@ class Mailbox {
1679
1667
  // Download missing attachments in batch
1680
1668
  try {
1681
1669
  let contentParts = await this.requireImapClient().downloadMany(messageInfo.uid, partList, {
1682
- uid: true
1670
+ uid: true,
1671
+ maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
1683
1672
  });
1684
1673
 
1685
1674
  if (contentParts) {
@@ -2653,7 +2642,8 @@ class Mailbox {
2653
2642
 
2654
2643
  // Download all referenced images in batch
2655
2644
  let contentParts = await connectionClient.downloadMany(messageInfo.uid, partList, {
2656
- uid: true
2645
+ uid: true,
2646
+ maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
2657
2647
  });
2658
2648
 
2659
2649
  if (contentParts) {
@@ -0,0 +1,75 @@
1
+ 'use strict';
2
+
3
+ // Label values for the `imap_responses` counter.
4
+ //
5
+ // ImapFlow reports every tagged response as `{ response, code }`: the status (OK, NO, BAD, ...)
6
+ // and the bracketed response code when there is one (`[ALERT]`, `[AUTHENTICATIONFAILED]`).
7
+ // Both are atoms the server chose, and every distinct label value is a new series held by the
8
+ // Prometheus registry on the main thread for the life of the process, so a server (or a proxy on
9
+ // the path) that varies them grows that memory without bound. Only the vocabulary below reaches
10
+ // the counter; anything else is counted under `other`, which keeps the count right while bounding
11
+ // the series.
12
+
13
+ // RFC 9051 status responses, plus the two a tagged response may carry on some servers
14
+ const KNOWN_RESPONSES = new Set(['OK', 'NO', 'BAD', 'BYE', 'PREAUTH']);
15
+
16
+ // RFC 9051 and RFC 5530 response codes, plus the extension codes EmailEngine reacts to
17
+ const KNOWN_CODES = new Set([
18
+ 'ALERT',
19
+ 'ALREADYEXISTS',
20
+ 'APPENDUID',
21
+ 'AUTHENTICATIONFAILED',
22
+ 'AUTHORIZATIONFAILED',
23
+ 'BADCHARSET',
24
+ 'CANNOT',
25
+ 'CAPABILITY',
26
+ 'CLIENTBUG',
27
+ 'CLOSED',
28
+ 'COMPRESSIONACTIVE',
29
+ 'CONTACTADMIN',
30
+ 'COPYUID',
31
+ 'CORRUPTION',
32
+ 'EXPIRED',
33
+ 'EXPUNGEISSUED',
34
+ 'HASCHILDREN',
35
+ 'HIGHESTMODSEQ',
36
+ 'INUSE',
37
+ 'LIMIT',
38
+ 'NOMODSEQ',
39
+ 'NONEXISTENT',
40
+ 'NOPERM',
41
+ 'OVERQUOTA',
42
+ 'PARSE',
43
+ 'PERMANENTFLAGS',
44
+ 'PRIVACYREQUIRED',
45
+ 'READ-ONLY',
46
+ 'READ-WRITE',
47
+ 'SERVERBUG',
48
+ 'TRYCREATE',
49
+ 'UIDNEXT',
50
+ 'UIDNOTSTICKY',
51
+ 'UIDVALIDITY',
52
+ 'UNAVAILABLE',
53
+ 'UNKNOWN-CTE',
54
+ 'UNSEEN'
55
+ ]);
56
+
57
+ const OTHER = 'other';
58
+
59
+ /**
60
+ * @param {Object} data - the `response` event payload from ImapFlow
61
+ * @returns {{response: String, code?: String}} the label values to count
62
+ */
63
+ function imapResponseLabels(data) {
64
+ let response = data && typeof data.response === 'string' ? data.response.toUpperCase() : '';
65
+ let labels = { response: KNOWN_RESPONSES.has(response) ? response : OTHER };
66
+
67
+ if (data && data.code !== undefined && data.code !== null) {
68
+ let code = typeof data.code === 'string' ? data.code.toUpperCase() : '';
69
+ labels.code = KNOWN_CODES.has(code) ? code : OTHER;
70
+ }
71
+
72
+ return labels;
73
+ }
74
+
75
+ module.exports = { imapResponseLabels, KNOWN_RESPONSES, KNOWN_CODES };
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { createImapClient } = require('../../create-imap-client');
4
- const { backOff } = require('exponential-backoff');
4
+ const { backOff } = require('../../utils/back-off');
5
5
  const { ReconnectBackoff } = require('../reconnect-backoff');
6
6
  const { detachImapClient } = require('./detach-client');
7
7
  const { connectionUnavailableError } = require('./connection-errors');
@@ -5,7 +5,7 @@ const { createImapClient } = require('../create-imap-client');
5
5
  const { Mailbox } = require('./imap/mailbox');
6
6
  const logger = require('../logger');
7
7
  const packageData = require('../../package.json');
8
- const { backOff } = require('exponential-backoff');
8
+ const { backOff } = require('../utils/back-off');
9
9
  const msgpack = require('../msgpack');
10
10
 
11
11
  const { oauth2ProviderData } = require('../oauth2-apps');
@@ -13,6 +13,7 @@ const { BaseClient } = require('./base-client');
13
13
  const { oauth2Apps } = require('../oauth2-apps');
14
14
 
15
15
  const { Subconnection } = require('./imap/subconnection');
16
+ const { imapResponseLabels } = require('./imap/response-metrics');
16
17
  const { decodeStoredListing, diffMailboxListing, buildStoredListingObject, matchesListingEntry, configuredPathIndex } = require('./imap/listing-diff');
17
18
  const { samePath } = require('../utils/mailbox-path');
18
19
  const { detachImapClient } = require('./imap/detach-client');
@@ -1834,9 +1835,11 @@ class IMAPClient extends BaseClient {
1834
1835
  }
1835
1836
  });
1836
1837
 
1837
- // Track IMAP command/response metrics
1838
+ // Track IMAP command/response metrics. The response status and code are atoms the
1839
+ // server chose, and a Prometheus label value is a series on the main thread, so
1840
+ // only the known vocabulary becomes a label and anything else is counted as `other`
1838
1841
  imapClient.on('response', data => {
1839
- metricsMeta({}, this.logger, 'imapResponses', 'inc', data);
1842
+ metricsMeta({}, this.logger, 'imapResponses', 'inc', imapResponseLabels(data));
1840
1843
 
1841
1844
  // update byte counters as well
1842
1845
  let imapStats = imapClient.stats(true);
@@ -5,6 +5,7 @@ const { oauth2ProviderData } = require('../oauth2-apps');
5
5
  const { useAuthServerForConnection, redactUrlCredentials } = require('../tools');
6
6
  const { resolveAuthServerCredentials } = require('./credential-errors');
7
7
  const { getLocalAddress } = require('../utils/network');
8
+ const { applyRequireTls } = require('../utils/require-tls');
8
9
  const settings = require('../settings');
9
10
  const { TLS_DEFAULTS } = require('../consts');
10
11
  const util = require('util');
@@ -85,7 +86,8 @@ class SmtpConfigBuilder {
85
86
  const config = {
86
87
  host: gatewayData.host,
87
88
  port: gatewayData.port,
88
- secure: gatewayData.secure
89
+ secure: gatewayData.secure,
90
+ requireTLS: gatewayData.requireTLS
89
91
  };
90
92
 
91
93
  if (gatewayData.user || gatewayData.pass) {
@@ -170,12 +172,14 @@ class SmtpConfigBuilder {
170
172
  // Build SMTP logger wrapper
171
173
  const smtpLogger = this.buildSmtpLogger();
172
174
 
173
- // Create settings object
175
+ // Create settings object. `account` names whose logger `transactionLog` writes to, so the
176
+ // pool manager does not share a logged pool between accounts (lib/email-client/smtp-pool-manager.js)
174
177
  const smtpSettings = Object.assign(
175
178
  {
176
179
  name,
177
180
  localAddress: address,
178
181
  transactionLog: true,
182
+ account: this.account,
179
183
  logger: smtpLogger
180
184
  },
181
185
  smtpConnectionConfig
@@ -194,6 +198,7 @@ class SmtpConfigBuilder {
194
198
 
195
199
  // Apply TLS defaults
196
200
  this.applyTlsDefaults(smtpSettings);
201
+ applyRequireTls(smtpSettings);
197
202
 
198
203
  // Apply proxy configuration
199
204
  await this.applyProxyConfig(smtpSettings, accountData, data);
@@ -97,8 +97,7 @@ class NotificationHandler {
97
97
  // Build notification payload
98
98
  const payload = this.buildPayload(mailbox, event, data, serviceUrl);
99
99
 
100
- const notifyPayload = await Webhooks.formatPayload(event, payload);
101
- await Webhooks.pushToQueue(event, notifyPayload);
100
+ await Webhooks.enqueue(event, payload);
102
101
  }
103
102
  }
104
103