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
@@ -3,12 +3,39 @@
3
3
  const libmime = require('libmime');
4
4
  const { UNSAFE_KEYS } = require('./unsafe-key');
5
5
 
6
+ // Largest header block handed to libmime. Its line unfolding used to be quadratic in the line
7
+ // count, and the bounce and complaint detectors decode blocks taken from attachments any sender
8
+ // controls, so the cut is made here rather than at each caller. No real header block comes
9
+ // anywhere near this
10
+ const MAX_HEADER_BLOCK_SIZE = 64 * 1024;
11
+
12
+ /**
13
+ * Returns a header block as a string, cut to MAX_HEADER_BLOCK_SIZE.
14
+ *
15
+ * decodeHeaders() applies this itself; it is exported for the callers that run their own
16
+ * line-based preprocessing over a block before decoding it, so that work is bounded the same way.
17
+ *
18
+ * @param {string|Buffer} content - Raw header block
19
+ * @returns {string}
20
+ */
21
+ function capHeaderBlock(content) {
22
+ if (!content) {
23
+ return '';
24
+ }
25
+ if (Buffer.isBuffer(content)) {
26
+ return content.subarray(0, MAX_HEADER_BLOCK_SIZE).toString();
27
+ }
28
+ content = content.toString();
29
+ return content.length > MAX_HEADER_BLOCK_SIZE ? content.substring(0, MAX_HEADER_BLOCK_SIZE) : content;
30
+ }
31
+
6
32
  /**
7
33
  * Parses a header block into a map of lowercased header name to array of values.
8
34
  *
9
- * Wraps libmime.decodeHeaders() to drop names that collide with Object.prototype. Header names
10
- * come from the message, so any sender can use one, and libmime returns them as real own
11
- * properties. Neither names a real header, so there is nothing to preserve by keeping them:
35
+ * Wraps libmime.decodeHeaders() to cut the block to MAX_HEADER_BLOCK_SIZE and to drop names that
36
+ * collide with Object.prototype. Header names come from the message, so any sender can use one,
37
+ * and libmime returns them as real own properties. Neither names a real header, so there is
38
+ * nothing to preserve by keeping them:
12
39
  *
13
40
  * - an own "__proto__" key is the one thing lib/msgpack.js refuses to decode, so a map carrying it
14
41
  * encodes into webhook logs and message payloads that can never be read back, and it hands
@@ -26,7 +53,7 @@ const { UNSAFE_KEYS } = require('./unsafe-key');
26
53
  * @returns {Object} Map of lowercased header name to array of values
27
54
  */
