emailengine-app 2.89.0 → 2.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +44 -0
  4. package/Dockerfile +5 -1
  5. package/bin/healthcheck.js +1 -1
  6. package/copy-static-files.sh +0 -8
  7. package/data/google-crawlers.json +1 -1
  8. package/encrypt.js +1 -4
  9. package/lib/account/field-codec.js +396 -0
  10. package/lib/account.js +158 -453
  11. package/lib/api-routes/account-routes.js +42 -6
  12. package/lib/api-routes/route-metadata.js +5 -2
  13. package/lib/api-routes/submit-routes.js +15 -2
  14. package/lib/api-token-auth.js +342 -274
  15. package/lib/arf-detect.js +174 -149
  16. package/lib/attachment-size.js +29 -0
  17. package/lib/autodetect-imap-settings.js +83 -234
  18. package/lib/consts.js +1 -5
  19. package/lib/db.js +1 -4
  20. package/lib/email-client/base-client.js +907 -780
  21. package/lib/email-client/gmail-client.js +557 -450
  22. package/lib/email-client/imap/cid-parts.js +61 -0
  23. package/lib/email-client/imap/mailbox.js +376 -422
  24. package/lib/email-client/imap/sync-operations.js +239 -178
  25. package/lib/email-client/new-message-steps.js +168 -2
  26. package/lib/email-client/outlook/graph-message.js +266 -0
  27. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  28. package/lib/email-client/outlook-client.js +652 -808
  29. package/lib/get-raw-email.js +338 -232
  30. package/lib/get-secret.js +1 -4
  31. package/lib/license-subscription.js +60 -0
  32. package/lib/load-env.js +48 -0
  33. package/lib/logger.js +1 -4
  34. package/lib/mcp/tools.js +244 -207
  35. package/lib/metric-values.js +76 -0
  36. package/lib/metrics.js +320 -0
  37. package/lib/oauth/gmail.js +39 -120
  38. package/lib/oauth/http-request.js +195 -0
  39. package/lib/oauth/mail-ru.js +24 -58
  40. package/lib/oauth/outlook.js +37 -137
  41. package/lib/oauth/pubsub/google.js +176 -117
  42. package/lib/oauth2-apps.js +440 -463
  43. package/lib/openapi/build-document.js +10 -10
  44. package/lib/read-env-value.js +1 -1
  45. package/lib/route-descriptors.js +78 -0
  46. package/lib/schemas.js +10 -1
  47. package/lib/sentry-integrations.js +299 -0
  48. package/lib/sentry.js +75 -27
  49. package/lib/sso-routes.js +249 -0
  50. package/lib/sso.js +29 -6
  51. package/lib/ui-routes/account-edit-form.js +198 -0
  52. package/lib/ui-routes/account-page.js +241 -0
  53. package/lib/ui-routes/account-routes.js +12 -318
  54. package/lib/ui-routes/auth-routes.js +10 -10
  55. package/lib/ui-view-context.js +328 -0
  56. package/lib/utils/public-suffix.js +22 -101
  57. package/lib/web-safe-html.js +20 -7
  58. package/lib/worker-metrics.js +82 -0
  59. package/list-generate.js +2 -5
  60. package/package.json +23 -19
  61. package/sbom.json +267 -908
  62. package/scripts/refresh-test-tokens.js +1 -1
  63. package/server.js +320 -676
  64. package/static/css/flyonui.css +1 -1
  65. package/static/css/src/app.tailwind.css +18 -0
  66. package/static/js/ee-client.js +2619 -645
  67. package/static/js/ui.js +12 -2
  68. package/static/licenses.html +219 -737
  69. package/translations/messages.pot +64 -53
  70. package/views/accounts/browse.hbs +19 -1
  71. package/workers/api.js +20 -451
  72. package/data/public_suffix_list.dat +0 -16698
@@ -770,6 +770,237 @@ class SyncOperations {
770
770
  }
771
771
  }
772
772
 
