emailengine-app 2.84.2 → 2.86.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 (164) hide show
  1. package/.ncurc.js +29 -9
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +107 -0
  6. package/Dockerfile +20 -1
  7. package/ENVIRONMENT.md +139 -0
  8. package/README.md +2 -2
  9. package/bin/emailengine.js +434 -408
  10. package/config/default.toml +2 -0
  11. package/copy-static-files.sh +41 -14
  12. package/data/google-crawlers.json +1 -1
  13. package/data/public_suffix_list.dat +16563 -0
  14. package/eslint.config.js +81 -99
  15. package/lib/account-assignment.js +19 -0
  16. package/lib/account.js +230 -170
  17. package/lib/api-error-codes.js +49 -0
  18. package/lib/api-reference/format.js +4 -3
  19. package/lib/api-reference/model.js +6 -1
  20. package/lib/api-routes/account-routes.js +255 -38
  21. package/lib/api-routes/blocklist-routes.js +91 -4
  22. package/lib/api-routes/delivery-test-routes.js +27 -4
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +110 -12
  25. package/lib/api-routes/index.js +4 -0
  26. package/lib/api-routes/license-routes.js +2 -2
  27. package/lib/api-routes/mailbox-routes.js +44 -5
  28. package/lib/api-routes/message-routes.js +112 -10
  29. package/lib/api-routes/oauth2-app-routes.js +63 -23
  30. package/lib/api-routes/outbox-routes.js +97 -52
  31. package/lib/api-routes/permission-map.js +67 -7
  32. package/lib/api-routes/scoped-routes.js +74 -0
  33. package/lib/api-routes/settings-routes.js +34 -6
  34. package/lib/api-routes/stats-routes.js +5 -1
  35. package/lib/api-routes/submit-routes.js +337 -309
  36. package/lib/api-routes/template-routes.js +45 -8
  37. package/lib/api-routes/token-routes.js +152 -100
  38. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  39. package/lib/api-routes/webhook-route-routes.js +132 -6
  40. package/lib/bounce-detect.js +397 -205
  41. package/lib/calendar-event.js +81 -1
  42. package/lib/consts.js +38 -45
  43. package/lib/db.js +14 -6
  44. package/lib/delivery-error.js +6 -0
  45. package/lib/deprecations.js +270 -0
  46. package/lib/email-client/base-client.js +137 -184
  47. package/lib/email-client/fallback-poll.js +62 -0
  48. package/lib/email-client/gmail-client.js +60 -22
  49. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  50. package/lib/email-client/imap/adaptive-idle.js +278 -0
  51. package/lib/email-client/imap/connection-errors.js +14 -1
  52. package/lib/email-client/imap/idle-settings.js +31 -5
  53. package/lib/email-client/imap/listing-diff.js +37 -0
  54. package/lib/email-client/imap/mailbox.js +372 -242
  55. package/lib/email-client/imap/subconnection.js +8 -30
  56. package/lib/email-client/imap/sync-operations.js +220 -127
  57. package/lib/email-client/imap-client.js +228 -164
  58. package/lib/email-client/message-builder.js +14 -79
  59. package/lib/email-client/notification-handler.js +1 -2
  60. package/lib/email-client/outlook-client.js +372 -338
  61. package/lib/email-client/smtp-pool-manager.js +16 -13
  62. package/lib/email-client/sync-state-fields.js +19 -0
  63. package/lib/encrypt.js +157 -41
  64. package/lib/enum-descriptions.js +3 -1
  65. package/lib/env-setting-overrides.js +288 -0
  66. package/lib/export-worker.js +751 -0
  67. package/lib/export.js +64 -15
  68. package/lib/gateway.js +19 -4
  69. package/lib/get-raw-email.js +25 -107
  70. package/lib/hapi-request-logger.js +107 -0
  71. package/lib/health.js +75 -0
  72. package/lib/imapproxy/imap-core/README.md +6 -5
  73. package/lib/lock-run.js +119 -0
  74. package/lib/logger-consts.js +48 -0
  75. package/lib/logger.js +1 -1
  76. package/lib/lua/z-head-scores.lua +28 -0
  77. package/lib/mcp/tools.js +37 -8
  78. package/lib/network-errors.js +1 -1
  79. package/lib/node-version.js +24 -0
  80. package/lib/notify-attachments.js +36 -0
  81. package/lib/oauth/outlook-mailbox.js +35 -0
  82. package/lib/oauth/state.js +24 -0
  83. package/lib/oauth2-apps.js +631 -656
  84. package/lib/outbox.js +184 -54
  85. package/lib/parse-message.js +3 -3
  86. package/lib/pbkdf2-phc.js +1 -1
  87. package/lib/privileged-settings.js +2 -2
  88. package/lib/queue-browser/definitions.js +11 -0
  89. package/lib/queue-browser/index.js +68 -19
  90. package/lib/queue-job-actions.js +18 -1
  91. package/lib/queue-retention.js +48 -12
  92. package/lib/queue-stats.js +11 -2
  93. package/lib/read-env-value.js +3 -0
  94. package/lib/redis-memory-warnings.js +99 -0
  95. package/lib/redis-reconnect.js +29 -0
  96. package/lib/request-timing.js +23 -0
  97. package/lib/respawn-backoff.js +35 -0
  98. package/lib/rewrite-text-nodes.js +19 -59
  99. package/lib/schemas.js +164 -40
  100. package/lib/settings.js +6 -2
  101. package/lib/smtp-auth.js +19 -1
  102. package/lib/sso.js +1 -1
  103. package/lib/swagger-options.js +1 -1
  104. package/lib/thread-diagnostics.js +63 -0
  105. package/lib/timezones.js +109 -0
  106. package/lib/tls/provision.js +6 -3
  107. package/lib/token-audit-log.js +19 -20
  108. package/lib/token-permission-view.js +7 -6
  109. package/lib/tools.js +48 -51
  110. package/lib/totp.js +2 -5
  111. package/lib/translations.js +1 -2
  112. package/lib/ui-routes/account-routes.js +475 -454
  113. package/lib/ui-routes/account-setup.js +99 -0
  114. package/lib/ui-routes/admin-config-routes.js +152 -100
  115. package/lib/ui-routes/admin-entities-routes.js +93 -21
  116. package/lib/ui-routes/auth-routes.js +90 -38
  117. package/lib/ui-routes/imap-idle-field.js +1 -1
  118. package/lib/ui-routes/internals-routes.js +5 -0
  119. package/lib/ui-routes/oauth-config-routes.js +124 -82
  120. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  121. package/lib/ui-routes/overridable-fields.js +84 -0
  122. package/lib/ui-routes/queue-routes.js +8 -5
  123. package/lib/ui-routes/route-helpers.js +19 -3
  124. package/lib/ui-routes/settings-page.js +6 -0
  125. package/lib/ui-routes/tls-config-routes.js +58 -15
  126. package/lib/utils/back-off.js +82 -0
  127. package/lib/utils/decode-headers.js +3 -12
  128. package/lib/utils/filter-empty.js +20 -0
  129. package/lib/utils/int-setting.js +48 -0
  130. package/lib/utils/murmurhash3.js +66 -0
  131. package/lib/utils/public-suffix.js +122 -0
  132. package/lib/utils/random-id.js +26 -0
  133. package/lib/utils/tracking-settings.js +35 -0
  134. package/lib/utils/version.js +74 -0
  135. package/lib/web-safe-html.js +18 -105
  136. package/lib/webhook-delivery.js +461 -0
  137. package/lib/webhook-failures.js +132 -0
  138. package/lib/webhook-request.js +29 -1
  139. package/lib/webhook-routing.js +56 -0
  140. package/lib/webhook-test.js +88 -0
  141. package/lib/webhooks.js +93 -45
  142. package/lib/worker-rpc-error.js +2 -1
  143. package/package.json +37 -38
  144. package/sbom.json +7902 -1
  145. package/server.js +784 -518
  146. package/static/js/ace/ace.js +1 -1
  147. package/static/licenses.html +225 -1060
  148. package/translations/messages.pot +62 -63
  149. package/views/config/ai.hbs +1 -1
  150. package/views/config/security.hbs +24 -2
  151. package/views/config/service.hbs +47 -0
  152. package/views/config/webhooks.hbs +36 -0
  153. package/views/internals/index.hbs +8 -0
  154. package/views/partials/queue_retention_note.hbs +12 -8
  155. package/views/partials/ui/env-managed-alert.hbs +16 -7
  156. package/views/partials/webhook_form.hbs +1 -1
  157. package/views/suppression-lists/index.hbs +1 -1
  158. package/workers/api.js +840 -611
  159. package/workers/export.js +17 -632
  160. package/workers/imap.js +13 -0
  161. package/workers/smtp.js +9 -11
  162. package/workers/submit.js +1 -1
  163. package/workers/webhooks.js +18 -448
  164. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -23,7 +23,7 @@ const { credentialErrorStatus, isTransientCredentialError, resolveAuthServerCred
23
23
  const { parseMessage } = require('../parse-message');
24
24
  const libmime = require('libmime');
25
25
  const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS } = require('../bounce-detect');
