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
@@ -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 };
package/list-generate.js CHANGED
@@ -33,8 +33,19 @@ const ALLOWED_LICENSES = [
33
33
  ];
34
34
 
35
35
  // Build-time packages whose output ships inside the compiled UI assets
36
- // (static/css/flyonui.css, static/js/flyonui.js)
37
- const ASSET_PACKAGES = ['tailwindcss', 'flyonui', '@iconify/tailwind4', '@iconify-json/tabler'];
36
+ // (static/css/flyonui.css, static/js/flyonui.js) or is copied under static/ by
37
+ // copy-static-files.sh (the ACE editor, the message browser client, the WebAuthn
38
+ // browser bundle). All devDependencies, so `npm ls --omit=dev` above never lists
39
+ // them and they have to be named here to appear in the listing at all.
40
+ const ASSET_PACKAGES = [
41
+ 'tailwindcss',
42
+ 'flyonui',
43
+ '@iconify/tailwind4',
44
+ '@iconify-json/tabler',
45
+ 'ace-builds',
46
+ '@postalsys/ee-client',
47
+ '@simplewebauthn/browser'
48
+ ];
38
49
 
39
50
  // Packages whose package.json declares no (or an unparseable) license even
40
51
  // though their shipped LICENSE file is clear. Keep each entry justified; fix