emailengine-app 2.87.0 → 2.87.1

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 (60) hide show
  1. package/.ncurc.js +2 -4
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +19 -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/email-client/base-client.js +23 -107
  17. package/lib/email-client/gmail-client.js +7 -4
  18. package/lib/email-client/imap/mailbox.js +89 -96
  19. package/lib/email-client/imap/sync-operations.js +13 -6
  20. package/lib/email-client/imap-client.js +28 -7
  21. package/lib/email-client/new-message-steps.js +162 -0
  22. package/lib/email-client/outlook-client.js +4 -2
  23. package/lib/env-setting-overrides.js +6 -2
  24. package/lib/export-worker.js +3 -2
  25. package/lib/export.js +43 -4
  26. package/lib/get-boolean.js +38 -0
  27. package/lib/health-probe.js +71 -0
  28. package/lib/imapproxy/imap-server.js +4 -55
  29. package/lib/net-tos-guard.js +42 -0
  30. package/lib/oauth2-apps.js +2 -1
  31. package/lib/read-env-value.js +19 -7
  32. package/lib/redis-keys.js +19 -0
  33. package/lib/redis-operations.js +7 -3
  34. package/lib/security-headers.js +18 -0
  35. package/lib/session-default.js +50 -0
  36. package/lib/settings.js +2 -1
  37. package/lib/stream-encrypt.js +71 -20
  38. package/lib/sub-script.js +8 -2
  39. package/lib/submit-lock.js +84 -0
  40. package/lib/submit-processor.js +283 -0
  41. package/lib/templates.js +6 -3
  42. package/lib/tls/context.js +2 -16
  43. package/lib/tools.js +8 -30
  44. package/lib/utils/redis-errors.js +44 -0
  45. package/lib/webhook-delivery.js +3 -4
  46. package/lib/worker-rpc-error.js +10 -5
  47. package/lib/worker-rpc.js +138 -0
  48. package/package.json +17 -19
  49. package/sbom.json +370 -1446
  50. package/server.js +6 -5
  51. package/static/css/flyonui.css +2 -2
  52. package/static/licenses.html +253 -1366
  53. package/translations/messages.pot +16 -16
  54. package/workers/api.js +41 -465
  55. package/workers/export.js +14 -55
  56. package/workers/imap-proxy.js +5 -18
  57. package/workers/imap.js +27 -49
  58. package/workers/smtp.js +7 -69
  59. package/workers/submit.js +21 -279
  60. package/workers/webhooks.js +7 -72
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { accountDataKey } = require('../redis-keys');
3
4
  const { threadId: workerThreadId } = require('worker_threads');
4
5
  const crypto = require('crypto');
5
6
  const logger = require('../logger');
@@ -16,10 +17,20 @@ const { addTrackers } = require('../add-trackers');
16
17
  const { getRawEmail } = require('../get-raw-email');
17
18
  const { getTemplate } = require('@postalsys/templates');
18
19
  const { deepEqual } = require('assert');
19
- const { arfDetect, camelCaseComplaint, FEEDBACK_REPORT_TYPE, ORIGINAL_MESSAGE_TYPES, COMPLAINT_ATTACHMENT_TYPES } = require('../arf-detect');
20
+ const { arfDetect, FEEDBACK_REPORT_TYPE, ORIGINAL_MESSAGE_TYPES, COMPLAINT_ATTACHMENT_TYPES } = require('../arf-detect');
21
+ const {
22
+ isFailedDelivery,
23
+ classifyBounce,
24
+ bounceNotification,
25
+ complaintNotification,
26
+ embedInlineImages,
27
+ markWebSafe,
28
+ notifyNewMessage
29
+ } = require('./new-message-steps');
20
30
  const { createTransaction } = require('../redis-operations');
21
31
  const { ACCOUNT_STATES } = require('../account/account-state');
22
32
  const { credentialErrorStatus, isTransientCredentialError, resolveAuthServerCredentials } = require('./credential-errors');
33
+ const { isTransientRedisError } = require('../utils/redis-errors');
23
34
  const { parseMessage } = require('../parse-message');
24
35
  const libmime = require('libmime');
25
36
  const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS } = require('../bounce-detect');
@@ -55,8 +66,7 @@ const {
55
66
  emitChangeEvent,
56
67
  getDateBuckets,
57
68
  useAuthServerForOAuth2,
58
- collectCidReferences,
59
- embedCidImages
69
+ collectCidReferences
60
70
  } = require('../tools');
61
71
  const { loadNotifyAttachments, API_ATTACHMENT_CONCURRENCY } = require('../notify-attachments');
62
72
  const { TRACKING_SETTINGS, needsTrackingSettings, resolveTracking } = require('../utils/tracking-settings');
