emailengine-app 2.81.1 → 2.82.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 (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  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-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. 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
 
@@ -340,8 +366,12 @@ module.exports = {
340
366
  FETCH_RETRY_INTERVAL: 1000,
341
367
  FETCH_RETRY_EXPONENTIAL: 2,
342
368
  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
369
+ // A FETCH is retried while its sync holds the folder's mailbox lock, which blocks IDLE, EXISTS
370
+ // handling and every API command routed to that connection. A server refusing the same FETCH
371
+ // every time (a corrupt message) used to hold the lock for a day; now the pass gives up after a
372
+ // few minutes, releases the lock, and the next resync pass tries again
373
+ FETCH_RETRY_MAX_TIME: 5 * 60 * 1000, // maximum retry duration under the lock
374
+ FETCH_RETRY_MIN_ATTEMPTS: 5, // minimum attempts before time limit applies
345
375
  DEFAULT_FETCH_BATCH_SIZE: 1000,
346
376
 
347
377
  // MS Graph webhook subscription settings
@@ -354,13 +384,24 @@ module.exports = {
354
384
  OUTLOOK_SUBSCRIPTION_LOCK_TTL: 4 * 60 * 1000, // ms - lock TTL for subscription operations (ioredfour uses ms)
355
385
  OUTLOOK_MAX_BATCH_SIZE: 20, // MS Graph batch request limit
356
386
  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
387
+ // Backoff for the subscription create/renew retries, which run in the background with no caller
388
+ // waiting on them (API requests use the shared policy in lib/email-client/api-retry.js)
389
+ OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY: 30, // seconds
390
+ OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY: 120, // seconds
359
391
  OUTLOOK_CLOCK_SKEW_BUFFER: 60 * 1000, // ms - buffer for clock skew between EmailEngine and MS Graph servers
392
+ // Graph retries an undeliverable change notification for up to 4 hours before dropping it and
393
+ // sending a `missed` lifecycle event, so the lost changes can be that old when recovery runs
394
+ OUTLOOK_MISSED_LOOKBACK: 4 * 60 * 60 * 1000, // ms
395
+ // How long announced new messages are remembered, so a recovery pass does not announce them again
396
+ OUTLOOK_ANNOUNCED_RETENTION: 6 * 60 * 60 * 1000, // ms
360
397
 
361
398
  // Google Pub/Sub subscription defaults
362
399
  GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL: '2678400s', // 31 days in seconds (Google's default)
363
400
  GMAIL_PUBSUB_ACK_DEADLINE_SECONDS: 30,
401
+ // A mailbox change the API clients (Gmail, MS Graph) failed to process on a transient provider
402
+ // error (5xx, 408, 429, network) is retried after each of these delays (ms), about 3.5 hours in all
403
+ CHANGE_EVENT_RETRY_DELAYS: [1, 4, 16, 60, 60, 60].map(minutes => minutes * 60 * 1000),
404
+
364
405
  // Transient network error codes that indicate a retry-worthy connection failure
365
406
  TRANSIENT_NETWORK_CODES: new Set([
366
407
  'ENOTFOUND',
@@ -376,6 +417,11 @@ module.exports = {
376
417
  // Error codes meaning "the IMAP connection is gone", as opposed to the command itself failing
377
418
  CONNECTION_CLOSING_CODES: new Set(['IMAPConnectionClosing', 'EConnectionClosed', 'NoConnection']),
378
419
 
420
+ // The last release that shipped the Document Store (Elasticsearch indexing, chat with
421
+ // emails, unified search). Named by the removal warning an instance shows while the
422
+ // `documentStoreEnabled` setting is still on
423
+ LAST_DOCUMENT_STORE_VERSION: '2.81.2',
424
+
379
425
  // Applied by lib/logger.js to the root logger, so every worker inherits it. A logged joi
380
426
  // ValidationError carries the full submitted payload in `_original` and the offending value in
381
427
  // 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
@@ -19,7 +19,7 @@ config.dbs = config.dbs || {
19
19
  redis: 'redis://127.0.0.1:6379/8'
20
20
  };
21
21
 
22
- const { Queue, FlowProducer } = require('bullmq');
22
+ const { Queue } = require('bullmq');
23
23
  const Redis = require('ioredis');
24
24
 
25
25
  // duplicate function declaration to avoid requiring tools.js
@@ -116,10 +116,25 @@ module.exports.queueConf = {
116
116
  prefix: `${REDIS_PREFIX}bull`
117
117
  };
118
118
 
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);
119
+ /**
120
+ * Routes the 'error' events of a BullMQ Worker, Queue or QueueEvents to the log.
121
+ * With no listener BullMQ catches the unhandled-'error' throw itself and prints it with
122
+ * console.error, so the error never reached pino or Sentry, and nothing crashed either
123
+ * @param {EventEmitter} emitter - The BullMQ object
124
+ * @param {string} component - What it is, e.g. 'queue:notify' or 'worker:submit'
125
+ * @returns {EventEmitter} The same object
126
+ */
127
+ const logBullErrors = (emitter, component) => {
128
+ emitter.on('error', err => {
129
+ logger.error({ msg: 'Queue error', component, err });
130
+ });
131
+ return emitter;
132
+ };
133
+ module.exports.logBullErrors = logBullErrors;
134
+
135
+ const notifyQueue = logBullErrors(new Queue('notify', module.exports.queueConf), 'queue:notify');
136
+ const submitQueue = logBullErrors(new Queue('submit', module.exports.queueConf), 'queue:submit');
137
+ const exportQueue = logBullErrors(new Queue('export', module.exports.queueConf), 'queue:export');
123
138
 
124
139
  const zExpungeScript = fs.readFileSync(pathlib.join(__dirname, '/lua/z-expunge.lua'), 'utf-8');
125
140
  const zSetScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-set.lua'), 'utf-8');
@@ -128,7 +143,6 @@ const zGetByUidScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-get-by-ui
128
143
  const zGetMailboxIdScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-get-mailbox-id.lua'), 'utf-8');
129
144
  const zGetMailboxPathScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-get-mailbox-path.lua'), 'utf-8');
130
145
  const sListAccountsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/s-list-accounts.lua'), 'utf-8');
131
- const hPushScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-push.lua'), 'utf-8');
132
146
  const hSetBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-bigger.lua'), 'utf-8');
133
147
  const hUpdateBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-update-bigger.lua'), 'utf-8');
134
148
  const hSetExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-exists.lua'), 'utf-8');
@@ -140,6 +154,9 @@ const hIncrbyExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-incrb
140
154
  const eeListAddScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-add.lua'), 'utf-8');
141
155
  const eeListRemoveScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-remove.lua'), 'utf-8');
142
156
  const eeGetIdempotencyScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-get-idempotency.lua'), 'utf-8');
157
+ const eeReserveAttemptsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-reserve-attempts.lua'), 'utf-8');
158
+ const eeReleaseAttemptsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-release-attempts.lua'), 'utf-8');
159
+ const eeExportQueueAddScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-export-queue-add.lua'), 'utf-8');
143
160
 
144
161
  redis.defineCommand('zExpunge', {
145
162
  numberOfKeys: 2,
@@ -156,11 +173,6 @@ redis.defineCommand('zGet', {
156
173
  lua: zGetScript
157
174
  });
158
175
 
159
- redis.defineCommand('hPush', {
160
- numberOfKeys: 1,
161
- lua: hPushScript
162
- });
163
-
164
176
  redis.defineCommand('zGetByUid', {
165
177
  numberOfKeys: 1,
166
178
  lua: zGetByUidScript
@@ -236,10 +248,24 @@ redis.defineCommand('eeGetIdempotency', {
236
248
  lua: eeGetIdempotencyScript
237
249
  });
238
250
 
251
+ // The budget scripts take one key per budget, so the key count is passed as the first argument
252
+ // (lib/rate-limit.js reserveAttempts / releaseAttempts)
253
+ redis.defineCommand('eeReserveAttempts', {
254
+ lua: eeReserveAttemptsScript
255
+ });
256
+
257
+ redis.defineCommand('eeReleaseAttempts', {
258
+ lua: eeReleaseAttemptsScript
259
+ });
260
+
261
+ redis.defineCommand('eeExportQueueAdd', {
262
+ numberOfKeys: 2,
263
+ lua: eeExportQueueAddScript
264
+ });
265
+
239
266
  module.exports.redis = redis;
240
267
  module.exports.notifyQueue = notifyQueue;
241
268
  module.exports.submitQueue = submitQueue;
242
- module.exports.documentsQueue = documentsQueue;
243
269
  module.exports.exportQueue = exportQueue;
244
270
 
245
271
  // Queues addressable by the name the API and the stats payload use for them. `export` is
@@ -247,15 +273,48 @@ module.exports.exportQueue = exportQueue;
247
273
  // against this same set of names.
248
274
  module.exports.QUEUES_BY_NAME = {
249
275
  notify: notifyQueue,
250
- submit: submitQueue,
251
- documents: documentsQueue
276
+ submit: submitQueue
252
277
  };
253
278
 
254
- // do not set up the flow producer by default
255
- module.exports.getFlowProducer = () => new FlowProducer(module.exports.queueConf /*, Redis*/);
256
-
257
279
  module.exports.REDIS_CONF = REDIS_CONF;
258
280
 
281
+ /**
282
+ * Calls `onReconnect` when a client that had been ready becomes ready again after losing its
283
+ * connection. ioredis emits 'end' only on a final close (retryStrategy returning a non-number, which
284
+ * the one above never does), so an ordinary reconnect is close -> reconnecting -> ready and a
285
+ * watcher that waited for 'end' never fired
286
+ * @param {Redis} client - ioredis client
287
+ * @param {Function} onReconnect - Called on the first 'ready' after a lost connection
288
+ * @param {Function} [onDisconnect] - Called once when a stable connection is lost
289
+ */
290
+ module.exports.watchRedisReconnect = (client, onReconnect, onDisconnect) => {
291
+ let hasSeenStableConnection = client.status === 'ready';
292
+ let wasDisconnected = false;
293
+
294
+ const lost = () => {
295
+ // A failed first connection is not a reconnect; only a connection that was ready counts
296
+ if (hasSeenStableConnection && !wasDisconnected) {
297
+ wasDisconnected = true;
298
+ if (onDisconnect) {
299
+ onDisconnect();
300
+ }
301
+ }
302
+ };
303
+
304
+ client.on('close', lost);
305
+ client.on('reconnecting', lost);
306
+ client.on('end', lost);
307
+
308
+ client.on('ready', () => {
309
+ if (wasDisconnected) {
310
+ wasDisconnected = false;
311
+ onReconnect();
312
+ return;
313
+ }
314
+ hasSeenStableConnection = true;
315
+ });
316
+ };
317
+
259
318
  let redisConnected = false;
260
319
  const showRedisError = (msg, err, forceClose) => {
261
320
  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
  /**
@@ -34,12 +34,62 @@ const BODY_HEADERS = new Set(['content-type', 'content-length', 'content-encodin
34
34
  // not a reason to hand it over. fetch() drops these on a cross-origin hop and so does this.
35
35
  const CREDENTIAL_HEADERS = new Set(['authorization', 'cookie', 'proxy-authorization']);
36
36
 
37
+ // Largest redirect body drained for connection reuse. A redirect body is a line of HTML at most,
38
+ // anything past this is not worth reading to keep a socket
39
+ const MAX_REDIRECT_BODY = 64 * 1024;
40
+
37
41
  function redirectError(message, code) {
38
42
  let err = new Error(message);
39
43
  err.code = code;
40
44
  return err;
41
45
  }
42
46
 
47
+ /**
48
+ * Reads a response body as text, refusing one larger than `maxBytes`.
49
+ *
50
+ * res.text() buffers whatever the server sends for as long as it keeps sending, and the dispatcher's
51
+ * body timeout only measures silence, so a host that streams without pause is never cut off by it.
52
+ * Reading chunk by chunk and cancelling the stream once the budget is spent keeps a response from a
53
+ * host the caller did not choose from growing the process.
54
+ *
55
+ * @param {Response} res - fetch response with its body unread
56
+ * @param {number} maxBytes - Largest body accepted
57
+ * @returns {Promise<string>} Body decoded as UTF-8
58
+ * @throws {Error} EBODYTOOLARGE when the body exceeds the budget, or whatever reading the stream throws
59
+ * (an aborted request rejects here)
60
+ */
61
+ async function readBodyCapped(res, maxBytes) {
62
+ const tooLarge = () => redirectError(`Response body exceeds ${maxBytes} bytes`, 'EBODYTOOLARGE');
63
+
64
+ if (!res.body || typeof res.body.getReader !== 'function') {
65
+ // No stream to read from (a bodyless response, or a stand-in in tests)
66
+ const text = await res.text();
67
+ if (Buffer.byteLength(text || '') > maxBytes) {
68
+ throw tooLarge();
69
+ }
70
+ return text;
71
+ }
72
+
73
+ const reader = res.body.getReader();
74
+ const chunks = [];
75
+ let size = 0;
76
+
77
+ for (;;) {
78
+ const { done, value } = await reader.read();
79
+ if (done) {
80
+ break;
81
+ }
82
+ size += value.byteLength;
83
+ if (size > maxBytes) {
84
+ await reader.cancel().catch(() => false);
85
+ throw tooLarge();
86
+ }
87
+ chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
88
+ }
89
+
90
+ return Buffer.concat(chunks).toString('utf-8');
91
+ }
92
+
43
93
  /**
44
94
  * Resolves the Location header of a redirect against the URL that answered it.
45
95
  *
@@ -119,8 +169,9 @@ async function fetchWithVettedRedirects(fetchImpl, url, options) {
119
169
  }
120
170
 
121
171
  // The hop is not taken, so its body is never read by the caller. Drain it here so the
122
- // keep-alive socket goes back to the pool instead of staying pinned
123
- await res.text().catch(() => false);
172
+ // keep-alive socket goes back to the pool instead of staying pinned, but only up to a size
173
+ // a redirect plausibly has: an endless body is cancelled instead
174
+ await readBodyCapped(res, MAX_REDIRECT_BODY).catch(() => false);
124
175
 
125
176
  if (hop >= MAX_REDIRECTS) {
126
177
  throw redirectError(`Too many redirects, gave up at ${current}`, 'EMAXREDIRECTS');
@@ -142,4 +193,4 @@ async function fetchWithVettedRedirects(fetchImpl, url, options) {
142
193
  }
143
194
  }
144
195
 
145
- module.exports = { fetchWithVettedRedirects, MAX_REDIRECTS };
196
+ module.exports = { fetchWithVettedRedirects, readBodyCapped, MAX_REDIRECTS };
@@ -30,6 +30,9 @@ const PRIVATE_BLOCKED_RANGES = new Set([
30
30
  'loopback',
31
31
  'private',
32
32
  'uniqueLocal',
33
+ // fec0::/10, the site-local range RFC 3879 deprecated; still routable on a network that
34
+ // never stopped using it, and as internal as uniqueLocal wherever it is
35
+ 'deprecatedSiteLocal',
33
36
  'carrierGradeNat',
34
37
  'reserved',
35
38
  'unspecified',
@@ -80,6 +83,14 @@ function embeddedIPv4(parsed) {
80
83
  return ipv4FromHextets(parts[1], parts[2]);
81
84
  case 'teredo': // 2001::/32, the client's IPv4 is the low 32 bits, bit-inverted
82
85
  return ipv4FromHextets(parts[6] ^ 0xffff, parts[7] ^ 0xffff);
86
+ case 'unicast':
87
+ // ::a.b.c.d, IPv4-compatible (::/96, deprecated by RFC 4291). ipaddr.js has no range
88
+ // for it, so it read as ordinary unicast. `::` and `::1` sit inside the same prefix but
89
+ // classify as unspecified and loopback, so they never reach this branch.
90
+ if (parts.slice(0, 6).every(part => part === 0)) {
91
+ return ipv4FromHextets(parts[6], parts[7]);
92
+ }
93
+ return null;
83
94
  default:
84
95
  return null;
85
96
  }