773
+ /**
774
+ * Decides whether one row of a full sync FETCH is compared with the index, counting it by kind
775
+ * and logging the ones that cannot be used
776
+ * @param {Object} messageData - The row
777
+ * @param {number} lastUid - The highest UID compared or pending so far
778
+ * @param {Object} query - The FETCH, { range, fields, opts }, for the log
779
+ * @param {Object} responseCounters - Rows seen by kind, counted up
780
+ * @returns {boolean} True for a row to compare with the index; false for an empty or partial
781
+ * row, or one an earlier batch already returned
782
+ */
783
+ classifyFetchRow(messageData, lastUid, query, responseCounters) {
784
+ if (!messageData) {
785
+ this.logger.debug({ msg: 'Empty FETCH response', code: 'empty_fetch', query });
786
+ responseCounters.empty++;
787
+ return false;
788
+ }
789
+
790
+ if (!messageData.uid || (query.fields.flags && !messageData.flags)) {
791
+ // TODO: support partial responses
792
+ // For now, without UID or FLAGS there's nothing to do
793
+ this.logger.debug({
794
+ msg: 'Partial FETCH response',
795
+ code: 'partial_fetch',
796
+ query,
797
+ responseKeys: Object.keys(messageData)
798
+ });
799
+ responseCounters.partial++;
800
+ return false;
801
+ }
802
+
803
+ if (messageData.uid <= lastUid) {
804
+ // already processed in the previous batch
805
+ // probably an older email was deleted which shifted message entries
806
+ return false;
807
+ }
808
+
809
+ responseCounters.messages++;
810
+ return true;
811
+ }
812
+
813
+ /**
814
+ * Runs one FETCH of a full sync batch and compares what it returns with the index. The rows
815
+ * are compared in chunks (see syncFetchedChunk()); rows of a chunk not compared yet when the
816
+ * FETCH fails are dropped, and the retry fetches them again
817
+ * @param {Object} imapClient - The connection to fetch on
818
+ * @param {Object} batch - { loopId, batchNumber, range, fields, opts }
819
+ * @param {Object} retry - { count, total, startTime }, for the log
820
+ * @param {Object} mailboxStatus - The folder status the batch runs with, for the log
821
+ * @param {Object} position - The last message compared with the index, moved on
822
+ * @param {Object} responseCounters - Rows seen by kind, counted up
823
+ */
824
+ async fetchBatchOnce(imapClient, batch, retry, mailboxStatus, position, responseCounters) {
825
+ const { loopId, batchNumber, range, fields, opts } = batch;
826
+ const query = { range, fields, opts };
827
+
828
+ this.logger.debug({
829
+ msg: 'Starting FETCH command',
830
+ code: 'fetch_start',
831
+ loopId,
832
+ batchNumber,
833
+ range,
834
+ retryCount: retry.count,
835
+ totalMessages: mailboxStatus.messages
836
+ });
837
+
838
+ let pending = [];
839
+ for await (let messageData of imapClient.fetch(range, fields, opts)) {
840
+ if (!this.classifyFetchRow(messageData, pending.length ? pending[pending.length - 1].uid : position.uid, query, responseCounters)) {
841
+ continue;
842
+ }
843
+
844
+ if (fields.internalDate && !messageData.internalDate) {
845
+ this.logger.debug({
846
+ msg: 'Missing INTERNALDATE',
847
+ code: 'fetch_date_missing',
848
+ query,
849
+ responseKeys: Object.keys(messageData)
850
+ });
851
+ }
852
+
853
+ // ignore Recent flag
854
+ messageData.flags.delete('\\Recent');
855
+
856
+ pending.push(messageData);
857
+ if (pending.length >= SYNC_CHUNK_SIZE) {
858
+ await this.syncFetchedChunk(pending, position);
859
+ pending = [];
860
+ }
861
+ }
862
+ await this.syncFetchedChunk(pending, position);
863
+
864
+ try {
865
+ // clear failure flag
866
+ await this.connection.redis.hdel(this.connection.getAccountKey(), 'syncError');
867
+ } catch (err) {
868
+ // ignore
869
+ }
870
+
871
+ this.logger.debug({
872
+ msg: 'FETCH completed successfully',
873
+ code: 'fetch_success',
874
+ loopId,
875
+ batchNumber,
876
+ range,
877
+ retryCount: retry.count
878
+ });
879
+ }
880
+
881
+ /**
882
+ * Handles a failed full sync FETCH: ends the pass when the connection is gone, otherwise records
883
+ * the failure on the account, waits, checks that the folder is still the one selected, and
884
+ * reads the folder status again, since it can have changed while the batch failed
885
+ * @param {Object} imapClient - The connection the FETCH ran on
886
+ * @param {Error} err - The FETCH failure
887
+ * @param {Object} batch - { loopId, batchNumber, range }
888
+ * @param {Object} retry - { count, total, startTime }; count is this batch's, total the pass's
889
+ * @param {Object} mailboxStatus - The folder status the batch ran with
890
+ * @returns {Promise<Object>} The folder status to continue with
891
+ */
892
+ async handleFetchFailure(imapClient, err, batch, retry, mailboxStatus) {
893
+ const { loopId, batchNumber, range } = batch;
894
+
895
+ if (syncInterrupted(imapClient, err)) {
896
+ // A connection dropped mid-FETCH is the most common way a full sync
897
+ // dies, and this path sets no syncError flag, so report it here
898
+ this.logger.warn({
899
+ msg: 'FETCH failed, connection is no longer usable',
900
+ code: 'fetch_error',
901
+ loopId,
902
+ batchNumber,
903
+ range,
904
+ retryCount: retry.count,
905
+ totalMessages: mailboxStatus.messages,
906
+ err
907
+ });
908
+
909
+ throw connectionClosedError(err);
910
+ }
911
+
912
+ try {
913
+ // set failure flag
914
+ await this.connection.redis.hSetExists(
915
+ this.connection.getAccountKey(),
916
+ 'syncError',
917
+ JSON.stringify({
918
+ path: this.mailbox.path,
919
+ time: new Date().toISOString(),
920
+ error: {
921
+ error: err.message,
922
+ responseStatus: err.responseStatus,
923
+ responseText: err.responseText
924
+ }
925
+ })
926
+ );
927
+ } catch (err) {
928
+ // ignore
929
+ }
930
+
931
+ // Retry with exponential backoff
932
+ retry.total++;
933
+ const fetchRetryDelay = calculateFetchBackoff(++retry.count);
934
+ this.logger.warn({
935
+ msg: 'FETCH failed, retrying',
936
+ code: 'fetch_error',
937
+ loopId,
938
+ batchNumber,
939
+ range,
940
+ retryCount: retry.count,
941
+ totalMessages: mailboxStatus.messages,
942
+ retryDelay: Math.round(fetchRetryDelay),
943
+ err
944
+ });
945
+ await new Promise(r => setTimeout(r, fetchRetryDelay));
946
+
947
+ if (syncInterrupted(imapClient, err)) {
948
+ // connection closed, throw so callers know sync was interrupted
949
+ throw connectionClosedError(err);
950
+ }
951
+
952
+ // Verify we're still on the correct mailbox after the delay
953
+ // Another operation might have changed the mailbox while we were waiting
954
+ const currentMailbox = this.connection.imapClient?.mailbox;
955
+ if (!currentMailbox || !samePath(currentMailbox.path, this.mailbox.path)) {
956
+ this.logger.warn({
957
+ msg: 'Mailbox changed during retry delay, aborting sync',
958
+ expectedPath: this.mailbox.path,
959
+ currentPath: currentMailbox ? currentMailbox.path : 'none',
960
+ loopId
961
+ });
962
+ throw new Error('Mailbox changed during sync operation', { cause: err });
963
+ }
964
+
965
+ // Refresh mailbox status in case it changed
966
+ const refreshedStatus = this.mailbox.getMailboxStatus();
967
+
968
+ this.logger.debug({
969
+ msg: 'Refreshed mailbox status after error',
970
+ code: 'mailbox_status_refresh',
971
+ loopId,
972
+ batchNumber,
973
+ oldMessages: mailboxStatus.messages,
974
+ newMessages: refreshedStatus.messages,
975
+ range
976
+ });
977
+
978
+ checkFetchRetryTimeout(retry.total, retry.startTime);
979
+
980
+ return refreshedStatus;
981
+ }
982
+
983
+ /**
984
+ * Ends a full sync: removes what the pass did not see, stores the status and announces what it
985
+ * found
986
+ * @param {Object} position - The last message compared with the index
987
+ * @param {Object} mailboxStatus - The folder status of the pass
988
+ */
989
+ async finishFullSync(position, mailboxStatus) {
990
+ // Delete any messages that weren't seen in this sync
991
+ await this.expungeTrailing(position, mailboxStatus.messages);
992
+
993
+ // Persist the pre-sync snapshot (plus the full-sync timestamp) so
994
+ // any arrivals that landed during this FETCH are still detected as
995
+ // drift on the next trigger.
996
+ let status = Object.assign({}, mailboxStatus, { lastFullSync: new Date() });
997
+
998
+ await this.mailbox.updateStoredStatus(status);
999
+ let storedStatus = await this.mailbox.getStoredStatus();
1000
+
1001
+ await this.mailbox.publishSyncedEvents(storedStatus);
1002
+ }
1003
+
773
1004
  /**
774
1005
  * Full sync - fetches all messages and detects additions, deletions, and changes
775
1006
  * Most thorough but slowest sync method
@@ -794,7 +1025,7 @@ class SyncOperations {
794
1025
  mailboxStatus
795
1026
  });
796
1027
 
797
- // The last message compared with the index, see syncFetchedChunk()
1028
+ // The last message compared with the index, shared by every batch, see syncFetchedChunk()
798
1029
  let position = { uid: 0, seq: 0 };
799
1030
 
800
1031
  let responseCounters = {
@@ -817,8 +1048,7 @@ class SyncOperations {
817
1048
  // Process messages in batches to avoid memory issues
818
1049
  let range = false;
819
1050
  let batchNumber = 0;
820
- let fetchStartTime = Date.now();
821
- let totalFetchRetryCount = 0;
1051
+ let retry = { count: 0, total: 0, startTime: Date.now() };
822
1052
  // process messages in batches
823
1053
  while ((range = getFetchRange(mailboxStatus.messages, range))) {
824
1054
  batchNumber++;
@@ -831,8 +1061,9 @@ class SyncOperations {
831
1061
  totalMessages: mailboxStatus.messages,
832
1062
  previousRange: batchNumber > 1 ? 'calculated' : 'initial'
833
1063
  });
1064
+ const batch = { loopId, batchNumber, range, fields, opts };
834
1065
  let fetchCompleted = false;
835
- let fetchRetryCount = 0;
1066
+ retry.count = 0;
836
1067
  while (!fetchCompleted) {
837
1068
  // Get fresh imapClient reference inside retry loop
838
1069
  // This ensures we use the current connection state
@@ -843,187 +1074,17 @@ class SyncOperations {
843
1074
  }
844
1075
 
845
1076
  try {
846
- this.logger.debug({
847
- msg: 'Starting FETCH command',
848
- code: 'fetch_start',
849
- loopId,
850
- batchNumber,
851
- range,
852
- retryCount: fetchRetryCount,
853
- totalMessages: mailboxStatus.messages
854
- });
855
-
856
- let pending = [];
857
- for await (let messageData of imapClient.fetch(range, fields, opts)) {
858
- if (!messageData) {
859
- this.logger.debug({ msg: 'Empty FETCH response', code: 'empty_fetch', query: { range, fields, opts } });
860
- responseCounters.empty++;
861
- continue;
862
- }
863
-
864
- if (!messageData.uid || (fields.flags && !messageData.flags)) {
865
- // TODO: support partial responses
866
- // For now, without UID or FLAGS there's nothing to do
867
- this.logger.debug({
868
- msg: 'Partial FETCH response',
869
- code: 'partial_fetch',
870
- query: { range, fields, opts },
871
- responseKeys: Object.keys(messageData)
872
- });
873
- responseCounters.partial++;
874
- continue;
875
- }
876
-
877
- if (messageData.uid <= (pending.length ? pending[pending.length - 1].uid : position.uid)) {
878
- // already processed in the previous batch
879
- // probably an older email was deleted which shifted message entries
880
- continue;
881
- }
882
-
883
- responseCounters.messages++;
884
-
885
- if (fields.internalDate && !messageData.internalDate) {
886
- this.logger.debug({
887
- msg: 'Missing INTERNALDATE',
888
- code: 'fetch_date_missing',
889
- query: { range, fields, opts },
890
- responseKeys: Object.keys(messageData)
891
- });
892
- }
893
-
894
- // ignore Recent flag
895
- messageData.flags.delete('\\Recent');
896
-
897
- // Compared in chunks, see syncFetchedChunk(). A FETCH that fails before
898
- // a chunk is compared fetches it again on the retry
899
- pending.push(messageData);
900
- if (pending.length >= SYNC_CHUNK_SIZE) {
901
- await this.syncFetchedChunk(pending, position);
902
- pending = [];
903
- }
904
- }
905
- await this.syncFetchedChunk(pending, position);
906
-
907
- try {
908
- // clear failure flag
909
- await this.connection.redis.hdel(this.connection.getAccountKey(), 'syncError');
910
- } catch (err) {
911
- // ignore
912
- }
913
-
914
- this.logger.debug({
915
- msg: 'FETCH completed successfully',
916
- code: 'fetch_success',
917
- loopId,
918
- batchNumber,
919
- range,
920
- retryCount: fetchRetryCount
921
- });
922
-
1077
+ await this.fetchBatchOnce(imapClient, batch, retry, mailboxStatus, position, responseCounters);
923
1078
  fetchCompleted = true;
924
1079
  } catch (err) {
925
- if (syncInterrupted(imapClient, err)) {
926
- // A connection dropped mid-FETCH is the most common way a full sync
927
- // dies, and this path sets no syncError flag, so report it here
928
- this.logger.warn({
929
- msg: 'FETCH failed, connection is no longer usable',
930
- code: 'fetch_error',
931
- loopId,
932
- batchNumber,
933
- range,
934
- retryCount: fetchRetryCount,
935
- totalMessages: mailboxStatus.messages,
936
- err
937
- });
938
-
939
- throw connectionClosedError(err);
940
- }
941
-
942
- try {
943
- // set failure flag
944
- await this.connection.redis.hSetExists(
945
- this.connection.getAccountKey(),
946
- 'syncError',
947
- JSON.stringify({
948
- path: this.mailbox.path,
949
- time: new Date().toISOString(),
950
- error: {
951
- error: err.message,
952
- responseStatus: err.responseStatus,
953
- responseText: err.responseText
954
- }
955
- })
956
- );
957
- } catch (err) {
958
- // ignore
959
- }
960
-
961
- // Retry with exponential backoff
962
- totalFetchRetryCount++;
963
- const fetchRetryDelay = calculateFetchBackoff(++fetchRetryCount);
964
- this.logger.warn({
965
- msg: 'FETCH failed, retrying',
966
- code: 'fetch_error',
967
- loopId,
968
- batchNumber,
969
- range,
970
- retryCount: fetchRetryCount,
971
- totalMessages: mailboxStatus.messages,
972
- retryDelay: Math.round(fetchRetryDelay),
973
- err
974
- });
975
- await new Promise(r => setTimeout(r, fetchRetryDelay));
976
-
977
- if (syncInterrupted(imapClient, err)) {
978
- // connection closed, throw so callers know sync was interrupted
979
- throw connectionClosedError(err);
980
- }
981
-
982
- // Verify we're still on the correct mailbox after the delay
983
- // Another operation might have changed the mailbox while we were waiting
984
- const currentMailbox = this.connection.imapClient?.mailbox;
985
- if (!currentMailbox || !samePath(currentMailbox.path, this.mailbox.path)) {
986
- this.logger.warn({
987
- msg: 'Mailbox changed during retry delay, aborting sync',
988
- expectedPath: this.mailbox.path,
989
- currentPath: currentMailbox ? currentMailbox.path : 'none',
990
- loopId
991
- });
992
- throw new Error('Mailbox changed during sync operation', { cause: err });
993
- }
994
-
995
- // Refresh mailbox status in case it changed
996
- const oldMailboxMessages = mailboxStatus.messages;
997
- mailboxStatus = this.mailbox.getMailboxStatus();
998
-
999
- this.logger.debug({
1000
- msg: 'Refreshed mailbox status after error',
1001
- code: 'mailbox_status_refresh',
1002
- loopId,
1003
- batchNumber,
1004
- oldMessages: oldMailboxMessages,
1005
- newMessages: mailboxStatus.messages,
1006
- range
1007
- });
1008
-
1009
- checkFetchRetryTimeout(totalFetchRetryCount, fetchStartTime);
1080
+ // the refreshed status moves where the remaining batches end
1081
+ mailboxStatus = await this.handleFetchFailure(imapClient, err, batch, retry, mailboxStatus);
1010
1082
  }
1011
1083
  }
1012
1084
  }
1013
1085
  }
1014
1086
 
1015
- // Delete any messages that weren't seen in this sync
1016
- await this.expungeTrailing(position, mailboxStatus.messages);
1017
-
1018
- // Persist the pre-sync snapshot (plus the full-sync timestamp) so
1019
- // any arrivals that landed during this FETCH are still detected as
1020
- // drift on the next trigger.
1021
- let status = Object.assign({}, mailboxStatus, { lastFullSync: new Date() });
1022
-
1023
- await this.mailbox.updateStoredStatus(status);
1024
- let storedStatus = await this.mailbox.getStoredStatus();
1025
-
1026
- await this.mailbox.publishSyncedEvents(storedStatus);
1087
+ await this.finishFullSync(position, mailboxStatus);
1027
1088
  } finally {
1028
1089
  this.releaseSyncLock(lock);
1029
1090
  }
@@ -7,7 +7,10 @@
7
7
  // drifted (the web-safe flag was set even when no web-safe copy came out, a classification failure
8
8
  // was an error on one path and a warning on the other). Those shared decisions live here.
9
9
 
10
- const { camelCaseComplaint } = require('../arf-detect');
10
+ const { arfDetect, camelCaseComplaint, COMPLAINT_ATTACHMENT_TYPES } = require('../arf-detect');
11
+ const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS } = require('../bounce-detect');
12
+ const { parseMessage } = require('../parse-message');
13
+ const { llmPreProcess } = require('../llm-pre-process');
11
14
  const { embedCidImages } = require('../tools');
12
15
  const { MESSAGE_NEW_NOTIFY, EMAIL_BOUNCE_NOTIFY, EMAIL_COMPLAINT_NOTIFY } = require('../consts');
13
16
 
@@ -159,4 +162,167 @@ async function notifyNewMessage(notify, target, messageData, { bounceNotifyInfo,
159
162
  }
160
163
  }
161
164
 
162
- module.exports = { isFailedDelivery, isOwnSent, classifyBounce, bounceNotification, complaintNotification, embedInlineImages, markWebSafe, notifyNewMessage };
165
+ /**
166
+ * Stores a downloaded part on its attachment without making it part of the payload: the complaint
167
+ * check reads it, the webhook does not carry it. The property is read-only, as it always was
168
+ * @param {Object} attachment - Attachment entry, changed in place
169
+ * @param {*} value - The part's content
170
+ */
171
+ function setHiddenContent(attachment, value) {
172
+ Object.defineProperty(attachment, 'content', {
173
+ value,
174
+ enumerable: false
175
+ });
176
+ }
177
+
178
+ // The default of runArrivalChecks(): every failure is logged and the message still announced
179
+ const swallow = () => false;
180
+
181
+ /**
182
+ * Logs a failed arrival check, unless the backend says the failure must propagate instead
183
+ * @param {Object} messageInfo
184
+ * @param {Error} err
185
+ * @param {string} msg
186
+ * @param {Function} rethrow - (err) => true for a failure that must propagate
187
+ * @param {Object} logger
188
+ */
189
+ function arrivalCheckFailed(messageInfo, err, msg, rethrow, logger) {
190
+ if (rethrow(err)) {
191
+ throw err;
192
+ }
193
+ logger.error({
194
+ msg,
195
+ id: messageInfo.id,
196
+ uid: messageInfo.uid,
197
+ messageId: messageInfo.messageId,
198
+ err
199
+ });
200
+ }
201
+
202
+ /**
203
+ * The complaint (ARF), delivery report (DSN) and bounce checks of a new message, in that order. The
204
+ * backends differ only in how content is downloaded, which the callbacks supply, and in which
205
+ * failures must not be swallowed: IMAP lets a gone connection propagate so the message stays
206
+ * queued instead of being announced half processed. Runs under whatever lock the caller holds.
207
+ * @param {Object} messageInfo - The new message, changed in place
208
+ * @param {Object} opts
209
+ * @param {Object} opts.detector - Has mightBeAComplaint(), mightBeDSNResponse() and mightBeABounce()
210
+ * @param {Function} opts.loadComplaintPart - async (attachment) => void, sets the hidden content
211
+ * @param {Function} opts.fetchSource - async () => the message source (a stream or a buffer)
212
+ * @param {Function} [opts.rethrow] - (err) => true for a failure that must propagate
213
+ * @param {Function} opts.call - RPC to the main thread, for the bounce classifier
214
+ * @param {Object} opts.logger
215
+ * @returns {Promise<{ bounceNotifyInfo: Object|undefined, complaintNotifyInfo: Object|undefined }>}
216
+ */
217
+ async function runArrivalChecks(messageInfo, opts) {
218
+ const { detector, loadComplaintPart, fetchSource, rethrow = swallow, call, logger } = opts;
219
+
220
+ let bounceNotifyInfo;
221
+ let complaintNotifyInfo;
222
+ let content;
223
+ // Set once a download found no content, so the bounce check does not ask again
224
+ let messageGone = false;
225
+
226
+ if (detector.mightBeAComplaint(messageInfo)) {
227
+ try {
228
+ for (let attachment of messageInfo.attachments || []) {
229
+ if (COMPLAINT_ATTACHMENT_TYPES.includes(attachment.contentType)) {
230
+ await loadComplaintPart(attachment);
231
+ }
232
+ }
233
+
234
+ const report = await arfDetect(messageInfo);
235
+
236
+ complaintNotifyInfo = complaintNotification(report, messageInfo);
237
+ } catch (err) {
238
+ arrivalCheckFailed(messageInfo, err, 'Failed to process ARF', rethrow, logger);
239
+ }
240
+ }
241
+
242
+ if (detector.mightBeDSNResponse(messageInfo)) {
243
+ let source;
244
+ try {
245
+ source = await fetchSource();
246
+
247
+ // No content means the message is gone: on IMAP it was expunged after it was detected
248
+ // (a server-side filter moving it to Junk, for instance), on the API backends the
249
+ // provider answered without the raw message. Neither is a failure, and asking again in
250
+ // the bounce check below would only repeat the download
251
+ if (!source) {
252
+ messageGone = true;
253
+ } else {
254
+ let parsed = await parseMessage(source, DSN_PARSER_OPTIONS);
255
+ if (parsed) {
256
+ content = { parsed };
257
+ applyDeliveryReport(parsed, messageInfo, logger);
258
+ }
259
+ }
260
+ } catch (err) {
261
+ // A parser failure leaves a streamed download unconsumed
262
+ source?.destroy?.();
263
+ arrivalCheckFailed(messageInfo, err, 'Failed to process DSN', rethrow, logger);
264
+ }
265
+ }
266
+
267
+ if (detector.mightBeABounce(messageInfo)) {
268
+ try {
269
+ if (!content && !messageGone) {
270
+ content = await fetchSource();
271
+ }
272
+
273
+ if (content) {
274
+ let bounce = await bounceDetect(content);
275
+
276
+ await classifyBounce(bounce, call, logger);
277
+ bounceNotifyInfo = bounceNotification(bounce, messageInfo);
278
+
279
+ logger.debug({
280
+ msg: 'Detected bounce message',
281
+ id: messageInfo.id,
282
+ uid: messageInfo.uid,
283
+ messageId: messageInfo.messageId,
284
+ bounce
285
+ });
286
+ }
287
+ } catch (err) {
288
+ // A parser failure leaves a streamed download unconsumed, as in the DSN check above
289
+ content?.destroy?.();
290
+ arrivalCheckFailed(messageInfo, err, 'Failed to process potential bounce', rethrow, logger);
291
+ }
292
+ }
293
+
294
+ return { bounceNotifyInfo, complaintNotifyInfo };
295
+ }
296
+
297
+ /**
298
+ * Runs the AI summary for an Inbox message when the pre-processing filter accepts it. A message
299
+ * with no text part has no text object at all, and nothing to summarize
300
+ * @param {Object} messageInfo - The new message, changed in place
301
+ * @param {string} account
302
+ * @param {Function} summarizeOptions - () => the options for llmPreProcess.summarize()
303
+ */
304
+ async function runLlmSummary(messageInfo, account, summarizeOptions) {
305
+ if (messageInfo.messageSpecialUse !== '\\Inbox' || !(messageInfo.text?.plain || messageInfo.text?.html)) {
306
+ return;
307
+ }
308
+
309
+ let llmMessageData = Object.assign({ account }, messageInfo);
310
+
311
+ if (await llmPreProcess.run(llmMessageData)) {
312
+ await llmPreProcess.summarize(messageInfo, summarizeOptions());
313
+ }
314
+ }
315
+
316
+ module.exports = {
317
+ isFailedDelivery,
318
+ isOwnSent,
319
+ classifyBounce,
320
+ bounceNotification,
321
+ complaintNotification,
322
+ embedInlineImages,
323
+ markWebSafe,
324
+ notifyNewMessage,
325
+ setHiddenContent,
326
+ runArrivalChecks,
327
+ runLlmSummary
328
+ };