26
- const { parseCalendarEvent, sortCalendarAttachments, CALENDAR_CONTENT_TYPES } = require('../calendar-event');
26
+ const { collectCalendarEvents } = require('../calendar-event');
27
27
  const { llmPreProcess, summaryFetchHeaders, summaryProvider } = require('../llm-pre-process');
28
28
  const { notificationHeaderFields, narrowHeaders } = require('../utils/header-map');
29
29
  const { mapConcurrent } = require('../utils/map-concurrent');
@@ -52,12 +52,13 @@ const {
52
52
  getByteSize,
53
53
  readEnvValue,
54
54
  emitChangeEvent,
55
- filterEmptyObjectValues,
56
55
  getDateBuckets,
57
56
  useAuthServerForOAuth2,
58
57
  collectCidReferences,
59
58
  embedCidImages
60
59
  } = require('../tools');
60
+ const { loadNotifyAttachments, API_ATTACHMENT_CONCURRENCY } = require('../notify-attachments');
61
+ const { TRACKING_SETTINGS, needsTrackingSettings, resolveTracking } = require('../utils/tracking-settings');
61
62
 
62
63
  // Import application constants
63
64
  const {
@@ -79,9 +80,12 @@ const {
79
80
  AUTH_FAILURE_DISABLED_DESCRIPTION,
80
81
  EMAIL_DELIVERY_ERROR_NOTIFY,
81
82
  EMAIL_SENT_NOTIFY,
82
- CHANGE_EVENT_RETRY_DELAYS
83
+ CHANGE_EVENT_RETRY_DELAYS,
84
+ NEW_MESSAGE_SETTINGS
83
85
  } = require('../consts');
84
86
  const { buildRetentionPolicy } = require('../queue-retention');
87
+ const { getFailedJobRetention } = require('../env-setting-overrides');
88
+ const outbox = require('../outbox');
85
89
  const { readImapData } = require('../account/imap-data');
86
90
  const { ReconnectBackoff } = require('./reconnect-backoff');
87
91
 
@@ -468,14 +472,56 @@ class BaseClient {
468
472
  return null;
469
473
  }
470
474
 
475
+ /**
476
+ * Stops syncing for an account flush. The Gmail API and Graph clients hold no connection, so
477
+ * pausing is closing them: timers stop and nothing more is processed until resume()
478
+ */
479
+ async pause() {
480
+ await this.close();
481
+ return true;
482
+ }
483
+
484
+ /**
485
+ * Starts syncing again after a flush. Not awaited, the way IMAPClient.resume() is not: the
486
+ * caller is an RPC with a timeout, and init() can take a token refresh and a subscription
487
+ */
471
488
  async resume() {
472
- return null;
489
+ this.resumeAfterFlush().catch(err => this.logger.error({ msg: 'Resuming failed', action: 'resume', account: this.account, err }));
490
+ return true;
491
+ }
492
+
493
+ /**
494
+ * What resume() starts. A client that has more to do after a flush than reconnect overrides it
495
+ */
496
+ async resumeAfterFlush() {
497
+ return await this.reconnect();
473
498
  }
474
499
 
475
500
  async reconnect() {
476
501
  return null;
477
502
  }
478
503
 
504
+ /**
505
+ * The account's connection state, for the connection counts behind /metrics and the
506
+ * dashboard. Answered from memory: the client is the only writer of the stored state after the
507
+ * account is created, so the stored value is this one. The Gmail API and Graph clients used to
508
+ * read it back from Redis instead, one HGET per account every second, one account at a time
509
+ * @returns {Promise<string>}
510
+ */
511
+ async currentState() {
512
+ return this.state || 'disconnected';
513
+ }
514
+
515
+ /**
516
+ * Removes what the provider keeps on the account's behalf (a Graph subscription, a Gmail Pub/Sub
517
+ * watch). Called while the account record still exists, because the request needs the
518
+ * account's token: once the record is unlinked there is no token left to make it with
519
+ * @returns {Promise<boolean>} True when something was removed
520
+ */
521
+ async releaseRemoteResources() {
522
+ return false;
523
+ }
524
+
479
525
  async getQuota() {
480
526
  return false;
481
527
  }
@@ -827,14 +873,6 @@ class BaseClient {
827
873
  return `${REDIS_PREFIX}iam:${this.account}:g`;
828
874
  }
829
875
 
830
- getLoggedAccountsKey() {
831
- return `${REDIS_PREFIX}iaz:logged`;
832
- }
833
-
834
- async currentState() {
835
- return 'connected';
836
- }
837
-
838
876
  /**
839
877
  * Creates a logger instance that logs to both main logger and account logger
840
878
  * @returns {Object} Synthetic logger that duplicates logs to account storage
@@ -1925,8 +1963,8 @@ class BaseClient {
1925
1963
 
1926
1964
  try {
1927
1965
  referencedMessage = await retryOnTransientError(
1928
- async () => {
1929
- return await this.getMessage(
1966
+ async () =>
1967
+ await this.getMessage(
1930
1968
  data.reference.message,
1931
1969
  {
1932
1970
  fields: !extendedData
@@ -1940,8 +1978,7 @@ class BaseClient {
1940
1978
  textType: extendedData ? '*' : false
1941
1979
  },
1942
1980
  connectionOptions
1943
- );
1944
- },
1981
+ ),
1945
1982
  {
1946
1983
  maxAttempts: 3,
1947
1984
  baseDelay: 1000,
@@ -2320,8 +2357,8 @@ class BaseClient {
2320
2357
 
2321
2358
  try {
2322
2359
  referencedMessage = await retryOnTransientError(
2323
- async () => {
2324
- return await this.getMessage(
2360
+ async () =>
2361
+ await this.getMessage(
2325
2362
  data.reference.message,
2326
2363
  {
2327
2364
  fields: !extendedData
@@ -2335,8 +2372,7 @@ class BaseClient {
2335
2372
  textType: extendedData ? '*' : false
2336
2373
  },
2337
2374
  connectionOptions
2338
- );
2339
- },
2375
+ ),
2340
2376
  {
2341
2377
  maxAttempts: 3,
2342
2378
  baseDelay: 1000,
@@ -2610,24 +2646,13 @@ class BaseClient {
2610
2646
  throw err;
2611
2647
  }
2612
2648
 
2613
- // Configure tracking settings
2614
- if (typeof trackingEnabled !== 'boolean') {
2615
- trackingEnabled = (await settings.get('trackSentMessages')) || false;
2616
- }
2617
-
2618
- if (typeof trackClicks !== 'boolean') {
2619
- trackClicks = await settings.get('trackClicks');
2620
- if (typeof trackClicks !== 'boolean') {
2621
- trackClicks = trackingEnabled;
2622
- }
2623
- }
2624
-
2625
- if (typeof trackOpens !== 'boolean') {
2626
- trackOpens = await settings.get('trackOpens');
2627
- if (typeof trackOpens !== 'boolean') {
2628
- trackOpens = trackingEnabled;
2629
- }
2630
- }
2649
+ // Configure tracking settings: what the message itself does not decide comes from one read
2650
+ // of the instance settings
2651
+ const messageTracking = { trackingEnabled, trackClicks, trackOpens };
2652
+ ({ trackClicks, trackOpens } = resolveTracking(
2653
+ messageTracking,
2654
+ needsTrackingSettings(messageTracking) ? await settings.getMulti(...TRACKING_SETTINGS) : undefined
2655
+ ));
2631
2656
 
2632
2657
  // Add tracking pixels and link tracking
2633
2658
  if (raw && (trackClicks || trackOpens) && baseUrl) {
@@ -2708,13 +2733,10 @@ class BaseClient {
2708
2733
  raw
2709
2734
  });
2710
2735
 
2711
- // Store message in Redis
2712
- await this.redis.hsetBuffer(`${REDIS_PREFIX}iaq:${this.account}`, queueId, msgEntry);
2713
-
2714
- let queueKeep = (await settings.get('queueKeep')) ?? true;
2715
-
2716
- // Configure delivery retry settings
2717
- let defaultDeliveryAttempts = await settings.get('deliveryAttempts');
2736
+ // Retention and retry settings, read together
2737
+ const [queueSettings, failedRetention] = await Promise.all([settings.getMulti('queueKeep', 'deliveryAttempts'), getFailedJobRetention()]);
2738
+ let queueKeep = queueSettings.queueKeep ?? true;
2739
+ let defaultDeliveryAttempts = queueSettings.deliveryAttempts;
2718
2740
  if (typeof defaultDeliveryAttempts !== 'number') {
2719
2741
  defaultDeliveryAttempts = DEFAULT_DELIVERY_ATTEMPTS;
2720
2742
  }
@@ -2736,7 +2758,7 @@ class BaseClient {
2736
2758
  let queueName = 'queued';
2737
2759
  let jobOpts = {
2738
2760
  jobId: queueId,
2739
- ...buildRetentionPolicy(queueKeep),
2761
+ ...buildRetentionPolicy(queueKeep, failedRetention),
2740
2762
  attempts: typeof deliveryAttempts === 'number' ? deliveryAttempts : defaultDeliveryAttempts,
2741
2763
  backoff: {
2742
2764
  type: 'exponential',
@@ -2751,8 +2773,18 @@ class BaseClient {
2751
2773
  jobOpts.delay = sendAt.getTime() - now.getTime();
2752
2774
  }
2753
2775
 
2754
- // Add job to queue
2755
- let job = await this.submitQueue.add(queueName, jobData, jobOpts);
2776
+ // The content and the job that points to it, written together, see outbox.enqueue()
2777
+ const job = await outbox.enqueue({
2778
+ redis: this.redis,
2779
+ queue: this.submitQueue,
2780
+ account: this.account,
2781
+ queueId,
2782
+ content: msgEntry,
2783
+ name: queueName,
2784
+ data: jobData,
2785
+ opts: jobOpts,
2786
+ logger: this.logger
2787
+ });
2756
2788
 
2757
2789
  try {
2758
2790
  await job.updateProgress({
@@ -2959,19 +2991,19 @@ class BaseClient {
2959
2991
  async getMessageFetchOptions() {
2960
2992
  let messageFetchOptions = {};
2961
2993
 
2994
+ const fetchSettings = await settings.getMulti('notifyText', 'notifyTextSize', 'notifyHeaders');
2995
+
2962
2996
  // Configure text content fetching
2963
- let notifyText = await settings.get('notifyText');
2964
- if (notifyText) {
2997
+ if (fetchSettings.notifyText) {
2965
2998
  messageFetchOptions.textType = '*';
2966
- let notifyTextSize = await settings.get('notifyTextSize');
2967
2999
 
2968
- if (notifyTextSize) {
2969
- messageFetchOptions.maxBytes = notifyTextSize;
3000
+ if (fetchSettings.notifyTextSize) {
3001
+ messageFetchOptions.maxBytes = fetchSettings.notifyTextSize;
2970
3002
  }
2971
3003
  }
2972
3004
 
2973
3005
  // Configure header fetching
2974
- let notifyHeaders = (await settings.get('notifyHeaders')) || [];
3006
+ let notifyHeaders = fetchSettings.notifyHeaders || [];
2975
3007
  if (notifyHeaders.length) {
2976
3008
  messageFetchOptions.headers = notifyHeaders.includes('*') ? true : notifyHeaders.length ? notifyHeaders : false;
2977
3009
  }
@@ -3131,129 +3163,27 @@ class BaseClient {
3131
3163
  }
3132
3164
  }
3133
3165
 
3134
- // Download attachment content if configured
3135
- let notifyAttachments = await settings.get('notifyAttachments');
3136
- let notifyAttachmentSize = await settings.get('notifyAttachmentSize');
3137
- if (notifyAttachments && messageData.attachments?.length) {
3138
- for (let attachment of messageData.attachments || []) {
3139
- if (notifyAttachmentSize && attachment.encodedSize && attachment.encodedSize > notifyAttachmentSize) {
3140
- // skip large attachments
3141
- continue;
3142
- }
3143
- if (!attachment.content) {
3144
- try {
3145
- attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
3146
- } catch (err) {
3147
- this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
3148
- }
3149
- }
3150
- }
3151
- }
3166
+ // The settings the rest of this pass reads, in one round trip instead of one each
3167
+ const { notifyAttachments, notifyAttachmentSize, notifyCalendarEvents, notifyWebSafeHtml } = await settings.getMulti(...NEW_MESSAGE_SETTINGS);
3152
3168
 
3153
- // Fetch inline attachments referenced in HTML
3154
- if (messageData.attachments && messageData.attachments.length && messageData.text && messageData.text.html) {
3155
- // fetch inline attachments
3156
- let cidReferences = collectCidReferences(messageData.text.html);
3157
- for (let attachment of messageData.attachments) {
3158
- if (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE) {
3159
- // skip large attachments
3160
- continue;
3161
- }
3162
-
3163
- if (!attachment.content && attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
3164
- try {
3165
- attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
3166
- } catch (err) {
3167
- this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
3168
- }
3169
- }
3169
+ const loadAttachment = async attachment => {
3170
+ try {
3171
+ attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
3172
+ } catch (err) {
3173
+ this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
3170
3174
  }
3175
+ };
3176
+
3177
+ // Download attachment content if configured
3178
+ if (notifyAttachments) {
3179
+ await loadNotifyAttachments(messageData.attachments, notifyAttachmentSize, loadAttachment, API_ATTACHMENT_CONCURRENCY);
3171
3180
  }
3172
3181
 
3173
3182
  // Fetch and process calendar events if needed
3174
- let notifyCalendarEvents = await settings.get('notifyCalendarEvents');
3175
- if (notifyCalendarEvents && messageData.attachments && messageData.attachments.length) {
3176
- let calendarEventMap = new Map();
3177
-
3178
- // Process calendar attachments, text/calendar before application/ics
3179
- for (let attachment of [...messageData.attachments].sort(sortCalendarAttachments)) {
3180
- if (CALENDAR_CONTENT_TYPES.includes(attachment.contentType)) {
3181
- if (!attachment.content) {
3182
- try {
3183
- let calendarBuf = (await this.getAttachment(attachment.id))?.data;
3184
- attachment.content = calendarBuf.toString('base64');
3185
- } catch (err) {
3186
- this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
3187
- }
3188
- }
3189
- if (attachment.content) {
3190
- let contentBuf = Buffer.from(attachment.content, 'base64');
3191
- try {
3192
- const event = parseCalendarEvent(contentBuf);
3193
- if (!event) {
3194
- continue;
3195
- }
3196
-
3197
- // Skip if we already processed this event
3198
- if (calendarEventMap.has(event.eventId)) {
3199
- if (attachment.filename) {
3200
- let existingEntry = calendarEventMap.get(event.eventId);
3201
- if (!existingEntry.filename) {
3202
- // inject filename
3203
- existingEntry.filename = attachment.filename;
3204
- }
3205
- }
3206
- continue;
3207
- }
3208
-
3209
- // Store calendar event data
3210
- calendarEventMap.set(
3211
- event.eventId,
3212
- filterEmptyObjectValues({
3213
- eventId: event.eventId,
3214
- attachment: attachment.id,
3215
- method: attachment.method || event.method || null,
3216
-
3217
- summary: event.summary,
3218
- description: event.description,
3219
- timezone: event.timezone,
3220
- startDate: event.startDate,
3221
- endDate: event.endDate,
3222
- organizer: event.organizer,
3223
-
3224
- filename: attachment.filename,
3225
- contentType: attachment.contentType,
3226
- encoding: 'base64',
3227
- content: attachment.content
3228
- })
3229
- );
3230
- } catch (err) {
3231
- this.logger.error({
3232
- msg: 'Failed to parse calendar event',
3233
- attachment: Object.assign({}, attachment, { content: `${contentBuf.length} bytes` }),
3234
- err
3235
- });
3236
- }
3237
- }
3238
- }
3239
- }
3240
-
3241
- if (calendarEventMap && calendarEventMap.size) {
3242
- // Convert map to array and set default filenames
3243
- messageData.calendarEvents = Array.from(calendarEventMap.values()).map(calendarEvent => {
3244
- if (!calendarEvent.filename) {
3245
- switch (calendarEvent.method && calendarEvent.method.toUpperCase()) {
3246
- case 'CANCEL':
3247
- case 'REQUEST':
3248
- calendarEvent.filename = 'invite.ics';
3249
- break;
3250
- default:
3251
- calendarEvent.filename = 'event.ics';
3252
- break;
3253
- }
3254
- }
3255
- return calendarEvent;
3256
- });
3183
+ if (notifyCalendarEvents) {
3184
+ const calendarEvents = await collectCalendarEvents(messageData.attachments, loadAttachment, this.logger);
3185
+ if (calendarEvents) {
3186
+ messageData.calendarEvents = calendarEvents;
3257
3187
  }
3258
3188
  }
3259
3189
 
@@ -3274,7 +3204,6 @@ class BaseClient {
3274
3204
  }
3275
3205
 
3276
3206
  // Convert message HTML to web safe HTML
3277
- let notifyWebSafeHtml = await settings.get('notifyWebSafeHtml');
3278
3207
  if (notifyWebSafeHtml && messageData.text && (messageData.text.html || messageData.text.plain)) {
3279
3208
  // convert to web safe
3280
3209
  messageData.text._generatedHtml = await messageWebSafeHtml(messageData);
@@ -3288,8 +3217,8 @@ class BaseClient {
3288
3217
  for (let attachment of messageData.attachments) {
3289
3218
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
3290
3219
  if (contentId && cidReferences.has(contentId)) {
3291
- // An attachment the earlier inline pass already loaded is embedded as is; the
3292
- // same size cap applies to anything downloaded here
3220
+ // An attachment notifyAttachments already loaded is embedded as is; anything
3221
+ // downloaded here is capped at the inline image size
3293
3222
  if (!attachment.content && !(attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE)) {
3294
3223
  try {
3295
3224
  attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
@@ -3649,7 +3578,7 @@ class BaseClient {
3649
3578
  }
3650
3579
 
3651
3580
  // Handle provider-specific message ID extraction
3652
- const originalMessageId = ProviderMessageIdHandler.processResponse(info, smtpSettings.host);
3581
+ const originalMessageId = ProviderMessageIdHandler.processResponse(info);
3653
3582
 
3654
3583
  // Update job progress
3655
3584
  try {
@@ -3676,7 +3605,7 @@ class BaseClient {
3676
3605
 
3677
3606
  // Clear cached SMTP error
3678
3607
  try {
3679
- await this.redis.hset(this.getAccountKey(), 'smtpStatus', JSON.stringify({ created: Date.now(), status: 'ok', response: info.response }));
3608
+ await this.redis.hSetExists(this.getAccountKey(), 'smtpStatus', JSON.stringify({ created: Date.now(), status: 'ok', response: info.response }));
3680
3609
  } catch (err) {
3681
3610
  // ignore
3682
3611
  }
@@ -3731,6 +3660,35 @@ class BaseClient {
3731
3660
  return { response: info.response, messageId: info.messageId };
3732
3661
  }
3733
3662
 
3663
+ /**
3664
+ * Puts the primary IMAP connection back into IDLE after a command that took it out, such as
3665
+ * an APPEND. Only the primary connection idles, and only while a mailbox is selected. IDLE
3666
+ * waits for the connection to be free (whenFree), so it never lands between the commands of
3667
+ * a sync or another API call holding the mailbox lock
3668
+ * @param {Object} connectionClient - The IMAP client the command ran on
3669
+ */
3670
+ resumeIdle(connectionClient) {
3671
+ if (!this.imapClient || connectionClient !== this.imapClient || !this.imapClient.mailbox || this.imapClient.idling) {
3672
+ return;
3673
+ }
3674
+ // one wait per connection: another upload while it is pending would only add a second
3675
+ if (this.idleResumeFor === connectionClient) {
3676
+ return;
3677
+ }
3678
+ this.idleResumeFor = connectionClient;
3679
+ connectionClient
3680
+ .idle({ whenFree: true })
3681
+ .catch(err => {
3682
+ // a connection that closed while IDLE waited for it is reconnected by its close handler
3683
+ this.logger[err.code === 'NoConnection' ? 'debug' : 'warn']({ msg: 'IDLE error', err });
3684
+ })
3685
+ .finally(() => {
3686
+ if (this.idleResumeFor === connectionClient) {
3687
+ this.idleResumeFor = null;
3688
+ }
3689
+ });
3690
+ }
3691
+
3734
3692
  /**
3735
3693
  * Uploads sent message to the Sent folder via IMAP
3736
3694
  * @param {Buffer} raw - Raw message content
@@ -3754,12 +3712,7 @@ class BaseClient {
3754
3712
 
3755
3713
  const connectionClient = await this.getImapConnection(connectionOptions, 'submitMessage');
3756
3714
  await connectionClient.append(sentMailbox.path, raw, ['\\Seen']);
3757
-
3758
- if (connectionClient === this.imapClient && this.imapClient.mailbox && !this.imapClient.idling) {
3759
- this.imapClient.idle().catch(err => {
3760
- this.logger.error({ msg: 'IDLE error', err });
3761
- });
3762
- }
3715
+ this.resumeIdle(connectionClient);
3763
3716
 
3764
3717
  return true;
3765
3718
  }
@@ -3896,7 +3849,7 @@ class BaseClient {
3896
3849
  if (smtpStatus) {
3897
3850
  // Store SMTP error for the account
3898
3851
  try {
3899
- await this.redis.hset(this.getAccountKey(), 'smtpStatus', JSON.stringify(smtpStatus));
3852
+ await this.redis.hSetExists(this.getAccountKey(), 'smtpStatus', JSON.stringify(smtpStatus));
3900
3853
  } catch (storeErr) {
3901
3854
  // ignore
3902
3855
  }
@@ -0,0 +1,62 @@
1
+ 'use strict';
2
+
3
+ const { readEnvValue, getDuration } = require('../tools');
4
+
5
+ const DEFAULT_FALLBACK_POLL_INTERVAL = 10 * 60 * 1000;
6
+ const MIN_FALLBACK_POLL_INTERVAL = 10 * 1000;
7
+
8
+ /**
9
+ * Reads a fallback poll interval: a duration ("10m", "30s") or a bare number of milliseconds.
10
+ * Blank and anything unreadable get the default
11
+ * @param {*} value - The raw environment value
12
+ * @param {Object} opts
13
+ * @param {boolean} opts.allowOff - Whether 0 switches the poller off; otherwise 0 gets the default
14
+ * @param {number} [opts.min] - Shortest interval a positive value is raised to
15
+ * @returns {number} Milliseconds, 0 when the poller is off
16
+ */
17
+ function parsePollInterval(value, { allowOff, min = 0 }) {
18
+ // blank is "unset", which getDuration() would read as 0
19
+ const raw = String(value ?? '').trim();
20
+ const duration = raw ? getDuration(raw) : DEFAULT_FALLBACK_POLL_INTERVAL;
21
+ if (typeof duration !== 'number' || !Number.isFinite(duration) || duration < 0 || (duration === 0 && !allowOff)) {
22
+ return DEFAULT_FALLBACK_POLL_INTERVAL;
23
+ }
24
+ return duration && Math.max(duration, min);
25
+ }
26
+
27
+ /**
28
+ * EENGINE_GMAIL_FALLBACK_POLL_INTERVAL: how often a Gmail API account polls for changes when no
29
+ * Pub/Sub notification arrives. A bare number of milliseconds was the only form it used to accept,
30
+ * and the integration tier still sets one; a "10m" fell through to the default without a word. This
31
+ * poller can not be switched off, so 0 gets the default
32
+ * @param {*} value - The raw environment value
33
+ * @returns {number} Milliseconds
34
+ */
35
+ function parseGmailFallbackPollInterval(value) {
36
+ return parsePollInterval(value, { allowOff: false });
37
+ }
38
+
39
+ /**
40
+ * EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL: 0 switches the periodic pass off, and a positive value is
41
+ * never shorter than ten seconds, so a typo can not point every account at Graph in a loop
42
+ * @param {*} value - The raw environment value
43
+ * @returns {number} Milliseconds, 0 when the pass is off
44
+ */
45
+ function parseFallbackPollInterval(value) {
46
+ return parsePollInterval(value, { allowOff: true, min: MIN_FALLBACK_POLL_INTERVAL });
47
+ }
48
+
49
+ const GMAIL_FALLBACK_POLL_INTERVAL = parseGmailFallbackPollInterval(readEnvValue('EENGINE_GMAIL_FALLBACK_POLL_INTERVAL'));
50
+
51
+ // The interval of the periodic missed-notification recovery pass (OutlookClient.setupFallbackPollTimer()).
52
+ // Its own module so the admin UI, which runs in the API worker, reads the same value the account
53
+ // workers run with
54
+ const OUTLOOK_FALLBACK_POLL_INTERVAL = parseFallbackPollInterval(readEnvValue('EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL'));
55
+
56
+ module.exports = {
57
+ parseGmailFallbackPollInterval,
58
+ parseFallbackPollInterval,
59
+ GMAIL_FALLBACK_POLL_INTERVAL,
60
+ OUTLOOK_FALLBACK_POLL_INTERVAL,
61
+ DEFAULT_FALLBACK_POLL_INTERVAL
62
+ };