emailengine-app 2.81.2 → 2.82.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 (226) hide show
  1. package/.ncurc.js +33 -10
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +71 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/Dockerfile +2 -0
  6. package/bin/emailengine.js +105 -25
  7. package/config/default.toml +0 -5
  8. package/config/test.toml +0 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +70 -42
  11. package/getswagger.sh +0 -4
  12. package/lib/account/account-state.js +2 -110
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +138 -1
  15. package/lib/account.js +289 -869
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-binding.js +58 -0
  19. package/lib/api-routes/account-routes.js +65 -37
  20. package/lib/api-routes/behavior-notes.js +4 -0
  21. package/lib/api-routes/blocklist-routes.js +2 -2
  22. package/lib/api-routes/bull-board-routes.js +1 -6
  23. package/lib/api-routes/export-routes.js +2 -22
  24. package/lib/api-routes/gateway-routes.js +15 -16
  25. package/lib/api-routes/index.js +1 -13
  26. package/lib/api-routes/mailbox-routes.js +2 -7
  27. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  28. package/lib/api-routes/mcp-routes.js +7 -7
  29. package/lib/api-routes/message-routes.js +50 -238
  30. package/lib/api-routes/mint-bounds.js +110 -0
  31. package/lib/api-routes/oauth2-app-routes.js +23 -32
  32. package/lib/api-routes/operation-impact.js +1 -1
  33. package/lib/api-routes/outbox-routes.js +3 -3
  34. package/lib/api-routes/permission-map.js +1 -7
  35. package/lib/api-routes/route-helpers.js +11 -5
  36. package/lib/api-routes/settings-routes.js +20 -21
  37. package/lib/api-routes/stats-routes.js +1 -1
  38. package/lib/api-routes/submit-routes.js +17 -18
  39. package/lib/api-routes/template-routes.js +4 -9
  40. package/lib/api-routes/token-routes.js +28 -6
  41. package/lib/api-token-scheme.js +71 -0
  42. package/lib/arf-detect.js +33 -6
  43. package/lib/auth-token.js +44 -24
  44. package/lib/autodetect-imap-settings.js +305 -123
  45. package/lib/bounce-detect.js +25 -16
  46. package/lib/calendar-event.js +78 -0
  47. package/lib/consts.js +54 -5
  48. package/lib/create-imap-client.js +24 -0
  49. package/lib/db.js +77 -30
  50. package/lib/delivery-error.js +70 -2
  51. package/lib/egress-fetch.js +54 -3
  52. package/lib/egress-filter.js +11 -0
  53. package/lib/email-client/api-retry.js +147 -0
  54. package/lib/email-client/base-client.js +383 -536
  55. package/lib/email-client/credential-errors.js +21 -5
  56. package/lib/email-client/gmail/gmail-api.js +38 -125
  57. package/lib/email-client/gmail/send-request.js +1 -1
  58. package/lib/email-client/gmail-client.js +77 -51
  59. package/lib/email-client/imap/mailbox.js +158 -324
  60. package/lib/email-client/imap/stale-view.js +109 -0
  61. package/lib/email-client/imap/subconnection.js +46 -9
  62. package/lib/email-client/imap/sync-operations.js +5 -37
  63. package/lib/email-client/imap-client.js +190 -65
  64. package/lib/email-client/message-builder.js +50 -25
  65. package/lib/email-client/notification-handler.js +5 -219
  66. package/lib/email-client/outlook/graph-api.js +147 -126
  67. package/lib/email-client/outlook/send-request.js +10 -4
  68. package/lib/email-client/outlook-client.js +389 -463
  69. package/lib/email-client/smtp-pool-manager.js +3 -2
  70. package/lib/encrypt.js +184 -19
  71. package/lib/enum-descriptions.js +6 -3
  72. package/lib/export.js +141 -41
  73. package/lib/gateway.js +25 -6
  74. package/lib/get-raw-email.js +26 -44
  75. package/lib/get-secret.js +1 -21
  76. package/lib/handlebars-helpers.js +31 -10
  77. package/lib/imap-proxy-auth.js +13 -29
  78. package/lib/imapproxy/imap-core/README.md +1 -0
  79. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  80. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  81. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  82. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  83. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  84. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  85. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  86. package/lib/imapproxy/imap-server.js +17 -177
  87. package/lib/imapproxy/proxy-handoff.js +235 -0
  88. package/lib/imapproxy/response-error.js +33 -0
  89. package/lib/imapproxy/upstream-client.js +2 -2
  90. package/lib/license-beacon.js +3 -9
  91. package/lib/llm-pre-process.js +182 -43
  92. package/lib/logger.js +1 -1
  93. package/lib/lua/ee-export-queue-add.lua +39 -0
  94. package/lib/lua/ee-get-idempotency.lua +15 -3
  95. package/lib/lua/ee-release-attempts.lua +23 -0
  96. package/lib/lua/ee-reserve-attempts.lua +42 -0
  97. package/lib/lua/h-set-bigger.lua +12 -2
  98. package/lib/lua/s-list-accounts.lua +6 -3
  99. package/lib/mcp/index.js +1 -2
  100. package/lib/mcp/listen.js +221 -18
  101. package/lib/mcp/oauth.js +44 -5
  102. package/lib/mcp/resources.js +8 -2
  103. package/lib/mcp/tools.js +108 -36
  104. package/lib/message-port-stream.js +64 -6
  105. package/lib/oauth/external-account-signer.js +16 -13
  106. package/lib/oauth/gmail.js +64 -32
  107. package/lib/oauth/mail-ru.js +24 -17
  108. package/lib/oauth/outlook.js +53 -40
  109. package/lib/oauth/pubsub/google.js +38 -2
  110. package/lib/oauth/scope-checker.js +39 -8
  111. package/lib/oauth/scope-list.js +55 -0
  112. package/lib/oauth/token-fetch.js +47 -0
  113. package/lib/oauth/verify-app.js +2 -2
  114. package/lib/oauth2-apps.js +154 -90
  115. package/lib/openapi/build-document.js +1 -1
  116. package/lib/openapi/joi-schema.js +78 -9
  117. package/lib/outbox.js +2 -7
  118. package/lib/parse-message.js +21 -0
  119. package/lib/payload-examples-webhooks.json +4 -7
  120. package/lib/pbkdf2-phc.js +101 -0
  121. package/lib/privileged-settings.js +0 -14
  122. package/lib/queue-retention.js +4 -2
  123. package/lib/rate-limit.js +54 -15
  124. package/lib/read-env-value.js +33 -2
  125. package/lib/redis-scan-delete.js +56 -29
  126. package/lib/redis-url.js +3 -1
  127. package/lib/respawn-backoff.js +5 -4
  128. package/lib/response-stream.js +25 -4
  129. package/lib/rewrite-text-nodes.js +27 -40
  130. package/lib/routes-ui.js +0 -5
  131. package/lib/schemas.js +180 -253
  132. package/lib/sentry.js +21 -5
  133. package/lib/settings.js +58 -59
  134. package/lib/smtp-auth.js +6 -2
  135. package/lib/smtp-message-processor.js +28 -7
  136. package/lib/sso.js +7 -3
  137. package/lib/stream-encrypt.js +14 -13
  138. package/lib/swagger-options.js +3 -1
  139. package/lib/tls/provision.js +69 -3
  140. package/lib/tls/store.js +14 -1
  141. package/lib/token-audit-log.js +3 -2
  142. package/lib/tools.js +114 -53
  143. package/lib/totp.js +16 -1
  144. package/lib/ui-routes/account-routes.js +67 -70
  145. package/lib/ui-routes/admin-config-routes.js +111 -134
  146. package/lib/ui-routes/admin-entities-routes.js +101 -191
  147. package/lib/ui-routes/ai-options.js +104 -0
  148. package/lib/ui-routes/auth-routes.js +98 -18
  149. package/lib/ui-routes/export-routes.js +3 -23
  150. package/lib/ui-routes/internals-routes.js +12 -9
  151. package/lib/ui-routes/network-config-routes.js +8 -18
  152. package/lib/ui-routes/oauth-config-routes.js +83 -228
  153. package/lib/ui-routes/route-helpers.js +63 -67
  154. package/lib/ui-routes/special-use-paths.js +33 -0
  155. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  156. package/lib/utils/decode-headers.js +32 -5
  157. package/lib/utils/header-map.js +62 -1
  158. package/lib/utils/network.js +11 -17
  159. package/lib/web-safe-html.js +77 -4
  160. package/lib/webhook-request.js +9 -1
  161. package/lib/webhook-routing.js +27 -1
  162. package/lib/webhooks.js +120 -43
  163. package/lib/worker-rpc-error.js +43 -2
  164. package/list-generate.js +13 -2
  165. package/package.json +38 -46
  166. package/sbom.json +1 -1
  167. package/scripts/refresh-test-tokens.js +42 -14
  168. package/server.js +338 -292
  169. package/setup-production.sh +16 -7
  170. package/static/css/flyonui.css +1 -1
  171. package/static/css/src/app.tailwind.css +7 -8
  172. package/static/js/ee-client.js +145 -70
  173. package/static/js/ui.js +350 -154
  174. package/static/licenses.html +349 -1740
  175. package/translations/messages.pot +129 -111
  176. package/views/account-workspace-error.hbs +30 -0
  177. package/views/accounts/account.hbs +9 -4
  178. package/views/accounts/browse.hbs +10 -4
  179. package/views/accounts/edit.hbs +11 -2
  180. package/views/config/ai.hbs +49 -41
  181. package/views/config/oauth/app.hbs +2 -1
  182. package/views/dashboard.hbs +18 -16
  183. package/views/internals/index.hbs +1 -1
  184. package/views/layout/app.hbs +0 -22
  185. package/views/layout/login.hbs +2 -1
  186. package/views/partials/filter_editor_js.hbs +4 -3
  187. package/views/partials/gmail_api_scopes.hbs +16 -0
  188. package/views/partials/oauth_form.hbs +67 -94
  189. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  190. package/views/partials/scope_info.hbs +14 -23
  191. package/views/partials/side_menu.hbs +0 -4
  192. package/views/partials/ui/account-picker.hbs +6 -32
  193. package/views/partials/ui/model-picker.hbs +31 -0
  194. package/views/partials/ui/pagination.hbs +6 -1
  195. package/views/partials/ui/picker.hbs +47 -0
  196. package/views/unsubscribe.hbs +1 -1
  197. package/workers/api.js +82 -47
  198. package/workers/export.js +55 -60
  199. package/workers/imap.js +132 -49
  200. package/workers/submit.js +5 -6
  201. package/workers/webhooks.js +46 -27
  202. package/.githooks/pre-commit +0 -80
  203. package/.github/CODE_OF_CONDUCT.md +0 -76
  204. package/.github/contributing.md +0 -17
  205. package/.github/dependabot.yml +0 -22
  206. package/.github/docker-smoke-test.sh +0 -61
  207. package/.github/workflows/deploy.yml +0 -215
  208. package/.github/workflows/e2e.yml +0 -55
  209. package/.github/workflows/release.yaml +0 -217
  210. package/.github/workflows/test.yml +0 -307
  211. package/lib/api-routes/chat-routes.js +0 -535
  212. package/lib/document-store.js +0 -75
  213. package/lib/es.js +0 -757
  214. package/lib/generate-text-preview.js +0 -61
  215. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  216. package/lib/pre-process.js +0 -196
  217. package/lib/threads.js +0 -155
  218. package/lib/ui-routes/document-store-routes.js +0 -806
  219. package/playwright.config.js +0 -47
  220. package/views/config/document-store/chat.hbs +0 -286
  221. package/views/config/document-store/index.hbs +0 -146
  222. package/views/config/document-store/mappings/index.hbs +0 -108
  223. package/views/config/document-store/mappings/new.hbs +0 -68
  224. package/views/config/document-store/pre-processing/index.hbs +0 -103
  225. package/views/partials/document_store_header.hbs +0 -30
  226. package/workers/documents.js +0 -1128