@@ -67,12 +77,9 @@ const {
67
77
  AUTH_SUCCESS_NOTIFY,
68
78
  ACCOUNT_INITIALIZED_NOTIFY,
69
79
  REDIS_PREFIX,
70
- MESSAGE_NEW_NOTIFY,
71
- EMAIL_BOUNCE_NOTIFY,
72
80
  DEFAULT_DELIVERY_ATTEMPTS,
73
81
  MIME_BOUNDARY_PREFIX,
74
82
  DEFAULT_DOWNLOAD_CHUNK_SIZE,
75
- EMAIL_COMPLAINT_NOTIFY,
76
83
  MAX_INLINE_ATTACHMENT_SIZE,
77
84
  MAIL_MERGE_CONCURRENCY,
78
85
  DEFAULT_MAX_IMAP_AUTH_FAILURE_TIME,
@@ -229,17 +236,6 @@ function buildReferences(referencedMessage) {
229
236
  return references;
230
237
  }
231
238
 
232
- /**
233
- * Whether a parsed bounce reports a failed delivery. A DSN also reports delivered, delayed,
234
- * relayed and expanded recipients, and none of those is a bounce to store or to fire emailBounce
235
- * for; a delayed DSN that landed in Junk used to reach the bounce path with its action set
236
- * @param {Object} bounce - Result of bounceDetect()
237
- * @returns {boolean}
238
- */
239
- function isFailedDelivery(bounce) {
240
- return !!bounce && typeof bounce.action === 'string' && bounce.action.trim().toLowerCase() === 'failed' && !!bounce.recipient && !!bounce.messageId;
241
- }
242
-
243
239
  // Finds the attachments of a referenced message whose content id the given HTML links to
244
240
  function findReferencedCidAttachments(html, attachments) {
245
241
  let cidAttachments = [];
@@ -577,7 +573,9 @@ class BaseClient {
577
573
  const messageIds = event.type === 'created' ? [typeof event.message === 'string' ? event.message : event.message?.id] : undefined;
578
574
  const logEntry = { account: this.account, eventType: event.type, messageIds, attempt: nextAttempt.attempt, err };
579
575
 
580
- if (delay && isTransientCredentialError(err)) {
576
+ // A step Redis refused for now (OOM, LOADING, a failover) is deferred like a failure of the
577
+ // service, since the deferral itself may still get past it
578
+ if (delay && (isTransientCredentialError(err) || isTransientRedisError(err))) {
581
579
  const dueTime = Date.now() + delay;
582
580
  // The change being retried right now is already stored as this attempt (its lease),
583
581
  // so moving that entry is the deferral
@@ -758,7 +756,7 @@ class BaseClient {
758
756
  // Redis key generators for different data types
759
757
 
760
758
  getAccountKey() {
761
- return `${REDIS_PREFIX}iad:${this.account}`;
759
+ return accountDataKey(this.account);
762
760
  }
763
761
 
764
762
  getMailboxListKey() {
@@ -3052,19 +3050,7 @@ class BaseClient {
3052
3050
  // Parse ARF report
3053
3051
  const report = await arfDetect(messageData);
3054
3052
 
3055
- if (report && report.arf && report.arf['original-rcpt-to'] && report.arf['original-rcpt-to'].length) {
3056
- // can send report
3057
- let complaint = camelCaseComplaint(report);
3058
-
3059
- complaintNotifyInfo = Object.assign({ complaintMessage: messageData.id }, complaint);
3060
-
3061
- messageData.isComplaint = true;
3062
-
3063
- // Link to original message
3064
- if (complaint.headers && complaint.headers.messageId) {
3065
- messageData.relatedMessageId = complaint.headers.messageId;
3066
- }
3067
- }
3053
+ complaintNotifyInfo = complaintNotification(report, messageData);
3068
3054
  } catch (err) {
3069
3055
  this.logger.error({
3070
3056
  msg: 'Failed to process ARF',
@@ -3108,43 +3094,8 @@ class BaseClient {
3108
3094
  if (content) {
3109
3095
  let bounce = await bounceDetect(content);
3110
3096
 
3111
- if (bounce?.response?.message) {
3112
- try {
3113
- let bounceType = await this.call({
3114
- cmd: 'bounceClassify',
3115
- data: {
3116
- message: bounce?.response?.message
3117
- },
3118
- timeout: 2 * 60 * 1000
3119
- });
3120
- if (bounceType?.label) {
3121
- bounce.response.category = bounceType.label;
3122
- }
3123
- if (bounceType?.action) {
3124
- bounce.response.recommendedAction = bounceType.action;
3125
- }
3126
- if (bounceType?.blocklist) {
3127
- bounce.response.blocklist = bounceType.blocklist;
3128
- }
3129
- if (bounceType?.retryAfter) {
3130
- bounce.response.retryAfter = bounceType.retryAfter;
3131
- }
3132
- } catch (err) {
3133
- // ignore, just do not include this information
3134
- this.logger.warn({
3135
- msg: 'Failed to classify bounce response',
3136
- bounceResponse: bounce?.response?.message,
3137
- err
3138
- });
3139
- }
3140
- }
3141
-
3142
- if (isFailedDelivery(bounce)) {
3143
- bounceNotifyInfo = Object.assign({ bounceMessage: messageData.id }, bounce);
3144
-
3145
- messageData.isBounce = true;
3146
- messageData.relatedMessageId = bounce.messageId;
3147
- }
3097
+ await classifyBounce(bounce, this.call, this.logger);
3098
+ bounceNotifyInfo = bounceNotification(bounce, messageData);
3148
3099
 
3149
3100
  this.logger.debug({
3150
3101
  msg: 'Detected bounce message',
@@ -3236,25 +3187,10 @@ class BaseClient {
3236
3187
  }
3237
3188
  }
3238
3189
 
3239
- // Replace CID references with data URIs. The web safe copy is what webhooks deliver
3240
- // in place of the HTML, so it gets the same treatment
3241
- if (attachmentList.size) {
3242
- const embedImages = html =>
3243
- embedCidImages(html, contentId => {
3244
- let { attachment, content } = attachmentList.get(contentId) || {};
3245
- return content && { contentType: attachment.contentType, content };
3246
- });
3247
-
3248
- messageData.text.html = embedImages(messageData.text.html);
3249
- if (messageData.text._generatedHtml) {
3250
- messageData.text._generatedHtml = embedImages(messageData.text._generatedHtml);
3251
- }
3252
- }
3190
+ embedInlineImages(messageData.text, attachmentList);
3253
3191
  }
3254
3192
 
3255
- if (messageData.text._generatedHtml) {
3256
- messageData.text.webSafe = true;
3257
- }
3193
+ markWebSafe(messageData.text);
3258
3194
  }
3259
3195
 
3260
3196
  // Narrow the headers to what the caller asked for. This runs last: the checks and the AI
@@ -3272,26 +3208,7 @@ class BaseClient {
3272
3208
  messageData.path = undefined;
3273
3209
  }
3274
3210
 
3275
- // Send new message notification
3276
- await this.notify(
3277
- {
3278
- path,
3279
- specialUse
3280
- },
3281
- MESSAGE_NEW_NOTIFY,
3282
- messageData
3283
- );
3284
-
3285
- // Send additional notifications for bounces and complaints
3286
- if (bounceNotifyInfo) {
3287
- // send bounce notification _after_ bounce email notification
3288
- await this.notify(false, EMAIL_BOUNCE_NOTIFY, bounceNotifyInfo);
3289
- }
3290
-
3291
- if (complaintNotifyInfo) {
3292
- // send complaint notification _after_ complaint email notification
3293
- await this.notify(false, EMAIL_COMPLAINT_NOTIFY, complaintNotifyInfo);
3294
- }
3211
+ await notifyNewMessage(this.notify.bind(this), { path, specialUse }, messageData, { bounceNotifyInfo, complaintNotifyInfo });
3295
3212
  }
3296
3213
 
3297
3214
  /**
@@ -3909,7 +3826,6 @@ module.exports = {
3909
3826
  metricsMeta: postMetrics,
3910
3827
  applyReferenceRecipients,
3911
3828
  buildReferences,
3912
- isFailedDelivery,
3913
3829
  markRejectedAccessToken,
3914
3830
  renewRejectedAccessToken
3915
3831
  };
@@ -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 { Account } = require('../account');
4
6
  const { oauth2Apps } = require('../oauth2-apps');
5
7
  const { checkAccountScopes, isSendOnlyByScopes } = require('../oauth/scope-checker');
@@ -2029,7 +2031,7 @@ class GmailClient extends BaseClient {
2029
2031
  // PRIVATE METHODS
2030
2032
 
2031
2033
  getAccountKey() {
2032
- return `${REDIS_PREFIX}iad:${this.account}`;
2034
+ return accountDataKey(this.account);
2033
2035
  }
2034
2036
 
2035
2037
  async getAccount() {
@@ -3431,9 +3433,6 @@ class GmailClient extends BaseClient {
3431
3433
  return;
3432
3434
  }
3433
3435
 
3434
- // All new emails are "new" as message movement between folders is reported as label changes
3435
- messageData.seemsLikeNew = true;
3436
-
3437
3436
  if (eventEntry.category) {
3438
3437
  messageData.category = eventEntry.category;
3439
3438
  }
@@ -3446,6 +3445,10 @@ class GmailClient extends BaseClient {
3446
3445
  }
3447
3446
  }
3448
3447
 
3448
+ // Moving a message between folders is a label change in Gmail and never reaches this path,
3449
+ // so there is no seen-before check here. What is not new is mail the account sent itself
3450
+ messageData.seemsLikeNew = !isOwnSent(messageData);
3451
+
3449
3452
  return messageData;
3450
3453
  }
3451
3454
 
@@ -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(