emailengine-app 2.86.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 (74) hide show
  1. package/.ncurc.js +2 -4
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +42 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +5 -6
  6. package/README.md +4 -0
  7. package/bin/emailengine.js +2 -4
  8. package/bin/healthcheck.js +20 -0
  9. package/data/google-crawlers.json +1 -1
  10. package/data/public_suffix_list.dat +3 -7
  11. package/lib/account/auth-failure-backfill.js +3 -2
  12. package/lib/account/expected-identity.js +2 -2
  13. package/lib/account.js +101 -39
  14. package/lib/api-listener.js +40 -0
  15. package/lib/api-routes/account-routes.js +14 -7
  16. package/lib/api-routes/submit-routes.js +21 -2
  17. package/lib/api-token-auth.js +406 -0
  18. package/lib/autodetect-imap-settings.js +36 -3
  19. package/lib/consts.js +5 -0
  20. package/lib/email-client/base-client.js +27 -109
  21. package/lib/email-client/gmail-client.js +15 -4
  22. package/lib/email-client/imap/mailbox.js +97 -97
  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 +10 -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/field-usage.js +1 -1
  31. package/lib/get-boolean.js +38 -0
  32. package/lib/get-raw-email.js +10 -1
  33. package/lib/health-probe.js +71 -0
  34. package/lib/imapproxy/imap-server.js +4 -55
  35. package/lib/net-tos-guard.js +42 -0
  36. package/lib/oauth/gmail.js +54 -29
  37. package/lib/oauth2-apps.js +2 -1
  38. package/lib/otp.js +66 -0
  39. package/lib/read-env-value.js +19 -7
  40. package/lib/redis-keys.js +19 -0
  41. package/lib/redis-operations.js +7 -3
  42. package/lib/schemas.js +62 -2
  43. package/lib/security-headers.js +18 -0
  44. package/lib/session-default.js +50 -0
  45. package/lib/settings.js +2 -1
  46. package/lib/stream-encrypt.js +71 -20
  47. package/lib/sub-script.js +8 -2
  48. package/lib/submit-lock.js +84 -0
  49. package/lib/submit-processor.js +283 -0
  50. package/lib/swagger-options.js +2 -2
  51. package/lib/templates.js +6 -3
  52. package/lib/tls/context.js +2 -16
  53. package/lib/tools.js +8 -30
  54. package/lib/utils/redis-errors.js +44 -0
  55. package/lib/webhook-delivery.js +3 -4
  56. package/lib/webhooks.js +5 -0
  57. package/lib/worker-rpc-error.js +10 -5
  58. package/lib/worker-rpc.js +138 -0
  59. package/package.json +25 -26
  60. package/sbom.json +660 -1736
  61. package/server.js +6 -5
  62. package/static/css/flyonui.css +2 -2
  63. package/static/js/ee-client.js +650 -196
  64. package/static/licenses.html +280 -1393
  65. package/translations/messages.pot +16 -16
  66. package/views/layout/app.hbs +9 -6
  67. package/views/legal.hbs +8 -0
  68. package/workers/api.js +51 -474
  69. package/workers/export.js +14 -55
  70. package/workers/imap-proxy.js +5 -18
  71. package/workers/imap.js +27 -49
  72. package/workers/smtp.js +7 -69
  73. package/workers/submit.js +21 -279
  74. 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,16 +17,27 @@ 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');
26
37
  const { collectCalendarEvents } = require('../calendar-event');
27
38
  const { llmPreProcess, summaryFetchHeaders, summaryProvider } = require('../llm-pre-process');
28
39
  const { notificationHeaderFields, narrowHeaders } = require('../utils/header-map');
40
+ const { notifyHeadersIncludeOtp, OTP_FETCH_HEADERS } = require('../otp');
29
41
  const { mapConcurrent } = require('../utils/map-concurrent');
30
42
  const { oauth2Apps } = require('../oauth2-apps');
31
43
  const { Account } = require('../account');
@@ -54,8 +66,7 @@ const {
54
66
  emitChangeEvent,
55
67
  getDateBuckets,
56
68
  useAuthServerForOAuth2,
57
- collectCidReferences,
58
- embedCidImages
69
+ collectCidReferences
59
70
  } = require('../tools');