@@ -22,10 +22,10 @@
22
22
  * @requires mailparser - For parsing email messages
23
23
  */
24
24
 
25
- const { decodeHeaders } = require('./utils/decode-headers');
25
+ const { decodeHeaders, capHeaderBlock, MAX_HEADER_BLOCK_SIZE } = require('./utils/decode-headers');
26
26
  const { isUnsafeTransformedKey } = require('./utils/unsafe-key');
27
27
  const { pushHeaderValue } = require('./utils/header-map');
28
- const simpleParser = require('mailparser').simpleParser;
28
+ const { parseMessage } = require('./parse-message');
29
29
  const { toCamelCase } = require('./utils/to-camel-case');
30
30
 
31
31
  // Wording of a notice that reports a delay rather than a failure. Sendmail and qmail-style MTAs
@@ -71,6 +71,11 @@ function splitAddressType(value) {
71
71
  return { label: value.substring(0, splitPos).trim(), value: value.substring(splitPos + 1).trim() };
72
72
  }
73
73
 
74
+ // Options for every parseMessage() call here. None of them reads the HTML, and without
75
+ // keepCidLinks mailparser inlines every cid: image as a data URL once per reference, which a small
76
+ // message can grow past the maximum string length, outside any promise.
77
+ const PARSER_OPTIONS = { keepDeliveryStatus: true, skipTextToHtml: true, skipImageLinks: true, keepCidLinks: true };
78
+
74
79
  /**
75
80
  * Splits the body of a message/delivery-status part into its header blocks
76
81
  *
@@ -84,8 +89,7 @@ function splitAddressType(value) {
84
89
  */
