emailengine-app 2.85.0 → 2.87.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 (137) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +97 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +16 -3
  6. package/ENVIRONMENT.md +139 -0
  7. package/README.md +5 -1
  8. package/config/default.toml +2 -0
  9. package/copy-static-files.sh +4 -2
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +4 -3
  12. package/lib/account-assignment.js +19 -0
  13. package/lib/account.js +285 -195
  14. package/lib/api-error-codes.js +49 -0
  15. package/lib/api-reference/model.js +6 -1
  16. package/lib/api-routes/account-routes.js +91 -32
  17. package/lib/api-routes/blocklist-routes.js +68 -2
  18. package/lib/api-routes/delivery-test-routes.js +1 -1
  19. package/lib/api-routes/gateway-routes.js +82 -10
  20. package/lib/api-routes/index.js +4 -0
  21. package/lib/api-routes/license-routes.js +2 -2
  22. package/lib/api-routes/mailbox-routes.js +3 -3
  23. package/lib/api-routes/message-routes.js +15 -7
  24. package/lib/api-routes/oauth2-app-routes.js +15 -8
  25. package/lib/api-routes/outbox-routes.js +77 -66
  26. package/lib/api-routes/permission-map.js +55 -6
  27. package/lib/api-routes/scoped-routes.js +74 -0
  28. package/lib/api-routes/settings-routes.js +11 -4
  29. package/lib/api-routes/stats-routes.js +5 -1
  30. package/lib/api-routes/submit-routes.js +25 -5
  31. package/lib/api-routes/template-routes.js +7 -6
  32. package/lib/api-routes/token-routes.js +11 -5
  33. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  34. package/lib/api-routes/webhook-route-routes.js +119 -4
  35. package/lib/calendar-event.js +81 -1
  36. package/lib/consts.js +38 -46
  37. package/lib/db.js +14 -6
  38. package/lib/delivery-error.js +6 -0
  39. package/lib/deprecations.js +270 -0
  40. package/lib/email-client/base-client.js +134 -158
  41. package/lib/email-client/fallback-poll.js +62 -0
  42. package/lib/email-client/gmail-client.js +59 -11
  43. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  44. package/lib/email-client/imap/adaptive-idle.js +278 -0
  45. package/lib/email-client/imap/connection-errors.js +14 -1
  46. package/lib/email-client/imap/idle-settings.js +31 -5
  47. package/lib/email-client/imap/listing-diff.js +37 -0
  48. package/lib/email-client/imap/mailbox.js +380 -227
  49. package/lib/email-client/imap/subconnection.js +7 -29
  50. package/lib/email-client/imap/sync-operations.js +220 -127
  51. package/lib/email-client/imap-client.js +227 -163
  52. package/lib/email-client/message-builder.js +14 -79
  53. package/lib/email-client/outlook-client.js +378 -338
  54. package/lib/email-client/smtp-pool-manager.js +16 -13
  55. package/lib/email-client/sync-state-fields.js +19 -0
  56. package/lib/encrypt.js +157 -41
  57. package/lib/enum-descriptions.js +3 -1
  58. package/lib/env-setting-overrides.js +288 -0
  59. package/lib/export-worker.js +751 -0
  60. package/lib/export.js +64 -15
  61. package/lib/field-usage.js +1 -1
  62. package/lib/gateway.js +17 -1
  63. package/lib/get-raw-email.js +35 -108
  64. package/lib/health.js +75 -0
  65. package/lib/lock-run.js +119 -0
  66. package/lib/logger-consts.js +48 -0
  67. package/lib/logger.js +1 -1
  68. package/lib/lua/z-head-scores.lua +28 -0
  69. package/lib/network-errors.js +1 -1
  70. package/lib/node-version.js +24 -0
  71. package/lib/notify-attachments.js +20 -1
  72. package/lib/oauth/gmail.js +54 -29
  73. package/lib/oauth2-apps.js +630 -655
  74. package/lib/otp.js +66 -0
  75. package/lib/outbox.js +184 -54
  76. package/lib/parse-message.js +3 -3
  77. package/lib/privileged-settings.js +2 -2
  78. package/lib/queue-browser/definitions.js +11 -0
  79. package/lib/queue-browser/index.js +68 -19
  80. package/lib/queue-job-actions.js +18 -1
  81. package/lib/queue-retention.js +48 -12
  82. package/lib/queue-stats.js +11 -2
  83. package/lib/read-env-value.js +3 -0
  84. package/lib/redis-memory-warnings.js +99 -0
  85. package/lib/redis-reconnect.js +29 -0
  86. package/lib/request-timing.js +23 -0
  87. package/lib/respawn-backoff.js +35 -0
  88. package/lib/rewrite-text-nodes.js +19 -59
  89. package/lib/schemas.js +225 -41
  90. package/lib/settings.js +6 -2
  91. package/lib/smtp-auth.js +19 -1
  92. package/lib/swagger-options.js +2 -2
  93. package/lib/thread-diagnostics.js +18 -1
  94. package/lib/tls/provision.js +6 -3
  95. package/lib/token-audit-log.js +19 -20
  96. package/lib/token-permission-view.js +4 -3
  97. package/lib/tools.js +8 -41
  98. package/lib/ui-routes/admin-config-routes.js +64 -90
  99. package/lib/ui-routes/admin-entities-routes.js +2 -14
  100. package/lib/ui-routes/imap-idle-field.js +1 -1
  101. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  102. package/lib/ui-routes/overridable-fields.js +84 -0
  103. package/lib/ui-routes/queue-routes.js +8 -5
  104. package/lib/ui-routes/settings-page.js +6 -0
  105. package/lib/utils/decode-headers.js +3 -12
  106. package/lib/utils/filter-empty.js +20 -0
  107. package/lib/utils/int-setting.js +48 -0
  108. package/lib/utils/tracking-settings.js +35 -0
  109. package/lib/web-safe-html.js +18 -105
  110. package/lib/webhook-delivery.js +461 -0
  111. package/lib/webhook-failures.js +132 -0
  112. package/lib/webhook-request.js +29 -1
  113. package/lib/webhook-routing.js +30 -1
  114. package/lib/webhook-test.js +88 -0
  115. package/lib/webhooks.js +59 -41
  116. package/lib/worker-rpc-error.js +2 -1
  117. package/package.json +28 -26
  118. package/sbom.json +600 -678
  119. package/server.js +149 -76
  120. package/static/css/flyonui.css +1 -1
  121. package/static/js/ace/ace.js +1 -1
  122. package/static/js/ee-client.js +650 -196
  123. package/static/licenses.html +49 -59
  124. package/translations/messages.pot +26 -26
  125. package/views/config/security.hbs +22 -0
  126. package/views/config/service.hbs +44 -0
  127. package/views/config/webhooks.hbs +36 -0
  128. package/views/layout/app.hbs +9 -6
  129. package/views/legal.hbs +8 -0
  130. package/views/partials/queue_retention_note.hbs +12 -8
  131. package/views/partials/ui/env-managed-alert.hbs +16 -7
  132. package/workers/api.js +112 -37
  133. package/workers/export.js +16 -631
  134. package/workers/imap.js +13 -0
  135. package/workers/smtp.js +9 -11
  136. package/workers/webhooks.js +18 -432
  137. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -23,9 +23,10 @@ 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