28
55
  function decodeHeaders(headers) {
29
- let parsed = libmime.decodeHeaders(headers);
56
+ let parsed = libmime.decodeHeaders(capHeaderBlock(headers));
30
57
 
31
58
  for (let name of UNSAFE_KEYS) {
32
59
  // Probing first is not needed for correctness, deleting a missing key is a no-op, but it is
@@ -39,4 +66,4 @@ function decodeHeaders(headers) {
39
66
  return parsed;
40
67
  }
41
68
 
42
- module.exports = { decodeHeaders };
69
+ module.exports = { decodeHeaders, capHeaderBlock, MAX_HEADER_BLOCK_SIZE };
@@ -45,4 +45,65 @@ function pushHeaderValue(headers, key, value) {
45
45
  return true;
46
46
  }
47
47
 
48
- module.exports = { pushHeaderValue };
48
+ // Headers the notification path needs for its own processing, whatever the notifyHeaders
49
+ // setting asks for: auto-reply detection, threading, the multipart/report check behind bounce
50
+ // and complaint detection, and the address fields as a fallback for an ENVELOPE that carries no
51
+ // usable address (Lark Mail omits them, and any server can mis-parse a malformed header into a
52
+ // display name with no address). They travel with the one header section the path already
53
+ // requests and are narrowed back out before the message is published
54
+ const NOTIFICATION_HEADERS = [
55
+ 'x-autoreply',
56
+ 'x-autorespond',
57
+ 'auto-submitted',
58
+ 'precedence',
59
+ 'in-reply-to',
60
+ 'references',
61
+ 'content-type',
62
+ 'from',
63
+ 'to',
64
+ 'cc',
65
+ 'bcc'
66
+ ];
67
+
68
+ /**
69
+ * Builds the header field list for a notification fetch: what the operator asked for, what the
70
+ * path needs for itself, and whatever else the caller has a use for this time (the AI summary's
71
+ * headers while summaries are on)
72
+ *
73
+ * @param {String[]|Boolean} configuredHeaders - Headers the notifyHeaders setting asks for
74
+ * @param {String[]} [extraHeaders] - Headers the caller wants fetched as well
75
+ * @returns {String[]} Header names to request from the server
76
+ */
77
+ function notificationHeaderFields(configuredHeaders, extraHeaders) {
78
+ const fetchHeaders = new Set(Array.isArray(configuredHeaders) ? configuredHeaders : []);
79
+
80
+ for (const key of NOTIFICATION_HEADERS.concat(extraHeaders || [])) {
81
+ fetchHeaders.add(key);
82
+ }
83
+
84
+ return Array.from(fetchHeaders);
85
+ }
86
+
87
+ /**
88
+ * Narrows a message's fetched headers to what the caller asked for, once every internal use of
89
+ * the extra ones is over. A list keeps those names, false drops the block, and anything else
90
+ * (every header was asked for) leaves it alone
91
+ *
92
+ * @param {Object} message - Message whose headers were fetched with notificationHeaderFields()
93
+ * @param {String[]|Boolean|undefined} requestedHeaders - What the caller asked for
94
+ */
95
+ function narrowHeaders(message, requestedHeaders) {
96
+ if (Array.isArray(requestedHeaders)) {
97
+ const narrowed = {};
98
+ for (const key of Object.keys(message.headers || {})) {
99
+ if (requestedHeaders.includes(key)) {
100
+ narrowed[key] = message.headers[key];
101
+ }
102
+ }
103
+ message.headers = narrowed;
104
+ } else if (requestedHeaders === false) {
105
+ delete message.headers;
106
+ }
107
+ }
108
+
109
+ module.exports = { pushHeaderValue, notificationHeaderFields, narrowHeaders, NOTIFICATION_HEADERS };
@@ -177,6 +177,11 @@ function resolveClientIp({ remoteAddress, forwardedFor, enableApiProxy, trustedP
177
177
  return remoteAddress;
178
178
  }
179
179
 
180
+ // Reverse-DNS suffixes of the scanners whose fetches must not count as a real open or click. No `g`
181
+ // flag: RegExp#test() advances lastIndex on a global regex, so a hoisted one would skip every other
182
+ // call - which is exactly how a shared instance of this would start letting scanner traffic through.
183
+ const SCANNER_HOSTNAME_PATTERN = /\bbarracuda\.com$|\bspfbl\.net$/i;
184
+
180
185
  /**
181
186
  * Detects if a request is from an automated scanner (Google, Barracuda, etc.)
182
187
  * @param {string} ip - IP address to check
@@ -213,23 +218,10 @@ async function detectAutomatedRequest(ip) {
213
218
  });
214
219
  }
215
220
 
216
- if (!hostnames || !hostnames.length) {
217
- return false;
218
- }
219
-
220
- const hostname = []
221
- .concat(hostnames || [])
222
- .shift()
223
- .toString()
224
- .trim()
225
- .toLowerCase();
226
-
227
- // Barracuda, spfbl
228
- if (/\bbarracuda\.com$|\bspfbl\.net$/gi.test(hostname)) {
229
- return true;
230
- }
231
-
232
- return false;
221
+ // Every PTR record, not just the first. An address is under no obligation to list the scanner's
222
+ // own name first, and this filter is the only thing keeping scanner fetches out of trackOpen and
223
+ // trackClick - reading one record of several reported them as real opens and clicks.
224
+ return [].concat(hostnames || []).some(entry => SCANNER_HOSTNAME_PATTERN.test(String(entry).trim().toLowerCase()));
233
225
  }
234
226
 
235
227
  /**
@@ -357,6 +349,8 @@ module.exports = {
357
349
  resolvePublicInterfaces,
358
350
  updatePublicInterfaces,
359
351
  getLocalAddress,
352
+ parseComparableIp,
353
+ parseComparableCidr,
360
354
  matchIp,
361
355
  resolveClientIp,
362
356
  detectAutomatedRequest,
@@ -1,10 +1,14 @@
1
1
  'use strict';
2
2
 
3
3
  const { analyze } = require('@postalsys/email-content');
4
- const { mimeHtml, textToHtml } = require('@postalsys/email-text-tools');
4
+ // Resolved at call time rather than destructured here: the package exposes mimeHtml through a
5
+ // lazy getter, and touching it loads jsdom (tens of MB of heap) into every process that merely
6
+ // requires this module, the main process included.
7
+ const textTools = require('@postalsys/email-text-tools');
5
8
  const { getBoolean, readEnvValue } = require('./tools');
6
9
  const { COLLAPSE_CLASS, COLLAPSE_TOGGLE_CLASS } = require('./consts');
7
10
  const logger = require('./logger');
11
+ const he = require('he');
8
12
 
9
13
  /**
10
14
  * Web-safe HTML generation for message bodies.
@@ -310,7 +314,13 @@ function collapseText(text, offset) {
310
314
  return null;
311
315
  }
312
316
 
313
- return PLAINTEXT_STYLE_BLOCK + textToHtml(text.slice(0, offset)) + COLLAPSE_OPEN_MARKUP + textToHtml(text.slice(offset)) + COLLAPSE_CLOSE_MARKUP;
317
+ return (
318
+ PLAINTEXT_STYLE_BLOCK +
319
+ textTools.textToHtml(text.slice(0, offset)) +
320
+ COLLAPSE_OPEN_MARKUP +
321
+ textTools.textToHtml(text.slice(offset)) +
322
+ COLLAPSE_CLOSE_MARKUP
323
+ );
314
324
  }
315
325
 
316
326
  /**
@@ -371,6 +381,59 @@ async function collapseThreadHistory(messageData) {
371
381
  return collapsed ? { html: collapsed } : null;
372
382
  }
373
383
 
384
+ // Class names reserved for the collapse marker (COLLAPSE_CLASS and COLLAPSE_TOGGLE_CLASS share the
385
+ // prefix). A renderer folds whatever carries them, so they must only ever come from us.
386
+ const RESERVED_CLASS_NAME = /^ee-collapsed-thread/i;
387
+
388
+ // A class attribute with its value in any of the three HTML syntaxes. The HTML parser treats '/'
389
+ // between attributes like whitespace, hence [\s/] rather than \s.
390
+ const CLASS_ATTRIBUTE = /([\s/]class\s*=\s*)(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi;
391
+
392
+ /**
393
+ * Removes the collapse marker's class names from sender HTML.
394
+ *
395
+ * The sanitizer keeps <details>, <summary> and class attributes, so without this a sender could
396
+ * write their own `<details class="ee-collapsed-thread">` and have a renderer fold whatever they
397
+ * chose to hide. Values are entity-decoded before they are checked, since the parser decodes them
398
+ * too.
399
+ *
400
+ * @param {string} html - Sender HTML
401
+ * @returns {string} HTML without the reserved class names
402
+ */
403
+ function stripReservedClasses(html) {
404
+ if (!html || typeof html !== 'string') {
405
+ return html;
406
+ }
407
+
408
+ return html.replace(CLASS_ATTRIBUTE, (match, prefix, doubleQuoted, singleQuoted, unquoted) => {
409
+ let raw = doubleQuoted !== undefined ? doubleQuoted : singleQuoted !== undefined ? singleQuoted : unquoted;
410
+ let tokens = he.decode(raw, { isAttributeValue: true }).split(/\s+/);
411
+ let kept = tokens.filter(token => token && !RESERVED_CLASS_NAME.test(token));
412
+ if (kept.length === tokens.filter(token => token).length) {
413
+ return match;
414
+ }
415
+ return `${prefix}"${he.escape(kept.join(' '))}"`;
416
+ });
417
+ }
418
+
419
+ /**
420
+ * Last-resort rendering when the sanitizer itself fails.
421
+ *
422
+ * mimeHtml() throws RangeError on hostile nesting (a few thousand nested elements or quote
423
+ * levels). The message is still delivered and still has to be readable, so it is shown as escaped
424
+ * text rather than dropped. Never the unconverted HTML: that has not been sanitized.
425
+ *
426
+ * @param {Object} source - `{ html, text }` as handed to mimeHtml()
427
+ * @returns {string} Escaped text in a wrapper
428
+ */
429
+ function escapedTextFallback(source) {
430
+ let text = source.text || '';
431
+ if (!text && source.html) {
432
+ text = he.decode(source.html.toString().replace(/<[^>]*>/g, ' '));
433
+ }
434
+ return `<div style="overflow: auto; white-space: pre-wrap;">${he.escape(text.toString())}</div>`;
435
+ }
436
+
374
437
  /**
375
438
  * Converts the bodies of a message object into sanitized, web-safe HTML.
376
439
  *
@@ -378,7 +441,12 @@ async function collapseThreadHistory(messageData) {
378
441
  * @returns {Promise<string>} Sanitized HTML
379
442
  */
380
443
  async function messageWebSafeHtml(messageData) {
381
- let source = { html: messageData.text.html, text: messageData.text.plain };
444
+ let html = stripReservedClasses(messageData.text.html);
445
+ if (html !== messageData.text.html) {
446
+ messageData = Object.assign({}, messageData, { text: Object.assign({}, messageData.text, { html }) });
447
+ }
448
+
449
+ let source = { html, text: messageData.text.plain };
382
450
 
383
451
  if (!DISABLE_THREAD_COLLAPSE) {
384
452
  try {
@@ -392,7 +460,12 @@ async function messageWebSafeHtml(messageData) {
392
460
  }
393
461
  }
394
462
 
395
- return mimeHtml(source);
463
+ try {
464
+ return textTools.mimeHtml(source);
465
+ } catch (err) {
466
+ logger.warn({ msg: 'Failed to convert message to web-safe HTML, rendering it as text', err });
467
+ return escapedTextFallback({ html: messageData.text.html, text: messageData.text.plain });
468
+ }
396
469
  }
397
470
 
398
471
  /**
@@ -105,4 +105,12 @@ async function sendWebhookRequest(fetchImpl, url, options) {
105
105
  return res.status;
106
106
  }
107
107
 
108
- module.exports = { sendWebhookRequest };
108
+ // Neither of these changes on a retry: the egress policy rejects the same destination every time,
109
+ // and an endpoint configured to redirect keeps redirecting. Such a delivery is final on its first
110
+ // failure, which decides both the log level and whether the remaining attempts are spent. Every
111
+ // other failure, 4xx included, keeps the full retry schedule (see .claude/rules/workers.md).
112
+ function isUnrecoverableWebhookError(err) {
113
+ return !!err && (err.code === 'EEGRESSBLOCKED' || err.code === 'EREDIRECTNOTFOLLOWED');
114
+ }
115
+
116
+ module.exports = { sendWebhookRequest, isUnrecoverableWebhookError };
@@ -30,6 +30,32 @@ function eventAllowed(webhookEvents, eventName) {
30
30
  return events.includes('*') || events.includes(eventName);
31
31
  }
32
32
 
33
+ // The custom headers of one delivery, later lists overriding earlier ones. A custom route carries
34
+ // its own headers and nothing else: the global and account-level headers belong to the default
35
+ // target, and letting them ride along sent an account's secrets to an operator-defined endpoint
36
+ // and let an account override the route's own Authorization.
37
+ function deliveryCustomHeaders(customRoute, globalHeaders, accountHeaders) {
38
+ let lists = customRoute ? [customRoute.customHeaders] : [globalHeaders, accountHeaders];
39
+ let headers = {};
40
+ for (let list of lists) {
41
+ for (let header of [].concat(list || [])) {
42
+ if (header && header.key) {
43
+ headers[header.key] = header.value;
44
+ }
45
+ }
46
+ }
47
+ return headers;
48
+ }
49
+
50
+ // Whether a queued custom-route job was meant to carry a mapped payload and does not. A route
51
+ // with a map script is queued with its mapping or not at all (lib/webhooks.js pushToQueue), so
52
+ // this only fires for jobs queued before that, which carry the result of a failed map as
53
+ // `mapping: null`. Such a job must be dropped: sending the original payload in its place
54
+ // delivers everything the map was there to strip.
55
+ function isRouteMappingMissing(routeMarker) {
56
+ return !!routeMarker && 'mapping' in routeMarker && routeMarker.mapping == null;
57
+ }
58
+
33
59
  // Assembles a render-ready description of the webhook routing that applies to one account.
34
60
  // All inputs are pre-fetched values; this function does not touch Redis or settings.
35
61
  function describeEffectiveRouting(opts) {
@@ -81,4 +107,4 @@ function describeEffectiveRouting(opts) {
81
107
  };
82
108
  }
83
109
 
84
- module.exports = { resolveTargetUrl, isDeliverableRoute, eventAllowed, describeEffectiveRouting };
110
+ module.exports = { resolveTargetUrl, isDeliverableRoute, eventAllowed, describeEffectiveRouting, deliveryCustomHeaders, isRouteMappingMissing };
package/lib/webhooks.js CHANGED
@@ -10,6 +10,15 @@ const settings = require('./settings');
10
10
  const { filterListPage, truncateTextContents } = require('./tools');
11
11
  const { buildRetentionPolicy } = require('./queue-retention');
12
12
  const { isDeliverableRoute } = require('./webhook-routing');
13
+ const { encryptField, decryptField } = require('./encrypt');
14
+ const getSecret = require('./get-secret');
15
+
16
+ // Route fields that carry credentials: the target URL may embed `user:pass@` and the custom
17
+ // headers usually hold an Authorization value. Encrypted inside the stored meta entry like the
18
+ // global `webhooks` / `webhooksCustomHeaders` settings; the header list is stored as encrypted
19
+ // JSON. A route written before this holds cleartext (and an array for the headers), which reads
20
+ // as is. `emailengine encrypt` re-encrypts exactly these fields.
21
+ const ENCRYPTED_ROUTE_FIELDS = ['targetUrl', 'customHeaders'];
13
22
 
14
23
  class WebhooksHandler {
15
24
  constructor(options) {
@@ -18,6 +27,8 @@ class WebhooksHandler {
18
27
 
19
28
  this.handlerCache = [];
20
29
  this.handlerCacheV = 0;
30
+ // the refresh in flight, shared by concurrent getWebhookHandlers() calls
31
+ this.handlerRefresh = null;
21
32
  }
22
33
 
23
34
  getWebhooksIndexKey() {
@@ -36,6 +47,67 @@ class WebhooksHandler {
36
47
  return `${REDIS_PREFIX}settings`;
37
48
  }
38
49
 
50
+ // Stored form of a route's meta entry, see ENCRYPTED_ROUTE_FIELDS
51
+ async encodeMeta(entry) {
52
+ const secret = await getSecret();
53
+ const stored = Object.assign({}, entry);
54
+ if (secret) {
55
+ if (typeof stored.targetUrl === 'string') {
56
+ stored.targetUrl = encryptField(stored.targetUrl, secret);
57
+ }
58
+ if (Array.isArray(stored.customHeaders)) {
59
+ stored.customHeaders = encryptField(JSON.stringify(stored.customHeaders), secret);
60
+ }
61
+ }
62
+ return msgpack.encode(stored);
63
+ }
64
+
65
+ // Decodes a stored meta entry. A field that does not decrypt with the current secret is left
66
+ // out and logged: without a targetUrl the route is not deliverable, which is the safe outcome
67
+ // for a route whose credentials cannot be read.
68
+ async decodeMeta(buf, id) {
69
+ const meta = msgpack.decode(buf);
70
+ if (!meta || typeof meta !== 'object') {
71
+ return meta;
72
+ }
73
+
74
+ const secret = await getSecret();
75
+
76
+ if (typeof meta.targetUrl === 'string') {
77
+ meta.targetUrl = decryptField(meta.targetUrl, secret, err =>
78
+ logger.error({ msg: 'Failed to decrypt webhook route field', webhook: id || meta.id, field: 'targetUrl', err })
79
+ );
80
+ if (typeof meta.targetUrl === 'undefined') {
81
+ delete meta.targetUrl;
82
+ }
83
+ }
84
+
85
+ if (typeof meta.customHeaders === 'string') {
86
+ // never log the value, it is a credential once decrypted
87
+ const report = err =>
88
+ logger.error({
89
+ msg: 'Failed to decrypt webhook route field',
90
+ webhook: id || meta.id,
91
+ field: 'customHeaders',
92
+ errorType: err.name,
93
+ code: err.code
94
+ });
95
+ const json = decryptField(meta.customHeaders, secret, report);
96
+ try {
97
+ // JSON.parse(undefined) throws, so a value that did not decrypt lands here too
98
+ // and is left out, already reported
99
+ meta.customHeaders = JSON.parse(json);
100
+ } catch (err) {
101
+ if (typeof json !== 'undefined') {
102
+ report(err);
103
+ }
104
+ delete meta.customHeaders;
105
+ }
106
+ }
107
+
108
+ return meta;
109
+ }
110
+
39
111
  async list(page, pageSize, query) {
40
112
  page = Math.max(Number(page) || 0, 0);
41
113
  pageSize = Math.max(Number(pageSize) || 20, 1);
@@ -80,7 +152,7 @@ class WebhooksHandler {
80
152
  }
81
153
 
82
154
  try {
83
- let webhookMeta = msgpack.decode(entry);
155
+ let webhookMeta = await this.decodeMeta(entry, selectedIds[i / 3]);
84
156
  if (webhookErrorFlag && typeof webhookErrorFlag === 'object' && !Object.keys(webhookErrorFlag).length) {
85
157
  webhookErrorFlag = null;
86
158
  }
@@ -123,7 +195,7 @@ class WebhooksHandler {
123
195
  .multi()
124
196
  .sadd(this.getWebhooksIndexKey(), id)
125
197
  .hmset(this.getWebhooksContentKey(), {
126
- [`${id}:meta`]: msgpack.encode(entry),
198
+ [`${id}:meta`]: await this.encodeMeta(entry),
127
199
  [`${id}:content`]: msgpack.encode(content),
128
200
  [`${id}:v`]: 1
129
201
  })
@@ -150,7 +222,7 @@ class WebhooksHandler {
150
222
  throw err;
151
223
  }
152
224
 
153
- let existingMeta = msgpack.decode(metaBuf);
225
+ let existingMeta = await this.decodeMeta(metaBuf, id);
154
226
 
155
227
  let entry = Object.assign(existingMeta, meta || {}, {
156
228
  id: existingMeta.id,
@@ -159,7 +231,7 @@ class WebhooksHandler {
159
231
  });
160
232
 
161
233
  let updates = {
162
- [`${id}:meta`]: msgpack.encode(entry)
234
+ [`${id}:meta`]: await this.encodeMeta(entry)
163
235
  };
164
236
 
165
237
  if (content) {
@@ -215,7 +287,7 @@ class WebhooksHandler {
215
287
 
216
288
  try {
217
289
  if (getResult[0]) {
218
- meta = msgpack.decode(getResult[0]);
290
+ meta = await this.decodeMeta(getResult[0], id);
219
291
  }
220
292
  } catch (err) {
221
293
  logger.error({ msg: 'Failed to process webhook', webhook: id, entry: getResult[0].toString('base64'), err });
@@ -240,7 +312,7 @@ class WebhooksHandler {
240
312
 
241
313
  try {
242
314
  if (getResult[0]) {
243
- meta = msgpack.decode(getResult[0]);
315
+ meta = await this.decodeMeta(getResult[0], id);
244
316
  }
245
317
  } catch (err) {
246
318
  logger.error({ msg: 'Failed to process webhook', webhook: id, entry: getResult[0].toString('base64'), err });
@@ -276,6 +348,9 @@ class WebhooksHandler {
276
348
  .hdel(this.getWebhooksContentKey(), [`${id}:meta`, `${id}:content`])
277
349
  .del(this.getWebhooksLogKey(id))
278
350
  .hincrby(this.getWebhooksContentKey(), `v`, 1)
351
+ // The per-route counters and error flag go with the route. Not counted below: they
352
+ // exist only once the route was updated, used or failed.
353
+ .hdel(this.getWebhooksContentKey(), [`${id}:v`, `${id}:tcount`, `${id}:webhookErrorFlag`])
279
354
  .exec();
280
355
 
281
356
  let hasError = (deleteResult[0] && deleteResult[0][0]) || (deleteResult[1] && deleteResult[1][0]);
@@ -437,6 +512,9 @@ class WebhooksHandler {
437
512
  await this.storeLog(id, 'map', payload, err.stack);
438
513
 
439
514
  logger.error({ msg: 'Failed to execute webhook script', type: 'map', webhook: webhookData.id, err });
515
+ // No mapping: pushToQueue() then skips the route. The worker used to be
516
+ // handed the unmapped payload in its place, everything a stripping map was
517
+ // there to remove
440
518
  return null;
441
519
  }
442
520
  };
@@ -445,7 +523,22 @@ class WebhooksHandler {
445
523
  return webhookData;
446
524
  }
447
525
 
526
+ // Concurrent callers share one refresh. pushToQueue() runs for every event, so two refreshes
527
+ // used to overlap: both saw the version change, both loaded the new route and both pushed it,
528
+ // and every matching event was then queued twice to that route until the worker restarted.
448
529
  async getWebhookHandlers() {
530
+ if (this.handlerRefresh) {
531
+ return await this.handlerRefresh;
532
+ }
533
+ this.handlerRefresh = this.refreshWebhookHandlers();
534
+ try {
535
+ return await this.handlerRefresh;
536
+ } finally {
537
+ this.handlerRefresh = null;
538
+ }
539
+ }
540
+
541
+ async refreshWebhookHandlers() {
449
542
  let v = await this.redis.hget(this.getWebhooksContentKey(), 'v');
450
543
  v = Number(v) || 0;
451
544
  if (v !== this.handlerCacheV) {
@@ -568,7 +661,7 @@ class WebhooksHandler {
568
661
  return payload;
569
662
  }
570
663
 
571
- async pushToQueue(event, originalPayload, opts = {}) {
664
+ async pushToQueue(event, originalPayload) {
572
665
  // custom webhook routes
573
666
  let webhookRoutes = await this.getWebhookHandlers();
574
667
  let queueKeep = (await settings.get('queueKeep')) ?? true;
@@ -600,42 +693,27 @@ class WebhooksHandler {
600
693
  logger.error({ msg: 'Failed to execute webhook script', type: 'filter', webhook: route.id, err });
601
694
  }
602
695
 
603
- if (canSend) {
604
- if (typeof route.mapFn === 'function') {
605
- try {
606
- payload._route.mapping = await route.mapFn(payload);
607
- } catch (err) {
608
- await this.storeLog(route.id, 'map', payload, err.stack);
609
-
610
- logger.error({ msg: 'Failed to execute webhook script', type: 'map', webhook: route.id, err });
611
- canSend = false;
612
- }
696
+ if (canSend && typeof route.mapFn === 'function') {
697
+ // A route with a map sends the mapped payload or nothing. mapFn logs its own
698
+ // failure and answers null for it, the same as a script opting out.
699
+ let mapping = await route.mapFn(payload);
700
+ if (mapping === null || typeof mapping === 'undefined' || mapping === false) {
701
+ logger.debug({ msg: 'Webhook map script returned no payload, skipping route', event, webhook: route.id });
702
+ canSend = false;
703
+ } else {
704
+ payload._route.mapping = mapping;
613
705
  }
614
706
  }
615
707
 
616
708
  if (canSend && payload) {
617
- if (opts.queueFlow) {
618
- opts.queueFlow.push({
619
- name: event,
620
- data: payload,
621
- queueName: 'notify'
622
- });
623
-
624
- logger.trace({
625
- msg: 'Added custom webhook route to queue flow',
626
- event,
627
- webhook: route.id
628
- });
629
- } else {
630
- let job = await notifyQueue.add(event, payload, jobOpts);
631
-
632
- logger.trace({
633
- msg: 'Triggered custom webhook route',
634
- event,
635
- webhook: route.id,
636
- job: job.id
637
- });
638
- }
709
+ let job = await notifyQueue.add(event, payload, jobOpts);
710
+
711
+ logger.trace({
712
+ msg: 'Triggered custom webhook route',
713
+ event,
714
+ webhook: route.id,
715
+ job: job.id
716
+ });
639
717
 
640
718
  try {
641
719
  await this.redis.hincrby(this.getWebhooksContentKey(), `${route.id}:tcount`, 1);
@@ -646,11 +724,10 @@ class WebhooksHandler {
646
724
  }
647
725
  }
648
726
 
649
- if (!opts.routesOnly) {
650
- // MAIN webhook
651
- await notifyQueue.add(event, originalPayload, jobOpts);
652
- }
727
+ // MAIN webhook
728
+ await notifyQueue.add(event, originalPayload, jobOpts);
653
729
  }
654
730
  }
655
731
 
656
732
  module.exports.webhooks = new WebhooksHandler({ redis });
733
+ module.exports.ENCRYPTED_ROUTE_FIELDS = ENCRYPTED_ROUTE_FIELDS;
@@ -14,7 +14,7 @@
14
14
  // one place makes that dependency explicit and unit-testable (see test/worker-rpc-error-test.js).
15
15
  //
16
16
  // These helpers are used at the delivery-error RPC path - the imap/submit workers and the main-thread
17
- // hub (server.js) that relays between them. The other workers (webhooks/export/documents/smtp/api)
17
+ // hub (server.js) that relays between them. The other workers (webhooks/export/smtp/api)
18
18
  // keep their own inline resp-handler copies: they never carry a delivery error, so `responseCode`
19
19
  // does not apply to them. Route a delivery error through a new worker and it must switch to these too.
20
20
  const RPC_ERROR_FIELDS = ['code', 'statusCode', 'responseCode', 'info'];
@@ -51,4 +51,45 @@ function unpackRpcError(message) {
51
51
  return err;
52
52
  }
53
53
 
54
- module.exports = { packRpcError, unpackRpcError };
54
+ // Longest string value describeRpcCommand() copies into a log line
55
+ const MAX_LOGGED_VALUE_LENGTH = 256;
56
+
57
+ /**
58
+ * What a failed-command log line says about an RPC command. The payload itself stays out: a
59
+ * submitMessage carries the whole message (attachment content, html and text bodies), and the log
60
+ * redaction only knows the request and error paths. Scalar fields (cmd, account, message id, path)
61
+ * are kept, nested objects are reduced to their key list and a size
62
+ * @param {Object} envelope - The RPC envelope ({ cmd: 'call', mid, message })
63
+ * @returns {Object}
64
+ */
65
+ function describeRpcCommand(envelope) {
66
+ let command = (envelope && envelope.message) || {};
67
+ let summary = { mid: envelope && envelope.mid };
68
+
69
+ for (let [key, value] of Object.entries(command)) {
70
+ switch (typeof value) {
71
+ case 'string':
72
+ summary[key] = value.length > MAX_LOGGED_VALUE_LENGTH ? `${value.slice(0, MAX_LOGGED_VALUE_LENGTH)}...` : value;
73
+ break;
74
+ case 'number':
75
+ case 'boolean':
76
+ summary[key] = value;
77
+ break;
78
+ }
79
+ }
80
+
81
+ let data = command.data;
82
+ if (data && typeof data === 'object' && !Buffer.isBuffer(data)) {
83
+ summary.dataKeys = Object.keys(data);
84
+ if (data.raw && typeof data.raw.length === 'number') {
85
+ summary.rawSize = data.raw.length;
86
+ }
87
+ if (Array.isArray(data.attachments)) {
88
+ summary.attachments = data.attachments.length;
89
+ }
90
+ }
91
+
92
+ return summary;
93
+ }
94
+
95
+ module.exports = { packRpcError, unpackRpcError, describeRpcCommand };