85
90
  function decodeDeliveryStatusBlocks(content) {
86
91
  return (
87
- (content || '')
88
- .toString()
92
+ capHeaderBlock(content)
89
93
  .replace(/\r\n|\r/g, '\n')
90
94
  .split(/\n{2,}/)
91
95
  .map(block => decodeHeaders(block))
@@ -333,7 +337,7 @@ async function bounceDetect(sourceStream) {
333
337
  parsed = sourceStream.parsed;
334
338
  } else {
335
339
  // Parse the email, keeping delivery status attachments intact
336
- parsed = await simpleParser(sourceStream, { keepDeliveryStatus: true });
340
+ parsed = await parseMessage(sourceStream, PARSER_OPTIONS);
337
341
  }
338
342
 
339
343
  let result = {};
@@ -399,7 +403,7 @@ async function bounceDetect(sourceStream) {
399
403
 
400
404
  // Process RFC822 headers attachment (contains headers of the original message)
401
405
  if (messageHeaders) {
402
- parsedMessageHeaders = decodeHeaders((messageHeaders.content || '').toString().trim());
406
+ parsedMessageHeaders = decodeHeaders(messageHeaders.content);
403
407
  result = Object.assign(result, parseDeliveryHeaders(parsedMessageHeaders));
404
408
  }
405
409
 
@@ -407,7 +411,7 @@ async function bounceDetect(sourceStream) {
407
411
  if (originalMessage) {
408
412
  try {
409
413
  // Parse the original message to extract its headers
410
- let parsedOriginal = await simpleParser(originalMessage.content, { keepDeliveryStatus: true });
414
+ let parsedOriginal = await parseMessage(originalMessage.content, PARSER_OPTIONS);
411
415
  if (parsedOriginal) {
412
416
  // Build headers object from headerLines for consistent access
413
417
  let headers = {};
@@ -442,7 +446,7 @@ async function bounceDetect(sourceStream) {
442
446
  if (!messageHeaders) {
443
447
  messageHeaders = originalAttachments.find(attachment => attachment.contentType?.toLowerCase() === 'text/rfc822-headers');
444
448
  if (messageHeaders) {
445
- let headerEntries = decodeHeaders((messageHeaders.content || '').toString().trim());
449
+ let headerEntries = decodeHeaders(messageHeaders.content);
446
450
  result = Object.assign(result, parseDeliveryHeaders(headerEntries));
447
451
  }
448
452
  }
@@ -490,11 +494,11 @@ async function bounceDetect(sourceStream) {
490
494
 
491
495
  if (isZohoBounce) {
492
496
  try {
493
- let parsedOriginal = await simpleParser(zohoOriginalMessage.content, { keepDeliveryStatus: true });
497
+ let parsedOriginal = await parseMessage(zohoOriginalMessage.content, PARSER_OPTIONS);
494
498
  // Zoho sometimes includes headers in the text body with no actual header structure
495
499
  if (parsedOriginal && parsedOriginal.text && (!parsedOriginal.headerLines || !parsedOriginal.headerLines.filter(h => h.key).length)) {
496
500
  // Remove leading spaces that indicate header continuation
497
- let headerContent = (parsedOriginal.text || '').toString().replace(/^ (?=[^ ])/gm, '');
501
+ let headerContent = capHeaderBlock(parsedOriginal.text).replace(/^ (?=[^ ])/gm, '');
498
502
 
499
503
  // Additional validation: content should look like email headers
500
504
  // Check for common header patterns (Received:, Message-ID:, Date:, From:)
@@ -544,7 +548,9 @@ async function bounceDetect(sourceStream) {
544
548
  * <user@example.com>: host mx.example.com[1.2.3.4] said:
545
549
  * 550 5.1.1 No such user (in reply to RCPT TO command)
546
550
  */
547
- let m = text.match(/<([^>@]+@[^>]+)>:\s*host\s+([a-z0-9._-]+)\s*(?:\[([^\]]+)\])?\s+said:/im);
551
+ // The address classes exclude '<' and whitespace and are bounded, so a run of '<' or of
552
+ // unterminated addresses can not make every start position scan to the end of the text
553
+ let m = text.match(/<([^<>@\s]{1,256}@[^<>\s]{1,256})>:\s*host\s+([a-z0-9._-]+)\s*(?:\[([^\]]+)\])?\s+said:/im);
548
554
  if (m) {
549
555
  // Find the end of the error message (double newline or end of string)
550
556
  let end = text.substr(m.index + m[0].length).match(/\r?\n\r?\n|$/);
@@ -615,7 +621,9 @@ async function bounceDetect(sourceStream) {
615
621
  *
616
622
  * 550-5.7.1 [1.2.3.4 11] Our system has detected that this message is not RFC 5322 compliant...
617
623
  */
618
- let m = text.match(/^\s*[45]\d{2}[\s-](\d+\.\d+\.\d+)[\s-]/im);
624
+ // [ \t]* rather than \s*: with the m flag every line start is a candidate, and \s* let each
625
+ // of them run across all the following blank lines (quadratic on a run of newlines)
626
+ let m = text.match(/^[ \t]*[45]\d{2}[\s-](\d+\.\d+\.\d+)[\s-]/im);
619
627
  if (m) {
620
628
  let end = text.substr(m.index + m[0].length).match(/\r?\n\r?\n|$/);
621
629
  if (end) {
@@ -650,7 +658,7 @@ async function bounceDetect(sourceStream) {
650
658
  * 550: 5.1.1 <user@example.com>: Recipient address rejected: User unknown in relay recipient table
651
659
  */
652
660
  // Use bounded quantifier to prevent ReDoS
653
- let m = text.match(/\n<([^>@]+@[^>]+)>:[\s\r\n]{1,100}/);
661
+ let m = text.match(/\n<([^<>@\s]{1,256}@[^<>\s]{1,256})>:[\s\r\n]{1,100}/);
654
662
  if (m) {
655
663
  result.recipient = result.recipient || m[1];
656
664
 
@@ -796,7 +804,7 @@ async function bounceDetect(sourceStream) {
796
804
  // Check if this block starts with or contains our recipient email
797
805
  if (block.includes(result.recipient)) {
798
806
  // Look for "host ... :" pattern followed by error message
799
- const hostMatch = block.match(/\shost\s+[^\n:]+:\s*(.+)/s);
807
+ const hostMatch = block.match(/\shost\s+[^\n:]{1,256}:\s*(.+)/s);
800
808
  if (hostMatch && hostMatch[1]) {
801
809
  const message = hostMatch[1].replace(/\s+/g, ' ').trim();
802
810
  if (message) {
@@ -896,7 +904,8 @@ async function bounceDetect(sourceStream) {
896
904
  * Message could not be delivered to mobile.
897
905
  * Error: No valid recipients for this MM
898
906
  */
899
- let m = text.match(/(?:Message could not be delivered|Error:[^\n]*(?:Invalid|No valid|not taken)[^\n]*)/i);
907
+ // Bounded, so a line of repeated "Error:" does not rescan the line from every occurrence
908
+ let m = text.match(/(?:Message could not be delivered|Error:[^\n]{0,256}?(?:Invalid|No valid|not taken)[^\n]{0,512})/i);
900
909
  if (m) {
901
910
  result.action = result.action || 'failed';
902
911
  result.response = result.response || {};
@@ -1014,4 +1023,4 @@ function applyDeliveryReport(parsed, messageInfo, logger) {
1014
1023
  return true;
1015
1024
  }
1016
1025
 
1017
- module.exports = { bounceDetect, decodeDeliveryStatus, parseDeliveryReport, applyDeliveryReport };
1026
+ module.exports = { bounceDetect, decodeDeliveryStatus, parseDeliveryReport, applyDeliveryReport, PARSER_OPTIONS, MAX_HEADER_BLOCK_SIZE };
@@ -0,0 +1,78 @@
1
+ 'use strict';
2
+
3
+ // The calendar event EmailEngine reports from an iCalendar attachment (text/calendar or
4
+ // application/ics). Shared by the IMAP sync (lib/email-client/imap/mailbox.js) and the API
5
+ // clients (lib/email-client/base-client.js), which used to carry two copies of this parse.
6
+ //
7
+ // A DTSTART or DTEND carrying a TZID is resolved against the VTIMEZONE embedded in the same
8
+ // VCALENDAR (ical.js 2.x; 1.x read such a value as floating, in the server's own zone), so the
9
+ // ISO timestamps are the instant the invite means wherever EmailEngine happens to run.
10
+
11
+ const ical = require('ical.js');
12
+
13
+ const CALENDAR_CONTENT_TYPES = ['text/calendar', 'application/ics'];
14
+
15
+ // text/calendar before application/ics: when an invite arrives as both, the first attachment
16
+ // seen for an event UID is the one reported, and text/calendar is the part the sending client
17
+ // marked as the calendar payload
18
+ function sortCalendarAttachments(a, b) {
19
+ if (a.contentType !== b.contentType) {
20
+ if (a.contentType === 'text/calendar') {
21
+ return -1;
22
+ }
23
+ if (b.contentType === 'text/calendar') {
24
+ return 1;
25
+ }
26
+ }
27
+ return a.contentType.localeCompare(b.contentType);
28
+ }
29
+
30
+ /**
31
+ * Reads the first VEVENT of an iCalendar document
32
+ *
33
+ * @param {string|Buffer} content - iCalendar text
34
+ * @returns {object|null} The event fields, or null when the document holds no VEVENT with a UID
35
+ * @throws When the content is not parseable iCalendar data
36
+ */
37
+ function parseCalendarEvent(content) {
38
+ const comp = new ical.Component(ical.parse(content.toString()));
39
+
40
+ const vevent = comp.getFirstSubcomponent('vevent');
41
+ if (!vevent) {
42
+ return null;
43
+ }
44
+
45
+ // REQUEST, CANCEL, REPLY and so on
46
+ const methodProp = comp.getFirstProperty('method');
47
+
48
+ const event = new ical.Event(vevent);
49
+ if (!event.uid) {
50
+ return null;
51
+ }
52
+
53
+ let timezone;
54
+ const vtz = comp.getFirstSubcomponent('vtimezone');
55
+ if (vtz) {
56
+ const tz = new ical.Timezone(vtz);
57
+ timezone = tz && tz.tzid;
58
+ }
59
+
60
+ let startDate = event.startDate && event.startDate.toJSDate();
61
+ // Without a DTEND the end is a copy of the start, and with neither the getter throws. A
62
+ // cancellation may carry no DTSTART at all (RFC 5546 3.2.5), so the end is only read when
63
+ // there is something to answer it from
64
+ let endDate = startDate || vevent.hasProperty('dtend') ? event.endDate && event.endDate.toJSDate() : null;
65
+
66
+ return {
67
+ eventId: event.uid,
68
+ method: methodProp ? methodProp.getFirstValue() : null,
69
+ summary: event.summary || null,
70
+ description: event.description || null,
71
+ timezone: timezone || null,
72
+ startDate: startDate ? startDate.toISOString() : null,
73
+ endDate: endDate ? endDate.toISOString() : null,
74
+ organizer: event.organizer && typeof event.organizer === 'string' ? event.organizer : null
75
+ };
76
+ }
77
+
78
+ module.exports = { CALENDAR_CONTENT_TYPES, sortCalendarAttachments, parseCalendarEvent };
package/lib/consts.js CHANGED
@@ -130,6 +130,24 @@ module.exports = {
130
130
  DEFAULT_MAX_ATTACHMENT_SIZE: 5 * 1024 * 1024,
131
131
  DEFAULT_MAX_SMTP_MESSAGE_SIZE: 25 * 1024 * 1024, // 25MB
132
132
 
133
+ // The settings a built-in listener reads only when its worker starts (enabled, port, host, the
134
+ // TLS switch) and the command that restarts that one worker. One table for the API settings
135
+ // route and the admin listener pages, so a write from either restarts exactly the listener
136
+ // that changed; the API route used to leave a listener on its old address until something
137
+ // else restarted it.
138
+ LISTENER_RELOADS: {
139
+ smtp: {
140
+ keys: ['smtpServerEnabled', 'smtpServerPort', 'smtpServerHost', 'smtpServerTLSEnabled'],
141
+ cmd: 'smtpReload',
142
+ action: 'request_reload_smtp'
143
+ },
144
+ imapProxy: {
145
+ keys: ['imapProxyServerEnabled', 'imapProxyServerPort', 'imapProxyServerHost', 'imapProxyServerTLSEnabled'],
146
+ cmd: 'imapProxyReload',
147
+ action: 'request_reload_imap_proxy'
148
+ }
149
+ },
150
+
133
151
  // IF IMAP authentications fail more than provided value, then disable IMAP for the account
134
152
  DEFAULT_MAX_IMAP_AUTH_FAILURE_TIME: 3 * 24 * 3600 * 1000, // 3 days
135
153
 
@@ -271,11 +289,19 @@ module.exports = {
271
289
  },
272
290
 
273
291
  URL_FETCH_TIMEOUT: Number((process.env.EENGINE_FETCH_TIMEOUT || '').toString().trim()) || 90 * 1000,
274
- URL_FETCH_RETRY_MAX: 5,
275
292
 
276
293
  // hard limit for subscript execution (does not include waiting for promises)
277
294
  SUBSCRIPT_RUNTIME_TIMEOUT: 30 * 1000,
278
295
 
296
+ // How long one request to the AI provider may take: the RPC that asks for it gives up after
297
+ // this, and the request in the main thread is aborted at the same time so it does not outlive
298
+ // its caller
299
+ AI_REQUEST_TIMEOUT: 2 * 60 * 1000,
300
+
301
+ // The settings the AI page edits besides the key, in the order the page shows them. The main
302
+ // thread reads the same keys for every request to the provider
303
+ AI_SETTING_KEYS: ['openAiModel', 'openAiAPIUrl', 'openAiPrompt', 'openAiTemperature', 'openAiTopP', 'openAiReasoningEffort', 'openAiMaxTokens'],
304
+
279
305
  // how long is an authentication form valid
280
306
  MAX_FORM_TTL: 1 * 24 * 3600 * 1000,
281
307
 
@@ -332,6 +358,16 @@ module.exports = {
332
358
  // the path and delimiter after the pick.
333
359
  MAILBOX_RESPONSE_FIELDS: ['path', 'specialUse', 'name', 'listed', 'subscribed', 'delimiter', 'specialUseSource', 'noInferiors'],
334
360
 
361
+ // The special-use folders an account may override, each stored on the account as
362
+ // `imap.<type>MailPath`. EmailEngine detects these folders from the server's own flags; an
363
+ // override is for a server that flags none of them, or flags the wrong one.
364
+ //
365
+ // One list because four places have to agree on it: the IMAP client turns it into the
366
+ // specialUseHints it passes to LIST, lib/schemas.js declares a field per entry for the account
367
+ // create and update schemas, and the admin edit form offers an input per entry. Only the client
368
+ // and the form used to carry a copy, and the form's had four of the five missing.
369
+ SPECIAL_USE_PATH_TYPES: ['sent', 'drafts', 'junk', 'trash', 'archive'],
370
+
335
371
  // nanoseconds
336
372
  ALLOWED_REDIS_LATENCY: 5 * 1000000,
337
373
 
@@ -340,8 +376,12 @@ module.exports = {
340
376
  FETCH_RETRY_INTERVAL: 1000,
341
377
  FETCH_RETRY_EXPONENTIAL: 2,
342
378
  FETCH_RETRY_MAX: 60 * 1000,
343
- FETCH_RETRY_MAX_TIME: 24 * 60 * 60 * 1000, // 1 day maximum retry duration
344
- FETCH_RETRY_MIN_ATTEMPTS: 20, // minimum attempts before time limit applies
379
+ // A FETCH is retried while its sync holds the folder's mailbox lock, which blocks IDLE, EXISTS
380
+ // handling and every API command routed to that connection. A server refusing the same FETCH
381
+ // every time (a corrupt message) used to hold the lock for a day; now the pass gives up after a
382
+ // few minutes, releases the lock, and the next resync pass tries again
383
+ FETCH_RETRY_MAX_TIME: 5 * 60 * 1000, // maximum retry duration under the lock
384
+ FETCH_RETRY_MIN_ATTEMPTS: 5, // minimum attempts before time limit applies
345
385
  DEFAULT_FETCH_BATCH_SIZE: 1000,
346
386
 
347
387
  // MS Graph webhook subscription settings
@@ -354,14 +394,18 @@ module.exports = {
354
394
  OUTLOOK_SUBSCRIPTION_LOCK_TTL: 4 * 60 * 1000, // ms - lock TTL for subscription operations (ioredfour uses ms)
355
395
  OUTLOOK_MAX_BATCH_SIZE: 20, // MS Graph batch request limit
356
396
  OUTLOOK_MAX_RETRY_ATTEMPTS: 3, // Maximum retry attempts for rate-limited requests
357
- OUTLOOK_RETRY_BASE_DELAY: 30, // seconds - base delay for exponential backoff
358
- OUTLOOK_RETRY_MAX_DELAY: 120, // seconds - maximum delay between retries
397
+ // Backoff for the subscription create/renew retries, which run in the background with no caller
398
+ // waiting on them (API requests use the shared policy in lib/email-client/api-retry.js)
399
+ OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY: 30, // seconds
400
+ OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY: 120, // seconds
359
401
  OUTLOOK_CLOCK_SKEW_BUFFER: 60 * 1000, // ms - buffer for clock skew between EmailEngine and MS Graph servers
360
402
  // Graph retries an undeliverable change notification for up to 4 hours before dropping it and
361
403
  // sending a `missed` lifecycle event, so the lost changes can be that old when recovery runs
362
404
  OUTLOOK_MISSED_LOOKBACK: 4 * 60 * 60 * 1000, // ms
363
405
  // How long announced new messages are remembered, so a recovery pass does not announce them again
364
406
  OUTLOOK_ANNOUNCED_RETENTION: 6 * 60 * 60 * 1000, // ms
407
+ // How far back a manual sync of a Graph account may be asked to look (PUT /v1/account/{account}/sync `since`)
408
+ OUTLOOK_SYNC_MAX_LOOKBACK: 30 * 24 * 60 * 60 * 1000, // ms
365
409
 
366
410
  // Google Pub/Sub subscription defaults
367
411
  GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL: '2678400s', // 31 days in seconds (Google's default)
@@ -385,6 +429,11 @@ module.exports = {
385
429
  // Error codes meaning "the IMAP connection is gone", as opposed to the command itself failing
386
430
  CONNECTION_CLOSING_CODES: new Set(['IMAPConnectionClosing', 'EConnectionClosed', 'NoConnection']),
387
431
 
432
+ // The last release that shipped the Document Store (Elasticsearch indexing, chat with
433
+ // emails, unified search). Named by the removal warning an instance shows while the
434
+ // `documentStoreEnabled` setting is still on
435
+ LAST_DOCUMENT_STORE_VERSION: '2.81.2',
436
+
388
437
  // Applied by lib/logger.js to the root logger, so every worker inherits it. A logged joi
389
438
  // ValidationError carries the full submitted payload in `_original` and the offending value in
390
439
  // each detail context, and `rawPacket` is a TLS-error field that can carry an unparsed
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ // Every ImapFlow client EmailEngine creates is created here, whatever the connection is for (an
4
+ // account's primary and command connections, a subconnection, the verification probes, the IMAP
5
+ // proxy's upstream), so an option every connection needs is set once. test/fips-guardrail-test.js
6
+ // refuses a `new ImapFlow(` anywhere else.
7
+ //
8
+ // idHashAlgorithm: ImapFlow derives a fallback message id from path:uidValidity:uid when the server
9
+ // provides no email id, with MD5 unless told otherwise, and an OpenSSL FIPS provider has no MD5, so
10
+ // every FETCH would fail on such a host. EmailEngine never reads that id (new messages are
11
+ // deduplicated on emailId or Message-ID, and the value only appears in a log line), so the
12
+ // algorithm is free to differ from ImapFlow's default on every installation.
13
+
14
+ const { ImapFlow } = require('imapflow');
15
+
16
+ /**
17
+ * @param {Object} config - Connection options, applied over the defaults
18
+ * @returns {ImapFlow}
19
+ */
20
+ function createImapClient(config) {
21
+ return new ImapFlow({ idHashAlgorithm: 'sha256', ...config });
22
+ }
23
+
24
+ module.exports = { createImapClient };
package/lib/db.js CHANGED
@@ -11,6 +11,7 @@ const pathlib = require('path');
11
11
  const redisUrl = require('./redis-url');
12
12
  const { threadId } = require('worker_threads');
13
13
  const logger = require('./logger');
14
+ const { readEnvValue } = require('./read-env-value');
14
15
  const { REDIS_PREFIX } = require('./consts');
15
16
  const Path = require('path');
16
17
  const { isMainThread } = require('worker_threads');
@@ -19,28 +20,9 @@ config.dbs = config.dbs || {
19
20
  redis: 'redis://127.0.0.1:6379/8'
20
21
  };
21
22
 
22
- const { Queue, FlowProducer } = require('bullmq');
23
+ const { Queue } = require('bullmq');
23
24
  const Redis = require('ioredis');
24
25
 
25
- // duplicate function declaration to avoid requiring tools.js
26
- const readEnvValue = key => {
27
- if (key in process.env) {
28
- return process.env[key];
29
- }
30
-
31
- if (typeof process.env[`${key}_FILE`] === 'string' && process.env[`${key}_FILE`]) {
32
- try {
33
- // try to load from file
34
- process.env[key] = fs.readFileSync(process.env[`${key}_FILE`], 'utf-8').replace(/\r?\n$/, '');
35
- logger.trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
36
- } catch (err) {
37
- logger.error({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
38
- process.env[key] = '';
39
- }
40
- return process.env[key];
41
- }
42
- };
43
-
44
26
  const redisConf = readEnvValue('EENGINE_REDIS') || readEnvValue('REDIS_URL') || config.dbs.redis;
45
27
  const REDIS_CONF = Object.assign(
46
28
  {
@@ -116,10 +98,25 @@ module.exports.queueConf = {
116
98
  prefix: `${REDIS_PREFIX}bull`
117
99
  };
118
100
 
119
- const notifyQueue = new Queue('notify', module.exports.queueConf);
120
- const submitQueue = new Queue('submit', module.exports.queueConf);
121
- const documentsQueue = new Queue('documents', module.exports.queueConf);
122
- const exportQueue = new Queue('export', module.exports.queueConf);
101
+ /**
102
+ * Routes the 'error' events of a BullMQ Worker, Queue or QueueEvents to the log.
103
+ * With no listener BullMQ catches the unhandled-'error' throw itself and prints it with
104
+ * console.error, so the error never reached pino or Sentry, and nothing crashed either
105
+ * @param {EventEmitter} emitter - The BullMQ object
106
+ * @param {string} component - What it is, e.g. 'queue:notify' or 'worker:submit'
107
+ * @returns {EventEmitter} The same object
108
+ */
109
+ const logBullErrors = (emitter, component) => {
110
+ emitter.on('error', err => {
111
+ logger.error({ msg: 'Queue error', component, err });
112
+ });
113
+ return emitter;
114
+ };
115
+ module.exports.logBullErrors = logBullErrors;
116
+
117
+ const notifyQueue = logBullErrors(new Queue('notify', module.exports.queueConf), 'queue:notify');
118
+ const submitQueue = logBullErrors(new Queue('submit', module.exports.queueConf), 'queue:submit');
119
+ const exportQueue = logBullErrors(new Queue('export', module.exports.queueConf), 'queue:export');
123
120
 
124
121
  const zExpungeScript = fs.readFileSync(pathlib.join(__dirname, '/lua/z-expunge.lua'), 'utf-8');
125
122
  const zSetScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-set.lua'), 'utf-8');
@@ -139,6 +136,9 @@ const hIncrbyExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-incrb
139
136
  const eeListAddScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-add.lua'), 'utf-8');
140
137
  const eeListRemoveScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-remove.lua'), 'utf-8');
141
138
  const eeGetIdempotencyScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-get-idempotency.lua'), 'utf-8');
139
+ const eeReserveAttemptsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-reserve-attempts.lua'), 'utf-8');
140
+ const eeReleaseAttemptsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-release-attempts.lua'), 'utf-8');
141
+ const eeExportQueueAddScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-export-queue-add.lua'), 'utf-8');
142
142
 
143
143
  redis.defineCommand('zExpunge', {
144
144
  numberOfKeys: 2,
@@ -230,10 +230,24 @@ redis.defineCommand('eeGetIdempotency', {
230
230
  lua: eeGetIdempotencyScript
231
231
  });
232
232
 
233
+ // The budget scripts take one key per budget, so the key count is passed as the first argument
234
+ // (lib/rate-limit.js reserveAttempts / releaseAttempts)
235
+ redis.defineCommand('eeReserveAttempts', {
236
+ lua: eeReserveAttemptsScript
237
+ });
238
+
239
+ redis.defineCommand('eeReleaseAttempts', {
240
+ lua: eeReleaseAttemptsScript
241
+ });
242
+
243
+ redis.defineCommand('eeExportQueueAdd', {
244
+ numberOfKeys: 2,
245
+ lua: eeExportQueueAddScript
246
+ });
247
+
233
248
  module.exports.redis = redis;
234
249
  module.exports.notifyQueue = notifyQueue;
235
250
  module.exports.submitQueue = submitQueue;
236
- module.exports.documentsQueue = documentsQueue;
237
251
  module.exports.exportQueue = exportQueue;
238
252
 
239
253
  // Queues addressable by the name the API and the stats payload use for them. `export` is
@@ -241,15 +255,48 @@ module.exports.exportQueue = exportQueue;
241
255
  // against this same set of names.
242
256
  module.exports.QUEUES_BY_NAME = {
243
257
  notify: notifyQueue,
244
- submit: submitQueue,
245
- documents: documentsQueue
258
+ submit: submitQueue
246
259
  };
247
260
 
248
- // do not set up the flow producer by default
249
- module.exports.getFlowProducer = () => new FlowProducer(module.exports.queueConf /*, Redis*/);
250
-
251
261
  module.exports.REDIS_CONF = REDIS_CONF;
252
262
 
263
+ /**
264
+ * Calls `onReconnect` when a client that had been ready becomes ready again after losing its
265
+ * connection. ioredis emits 'end' only on a final close (retryStrategy returning a non-number, which
266
+ * the one above never does), so an ordinary reconnect is close -> reconnecting -> ready and a
267
+ * watcher that waited for 'end' never fired
268
+ * @param {Redis} client - ioredis client
269
+ * @param {Function} onReconnect - Called on the first 'ready' after a lost connection
270
+ * @param {Function} [onDisconnect] - Called once when a stable connection is lost
271
+ */
272
+ module.exports.watchRedisReconnect = (client, onReconnect, onDisconnect) => {
273
+ let hasSeenStableConnection = client.status === 'ready';
274
+ let wasDisconnected = false;
275
+
276
+ const lost = () => {
277
+ // A failed first connection is not a reconnect; only a connection that was ready counts
278
+ if (hasSeenStableConnection && !wasDisconnected) {
279
+ wasDisconnected = true;
280
+ if (onDisconnect) {
281
+ onDisconnect();
282
+ }
283
+ }
284
+ };
285
+
286
+ client.on('close', lost);
287
+ client.on('reconnecting', lost);
288
+ client.on('end', lost);
289
+
290
+ client.on('ready', () => {
291
+ if (wasDisconnected) {
292
+ wasDisconnected = false;
293
+ onReconnect();
294
+ return;
295
+ }
296
+ hasSeenStableConnection = true;
297
+ });
298
+ };
299
+
253
300
  let redisConnected = false;
254
301
  const showRedisError = (msg, err, forceClose) => {
255
302
  if (isMainThread && (forceClose || (!redisConnected && process.stdout.isTTY && isMainThread && !process.env.ENCRYPT_SECRET))) {
@@ -19,7 +19,8 @@ const NON_RETRYABLE_CODES = new Set([
19
19
  'ETLS', // TLS handshake failed
20
20
  'EENVELOPE', // invalid sender/recipients
21
21
  'EMESSAGE', // message content error
22
- 'EPROTOCOL' // SMTP protocol mismatch
22
+ 'EPROTOCOL', // SMTP protocol mismatch
23
+ 'GatewayNotFound' // the gateway the message was queued for no longer exists
23
24
  ]);
24
25
 
25
26
  /**
@@ -111,4 +112,71 @@ function isFinalFailedAttempt(job) {
111
112
  return !!job.finishedOn || job.attemptsMade >= (job.opts.attempts || 1);
112
113
  }
113
114
 
114
- module.exports = { NON_RETRYABLE_CODES, isPermanentDeliveryError, shouldDiscardJob, willBeFinalAttempt, isFinalFailedAttempt };
115
+ // The same phase difference decides the retry TIME reported as `nextAttempt`, and the two call sites
116
+ // read a job in the two different phases, so they used to carry exponents that differ by one and
117
+ // looked like one of them was wrong. BullMQ's exponential strategy delays retry number r by
118
+ // 2^(r-1) * backoff.delay (Backoffs.builtinStrategies.exponential), and Job#shouldRetryJob() calls it
119
+ // with attemptsMade + 1, so the wait after the attempt numbered k fails is 2^(k-1) * delay. Verified
120
+ // against bullmq 6.3.11. Jitter is deliberately not applied: submissions are queued with
121
+ // jitter: 0.2, which spreads the real wait over [0.8, 1.0) of this figure, so what is reported is
122
+ // the latest the retry can happen. The schema calls it approximate for that reason.
123
+
124
+ /**
125
+ * How long BullMQ waits before retrying, once the attempt numbered `attemptNumber` has failed.
126
+ *
127
+ * @param {Number} attemptNumber - 1-based number of the attempt that failed
128
+ * @param {Object} job - BullMQ job, for its backoff options
129
+ * @returns {Number} Delay in milliseconds (0 when the job has no exponential backoff)
130
+ */
131
+ function retryDelayAfterAttempt(attemptNumber, job) {
132
+ const backoffDelay = Number(job.opts.backoff && job.opts.backoff.delay) || 0;
133
+ return Math.pow(2, attemptNumber - 1) * backoffDelay;
134
+ }
135
+
136
+ /**
137
+ * Inside a job processor: when would a failure of the CURRENTLY RUNNING attempt be retried?
138
+ * attemptsMade is not yet incremented here, so the running attempt is attemptsMade + 1.
139
+ *
140
+ * @param {Object} job - BullMQ job (mid-processing)
141
+ * @returns {Number|false} Epoch milliseconds, or false when this attempt is the job's last
142
+ */
143
+ function nextAttemptWhileProcessing(job) {
144
+ if (willBeFinalAttempt(job)) {
145
+ return false;
146
+ }
147
+ return Math.round(job.processedOn + retryDelayAfterAttempt(job.attemptsMade + 1, job));
148
+ }
149
+
150
+ /**
151
+ * Reading a job back out of Redis (the outbox listing): when is its next attempt due? attemptsMade
152
+ * already counts the attempt that failed, so that attempt is attemptsMade itself.
153
+ *
154
+ * @param {Object} job - BullMQ job as stored
155
+ * @param {Number} scheduled - Epoch milliseconds the job was queued for, used while nothing has failed
156
+ * @returns {Number|false} Epoch milliseconds, or false when every attempt has been used up
157
+ */
158
+ function nextAttemptOfStoredJob(job, scheduled) {
159
+ // isFinalFailedAttempt() rather than the attempts bound alone, for its finishedOn clause: a job
160
+ // the submit worker ended early with UnrecoverableError (every permanent SMTP rejection) is listed
161
+ // by the outbox with attempts left over, and reporting a retry time for a delivery that is dead
162
+ // for good is exactly the figure this module exists to get right
163
+ if (isFinalFailedAttempt(job)) {
164
+ return false;
165
+ }
166
+ if (!job.attemptsMade) {
167
+ // Nothing has failed yet, so the job is still waiting for its scheduled time
168
+ return scheduled;
169
+ }
170
+ return Math.round(job.processedOn + retryDelayAfterAttempt(job.attemptsMade, job));
171
+ }
172
+
173
+ module.exports = {
174
+ NON_RETRYABLE_CODES,
175
+ isPermanentDeliveryError,
176
+ shouldDiscardJob,
177
+ willBeFinalAttempt,
178
+ isFinalFailedAttempt,
179
+ retryDelayAfterAttempt,
180
+ nextAttemptWhileProcessing,
181
+ nextAttemptOfStoredJob
182
+ };