60
71
  const { loadNotifyAttachments, API_ATTACHMENT_CONCURRENCY } = require('../notify-attachments');
61
72
  const { TRACKING_SETTINGS, needsTrackingSettings, resolveTracking } = require('../utils/tracking-settings');
@@ -66,12 +77,9 @@ const {
66
77
  AUTH_SUCCESS_NOTIFY,
67
78
  ACCOUNT_INITIALIZED_NOTIFY,
68
79
  REDIS_PREFIX,
69
- MESSAGE_NEW_NOTIFY,
70
- EMAIL_BOUNCE_NOTIFY,
71
80
  DEFAULT_DELIVERY_ATTEMPTS,
72
81
  MIME_BOUNDARY_PREFIX,
73
82
  DEFAULT_DOWNLOAD_CHUNK_SIZE,
74
- EMAIL_COMPLAINT_NOTIFY,
75
83
  MAX_INLINE_ATTACHMENT_SIZE,
76
84
  MAIL_MERGE_CONCURRENCY,
77
85
  DEFAULT_MAX_IMAP_AUTH_FAILURE_TIME,
@@ -228,17 +236,6 @@ function buildReferences(referencedMessage) {
228
236
  return references;
229
237
  }
230
238
 
231
- /**
232
- * Whether a parsed bounce reports a failed delivery. A DSN also reports delivered, delayed,
233
- * relayed and expanded recipients, and none of those is a bounce to store or to fire emailBounce
234
- * for; a delayed DSN that landed in Junk used to reach the bounce path with its action set
235
- * @param {Object} bounce - Result of bounceDetect()
236
- * @returns {boolean}
237
- */
238
- function isFailedDelivery(bounce) {
239
- return !!bounce && typeof bounce.action === 'string' && bounce.action.trim().toLowerCase() === 'failed' && !!bounce.recipient && !!bounce.messageId;
240
- }
241
-
242
239
  // Finds the attachments of a referenced message whose content id the given HTML links to
243
240
  function findReferencedCidAttachments(html, attachments) {
244
241
  let cidAttachments = [];
@@ -576,7 +573,9 @@ class BaseClient {
576
573
  const messageIds = event.type === 'created' ? [typeof event.message === 'string' ? event.message : event.message?.id] : undefined;
577
574
  const logEntry = { account: this.account, eventType: event.type, messageIds, attempt: nextAttempt.attempt, err };
578
575
 
579
- 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))) {
580
579
  const dueTime = Date.now() + delay;
581
580
  // The change being retried right now is already stored as this attempt (its lease),
582
581
  // so moving that entry is the deferral
@@ -757,7 +756,7 @@ class BaseClient {
757
756
  // Redis key generators for different data types
758
757
 
759
758
  getAccountKey() {
760
- return `${REDIS_PREFIX}iad:${this.account}`;
759
+ return accountDataKey(this.account);
761
760
  }
762
761
 
763
762
  getMailboxListKey() {
@@ -1836,7 +1835,7 @@ class BaseClient {
1836
1835
  messageCopy.to = [mailMergeEntry.to];
1837
1836
 
1838
1837
  // Apply recipient-specific overrides
1839
- for (let key of ['messageId', 'sendAt']) {
1838
+ for (let key of ['messageId', 'sendAt', 'otp']) {
1840
1839
  if (mailMergeEntry[key]) {
1841
1840
  messageCopy[key] = mailMergeEntry[key];
1842
1841
  }
@@ -3012,7 +3011,8 @@ class BaseClient {
3012
3011
  // while summaries are on. Skipped when the setting already asks for every header
3013
3012
  if (messageFetchOptions.headers !== true) {
3014
3013
  const summaryHeaders = (await llmPreProcess.getPreProcessHandler()) ? summaryFetchHeaders(this.summaryProvider()) : [];
3015
- messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers, summaryHeaders);
3014
+ const otpHeaders = notifyHeadersIncludeOtp(notifyHeaders) ? OTP_FETCH_HEADERS : [];
3015
+ messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers, summaryHeaders.concat(otpHeaders));
3016
3016
  }
3017
3017
 
3018
3018
  return messageFetchOptions;
@@ -3050,19 +3050,7 @@ class BaseClient {
3050
3050
  // Parse ARF report
3051
3051
  const report = await arfDetect(messageData);
3052
3052
 
3053
- if (report && report.arf && report.arf['original-rcpt-to'] && report.arf['original-rcpt-to'].length) {
3054
- // can send report
3055
- let complaint = camelCaseComplaint(report);
3056
-
3057
- complaintNotifyInfo = Object.assign({ complaintMessage: messageData.id }, complaint);
3058
-
3059
- messageData.isComplaint = true;
3060
-
3061
- // Link to original message
3062
- if (complaint.headers && complaint.headers.messageId) {
3063
- messageData.relatedMessageId = complaint.headers.messageId;
3064
- }
3065
- }
3053
+ complaintNotifyInfo = complaintNotification(report, messageData);
3066
3054
  } catch (err) {
3067
3055
  this.logger.error({
3068
3056
  msg: 'Failed to process ARF',
@@ -3106,43 +3094,8 @@ class BaseClient {
3106
3094
  if (content) {
3107
3095
  let bounce = await bounceDetect(content);
3108
3096
 
3109
- if (bounce?.response?.message) {
3110
- try {
3111
- let bounceType = await this.call({
3112
- cmd: 'bounceClassify',
3113
- data: {
3114
- message: bounce?.response?.message
3115
- },
3116
- timeout: 2 * 60 * 1000
3117
- });
3118
- if (bounceType?.label) {
3119
- bounce.response.category = bounceType.label;
3120
- }
3121
- if (bounceType?.action) {
3122
- bounce.response.recommendedAction = bounceType.action;
3123
- }
3124
- if (bounceType?.blocklist) {
3125
- bounce.response.blocklist = bounceType.blocklist;
3126
- }
3127
- if (bounceType?.retryAfter) {
3128
- bounce.response.retryAfter = bounceType.retryAfter;
3129
- }
3130
- } catch (err) {
3131
- // ignore, just do not include this information
3132
- this.logger.warn({
3133
- msg: 'Failed to classify bounce response',
3134
- bounceResponse: bounce?.response?.message,
3135
- err
3136
- });
3137
- }
3138
- }
3139
-
3140
- if (isFailedDelivery(bounce)) {
3141
- bounceNotifyInfo = Object.assign({ bounceMessage: messageData.id }, bounce);
3142
-
3143
- messageData.isBounce = true;
3144
- messageData.relatedMessageId = bounce.messageId;
3145
- }
3097
+ await classifyBounce(bounce, this.call, this.logger);
3098
+ bounceNotifyInfo = bounceNotification(bounce, messageData);
3146
3099
 
3147
3100
  this.logger.debug({
3148
3101
  msg: 'Detected bounce message',
@@ -3234,25 +3187,10 @@ class BaseClient {
3234
3187
  }
3235
3188
  }
3236
3189
 
3237
- // Replace CID references with data URIs. The web safe copy is what webhooks deliver
3238
- // in place of the HTML, so it gets the same treatment
3239
- if (attachmentList.size) {
3240
- const embedImages = html =>
3241
- embedCidImages(html, contentId => {
3242
- let { attachment, content } = attachmentList.get(contentId) || {};
3243
- return content && { contentType: attachment.contentType, content };
3244
- });
3245
-
3246
- messageData.text.html = embedImages(messageData.text.html);
3247
- if (messageData.text._generatedHtml) {
3248
- messageData.text._generatedHtml = embedImages(messageData.text._generatedHtml);
3249
- }
3250
- }
3190
+ embedInlineImages(messageData.text, attachmentList);
3251
3191
  }
3252
3192
 
3253
- if (messageData.text._generatedHtml) {
3254
- messageData.text.webSafe = true;
3255
- }
3193
+ markWebSafe(messageData.text);
3256
3194
  }
3257
3195
 
3258
3196
  // Narrow the headers to what the caller asked for. This runs last: the checks and the AI
@@ -3270,26 +3208,7 @@ class BaseClient {
3270
3208
  messageData.path = undefined;
3271
3209
  }
3272
3210
 
3273
- // Send new message notification
3274
- await this.notify(
3275
- {
3276
- path,
3277
- specialUse
3278
- },
3279
- MESSAGE_NEW_NOTIFY,
3280
- messageData
3281
- );
3282
-
3283
- // Send additional notifications for bounces and complaints
3284
- if (bounceNotifyInfo) {
3285
- // send bounce notification _after_ bounce email notification
3286
- await this.notify(false, EMAIL_BOUNCE_NOTIFY, bounceNotifyInfo);
3287
- }
3288
-
3289
- if (complaintNotifyInfo) {
3290
- // send complaint notification _after_ complaint email notification
3291
- await this.notify(false, EMAIL_COMPLAINT_NOTIFY, complaintNotifyInfo);
3292
- }
3211
+ await notifyNewMessage(this.notify.bind(this), { path, specialUse }, messageData, { bounceNotifyInfo, complaintNotifyInfo });
3293
3212
  }
3294
3213
 
3295
3214
  /**
@@ -3907,7 +3826,6 @@ module.exports = {
3907
3826
  metricsMeta: postMetrics,
3908
3827
  applyReferenceRecipients,
3909
3828
  buildReferences,
3910
- isFailedDelivery,
3911
3829
  markRejectedAccessToken,
3912
3830
  renewRejectedAccessToken
3913
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');
@@ -40,6 +42,7 @@ function isGmailNotFound(err) {
40
42
  }
41
43
  const { buildSendRequest, buildDraftSendRequest } = require('./gmail/send-request');
42
44
  const { pushHeaderValue } = require('../utils/header-map');
45
+ const { getMessageOtp } = require('../otp');
43
46
 
44
47
  const MAX_GMAIL_BATCH_SIZE = 50;
45
48
 
@@ -285,6 +288,8 @@ class PageCursor {
285
288
  class GmailClient extends BaseClient {
286
289
  constructor(account, options) {
287
290
  super(account, options);
291
+ // what the AI summary's and the OTP-Token's authentication trust rule key on, see summaryProvider()
292
+ this.type = 'gmail';
288
293
 
289
294
  // A failed init() is scheduled again by the worker, see BaseClient.scheduleInitRetry()
290
295
  this.retriesInit = true;
@@ -2026,7 +2031,7 @@ class GmailClient extends BaseClient {
2026
2031
  // PRIVATE METHODS
2027
2032
 
2028
2033
  getAccountKey() {
2029
- return `${REDIS_PREFIX}iad:${this.account}`;
2034
+ return accountDataKey(this.account);
2030
2035
  }
2031
2036
 
2032
2037
  async getAccount() {
@@ -2733,6 +2738,11 @@ class GmailClient extends BaseClient {
2733
2738
  result.isAutoReply = true;
2734
2739
  }
2735
2740
 
2741
+ const otp = getMessageOtp(result.headers, this.summaryProvider());
2742
+ if (otp) {
2743
+ result.otp = otp;
2744
+ }
2745
+
2736
2746
  // Set special-use based on labels
2737
2747
  for (let specialUseTag of ['\\Junk', '\\Sent', '\\Trash', '\\Inbox', '\\Drafts']) {
2738
2748
  if (result.labels && result.labels.includes(specialUseTag)) {
@@ -3423,9 +3433,6 @@ class GmailClient extends BaseClient {
3423
3433
  return;
3424
3434
  }
3425
3435
 
3426
- // All new emails are "new" as message movement between folders is reported as label changes
3427
- messageData.seemsLikeNew = true;
3428
-
3429
3436
  if (eventEntry.category) {
3430
3437
  messageData.category = eventEntry.category;
3431
3438
  }
@@ -3438,6 +3445,10 @@ class GmailClient extends BaseClient {
3438
3445
  }
3439
3446
  }
3440
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
+
3441
3452
  return messageData;
3442
3453
  }
3443
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,24 +24,32 @@ 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');
30
31
  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
- const { isFailedDelivery } = require('../base-client');
34
+ const { getMessageOtp, notifyHeadersIncludeOtp, OTP_FETCH_HEADERS } = require('../../otp');
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');
34
46
 
35
47
  const {
36
- MESSAGE_NEW_NOTIFY,
37
48
  MAILBOX_DELETED_NOTIFY,
38
49
  MESSAGE_DELETED_NOTIFY,
39
50
  MESSAGE_UPDATED_NOTIFY,
40
51
  MESSAGE_MISSING_NOTIFY,
41
52
  MAILBOX_NEW_NOTIFY,
42
- EMAIL_BOUNCE_NOTIFY,
43
- EMAIL_COMPLAINT_NOTIFY,
44
53
  REDIS_PREFIX,
45
54
  MAX_INLINE_ATTACHMENT_SIZE,
46
55
  MAX_ALLOWED_DOWNLOAD_SIZE,
@@ -105,13 +114,32 @@ function isConnectionGone(err) {
105
114
  * @returns {Boolean}
106
115
  */
107
116
  function keepsArrivalQueued(err) {
108
- 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
+ );
109
125
  }
110
126
 
111
127
  // Passes a queued arrival may be throttled on before it is dropped, so a message the server
112
128
  // throttles every time cannot hold up every later arrival in its folder
113
129
  const MAX_THROTTLED_ARRIVAL_PASSES = 5;
114
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
+
115
143
  /**
116
144
  * Whether a message reference decoded from an API id still names a message in the folder the
117
145
  * connection has open. The id carries the UIDVALIDITY it was issued under, and a folder that was
@@ -1227,24 +1255,38 @@ class Mailbox {
1227
1255
  }
1228
1256
 
1229
1257
  /**
1230
- * 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
1231
1263
  * @param {Function} shouldRun - Async check made when the timer fires
1232
1264
  * @param {string} trigger - What asked for it, for the log
1265
+ * @param {number} [delay] - Milliseconds to wait
1233
1266
  */
1234
- schedulePartialSync(shouldRun, trigger) {
1267
+ schedulePartialSync(shouldRun, trigger, delay = PARTIAL_SYNC_DEBOUNCE) {
1235
1268
  clearTimeout(this.runPartialSyncTimer);
1236
1269
  this.runPartialSyncTimer = setTimeout(() => {
1237
1270
  this.runPartialSyncTimer = null;
1238
1271
  shouldRun()
1239
1272
  .then(run => (run ? this.partialSync() : false))
1273
+ .then(() => {
1274
+ this.partialSyncRetries = 0;
1275
+ })
1240
1276
  .catch(err => {
1241
1277
  if (CONNECTION_CLOSING_CODES.has(err.code)) {
1242
1278
  this.logger.debug({ msg: 'Sync skipped, connection closing', err });
1243
- } else {
1244
- 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));
1245
1287
  }
1246
1288
  });
1247
- }, 1000);
1289
+ }, delay);
1248
1290
  }
1249
1291
 
1250
1292
  /**
@@ -1535,18 +1577,7 @@ class Mailbox {
1535
1577
  // Parse ARF report
1536
1578
  const report = await arfDetect(messageInfo);
1537
1579
 
1538
- if (report && report.arf && report.arf['original-rcpt-to'] && report.arf['original-rcpt-to'].length) {
1539
- // Valid complaint found - prepare notification data
1540
- let complaint = camelCaseComplaint(report);
1541
-
1542
- complaintNotifyInfo = Object.assign({ complaintMessage: messageInfo.id }, complaint);
1543
-
1544
- messageInfo.isComplaint = true;
1545
-
1546
- if (complaint.headers && complaint.headers.messageId) {
1547
- messageInfo.relatedMessageId = complaint.headers.messageId;
1548
- }
1549
- }
1580
+ complaintNotifyInfo = complaintNotification(report, messageInfo);
1550
1581
  } catch (err) {
1551
1582
  if (isConnectionGone(err)) {
1552
1583
  throw err;
@@ -1619,44 +1650,8 @@ class Mailbox {
1619
1650
  // Detect bounce details
1620
1651
  let bounce = await bounceDetect(content);
1621
1652
 
1622
- if (bounce?.response?.message) {
1623
- try {
1624
- let bounceType = await this.connection.call({
1625
- cmd: 'bounceClassify',
1626
- data: {
1627
- message: bounce?.response?.message
1628
- },
1629
- timeout: 2 * 60 * 1000
1630
- });
1631
-
1632
- if (bounceType?.label) {
1633
- bounce.response.category = bounceType.label;
1634
- }
1635
- if (bounceType?.action) {
1636
- bounce.response.recommendedAction = bounceType.action;
1637
- }
1638
- if (bounceType?.blocklist) {
1639
- bounce.response.blocklist = bounceType.blocklist;
1640
- }
1641
- if (bounceType?.retryAfter) {
1642
- bounce.response.retryAfter = bounceType.retryAfter;
1643
- }
1644
- } catch (err) {
1645
- // ignore, just do not include this information
1646
- this.logger.error({
1647
- msg: 'Failed to classify bounce response',
1648
- bounceResponse: bounce?.response?.message,
1649
- err
1650
- });
1651
- }
1652
- }
1653
-
1654
- if (isFailedDelivery(bounce)) {
1655
- bounceNotifyInfo = Object.assign({ bounceMessage: messageInfo.id }, bounce);
1656
-
1657
- messageInfo.isBounce = true;
1658
- messageInfo.relatedMessageId = bounce.messageId;
1659
- }
1653
+ await classifyBounce(bounce, this.connection.call, this.logger);
1654
+ bounceNotifyInfo = bounceNotification(bounce, messageInfo);
1660
1655
 
1661
1656
  this.logger.debug({
1662
1657
  msg: 'Detected bounce message',
@@ -1730,8 +1725,7 @@ class Mailbox {
1730
1725
 
1731
1726
  // Check if we have seen this message before using HyperLogLog
1732
1727
  messageInfo.seemsLikeNew =
1733
- this.listingEntry.specialUse !== '\\Sent' &&
1734
- !(messageInfo.labels && messageInfo.labels.includes('\\Sent')) &&
1728
+ !isOwnSent(messageInfo, this.listingEntry.specialUse) &&
1735
1729
  !!(await this.connection.redis.pfadd(this.getSeenMessagesKey(), messageInfo.emailId || messageInfo.messageId));
1736
1730
 
1737
1731
  // Process with LLM if configured for inbox messages. A message with no text part has no
@@ -1754,7 +1748,7 @@ class Mailbox {
1754
1748
  if (notifyWebSafeHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
1755
1749
  // convert to web safe
1756
1750
  messageInfo.text._generatedHtml = await messageWebSafeHtml(messageInfo);
1757
- messageInfo.text.webSafe = true;
1751
+ markWebSafe(messageInfo.text);
1758
1752
 
1759
1753
  // Embed images referenced by Content-ID
1760
1754
  if (messageInfo.text.html && messageInfo.attachments) {
@@ -1814,18 +1808,7 @@ class Mailbox {
1814
1808
  }
1815
1809
  }
1816
1810
 
1817
- // Replace CID references with data URIs. The web safe copy is what webhooks
1818
- // deliver in place of the HTML, so it gets the same treatment
1819
- const embedImages = html =>
1820
- embedCidImages(html, contentId => {
1821
- let { attachment, content } = attachmentList.get(contentId) || {};
1822
- return content && { contentType: attachment.contentType, content };
1823
- });
1824
-
1825
- messageInfo.text.html = embedImages(messageInfo.text.html);
1826
- if (messageInfo.text._generatedHtml) {
1827
- messageInfo.text._generatedHtml = embedImages(messageInfo.text._generatedHtml);
1828
- }
1811
+ embedInlineImages(messageInfo.text, attachmentList);
1829
1812
  }
1830
1813
  }
1831
1814
  }
@@ -1837,20 +1820,7 @@ class Mailbox {
1837
1820
  narrowHeaders(messageInfo, requestedHeaders);
1838
1821
  }
1839
1822
 
1840
- // Send new message notification
1841
- await this.connection.notify(this, MESSAGE_NEW_NOTIFY, messageInfo);
1842
-
1843
- // Send bounce notification if detected
1844
- if (bounceNotifyInfo) {
1845
- // send bounce notification _after_ bounce email notification
1846
- await this.connection.notify(false, EMAIL_BOUNCE_NOTIFY, bounceNotifyInfo);
1847
- }
1848
-
1849
- // Send complaint notification if detected
1850
- if (complaintNotifyInfo) {
1851
- // send complaint notification _after_ complaint email notification
1852
- await this.connection.notify(false, EMAIL_COMPLAINT_NOTIFY, complaintNotifyInfo);
1853
- }
1823
+ await notifyNewMessage(this.connection.notify.bind(this.connection), this, messageInfo, { bounceNotifyInfo, complaintNotifyInfo });
1854
1824
  }
1855
1825
 
1856
1826
  /**
@@ -2010,6 +1980,11 @@ class Mailbox {
2010
1980
  result.isAutoReply = true;
2011
1981
  }
2012
1982
 
1983
+ const otp = extended && getMessageOtp(headers, summaryProvider(this.connection));
1984
+ if (otp) {
1985
+ result.otp = otp;
1986
+ }
1987
+
2013
1988
  return result;
2014
1989
  }
2015
1990
 
@@ -2232,7 +2207,8 @@ class Mailbox {
2232
2207
  (this.isAllMail || this.listingEntry.specialUse === '\\Inbox') && (await llmPreProcess.getPreProcessHandler())
2233
2208
  ? summaryFetchHeaders(summaryProvider(this.connection))
2234
2209
  : [];
2235
- messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers, summaryHeaders);
2210
+ const otpHeaders = notifyHeadersIncludeOtp(notifyHeaders) ? OTP_FETCH_HEADERS : [];
2211
+ messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers, summaryHeaders.concat(otpHeaders));
2236
2212
  }
2237
2213
 
2238
2214
  // Gmail categories of the messages this pass announces, looked up together
@@ -2298,6 +2274,7 @@ class Mailbox {
2298
2274
  */
2299
2275
  async onOpen(event, openedClient) {
2300
2276
  clearTimeout(this.runPartialSyncTimer);
2277
+ this.partialSyncRetries = 0;
2301
2278
  this.selected = true;
2302
2279
 
2303
2280
  // The latch is scoped to the connection that emitted the open event.
@@ -2482,6 +2459,7 @@ class Mailbox {
2482
2459
  */
2483
2460
  async onClose() {
2484
2461
  clearTimeout(this.runPartialSyncTimer);
2462
+ this.partialSyncRetries = 0;
2485
2463
  this.selected = false;
2486
2464
  }
2487
2465
 
@@ -2528,8 +2506,15 @@ class Mailbox {
2528
2506
  if (!content) {
2529
2507
  continue;
2530
2508
  }
2531
- let text = await download(content);
2532
- 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');
2533
2518
 
2534
2519
  // Group by content type (plain, html, etc). The subtype comes from the message,
2535
2520
  // so a sender picks it: for "text/__proto__" the `!result[typeKey]` probe below
@@ -3027,7 +3012,7 @@ class Mailbox {
3027
3012
  // Get new UID in target mailbox
3028
3013
  if (value && value.uidMap && value.uidMap.has(message.uid)) {
3029
3014
  let uid = value.uidMap.get(message.uid);
3030
- let packed = await this.connection.packUid(target.path, uid);
3015
+ let packed = await this.connection.packUid(value.destination || target.path, uid, null, value.uidValidity);
3031
3016
  result.id = packed;
3032
3017
  result.uid = uid;
3033
3018
  }
@@ -3060,8 +3045,13 @@ class Mailbox {
3060
3045
  // Build ID map for moved messages
3061
3046
  if (value && value.uidMap && value.uidMap.size) {
3062
3047
  let moveMap = [];
3048
+ // One status read for the source folder, not one per message
3049
+ let sourceStatus = new Map();
3063
3050
  for (let [suid, tuid] of value.uidMap) {
3064
- 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
+ ]);
3065
3055
  }
3066
3056
  result.idMap = moveMap;
3067
3057
  }
@@ -3104,7 +3094,12 @@ class Mailbox {
3104
3094
  destination: moved.destination
3105
3095
  };
3106
3096
  if (moved && moved.uidMap && moved.uidMap.has(message.uid)) {
3107
- 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
+ );
3108
3103
  }
3109
3104
  }
3110
3105
  }
@@ -3148,8 +3143,13 @@ class Mailbox {
3148
3143
  };
3149
3144
  if (moved && moved.uidMap && moved.uidMap.size) {
3150
3145
  let moveMap = [];
3146
+ // One status read for the source folder, not one per message
3147
+ let sourceStatus = new Map();
3151
3148
  for (let [suid, tuid] of moved.uidMap) {
3152
- 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
+ ]);
3153
3153
  }
3154
3154
  result.moved.idMap = moveMap;
3155
3155
  }