+ const { notifyHeadersIncludeOtp, OTP_FETCH_HEADERS } = require('../otp');
29
30
  const { mapConcurrent } = require('../utils/map-concurrent');
30
31
  const { oauth2Apps } = require('../oauth2-apps');
31
32
  const { Account } = require('../account');
@@ -52,13 +53,13 @@ const {
52
53
  getByteSize,
53
54
  readEnvValue,
54
55
  emitChangeEvent,
55
- filterEmptyObjectValues,
56
56
  getDateBuckets,
57
57
  useAuthServerForOAuth2,
58
58
  collectCidReferences,
59
59
  embedCidImages
60
60
  } = require('../tools');
61
- const { withinNotifyAttachmentSize } = require('../notify-attachments');
61
+ const { loadNotifyAttachments, API_ATTACHMENT_CONCURRENCY } = require('../notify-attachments');
62
+ const { TRACKING_SETTINGS, needsTrackingSettings, resolveTracking } = require('../utils/tracking-settings');
62
63
 
63
64
  // Import application constants
64
65
  const {
@@ -80,9 +81,12 @@ const {
80
81
  AUTH_FAILURE_DISABLED_DESCRIPTION,
81
82
  EMAIL_DELIVERY_ERROR_NOTIFY,
82
83
  EMAIL_SENT_NOTIFY,
83
- CHANGE_EVENT_RETRY_DELAYS
84
+ CHANGE_EVENT_RETRY_DELAYS,
85
+ NEW_MESSAGE_SETTINGS
84
86
  } = require('../consts');
85
87
  const { buildRetentionPolicy } = require('../queue-retention');
88
+ const { getFailedJobRetention } = require('../env-setting-overrides');
89
+ const outbox = require('../outbox');
86
90
  const { readImapData } = require('../account/imap-data');
87
91
  const { ReconnectBackoff } = require('./reconnect-backoff');
88
92
 
@@ -469,14 +473,56 @@ class BaseClient {
469
473
  return null;
470
474
  }
471
475
 
476
+ /**
477
+ * Stops syncing for an account flush. The Gmail API and Graph clients hold no connection, so
478
+ * pausing is closing them: timers stop and nothing more is processed until resume()
479
+ */
480
+ async pause() {
481
+ await this.close();
482
+ return true;
483
+ }
484
+
485
+ /**
486
+ * Starts syncing again after a flush. Not awaited, the way IMAPClient.resume() is not: the
487
+ * caller is an RPC with a timeout, and init() can take a token refresh and a subscription
488
+ */
472
489
  async resume() {
473
- return null;
490
+ this.resumeAfterFlush().catch(err => this.logger.error({ msg: 'Resuming failed', action: 'resume', account: this.account, err }));
491
+ return true;
492
+ }
493
+
494
+ /**
495
+ * What resume() starts. A client that has more to do after a flush than reconnect overrides it
496
+ */
497
+ async resumeAfterFlush() {
498
+ return await this.reconnect();
474
499
  }
475
500
 
476
501
  async reconnect() {
477
502
  return null;
478
503
  }
479
504
 
505
+ /**
506
+ * The account's connection state, for the connection counts behind /metrics and the
507
+ * dashboard. Answered from memory: the client is the only writer of the stored state after the
508
+ * account is created, so the stored value is this one. The Gmail API and Graph clients used to
509
+ * read it back from Redis instead, one HGET per account every second, one account at a time
510
+ * @returns {Promise<string>}
511
+ */
512
+ async currentState() {
513
+ return this.state || 'disconnected';
514
+ }
515
+
516
+ /**
517
+ * Removes what the provider keeps on the account's behalf (a Graph subscription, a Gmail Pub/Sub
518
+ * watch). Called while the account record still exists, because the request needs the
519
+ * account's token: once the record is unlinked there is no token left to make it with
520
+ * @returns {Promise<boolean>} True when something was removed
521
+ */
522
+ async releaseRemoteResources() {
523
+ return false;
524
+ }
525
+
480
526
  async getQuota() {
481
527
  return false;
482
528
  }
@@ -828,14 +874,6 @@ class BaseClient {
828
874
  return `${REDIS_PREFIX}iam:${this.account}:g`;
829
875
  }
830
876
 
831
- getLoggedAccountsKey() {
832
- return `${REDIS_PREFIX}iaz:logged`;
833
- }
834
-
835
- async currentState() {
836
- return 'connected';
837
- }
838
-
839
877
  /**
840
878
  * Creates a logger instance that logs to both main logger and account logger
841
879
  * @returns {Object} Synthetic logger that duplicates logs to account storage
@@ -1799,7 +1837,7 @@ class BaseClient {
1799
1837
  messageCopy.to = [mailMergeEntry.to];
1800
1838
 
1801
1839
  // Apply recipient-specific overrides
1802
- for (let key of ['messageId', 'sendAt']) {
1840
+ for (let key of ['messageId', 'sendAt', 'otp']) {
1803
1841
  if (mailMergeEntry[key]) {
1804
1842
  messageCopy[key] = mailMergeEntry[key];
1805
1843
  }
@@ -2609,24 +2647,13 @@ class BaseClient {
2609
2647
  throw err;
2610
2648
  }
2611
2649
 
2612
- // Configure tracking settings
2613
- if (typeof trackingEnabled !== 'boolean') {
2614
- trackingEnabled = (await settings.get('trackSentMessages')) || false;
2615
- }
2616
-
2617
- if (typeof trackClicks !== 'boolean') {
2618
- trackClicks = await settings.get('trackClicks');
2619
- if (typeof trackClicks !== 'boolean') {
2620
- trackClicks = trackingEnabled;
2621
- }
2622
- }
2623
-
2624
- if (typeof trackOpens !== 'boolean') {
2625
- trackOpens = await settings.get('trackOpens');
2626
- if (typeof trackOpens !== 'boolean') {
2627
- trackOpens = trackingEnabled;
2628
- }
2629
- }
2650
+ // Configure tracking settings: what the message itself does not decide comes from one read
2651
+ // of the instance settings
2652
+ const messageTracking = { trackingEnabled, trackClicks, trackOpens };
2653
+ ({ trackClicks, trackOpens } = resolveTracking(
2654
+ messageTracking,
2655
+ needsTrackingSettings(messageTracking) ? await settings.getMulti(...TRACKING_SETTINGS) : undefined
2656
+ ));
2630
2657
 
2631
2658
  // Add tracking pixels and link tracking
2632
2659
  if (raw && (trackClicks || trackOpens) && baseUrl) {
@@ -2707,13 +2734,10 @@ class BaseClient {
2707
2734
  raw
2708
2735
  });
2709
2736
 
2710
- // Store message in Redis
2711
- await this.redis.hsetBuffer(`${REDIS_PREFIX}iaq:${this.account}`, queueId, msgEntry);
2712
-
2713
- let queueKeep = (await settings.get('queueKeep')) ?? true;
2714
-
2715
- // Configure delivery retry settings
2716
- let defaultDeliveryAttempts = await settings.get('deliveryAttempts');
2737
+ // Retention and retry settings, read together
2738
+ const [queueSettings, failedRetention] = await Promise.all([settings.getMulti('queueKeep', 'deliveryAttempts'), getFailedJobRetention()]);
2739
+ let queueKeep = queueSettings.queueKeep ?? true;
2740
+ let defaultDeliveryAttempts = queueSettings.deliveryAttempts;
2717
2741
  if (typeof defaultDeliveryAttempts !== 'number') {
2718
2742
  defaultDeliveryAttempts = DEFAULT_DELIVERY_ATTEMPTS;
2719
2743
  }
@@ -2735,7 +2759,7 @@ class BaseClient {
2735
2759
  let queueName = 'queued';
2736
2760
  let jobOpts = {
2737
2761
  jobId: queueId,
2738
- ...buildRetentionPolicy(queueKeep),
2762
+ ...buildRetentionPolicy(queueKeep, failedRetention),
2739
2763
  attempts: typeof deliveryAttempts === 'number' ? deliveryAttempts : defaultDeliveryAttempts,
2740
2764
  backoff: {
2741
2765
  type: 'exponential',
@@ -2750,8 +2774,18 @@ class BaseClient {
2750
2774
  jobOpts.delay = sendAt.getTime() - now.getTime();
2751
2775
  }
2752
2776
 
2753
- // Add job to queue
2754
- let job = await this.submitQueue.add(queueName, jobData, jobOpts);
2777
+ // The content and the job that points to it, written together, see outbox.enqueue()
2778
+ const job = await outbox.enqueue({
2779
+ redis: this.redis,
2780
+ queue: this.submitQueue,
2781
+ account: this.account,
2782
+ queueId,
2783
+ content: msgEntry,
2784
+ name: queueName,
2785
+ data: jobData,
2786
+ opts: jobOpts,
2787
+ logger: this.logger
2788
+ });
2755
2789
 
2756
2790
  try {
2757
2791
  await job.updateProgress({
@@ -2958,19 +2992,19 @@ class BaseClient {
2958
2992
  async getMessageFetchOptions() {
2959
2993
  let messageFetchOptions = {};
2960
2994
 
2995
+ const fetchSettings = await settings.getMulti('notifyText', 'notifyTextSize', 'notifyHeaders');
2996
+
2961
2997
  // Configure text content fetching
2962
- let notifyText = await settings.get('notifyText');
2963
- if (notifyText) {
2998
+ if (fetchSettings.notifyText) {
2964
2999
  messageFetchOptions.textType = '*';
2965
- let notifyTextSize = await settings.get('notifyTextSize');
2966
3000
 
2967
- if (notifyTextSize) {
2968
- messageFetchOptions.maxBytes = notifyTextSize;
3001
+ if (fetchSettings.notifyTextSize) {
3002
+ messageFetchOptions.maxBytes = fetchSettings.notifyTextSize;
2969
3003
  }
2970
3004
  }
2971
3005
 
2972
3006
  // Configure header fetching
2973
- let notifyHeaders = (await settings.get('notifyHeaders')) || [];
3007
+ let notifyHeaders = fetchSettings.notifyHeaders || [];
2974
3008
  if (notifyHeaders.length) {
2975
3009
  messageFetchOptions.headers = notifyHeaders.includes('*') ? true : notifyHeaders.length ? notifyHeaders : false;
2976
3010
  }
@@ -2979,7 +3013,8 @@ class BaseClient {
2979
3013
  // while summaries are on. Skipped when the setting already asks for every header
2980
3014
  if (messageFetchOptions.headers !== true) {
2981
3015
  const summaryHeaders = (await llmPreProcess.getPreProcessHandler()) ? summaryFetchHeaders(this.summaryProvider()) : [];
2982
- messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers, summaryHeaders);
3016
+ const otpHeaders = notifyHeadersIncludeOtp(notifyHeaders) ? OTP_FETCH_HEADERS : [];
3017
+ messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers, summaryHeaders.concat(otpHeaders));
2983
3018
  }
2984
3019
 
2985
3020
  return messageFetchOptions;
@@ -3130,109 +3165,27 @@ class BaseClient {
3130
3165
  }
3131
3166
  }
3132
3167
 
3133
- // Download attachment content if configured
3134
- let notifyAttachments = await settings.get('notifyAttachments');
3135
- let notifyAttachmentSize = await settings.get('notifyAttachmentSize');
3136
- if (notifyAttachments && messageData.attachments?.length) {
3137
- for (let attachment of messageData.attachments || []) {
3138
- if (!withinNotifyAttachmentSize(attachment, notifyAttachmentSize)) {
3139
- // skip large attachments
3140
- continue;
3141
- }
3142
- if (!attachment.content) {
3143
- try {
3144
- attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
3145
- } catch (err) {
3146
- this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
3147
- }
3148
- }
3168
+ // The settings the rest of this pass reads, in one round trip instead of one each
3169
+ const { notifyAttachments, notifyAttachmentSize, notifyCalendarEvents, notifyWebSafeHtml } = await settings.getMulti(...NEW_MESSAGE_SETTINGS);
3170
+
3171
+ const loadAttachment = async attachment => {
3172
+ try {
3173
+ attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
3174
+ } catch (err) {
3175
+ this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
3149
3176
  }
3177
+ };
3178
+
3179
+ // Download attachment content if configured
3180
+ if (notifyAttachments) {
3181
+ await loadNotifyAttachments(messageData.attachments, notifyAttachmentSize, loadAttachment, API_ATTACHMENT_CONCURRENCY);
3150
3182
  }
3151
3183
 
3152
3184
  // Fetch and process calendar events if needed
3153
- let notifyCalendarEvents = await settings.get('notifyCalendarEvents');
3154
- if (notifyCalendarEvents && messageData.attachments && messageData.attachments.length) {
3155
- let calendarEventMap = new Map();
3156
-
3157
- // Process calendar attachments, text/calendar before application/ics
3158
- for (let attachment of [...messageData.attachments].sort(sortCalendarAttachments)) {
3159
- if (CALENDAR_CONTENT_TYPES.includes(attachment.contentType)) {
3160
- if (!attachment.content) {
3161
- try {
3162
- let calendarBuf = (await this.getAttachment(attachment.id))?.data;
3163
- attachment.content = calendarBuf.toString('base64');
3164
- } catch (err) {
3165
- this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
3166
- }
3167
- }
3168
- if (attachment.content) {
3169
- let contentBuf = Buffer.from(attachment.content, 'base64');
3170
- try {
3171
- const event = parseCalendarEvent(contentBuf);
3172
- if (!event) {
3173
- continue;
3174
- }
3175
-
3176
- // Skip if we already processed this event
3177
- if (calendarEventMap.has(event.eventId)) {
3178
- if (attachment.filename) {
3179
- let existingEntry = calendarEventMap.get(event.eventId);
3180
- if (!existingEntry.filename) {
3181
- // inject filename
3182
- existingEntry.filename = attachment.filename;
3183
- }
3184
- }
3185
- continue;
3186
- }
3187
-
3188
- // Store calendar event data
3189
- calendarEventMap.set(
3190
- event.eventId,
3191
- filterEmptyObjectValues({
3192
- eventId: event.eventId,
3193
- attachment: attachment.id,
3194
- method: attachment.method || event.method || null,
3195
-
3196
- summary: event.summary,
3197
- description: event.description,
3198
- timezone: event.timezone,
3199
- startDate: event.startDate,
3200
- endDate: event.endDate,
3201
- organizer: event.organizer,
3202
-
3203
- filename: attachment.filename,
3204
- contentType: attachment.contentType,
3205
- encoding: 'base64',
3206
- content: attachment.content
3207
- })
3208
- );
3209
- } catch (err) {
3210
- this.logger.error({
3211
- msg: 'Failed to parse calendar event',
3212
- attachment: Object.assign({}, attachment, { content: `${contentBuf.length} bytes` }),
3213
- err
3214
- });
3215
- }
3216
- }
3217
- }
3218
- }
3219
-
3220
- if (calendarEventMap && calendarEventMap.size) {
3221
- // Convert map to array and set default filenames
3222
- messageData.calendarEvents = Array.from(calendarEventMap.values()).map(calendarEvent => {
3223
- if (!calendarEvent.filename) {
3224
- switch (calendarEvent.method && calendarEvent.method.toUpperCase()) {
3225
- case 'CANCEL':
3226
- case 'REQUEST':
3227
- calendarEvent.filename = 'invite.ics';
3228
- break;
3229
- default:
3230
- calendarEvent.filename = 'event.ics';
3231
- break;
3232
- }
3233
- }
3234
- return calendarEvent;
3235
- });
3185
+ if (notifyCalendarEvents) {
3186
+ const calendarEvents = await collectCalendarEvents(messageData.attachments, loadAttachment, this.logger);
3187
+ if (calendarEvents) {
3188
+ messageData.calendarEvents = calendarEvents;
3236
3189
  }
3237
3190
  }
3238
3191
 
@@ -3253,7 +3206,6 @@ class BaseClient {
3253
3206
  }
3254
3207
 
3255
3208
  // Convert message HTML to web safe HTML
3256
- let notifyWebSafeHtml = await settings.get('notifyWebSafeHtml');
3257
3209
  if (notifyWebSafeHtml && messageData.text && (messageData.text.html || messageData.text.plain)) {
3258
3210
  // convert to web safe
3259
3211
  messageData.text._generatedHtml = await messageWebSafeHtml(messageData);
@@ -3628,7 +3580,7 @@ class BaseClient {
3628
3580
  }
3629
3581
 
3630
3582
  // Handle provider-specific message ID extraction
3631
- const originalMessageId = ProviderMessageIdHandler.processResponse(info, smtpSettings.host);
3583
+ const originalMessageId = ProviderMessageIdHandler.processResponse(info);
3632
3584
 
3633
3585
  // Update job progress
3634
3586
  try {
@@ -3655,7 +3607,7 @@ class BaseClient {
3655
3607
 
3656
3608
  // Clear cached SMTP error
3657
3609
  try {
3658
- await this.redis.hset(this.getAccountKey(), 'smtpStatus', JSON.stringify({ created: Date.now(), status: 'ok', response: info.response }));
3610
+ await this.redis.hSetExists(this.getAccountKey(), 'smtpStatus', JSON.stringify({ created: Date.now(), status: 'ok', response: info.response }));
3659
3611
  } catch (err) {
3660
3612
  // ignore
3661
3613
  }
@@ -3710,6 +3662,35 @@ class BaseClient {
3710
3662
  return { response: info.response, messageId: info.messageId };
3711
3663
  }
3712
3664
 
3665
+ /**
3666
+ * Puts the primary IMAP connection back into IDLE after a command that took it out, such as
3667
+ * an APPEND. Only the primary connection idles, and only while a mailbox is selected. IDLE
3668
+ * waits for the connection to be free (whenFree), so it never lands between the commands of
3669
+ * a sync or another API call holding the mailbox lock
3670
+ * @param {Object} connectionClient - The IMAP client the command ran on
3671
+ */
3672
+ resumeIdle(connectionClient) {
3673
+ if (!this.imapClient || connectionClient !== this.imapClient || !this.imapClient.mailbox || this.imapClient.idling) {
3674
+ return;
3675
+ }
3676
+ // one wait per connection: another upload while it is pending would only add a second
3677
+ if (this.idleResumeFor === connectionClient) {
3678
+ return;
3679
+ }
3680
+ this.idleResumeFor = connectionClient;
3681
+ connectionClient
3682
+ .idle({ whenFree: true })
3683
+ .catch(err => {
3684
+ // a connection that closed while IDLE waited for it is reconnected by its close handler
3685
+ this.logger[err.code === 'NoConnection' ? 'debug' : 'warn']({ msg: 'IDLE error', err });
3686
+ })
3687
+ .finally(() => {
3688
+ if (this.idleResumeFor === connectionClient) {
3689
+ this.idleResumeFor = null;
3690
+ }
3691
+ });
3692
+ }
3693
+
3713
3694
  /**
3714
3695
  * Uploads sent message to the Sent folder via IMAP
3715
3696
  * @param {Buffer} raw - Raw message content
@@ -3733,12 +3714,7 @@ class BaseClient {
3733
3714
 
3734
3715
  const connectionClient = await this.getImapConnection(connectionOptions, 'submitMessage');
3735
3716
  await connectionClient.append(sentMailbox.path, raw, ['\\Seen']);
3736
-
3737
- if (connectionClient === this.imapClient && this.imapClient.mailbox && !this.imapClient.idling) {
3738
- this.imapClient.idle().catch(err => {
3739
- this.logger.error({ msg: 'IDLE error', err });
3740
- });
3741
- }
3717
+ this.resumeIdle(connectionClient);
3742
3718
 
3743
3719
  return true;
3744
3720
  }
@@ -3875,7 +3851,7 @@ class BaseClient {
3875
3851
  if (smtpStatus) {
3876
3852
  // Store SMTP error for the account
3877
3853
  try {
3878
- await this.redis.hset(this.getAccountKey(), 'smtpStatus', JSON.stringify(smtpStatus));
3854
+ await this.redis.hSetExists(this.getAccountKey(), 'smtpStatus', JSON.stringify(smtpStatus));
3879
3855
  } catch (storeErr) {
3880
3856
  // ignore
3881
3857
  }
@@ -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
+ };