emailengine-app 2.87.0 → 2.87.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 (71) hide show
  1. package/.ncurc.js +2 -4
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/Dockerfile +3 -4
  5. package/bin/emailengine.js +2 -4
  6. package/bin/healthcheck.js +20 -0
  7. package/data/google-crawlers.json +1 -1
  8. package/data/public_suffix_list.dat +3 -7
  9. package/lib/account/auth-failure-backfill.js +3 -2
  10. package/lib/account/expected-identity.js +2 -2
  11. package/lib/account.js +9 -8
  12. package/lib/api-listener.js +40 -0
  13. package/lib/api-token-auth.js +406 -0
  14. package/lib/autodetect-imap-settings.js +36 -3
  15. package/lib/consts.js +5 -0
  16. package/lib/dbsc/index.js +292 -0
  17. package/lib/dbsc/jwt.js +157 -0
  18. package/lib/dbsc/protocol.js +132 -0
  19. package/lib/dbsc/store.js +136 -0
  20. package/lib/email-client/base-client.js +23 -107
  21. package/lib/email-client/gmail-client.js +7 -4
  22. package/lib/email-client/imap/mailbox.js +89 -96
  23. package/lib/email-client/imap/sync-operations.js +13 -6
  24. package/lib/email-client/imap-client.js +28 -7
  25. package/lib/email-client/new-message-steps.js +162 -0
  26. package/lib/email-client/outlook-client.js +4 -2
  27. package/lib/env-setting-overrides.js +6 -2
  28. package/lib/export-worker.js +3 -2
  29. package/lib/export.js +43 -4
  30. package/lib/get-boolean.js +38 -0
  31. package/lib/health-probe.js +71 -0
  32. package/lib/imapproxy/imap-server.js +4 -55
  33. package/lib/net-tos-guard.js +42 -0
  34. package/lib/oauth2-apps.js +2 -1
  35. package/lib/privileged-settings.js +6 -0
  36. package/lib/read-env-value.js +19 -7
  37. package/lib/redis-keys.js +19 -0
  38. package/lib/redis-operations.js +7 -3
  39. package/lib/routes-ui.js +4 -1
  40. package/lib/schemas.js +8 -0
  41. package/lib/security-headers.js +18 -0
  42. package/lib/session-default.js +60 -0
  43. package/lib/settings.js +2 -1
  44. package/lib/stream-encrypt.js +71 -20
  45. package/lib/sub-script.js +8 -2
  46. package/lib/submit-lock.js +84 -0
  47. package/lib/submit-processor.js +283 -0
  48. package/lib/templates.js +6 -3
  49. package/lib/tls/context.js +2 -16
  50. package/lib/tools.js +8 -30
  51. package/lib/ui-routes/admin-config-routes.js +27 -5
  52. package/lib/ui-routes/auth-routes.js +4 -0
  53. package/lib/ui-routes/dbsc-routes.js +43 -0
  54. package/lib/utils/redis-errors.js +44 -0
  55. package/lib/webhook-delivery.js +3 -4
  56. package/lib/worker-rpc-error.js +10 -5
  57. package/lib/worker-rpc.js +138 -0
  58. package/package.json +17 -19
  59. package/sbom.json +370 -1446
  60. package/server.js +6 -5
  61. package/static/css/flyonui.css +2 -2
  62. package/static/licenses.html +253 -1366
  63. package/translations/messages.pot +16 -16
  64. package/views/config/security.hbs +37 -0
  65. package/workers/api.js +61 -467
  66. package/workers/export.js +14 -55
  67. package/workers/imap-proxy.js +5 -18
  68. package/workers/imap.js +27 -49
  69. package/workers/smtp.js +7 -69
  70. package/workers/submit.js +21 -279
  71. package/workers/webhooks.js +7 -72
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { finished } = require('stream');
4
+ const { StringDecoder } = require('string_decoder');
4
5
  const { ImapFlowErrorCode } = require('imapflow');
5
6
  const {
6
7
  serialize,
@@ -23,7 +24,7 @@ const settings = require('../../settings');
23
24
  const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS } = require('../../bounce-detect');
24
25
  const { decodeHeaders } = require('../../utils/decode-headers');
25
26
  const { isUnsafeKey } = require('../../utils/unsafe-key');
26
- const { arfDetect, camelCaseComplaint, COMPLAINT_ATTACHMENT_TYPES } = require('../../arf-detect');
27
+ const { arfDetect, COMPLAINT_ATTACHMENT_TYPES } = require('../../arf-detect');
27
28
  const { messageWebSafeHtml } = require('../../web-safe-html');
28
29
  const { parseMessage } = require('../../parse-message');
29
30
  const { collectCalendarEvents } = require('../../calendar-event');
@@ -31,17 +32,24 @@ const { parseAddressHeader: parseMailboxes } = require('mailparser');
31
32
  const { llmPreProcess, summaryFetchHeaders, summaryProvider } = require('../../llm-pre-process');
32
33
  const { notificationHeaderFields, narrowHeaders } = require('../../utils/header-map');
33
34
  const { getMessageOtp, notifyHeadersIncludeOtp, OTP_FETCH_HEADERS } = require('../../otp');
34
- const { isFailedDelivery } = require('../base-client');
35
+ const {
36
+ isOwnSent,
37
+ classifyBounce,
38
+ bounceNotification,
39
+ complaintNotification,
40
+ embedInlineImages,
41
+ markWebSafe,
42
+ notifyNewMessage
43
+ } = require('../new-message-steps');
44
+ const { isTransientRedisError } = require('../../utils/redis-errors');
45
+ const { getDelay } = require('../../utils/back-off');
35
46
 
36
47
  const {
37
- MESSAGE_NEW_NOTIFY,
38
48
  MAILBOX_DELETED_NOTIFY,
39
49
  MESSAGE_DELETED_NOTIFY,
40
50
  MESSAGE_UPDATED_NOTIFY,
41
51
  MESSAGE_MISSING_NOTIFY,
42
52
  MAILBOX_NEW_NOTIFY,
43
- EMAIL_BOUNCE_NOTIFY,
44
- EMAIL_COMPLAINT_NOTIFY,
45
53
  REDIS_PREFIX,
46
54
  MAX_INLINE_ATTACHMENT_SIZE,
47
55
  MAX_ALLOWED_DOWNLOAD_SIZE,
@@ -106,13 +114,32 @@ function isConnectionGone(err) {
106
114
  * @returns {Boolean}
107
115
  */
108
116
  function keepsArrivalQueued(err) {
109
- return isConnectionGone(err) || TRANSIENT_NETWORK_CODES.has(err?.code) || err?.code === ImapFlowErrorCode.ETHROTTLE;
117
+ return (
118
+ isConnectionGone(err) ||
119
+ TRANSIENT_NETWORK_CODES.has(err?.code) ||
120
+ err?.code === ImapFlowErrorCode.ETHROTTLE ||
121
+ // Redis refused a step for now (OOM, LOADING, a failover): queueing the webhook or storing
122
+ // the message index, say. Dropping the entry lost the message for good
123
+ isTransientRedisError(err)
124
+ );
110
125
  }
111
126
 
112
127
  // Passes a queued arrival may be throttled on before it is dropped, so a message the server
113
128
  // throttles every time cannot hold up every later arrival in its folder
114
129
  const MAX_THROTTLED_ARRIVAL_PASSES = 5;
115
130
 
131
+ // How long a burst of changes is collected into one partial sync
132
+ const PARTIAL_SYNC_DEBOUNCE = 1000;
133
+
134
+ /**
135
+ * Delay before running a partial sync again that Redis refused for now
136
+ * @param {number} retry - Consecutive failed attempts, 1 based
137
+ * @returns {number} Milliseconds, doubling from 2 s up to a minute
138
+ */
139
+ function partialSyncRetryDelay(retry) {
140
+ return getDelay({ startingDelay: 2000, timeMultiple: 2, maxDelay: 60 * 1000 }, retry);
141
+ }
142
+
116
143
  /**
117
144
  * Whether a message reference decoded from an API id still names a message in the folder the
118
145
  * connection has open. The id carries the UIDVALIDITY it was issued under, and a folder that was
@@ -1228,24 +1255,38 @@ class Mailbox {
1228
1255
  }
1229
1256
 
1230
1257
  /**
1231
- * Debounces a partial sync so a burst of changes runs one
1258
+ * Debounces a partial sync so a burst of changes runs one. One that Redis refused for now (OOM,
1259
+ * LOADING, a failover) runs again after a backoff: the main mailbox is synced only on its own
1260
+ * changes (the periodic resync skips it), so the arrival the failed pass kept queued, or never
1261
+ * fetched at all, would otherwise wait for the next message in the folder. A new change, a
1262
+ * reopen or a close replaces the retry
1232
1263
  * @param {Function} shouldRun - Async check made when the timer fires
1233
1264
  * @param {string} trigger - What asked for it, for the log
1265
+ * @param {number} [delay] - Milliseconds to wait
1234
1266
  */
1235
- schedulePartialSync(shouldRun, trigger) {
1267
+ schedulePartialSync(shouldRun, trigger, delay = PARTIAL_SYNC_DEBOUNCE) {
1236
1268
  clearTimeout(this.runPartialSyncTimer);
1237
1269
  this.runPartialSyncTimer = setTimeout(() => {
1238
1270
  this.runPartialSyncTimer = null;
1239
1271
  shouldRun()
1240
1272
  .then(run => (run ? this.partialSync() : false))
1273
+ .then(() => {
1274
+ this.partialSyncRetries = 0;
1275
+ })
1241
1276
  .catch(err => {
1242
1277
  if (CONNECTION_CLOSING_CODES.has(err.code)) {
1243
1278
  this.logger.debug({ msg: 'Sync skipped, connection closing', err });
1244
- } else {
1245
- this.logger.warn({ msg: `Failed to sync mailbox after ${trigger}`, err });
1279
+ return;
1280
+ }
1281
+ this.logger.warn({ msg: `Failed to sync mailbox after ${trigger}`, err });
1282
+ if (isTransientRedisError(err)) {
1283
+ this.partialSyncRetries = (this.partialSyncRetries || 0) + 1;
1284
+ // The check may well say nothing changed now (the failed pass stored the
1285
+ // new UIDNEXT before it announced), so the retry syncs regardless
1286
+ this.schedulePartialSync(async () => true, 'a failed sync', partialSyncRetryDelay(this.partialSyncRetries));
1246
1287
  }
1247
1288
  });
1248
- }, 1000);
1289
+ }, delay);
1249
1290
  }
1250
1291
 
1251
1292
  /**
@@ -1536,18 +1577,7 @@ class Mailbox {
1536
1577
  // Parse ARF report
1537
1578
  const report = await arfDetect(messageInfo);
1538
1579
 
1539
- if (report && report.arf && report.arf['original-rcpt-to'] && report.arf['original-rcpt-to'].length) {
1540
- // Valid complaint found - prepare notification data
1541
- let complaint = camelCaseComplaint(report);
1542
-
1543
- complaintNotifyInfo = Object.assign({ complaintMessage: messageInfo.id }, complaint);
1544
-
1545
- messageInfo.isComplaint = true;
1546
-
1547
- if (complaint.headers && complaint.headers.messageId) {
1548
- messageInfo.relatedMessageId = complaint.headers.messageId;
1549
- }
1550
- }
1580
+ complaintNotifyInfo = complaintNotification(report, messageInfo);
1551
1581
  } catch (err) {
1552
1582
  if (isConnectionGone(err)) {
1553
1583
  throw err;
@@ -1620,44 +1650,8 @@ class Mailbox {
1620
1650
  // Detect bounce details
1621
1651
  let bounce = await bounceDetect(content);
1622
1652
 
1623
- if (bounce?.response?.message) {
1624
- try {
1625
- let bounceType = await this.connection.call({
1626
- cmd: 'bounceClassify',
1627
- data: {
1628
- message: bounce?.response?.message
1629
- },
1630
- timeout: 2 * 60 * 1000
1631
- });
1632
-
1633
- if (bounceType?.label) {
1634
- bounce.response.category = bounceType.label;
1635
- }
1636
- if (bounceType?.action) {
1637
- bounce.response.recommendedAction = bounceType.action;
1638
- }
1639
- if (bounceType?.blocklist) {
1640
- bounce.response.blocklist = bounceType.blocklist;
1641
- }
1642
- if (bounceType?.retryAfter) {
1643
- bounce.response.retryAfter = bounceType.retryAfter;
1644
- }
1645
- } catch (err) {
1646
- // ignore, just do not include this information
1647
- this.logger.error({
1648
- msg: 'Failed to classify bounce response',
1649
- bounceResponse: bounce?.response?.message,
1650
- err
1651
- });
1652
- }
1653
- }
1654
-
1655
- if (isFailedDelivery(bounce)) {
1656
- bounceNotifyInfo = Object.assign({ bounceMessage: messageInfo.id }, bounce);
1657
-
1658
- messageInfo.isBounce = true;
1659
- messageInfo.relatedMessageId = bounce.messageId;
1660
- }
1653
+ await classifyBounce(bounce, this.connection.call, this.logger);
1654
+ bounceNotifyInfo = bounceNotification(bounce, messageInfo);
1661
1655
 
1662
1656
  this.logger.debug({
1663
1657
  msg: 'Detected bounce message',
@@ -1731,8 +1725,7 @@ class Mailbox {
1731
1725
 
1732
1726
  // Check if we have seen this message before using HyperLogLog
1733
1727
  messageInfo.seemsLikeNew =
1734
- this.listingEntry.specialUse !== '\\Sent' &&
1735
- !(messageInfo.labels && messageInfo.labels.includes('\\Sent')) &&
1728
+ !isOwnSent(messageInfo, this.listingEntry.specialUse) &&
1736
1729
  !!(await this.connection.redis.pfadd(this.getSeenMessagesKey(), messageInfo.emailId || messageInfo.messageId));
1737
1730
 
1738
1731
  // Process with LLM if configured for inbox messages. A message with no text part has no
@@ -1755,7 +1748,7 @@ class Mailbox {
1755
1748
  if (notifyWebSafeHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
1756
1749
  // convert to web safe
1757
1750
  messageInfo.text._generatedHtml = await messageWebSafeHtml(messageInfo);
1758
- messageInfo.text.webSafe = true;
1751
+ markWebSafe(messageInfo.text);
1759
1752
 
1760
1753
  // Embed images referenced by Content-ID
1761
1754
  if (messageInfo.text.html && messageInfo.attachments) {
@@ -1815,18 +1808,7 @@ class Mailbox {
1815
1808
  }
1816
1809
  }
1817
1810
 
1818
- // Replace CID references with data URIs. The web safe copy is what webhooks
1819
- // deliver in place of the HTML, so it gets the same treatment
1820
- const embedImages = html =>
1821
- embedCidImages(html, contentId => {
1822
- let { attachment, content } = attachmentList.get(contentId) || {};
1823
- return content && { contentType: attachment.contentType, content };
1824
- });
1825
-
1826
- messageInfo.text.html = embedImages(messageInfo.text.html);
1827
- if (messageInfo.text._generatedHtml) {
1828
- messageInfo.text._generatedHtml = embedImages(messageInfo.text._generatedHtml);
1829
- }
1811
+ embedInlineImages(messageInfo.text, attachmentList);
1830
1812
  }
1831
1813
  }
1832
1814
  }
@@ -1838,20 +1820,7 @@ class Mailbox {
1838
1820
  narrowHeaders(messageInfo, requestedHeaders);
1839
1821
  }
1840
1822
 
1841
- // Send new message notification
1842
- await this.connection.notify(this, MESSAGE_NEW_NOTIFY, messageInfo);
1843
-
1844
- // Send bounce notification if detected
1845
- if (bounceNotifyInfo) {
1846
- // send bounce notification _after_ bounce email notification
1847
- await this.connection.notify(false, EMAIL_BOUNCE_NOTIFY, bounceNotifyInfo);
1848
- }
1849
-
1850
- // Send complaint notification if detected
1851
- if (complaintNotifyInfo) {
1852
- // send complaint notification _after_ complaint email notification
1853
- await this.connection.notify(false, EMAIL_COMPLAINT_NOTIFY, complaintNotifyInfo);
1854
- }
1823
+ await notifyNewMessage(this.connection.notify.bind(this.connection), this, messageInfo, { bounceNotifyInfo, complaintNotifyInfo });
1855
1824
  }
1856
1825
 
1857
1826
  /**
@@ -2305,6 +2274,7 @@ class Mailbox {
2305
2274
  */
2306
2275
  async onOpen(event, openedClient) {
2307
2276
  clearTimeout(this.runPartialSyncTimer);
2277
+ this.partialSyncRetries = 0;
2308
2278
  this.selected = true;
2309
2279
 
2310
2280
  // The latch is scoped to the connection that emitted the open event.
@@ -2489,6 +2459,7 @@ class Mailbox {
2489
2459
  */
2490
2460
  async onClose() {
2491
2461
  clearTimeout(this.runPartialSyncTimer);
2462
+ this.partialSyncRetries = 0;
2492
2463
  this.selected = false;
2493
2464
  }
2494
2465
 
@@ -2535,8 +2506,15 @@ class Mailbox {
2535
2506
  if (!content) {
2536
2507
  continue;
2537
2508
  }
2538
- let text = await download(content);
2539
- text = text.toString().replace(/\r?\n/g, '\n');
2509
+ let buffer = await download(content);
2510
+
2511
+ // maxBytes caps decoded bytes, so judge the cut on the bytes: multibyte characters and
2512
+ // the CRLF normalization below both leave the string shorter than the limit.
2513
+ // StringDecoder drops a multibyte sequence split at the cut.
2514
+ if (buffer.length > maxBytes) {
2515
+ hasMore = true;
2516
+ }
2517
+ let text = new StringDecoder('utf8').write(buffer).replace(/\r?\n/g, '\n');
2540
2518
 
2541
2519
  // Group by content type (plain, html, etc). The subtype comes from the message,
2542
2520
  // so a sender picks it: for "text/__proto__" the `!result[typeKey]` probe below
@@ -3034,7 +3012,7 @@ class Mailbox {
3034
3012
  // Get new UID in target mailbox
3035
3013
  if (value && value.uidMap && value.uidMap.has(message.uid)) {
3036
3014
  let uid = value.uidMap.get(message.uid);
3037
- let packed = await this.connection.packUid(target.path, uid);
3015
+ let packed = await this.connection.packUid(value.destination || target.path, uid, null, value.uidValidity);
3038
3016
  result.id = packed;
3039
3017
  result.uid = uid;
3040
3018
  }
@@ -3067,8 +3045,13 @@ class Mailbox {
3067
3045
  // Build ID map for moved messages
3068
3046
  if (value && value.uidMap && value.uidMap.size) {
3069
3047
  let moveMap = [];
3048
+ // One status read for the source folder, not one per message
3049
+ let sourceStatus = new Map();
3070
3050
  for (let [suid, tuid] of value.uidMap) {
3071
- moveMap.push([await this.connection.packUid(this.path, suid), await this.connection.packUid(target.path, tuid)]);
3051
+ moveMap.push([
3052
+ await this.connection.packUid(this.path, suid, sourceStatus),
3053
+ await this.connection.packUid(value.destination || target.path, tuid, null, value.uidValidity)
3054
+ ]);
3072
3055
  }
3073
3056
  result.idMap = moveMap;
3074
3057
  }
@@ -3111,7 +3094,12 @@ class Mailbox {
3111
3094
  destination: moved.destination
3112
3095
  };
3113
3096
  if (moved && moved.uidMap && moved.uidMap.has(message.uid)) {
3114
- result.moved.message = await this.connection.packUid(trashMailbox.path, moved.uidMap.get(message.uid));
3097
+ result.moved.message = await this.connection.packUid(
3098
+ moved.destination || trashMailbox.path,
3099
+ moved.uidMap.get(message.uid),
3100
+ null,
3101
+ moved.uidValidity
3102
+ );
3115
3103
  }
3116
3104
  }
3117
3105
  }
@@ -3155,8 +3143,13 @@ class Mailbox {
3155
3143
  };
3156
3144
  if (moved && moved.uidMap && moved.uidMap.size) {
3157
3145
  let moveMap = [];
3146
+ // One status read for the source folder, not one per message
3147
+ let sourceStatus = new Map();
3158
3148
  for (let [suid, tuid] of moved.uidMap) {
3159
- moveMap.push([await this.connection.packUid(this.path, suid), await this.connection.packUid(trashMailbox.path, tuid)]);
3149
+ moveMap.push([
3150
+ await this.connection.packUid(this.path, suid, sourceStatus),
3151
+ await this.connection.packUid(moved.destination || trashMailbox.path, tuid, null, moved.uidValidity)
3152
+ ]);
3160
3153
  }
3161
3154
  result.moved.idMap = moveMap;
3162
3155
  }
@@ -4,6 +4,7 @@ const { samePath } = require('../../utils/mailbox-path');
4
4
  const { connectionClosedError, connectionNotAvailableError, syncInterrupted } = require('./connection-errors');
5
5
  const crypto = require('crypto');
6
6
  const { createTransaction } = require('../../redis-operations');
7
+ const { isTransientRedisError } = require('../../utils/redis-errors');
7
8
  const { compareExisting, calculateFetchBackoff, readEnvValue, validUidValidity } = require('../../tools');
8
9
  const config = require('@zone-eu/wild-config');
9
10
  const { DEFAULT_FETCH_BATCH_SIZE, FETCH_RETRY_MAX_TIME, FETCH_RETRY_MIN_ATTEMPTS, MAILBOX_RESET_NOTIFY } = require('../../consts');
@@ -692,12 +693,11 @@ class SyncOperations {
692
693
 
693
694
  let changes;
694
695
  if (!storedMessage) {
695
- // New message
696
- let seq = await this.mailbox.entryListSet(messageData);
697
- if (seq) {
698
- // Queue for processing
699
- await this.connection.redis.zadd(this.mailbox.getNotificationsKey(), messageData.uid, notificationEntry(messageData));
700
- }
696
+ // New message: indexed and queued for processing in one transaction.
697
+ // Written apart, a queue write Redis refused after the index write
698
+ // went through left a message the retried FETCH found indexed, so
699
+ // it was never announced
700
+ await this.writeChunk([messageData], []);
701
701
  } else if ((changes = compareExisting(storedMessage.entry, messageData))) {
702
702
  // Existing message with changes
703
703
  let seq = await this.mailbox.entryListSet(messageData);
@@ -714,6 +714,13 @@ class SyncOperations {
714
714
  }
715
715
  fetchCompleted = true;
716
716
  } catch (err) {
717
+ if (isTransientRedisError(err)) {
718
+ // Redis refused to store what the FETCH returned, which fetching it
719
+ // again from the server cannot change; the pass ends and gives the
720
+ // mailbox lock back, and the caller runs it again once Redis recovers
721
+ // (Mailbox.schedulePartialSync())
722
+ throw err;
723
+ }
717
724
  try {
718
725
  // set failure flag
719
726
  await this.connection.redis.hSetExists(
@@ -538,9 +538,11 @@ class IMAPClient extends BaseClient {
538
538
  * @param {number} uid - Message UID
539
539
  * @param {Map} [statusCache] - Stored status by mailbox path, for a caller packing many UIDs
540
540
  * of the same folder (a listing): the status is read once instead of one HGETALL per message
541
+ * @param {bigint|number} [knownUidValidity] - The UIDVALIDITY the server just reported for the
542
+ * folder (COPYUID, APPENDUID); used instead of the stored one, which is then not read at all
541
543
  * @returns {string|false} Base64url encoded ID or false on error
542
544
  */
543
- async packUid(mailbox, uid, statusCache) {
545
+ async packUid(mailbox, uid, statusCache, knownUidValidity) {
544
546
  if (isNaN(uid) || !mailbox) {
545
547
  return false;
546
548
  }
@@ -551,13 +553,21 @@ class IMAPClient extends BaseClient {
551
553
 
552
554
  // Convert mailbox path to mailbox object if needed
553
555
  if (typeof mailbox === 'string') {
554
- if (this.mailboxes.has(normalizePath(mailbox))) {
555
- mailbox = this.mailboxes.get(normalizePath(mailbox));
556
- } else {
556
+ const registered = this.mailboxes.get(normalizePath(mailbox));
557
+ if (registered) {
558
+ mailbox = registered;
559
+ } else if (!validUidValidity(knownUidValidity)) {
557
560
  return false;
558
561
  }
559
562
  }
560
563
 
564
+ // The UIDVALIDITY the server just reported (COPYUID of a MOVE or COPY, APPENDUID of an
565
+ // APPEND) is current, where a stored one can be missing (a folder created moments ago and
566
+ // not registered or synced yet) or stale (a folder recreated since), so nothing is read
567
+ if (validUidValidity(knownUidValidity)) {
568
+ return await this.packMailboxUid(typeof mailbox === 'string' ? mailbox : mailbox.path, knownUidValidity, uid);
569
+ }
570
+
561
571
  // Get stored mailbox status including UID validity
562
572
  let storedStatus = statusCache?.get(mailbox.path);
563
573
  if (!storedStatus) {
@@ -609,10 +619,21 @@ class IMAPClient extends BaseClient {
609
619
  // Only a usable status is reused, so a folder whose status is missing is looked at again
610
620
  statusCache?.set(mailbox.path, storedStatus);
611
621
 
622
+ return await this.packMailboxUid(storedStatus.path, storedStatus.uidValidity, uid);
623
+ }
624
+
625
+ /**
626
+ * The message id of a UID in a folder whose path and UIDVALIDITY are known
627
+ * @param {string} path - Folder path as the server spells it
628
+ * @param {bigint|number} uidValidity
629
+ * @param {number} uid
630
+ * @returns {Promise<string|false>}
631
+ */
632
+ async packMailboxUid(path, uidValidity, uid) {
612
633
  // Pack UID validity and mailbox path into a buffer
613
634
  let uidValBuf = Buffer.alloc(8);
614
- uidValBuf.writeBigUInt64BE(storedStatus.uidValidity, 0);
615
- let mailboxBuf = Buffer.concat([uidValBuf, Buffer.from(storedStatus.path)]);
635
+ uidValBuf.writeBigUInt64BE(BigInt(uidValidity), 0);
636
+ let mailboxBuf = Buffer.concat([uidValBuf, Buffer.from(path)]);
616
637
 
617
638
  // Get or create a numeric mailbox ID for efficient storage
618
639
  let mailboxId;
@@ -3028,7 +3049,7 @@ class IMAPClient extends BaseClient {
3028
3049
  let destinationPath = uploadResponse.destination || uploadResponse.path || data.path;
3029
3050
 
3030
3051
  if (uploadResponse.uid) {
3031
- response.id = await this.packUid(destinationPath, uploadResponse.uid);
3052
+ response.id = await this.packUid(destinationPath, uploadResponse.uid, null, uploadResponse.uidValidity);
3032
3053
  }
3033
3054
 
3034
3055
  response.path = destinationPath;
@@ -0,0 +1,162 @@
1
+ 'use strict';
2
+
3
+ // The steps of new-message processing that are the same for every backend. Mailbox.processNew()
4
+ // (IMAP) and BaseClient.processNew() (Gmail API, MS Graph) differ in how they fetch content - IMAP
5
+ // streams parts with size caps and rethrows a lost connection, the API clients ask for attachments
6
+ // by id - but what they do with that content has to agree, and two hand-kept copies had already
7
+ // drifted (the web-safe flag was set even when no web-safe copy came out, a classification failure
8
+ // was an error on one path and a warning on the other). Those shared decisions live here.
9
+
10
+ const { camelCaseComplaint } = require('../arf-detect');
11
+ const { embedCidImages } = require('../tools');
12
+ const { MESSAGE_NEW_NOTIFY, EMAIL_BOUNCE_NOTIFY, EMAIL_COMPLAINT_NOTIFY } = require('../consts');
13
+
14
+ const BOUNCE_CLASSIFY_TIMEOUT = 2 * 60 * 1000;
15
+
16
+ /**
17
+ * Whether a parsed bounce reports a failed delivery. A DSN also reports delivered, delayed,
18
+ * relayed and expanded recipients, and none of those is a bounce to store or to fire emailBounce
19
+ * for; a delayed DSN that landed in Junk used to reach the bounce path with its action set
20
+ * @param {Object} bounce - Result of bounceDetect()
21
+ * @returns {boolean}
22
+ */
23
+ function isFailedDelivery(bounce) {
24
+ return !!bounce && typeof bounce.action === 'string' && bounce.action.trim().toLowerCase() === 'failed' && !!bounce.recipient && !!bounce.messageId;
25
+ }
26
+
27
+ /**
28
+ * Whether a new message is one the account sent itself, which is never reported as new: it is
29
+ * listed in a Sent folder, resolved to the Sent special use, or (Gmail) carries the \\Sent label,
30
+ * even next to \\Inbox
31
+ * @param {Object} messageData
32
+ * @param {String} [folderSpecialUse] - special use of the folder the message was found in
33
+ * @returns {Boolean}
34
+ */
35
+ function isOwnSent(messageData, folderSpecialUse) {
36
+ return (
37
+ folderSpecialUse === '\\Sent' ||
38
+ messageData.messageSpecialUse === '\\Sent' ||
39
+ !!(Array.isArray(messageData.labels) && messageData.labels.includes('\\Sent'))
40
+ );
41
+ }
42
+
43
+ /**
44
+ * Adds the classifier's verdict to a detected bounce's response. Best effort: a failed
45
+ * classification leaves the bounce as it was.
46
+ * @param {Object} bounce - bounceDetect() result, changed in place
47
+ * @param {Function} call - RPC to the main thread, where the classifier runs
48
+ * @param {Object} logger
49
+ */
50
+ async function classifyBounce(bounce, call, logger) {
51
+ const message = bounce?.response?.message;
52
+ if (!message) {
53
+ return;
54
+ }
55
+ try {
56
+ const bounceType = await call({ cmd: 'bounceClassify', data: { message }, timeout: BOUNCE_CLASSIFY_TIMEOUT });
57
+ if (bounceType?.label) {
58
+ bounce.response.category = bounceType.label;
59
+ }
60
+ if (bounceType?.action) {
61
+ bounce.response.recommendedAction = bounceType.action;
62
+ }
63
+ if (bounceType?.blocklist) {
64
+ bounce.response.blocklist = bounceType.blocklist;
65
+ }
66
+ if (bounceType?.retryAfter) {
67
+ bounce.response.retryAfter = bounceType.retryAfter;
68
+ }
69
+ } catch (err) {
70
+ // ignore, just do not include this information
71
+ logger.warn({ msg: 'Failed to classify bounce response', bounceResponse: message, err });
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Marks a message that is a failed-delivery bounce and returns the payload of its bounce event
77
+ * @param {Object} bounce - bounceDetect() result
78
+ * @param {Object} messageData - the new message, changed in place
79
+ * @returns {Object|undefined} the emailBounce payload, or nothing when it is no bounce
80
+ */
81
+ function bounceNotification(bounce, messageData) {
82
+ if (!isFailedDelivery(bounce)) {
83
+ return undefined;
84
+ }
85
+ messageData.isBounce = true;
86
+ messageData.relatedMessageId = bounce.messageId;
87
+ return Object.assign({ bounceMessage: messageData.id }, bounce);
88
+ }
89
+
90
+ /**
91
+ * Marks a message that is an abuse report naming its recipient and returns the payload of its
92
+ * complaint event
93
+ * @param {Object} report - arfDetect() result
94
+ * @param {Object} messageData - the new message, changed in place
95
+ * @returns {Object|undefined} the emailComplained payload, or nothing when it is no usable report
96
+ */
97
+ function complaintNotification(report, messageData) {
98
+ if (!report || !report.arf || !report.arf['original-rcpt-to'] || !report.arf['original-rcpt-to'].length) {
99
+ return undefined;
100
+ }
101
+ const complaint = camelCaseComplaint(report);
102
+ messageData.isComplaint = true;
103
+ if (complaint.headers && complaint.headers.messageId) {
104
+ messageData.relatedMessageId = complaint.headers.messageId;
105
+ }
106
+ return Object.assign({ complaintMessage: messageData.id }, complaint);
107
+ }
108
+
109
+ /**
110
+ * Replaces the Content-ID references of the HTML and of its web-safe copy with data URIs. The
111
+ * web-safe copy is what webhooks deliver in place of the HTML, so it gets the same treatment.
112
+ * @param {Object} text - messageData.text, changed in place
113
+ * @param {Map} attachmentList - contentId -> { attachment, content } (content base64 or null)
114
+ */
115
+ function embedInlineImages(text, attachmentList) {
116
+ if (!attachmentList.size) {
117
+ return;
118
+ }
119
+ const embedImages = html =>
120
+ embedCidImages(html, contentId => {
121
+ const { attachment, content } = attachmentList.get(contentId) || {};
122
+ return content && { contentType: attachment.contentType, content };
123
+ });
124
+
125
+ text.html = embedImages(text.html);
126
+ if (text._generatedHtml) {
127
+ text._generatedHtml = embedImages(text._generatedHtml);
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Flags the text as web-safe only when a web-safe copy was produced: the webhook delivery swaps the
133
+ * HTML for that copy only when there is one, so a flag without it would mark the raw HTML safe
134
+ * @param {Object} text - messageData.text, changed in place
135
+ */
136
+ function markWebSafe(text) {
137
+ if (text._generatedHtml) {
138
+ text.webSafe = true;
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Sends messageNew, then the bounce and complaint events it carries, in that order: a receiver
144
+ * sees the message before the events that refer to it
145
+ * @param {Function} notify - (target, event, data) => Promise
146
+ * @param {Object} target - what messageNew is reported against (a mailbox, or a path and special use)
147
+ * @param {Object} messageData
148
+ * @param {Object} [related]
149
+ * @param {Object} [related.bounceNotifyInfo]
150
+ * @param {Object} [related.complaintNotifyInfo]
151
+ */
152
+ async function notifyNewMessage(notify, target, messageData, { bounceNotifyInfo, complaintNotifyInfo } = {}) {
153
+ await notify(target, MESSAGE_NEW_NOTIFY, messageData);
154
+ if (bounceNotifyInfo) {
155
+ await notify(false, EMAIL_BOUNCE_NOTIFY, bounceNotifyInfo);
156
+ }
157
+ if (complaintNotifyInfo) {
158
+ await notify(false, EMAIL_COMPLAINT_NOTIFY, complaintNotifyInfo);
159
+ }
160
+ }
161
+
162
+ module.exports = { isFailedDelivery, isOwnSent, classifyBounce, bounceNotification, complaintNotification, embedInlineImages, markWebSafe, notifyNewMessage };
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { accountDataKey } = require('../redis-keys');
4
+ const { isOwnSent } = require('./new-message-steps');
3
5
  const { BaseClient, metricsMeta } = require('./base-client');
4
6
  const { isSafePathSegment } = require('../utils/provider-id');
5
7
  const { isTransientCredentialError } = require('./credential-errors');
@@ -2912,7 +2914,7 @@ class OutlookClient extends BaseClient {
2912
2914
  * Get Redis key for account data
2913
2915
  */
2914
2916
  getAccountKey() {
2915
- return `${REDIS_PREFIX}iad:${this.account}`;
2917
+ return accountDataKey(this.account);
2916
2918
  }
2917
2919
 
2918
2920
  /**
@@ -4637,7 +4639,7 @@ class OutlookClient extends BaseClient {
4637
4639
  }
4638
4640
 
4639
4641
  // check if we have seen this message before or not (approximate estimation using HyperLogLog)
4640
- messageData.seemsLikeNew = messageData.messageSpecialUse !== '\\Sent' && !!(await this.redis.pfadd(this.getSeenMessagesKey(), messageData.messageId));
4642
+ messageData.seemsLikeNew = !isOwnSent(messageData) && !!(await this.redis.pfadd(this.getSeenMessagesKey(), messageData.messageId));
4641
4643
 
4642
4644
  return messageData;
4643
4645
  }
@@ -202,9 +202,13 @@ async function getOverridableSettings(...keys) {
202
202
  });
203
203
  }
204
204
 
205
+ // Taken before awaiting any of them: a failed read deletes its entries once it settles, and
206
+ // reading the cache after the first await then found the next key gone (a TypeError that failed
207
+ // whatever asked, a webhook being queued for one)
208
+ const pending = keys.map(key => [key, cache.get(key).value]);
205
209
  const result = {};
206
- for (const key of keys) {
207
- result[key] = await cache.get(key).value;
210
+ for (const [key, value] of pending) {
211
+ result[key] = await value;
208
212
  }
209
213
  return result;
210
214
  }
@@ -5,8 +5,9 @@
5
5
  // tested without booting the BullMQ worker; the worker builds this with its own collaborators, a
6
6
  // test with fakes.
7
7
 
8
+ const { accountDataKey } = require('./redis-keys');
8
9
  const defaultLogger = require('./logger');
9
- const { REDIS_PREFIX, DEFAULT_EXPORT_MAX_MESSAGE_SIZE, DEFAULT_EXPORT_MAX_MESSAGES, DEFAULT_EXPORT_MAX_SIZE } = require('./consts');
10
+ const { DEFAULT_EXPORT_MAX_MESSAGE_SIZE, DEFAULT_EXPORT_MAX_MESSAGES, DEFAULT_EXPORT_MAX_SIZE } = require('./consts');
10
11
  const {
11
12
  Export: DefaultExport,
12
13
  isTransientError,
@@ -134,7 +135,7 @@ function finalizeOutput(output) {
134
135
  }
135
136
 
136
137
  // One field is enough to tell whether the account still exists; reading the whole hash was not
137
- const accountExists = async (redis, account) => (await redis.hexists(`${REDIS_PREFIX}iad:${account}`, 'account')) === 1;
138
+ const accountExists = async (redis, account) => (await redis.hexists(accountDataKey(account), 'account')) === 1;
138
139
 
139
140
  /**
140
141
  * @param {Object} deps