emailengine-app 2.84.2 → 2.86.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 (164) hide show
  1. package/.ncurc.js +29 -9
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +107 -0
  6. package/Dockerfile +20 -1
  7. package/ENVIRONMENT.md +139 -0
  8. package/README.md +2 -2
  9. package/bin/emailengine.js +434 -408
  10. package/config/default.toml +2 -0
  11. package/copy-static-files.sh +41 -14
  12. package/data/google-crawlers.json +1 -1
  13. package/data/public_suffix_list.dat +16563 -0
  14. package/eslint.config.js +81 -99
  15. package/lib/account-assignment.js +19 -0
  16. package/lib/account.js +230 -170
  17. package/lib/api-error-codes.js +49 -0
  18. package/lib/api-reference/format.js +4 -3
  19. package/lib/api-reference/model.js +6 -1
  20. package/lib/api-routes/account-routes.js +255 -38
  21. package/lib/api-routes/blocklist-routes.js +91 -4
  22. package/lib/api-routes/delivery-test-routes.js +27 -4
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +110 -12
  25. package/lib/api-routes/index.js +4 -0
  26. package/lib/api-routes/license-routes.js +2 -2
  27. package/lib/api-routes/mailbox-routes.js +44 -5
  28. package/lib/api-routes/message-routes.js +112 -10
  29. package/lib/api-routes/oauth2-app-routes.js +63 -23
  30. package/lib/api-routes/outbox-routes.js +97 -52
  31. package/lib/api-routes/permission-map.js +67 -7
  32. package/lib/api-routes/scoped-routes.js +74 -0
  33. package/lib/api-routes/settings-routes.js +34 -6
  34. package/lib/api-routes/stats-routes.js +5 -1
  35. package/lib/api-routes/submit-routes.js +337 -309
  36. package/lib/api-routes/template-routes.js +45 -8
  37. package/lib/api-routes/token-routes.js +152 -100
  38. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  39. package/lib/api-routes/webhook-route-routes.js +132 -6
  40. package/lib/bounce-detect.js +397 -205
  41. package/lib/calendar-event.js +81 -1
  42. package/lib/consts.js +38 -45
  43. package/lib/db.js +14 -6
  44. package/lib/delivery-error.js +6 -0
  45. package/lib/deprecations.js +270 -0
  46. package/lib/email-client/base-client.js +137 -184
  47. package/lib/email-client/fallback-poll.js +62 -0
  48. package/lib/email-client/gmail-client.js +60 -22
  49. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  50. package/lib/email-client/imap/adaptive-idle.js +278 -0
  51. package/lib/email-client/imap/connection-errors.js +14 -1
  52. package/lib/email-client/imap/idle-settings.js +31 -5
  53. package/lib/email-client/imap/listing-diff.js +37 -0
  54. package/lib/email-client/imap/mailbox.js +372 -242
  55. package/lib/email-client/imap/subconnection.js +8 -30
  56. package/lib/email-client/imap/sync-operations.js +220 -127
  57. package/lib/email-client/imap-client.js +228 -164
  58. package/lib/email-client/message-builder.js +14 -79
  59. package/lib/email-client/notification-handler.js +1 -2
  60. package/lib/email-client/outlook-client.js +372 -338
  61. package/lib/email-client/smtp-pool-manager.js +16 -13
  62. package/lib/email-client/sync-state-fields.js +19 -0
  63. package/lib/encrypt.js +157 -41
  64. package/lib/enum-descriptions.js +3 -1
  65. package/lib/env-setting-overrides.js +288 -0
  66. package/lib/export-worker.js +751 -0
  67. package/lib/export.js +64 -15
  68. package/lib/gateway.js +19 -4
  69. package/lib/get-raw-email.js +25 -107
  70. package/lib/hapi-request-logger.js +107 -0
  71. package/lib/health.js +75 -0
  72. package/lib/imapproxy/imap-core/README.md +6 -5
  73. package/lib/lock-run.js +119 -0
  74. package/lib/logger-consts.js +48 -0
  75. package/lib/logger.js +1 -1
  76. package/lib/lua/z-head-scores.lua +28 -0
  77. package/lib/mcp/tools.js +37 -8
  78. package/lib/network-errors.js +1 -1
  79. package/lib/node-version.js +24 -0
  80. package/lib/notify-attachments.js +36 -0
  81. package/lib/oauth/outlook-mailbox.js +35 -0
  82. package/lib/oauth/state.js +24 -0
  83. package/lib/oauth2-apps.js +631 -656
  84. package/lib/outbox.js +184 -54
  85. package/lib/parse-message.js +3 -3
  86. package/lib/pbkdf2-phc.js +1 -1
  87. package/lib/privileged-settings.js +2 -2
  88. package/lib/queue-browser/definitions.js +11 -0
  89. package/lib/queue-browser/index.js +68 -19
  90. package/lib/queue-job-actions.js +18 -1
  91. package/lib/queue-retention.js +48 -12
  92. package/lib/queue-stats.js +11 -2
  93. package/lib/read-env-value.js +3 -0
  94. package/lib/redis-memory-warnings.js +99 -0
  95. package/lib/redis-reconnect.js +29 -0
  96. package/lib/request-timing.js +23 -0
  97. package/lib/respawn-backoff.js +35 -0
  98. package/lib/rewrite-text-nodes.js +19 -59
  99. package/lib/schemas.js +164 -40
  100. package/lib/settings.js +6 -2
  101. package/lib/smtp-auth.js +19 -1
  102. package/lib/sso.js +1 -1
  103. package/lib/swagger-options.js +1 -1
  104. package/lib/thread-diagnostics.js +63 -0
  105. package/lib/timezones.js +109 -0
  106. package/lib/tls/provision.js +6 -3
  107. package/lib/token-audit-log.js +19 -20
  108. package/lib/token-permission-view.js +7 -6
  109. package/lib/tools.js +48 -51
  110. package/lib/totp.js +2 -5
  111. package/lib/translations.js +1 -2
  112. package/lib/ui-routes/account-routes.js +475 -454
  113. package/lib/ui-routes/account-setup.js +99 -0
  114. package/lib/ui-routes/admin-config-routes.js +152 -100
  115. package/lib/ui-routes/admin-entities-routes.js +93 -21
  116. package/lib/ui-routes/auth-routes.js +90 -38
  117. package/lib/ui-routes/imap-idle-field.js +1 -1
  118. package/lib/ui-routes/internals-routes.js +5 -0
  119. package/lib/ui-routes/oauth-config-routes.js +124 -82
  120. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  121. package/lib/ui-routes/overridable-fields.js +84 -0
  122. package/lib/ui-routes/queue-routes.js +8 -5
  123. package/lib/ui-routes/route-helpers.js +19 -3
  124. package/lib/ui-routes/settings-page.js +6 -0
  125. package/lib/ui-routes/tls-config-routes.js +58 -15
  126. package/lib/utils/back-off.js +82 -0
  127. package/lib/utils/decode-headers.js +3 -12
  128. package/lib/utils/filter-empty.js +20 -0
  129. package/lib/utils/int-setting.js +48 -0
  130. package/lib/utils/murmurhash3.js +66 -0
  131. package/lib/utils/public-suffix.js +122 -0
  132. package/lib/utils/random-id.js +26 -0
  133. package/lib/utils/tracking-settings.js +35 -0
  134. package/lib/utils/version.js +74 -0
  135. package/lib/web-safe-html.js +18 -105
  136. package/lib/webhook-delivery.js +461 -0
  137. package/lib/webhook-failures.js +132 -0
  138. package/lib/webhook-request.js +29 -1
  139. package/lib/webhook-routing.js +56 -0
  140. package/lib/webhook-test.js +88 -0
  141. package/lib/webhooks.js +93 -45
  142. package/lib/worker-rpc-error.js +2 -1
  143. package/package.json +37 -38
  144. package/sbom.json +7902 -1
  145. package/server.js +784 -518
  146. package/static/js/ace/ace.js +1 -1
  147. package/static/licenses.html +225 -1060
  148. package/translations/messages.pot +62 -63
  149. package/views/config/ai.hbs +1 -1
  150. package/views/config/security.hbs +24 -2
  151. package/views/config/service.hbs +47 -0
  152. package/views/config/webhooks.hbs +36 -0
  153. package/views/internals/index.hbs +8 -0
  154. package/views/partials/queue_retention_note.hbs +12 -8
  155. package/views/partials/ui/env-managed-alert.hbs +16 -7
  156. package/views/partials/webhook_form.hbs +1 -1
  157. package/views/suppression-lists/index.hbs +1 -1
  158. package/workers/api.js +840 -611
  159. package/workers/export.js +17 -632
  160. package/workers/imap.js +13 -0
  161. package/workers/smtp.js +9 -11
  162. package/workers/submit.js +1 -1
  163. package/workers/webhooks.js +18 -448
  164. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -1,10 +1,8 @@
1
1
  'use strict';
2
2
 
3
- const { readEnvValue } = require('./read-env-value');
4
-
5
3
  // Retention policies for BullMQ job entries.
6
4
  //
7
- // This module is deliberately dependency-free (no Redis, no settings) so it can be unit tested
5
+ // This module is deliberately dependency-free (no Redis, no settings, no environment) so it can be unit tested
8
6
  // directly. Four call sites used to build these policies inline from the `queueKeep` setting and
9
7
  // had already drifted apart: three read the setting with `?? true` and one with `|| true`, which
10
8
  // silently turned an explicit `queueKeep = 0` into "keep everything".
@@ -19,8 +17,26 @@ const COMPLETED_JOB_RETENTION_AGE = 24 * 3600;
19
17
  // Both are overridable because the right bound depends on payload size: a `messageNew` webhook
20
18
  // carries up to `notifyTextSize` (2MB by default) of message text, and a receiver that is down
21
19
  // turns every event into a retained entry.
22
- const FAILED_JOB_RETENTION_AGE = Number(readEnvValue('EENGINE_QUEUE_KEEP_FAILED_AGE')) || 7 * 24 * 3600;
23
- const FAILED_JOB_RETENTION_COUNT = Number(readEnvValue('EENGINE_QUEUE_KEEP_FAILED')) || 500;
20
+ //
21
+ // Both are settings (queueKeepFailedAge, queueKeepFailed) and environment variables, which
22
+ // lib/env-setting-overrides.js resolves, the environment winning; the values below are only the
23
+ // defaults. Every caller passes the resolved bounds in, so there is one parser for the variables.
24
+ const FAILED_JOB_RETENTION_AGE_DEFAULT = 7 * 24 * 3600;
25
+ const FAILED_JOB_RETENTION_COUNT_DEFAULT = 500;
26
+
27
+ /**
28
+ * @param {{age: number, count: number}} failedRetention
29
+ * @returns {{age: number, count: number}} The same bounds, checked
30
+ */
31
+ function requireFailedRetention(failedRetention) {
32
+ const age = Number(failedRetention?.age);
33
+ const count = Number(failedRetention?.count);
34
+ if (!(age > 0) || !(count > 0)) {
35
+ // the bounds come from getFailedJobRetention(); a default here would ignore the setting
36
+ throw new TypeError('The failed-job retention bounds are required, see getFailedJobRetention()');
37
+ }
38
+ return { age, count };
39
+ }
24
40
 
25
41
  /**
26
42
  * Builds the `removeOnComplete` / `removeOnFail` pair for a queue job.
@@ -28,23 +44,27 @@ const FAILED_JOB_RETENTION_COUNT = Number(readEnvValue('EENGINE_QUEUE_KEEP_FAILE
28
44
  * A job reaches the failed set only after every retry is exhausted, which for a webhook means the
29
45
  * event is gone. `queueKeep` defaults to 0, so applying it to failures too (the previous behavior)
30
46
  * deleted that record the moment it was written and left nothing but a log line behind. Failures
31
- * therefore get their own floor: at least `FAILED_JOB_RETENTION_COUNT` entries for
32
- * `FAILED_JOB_RETENTION_AGE` seconds, regardless of how few completed entries are wanted.
47
+ * therefore get their own floor: at least `failedRetention.count` entries for `failedRetention.age`
48
+ * seconds, regardless of how few completed entries are wanted.
33
49
  *
34
50
  * BullMQ reads these values as "when to remove", not "how much to keep": `true` removes the entry
35
51
  * immediately, `false` keeps it forever, a number keeps the last N, and `{age, count}` keeps
36
52
  * entries younger than `age` up to `count` of them.
37
53
  *
38
54
  * @param {boolean|number} queueKeep - The `queueKeep` setting: entries to retain, or a boolean
55
+ * @param {{age: number, count: number}} failedRetention - The failed-job bounds in effect (age in
56
+ * seconds), as getFailedJobRetention() resolves them
39
57
  * @returns {{removeOnComplete: boolean|Object, removeOnFail: boolean|Object}} BullMQ job options
40
58
  */
41
- function buildRetentionPolicy(queueKeep) {
59
+ function buildRetentionPolicy(queueKeep, failedRetention) {
60
+ const { age: failedAge, count: failedCount } = requireFailedRetention(failedRetention);
61
+
42
62
  const removeOnComplete = typeof queueKeep === 'number' ? { age: COMPLETED_JOB_RETENTION_AGE, count: queueKeep } : queueKeep;
43
63
 
44
64
  // Always bounded, and widened when the operator asked to keep more entries than the floor
45
65
  const removeOnFail = {
46
- age: FAILED_JOB_RETENTION_AGE,
47
- count: typeof queueKeep === 'number' ? Math.max(queueKeep, FAILED_JOB_RETENTION_COUNT) : FAILED_JOB_RETENTION_COUNT
66
+ age: failedAge,
67
+ count: typeof queueKeep === 'number' ? Math.max(queueKeep, failedCount) : failedCount
48
68
  };
49
69
 
50
70
  return { removeOnComplete, removeOnFail };
@@ -99,12 +119,28 @@ function selectFailedContentToDrop(entries, limits) {
99
119
  return drop.reverse();
100
120
  }
101
121
 
122
+ /**
123
+ * Ages for the periodic queue clean in server.js, in milliseconds as BullMQ's clean() takes them
124
+ * (the retention ages above are seconds, as removeOnComplete/removeOnFail take them). The clean used
125
+ * hardcoded 24 hours and 7 days, so a longer failed-job retention kept failed jobs no longer than a
126
+ * week anyway
127
+ * @param {{age: number, count: number}} failedRetention - As getFailedJobRetention() resolves it
128
+ * @returns {{ completed: number, failed: number }}
129
+ */
130
+ function queueCleanAges(failedRetention) {
131
+ return {
132
+ completed: COMPLETED_JOB_RETENTION_AGE * 1000,
133
+ failed: requireFailedRetention(failedRetention).age * 1000
134
+ };
135
+ }
136
+
102
137
  module.exports = {
103
138
  buildRetentionPolicy,
139
+ queueCleanAges,
104
140
  selectFailedContentToDrop,
105
141
  COMPLETED_JOB_RETENTION_AGE,
106
- FAILED_JOB_RETENTION_AGE,
107
- FAILED_JOB_RETENTION_COUNT,
142
+ FAILED_JOB_RETENTION_AGE_DEFAULT,
143
+ FAILED_JOB_RETENTION_COUNT_DEFAULT,
108
144
  DEFAULT_FAILED_CONTENT_RETENTION_COUNT,
109
145
  DEFAULT_FAILED_CONTENT_RETENTION_SIZE
110
146
  };
@@ -22,13 +22,18 @@ const COUNTED_STATES = ['active', 'delayed', 'waiting'];
22
22
  * Counts the pending jobs of a queue and reports whether the queue is paused.
23
23
  *
24
24
  * @param {Object} queueObj - BullMQ Queue instance
25
+ * @param {Object} [opts]
26
+ * @param {boolean} [opts.failed] - Also count the failed jobs the queue still retains, in the same
27
+ * read, as `failed`. Kept out of `total` and out of the published payloads: a failed job is not
28
+ * pending work, it is the record that a delivery was given up on, which is what /metrics alerts on
25
29
  * @returns {Promise<Object>} `active`, `delayed` and `waiting` counts plus their `total`, the
26
30
  * `isPaused` flag, and a `paused` count that is always 0 - BullMQ 6 no longer parks jobs in a
27
31
  * separate paused list, so a paused queue holds them in `waiting` and they are counted there.
28
32
  * The key is kept because it is part of both published payloads.
29
33
  */
30
- async function queueStats(queueObj) {
31
- const [counts, isPaused] = await Promise.all([queueObj.getJobCounts(...COUNTED_STATES), queueObj.isPaused()]);
34
+ async function queueStats(queueObj, opts = {}) {
35
+ const states = opts.failed ? COUNTED_STATES.concat('failed') : COUNTED_STATES;
36
+ const [counts, isPaused] = await Promise.all([queueObj.getJobCounts(...states), queueObj.isPaused()]);
32
37
 
33
38
  const stats = {
34
39
  paused: 0,
@@ -43,6 +48,10 @@ async function queueStats(queueObj) {
43
48
  }
44
49
  stats.total = total;
45
50
 
51
+ if (opts.failed) {
52
+ stats.failed = Number(counts.failed) || 0;
53
+ }
54
+
46
55
  return stats;
47
56
  }
48
57
 
@@ -5,6 +5,9 @@
5
5
  // would create). Still re-exported from lib/tools.js, which is where most callers reach it.
6
6
 
7
7
  const Fs = require('fs');
8
+
9
+ // lib/logger.js takes its constants from lib/logger-consts.js rather than lib/consts.js, which reads
10
+ // its own variables through this helper, so the logger can be required here directly
8
11
  const logger = require('./logger');
9
12
 
10
13
  // The keys that lib/db.js and lib/get-secret.js used to resolve through private copies of this
@@ -0,0 +1,99 @@
1
+ 'use strict';
2
+
3
+ // Dashboard warnings about how Redis manages its memory, derived from INFO. Pure, so the decisions
4
+ // can be tested without a Redis to put into each state.
5
+ //
6
+ // EmailEngine uses Redis as a database, not a cache. Any eviction silently drops sync state, which
7
+ // makes already-synced messages look new and triggers duplicate webhooks. With the required
8
+ // noeviction policy the failure is the other one: once used memory reaches maxmemory, Redis refuses
9
+ // every write with an OOM reply, and sync, delivery and webhooks stop together. Neither eviction
10
+ // warning fires for that, so a separate one says how close to the limit Redis is.
11
+
12
+ const { humanSize } = require('./queue-browser/format');
13
+
14
+ // Share of maxmemory at which the dashboard starts warning, and at which the warning turns red
15
+ const MEMORY_WARNING_RATIO = 0.8;
16
+ const MEMORY_DANGER_RATIO = 0.95;
17
+
18
+ /**
19
+ * Warning about eviction, either already happened or allowed by the configured policy
20
+ * @param {Object} redisInfo - Parsed INFO output
21
+ * @returns {Object|null} Warning entry, or null
22
+ */
23
+ function evictionWarning(redisInfo) {
24
+ let maxmemoryPolicy = typeof redisInfo.maxmemory_policy === 'string' ? redisInfo.maxmemory_policy : null;
25
+ let maxmemory = Number(redisInfo.maxmemory) || 0;
26
+ let evictedKeys = Number(redisInfo.evicted_keys) || 0;
27
+
28
+ if (evictedKeys > 0) {
29
+ // Definitive: Redis has already evicted keys
30
+ return {
31
+ key: 'evicted-keys',
32
+ color: 'danger',
33
+ title: 'Redis eviction detected',
34
+ details: [
35
+ `Redis has evicted ${evictedKeys.toLocaleString('en-US')} key${evictedKeys === 1 ? '' : 's'} after reaching its memory limit.`,
36
+ 'EmailEngine uses Redis as its primary database, not a cache. Evicted keys cause already-synced messages to be reprocessed - generating duplicate webhooks - and can lead to data loss.',
37
+ 'Set the Redis "maxmemory-policy" to "noeviction" and provision enough memory so Redis never reaches its limit.'
38
+ ]
39
+ };
40
+ }
41
+
42
+ if (maxmemoryPolicy && maxmemoryPolicy !== 'noeviction') {
43
+ // Latent risk: an eviction policy is configured but nothing has been evicted yet
44
+ return {
45
+ key: 'maxmemory-policy',
46
+ color: maxmemory > 0 ? 'danger' : 'warning',
47
+ title: 'Unsafe Redis eviction policy',
48
+ details: [
49
+ `The Redis "maxmemory-policy" is set to "${maxmemoryPolicy}", but EmailEngine requires "noeviction".`,
50
+ 'With any other policy, Redis can delete EmailEngine sync state under memory pressure, causing already-synced messages to be reprocessed - generating duplicate webhooks - and possible data loss.',
51
+ 'Set "maxmemory-policy noeviction" and make sure Redis has enough memory for your workload.'
52
+ ]
53
+ };
54
+ }
55
+
56
+ return null;
57
+ }
58
+
59
+ /**
60
+ * Warning about used memory approaching maxmemory. Without a maxmemory there is no limit for
61
+ * Redis to refuse writes at, so nothing is reported
62
+ * @param {Object} redisInfo - Parsed INFO output
63
+ * @returns {Object|null} Warning entry, or null
64
+ */
65
+ function memoryLimitWarning(redisInfo) {
66
+ let maxmemory = Number(redisInfo.maxmemory) || 0;
67
+ let usedMemory = Number(redisInfo.used_memory) || 0;
68
+ if (maxmemory <= 0 || usedMemory <= 0) {
69
+ return null;
70
+ }
71
+
72
+ let ratio = usedMemory / maxmemory;
73
+ if (ratio < MEMORY_WARNING_RATIO) {
74
+ return null;
75
+ }
76
+
77
+ return {
78
+ key: 'memory-limit',
79
+ color: ratio >= MEMORY_DANGER_RATIO ? 'danger' : 'warning',
80
+ title: 'Redis is close to its memory limit',
81
+ details: [
82
+ `Redis is using ${humanSize(usedMemory)} of its ${humanSize(maxmemory)} "maxmemory" limit (${Math.min(Math.round(ratio * 100), 100)}%).`,
83
+ 'Once the limit is reached Redis refuses every write, and syncing, sending and webhook delivery stop until memory is freed.',
84
+ 'Raise "maxmemory", or find what is growing: a webhook backlog for a receiver that is down, account logs, or failed queue entries.'
85
+ ]
86
+ };
87
+ }
88
+
89
+ /**
90
+ * All memory warnings for the dashboard, in display order
91
+ * @param {Object} redisInfo - Parsed INFO output
92
+ * @returns {Object[]} Warning entries
93
+ */
94
+ function redisMemoryWarnings(redisInfo) {
95
+ redisInfo = redisInfo || {};
96
+ return [evictionWarning(redisInfo), memoryLimitWarning(redisInfo)].filter(Boolean);
97
+ }
98
+
99
+ module.exports = { redisMemoryWarnings };
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ // ioredis calls `reconnectOnError` for every error REPLY, not for connection errors: a refused
4
+ // write under `maxmemory` (OOM), a WRONGTYPE, a NOSCRIPT before the script is loaded again, and an
5
+ // error raised by a BullMQ Lua script all pass through it. Answering true to all of them dropped the
6
+ // connection on each one, and the IMAP worker exits on every Redis reconnect (workers/imap.js), so a
7
+ // full Redis turned into a loop of worker restarts and account resyncs, each writing more to a
8
+ // database that was already refusing writes.
9
+ //
10
+ // The only reply a reconnect fixes is READONLY: the client is still connected to a node that was
11
+ // demoted in a failover, and reconnecting reaches the new primary. Returning 2 makes ioredis resend
12
+ // the command once it has.
13
+
14
+ const RESEND_AFTER_RECONNECT = 2;
15
+
16
+ /**
17
+ * Decides whether an error reply means the connection should be re-established
18
+ * @param {Error} err - The error reply ioredis received
19
+ * @returns {number|boolean} 2 to reconnect and resend the command, false to just reject it
20
+ */
21
+ function reconnectOnErrorReply(err) {
22
+ let message = (err && typeof err.message === 'string' && err.message) || '';
23
+ if (/^READONLY\b/.test(message)) {
24
+ return RESEND_AFTER_RECONNECT;
25
+ }
26
+ return false;
27
+ }
28
+
29
+ module.exports = { reconnectOnErrorReply, RESEND_AFTER_RECONNECT };
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * How long an API request took, for the api_call_duration_seconds histogram. Read off Hapi's
5
+ * request.info in the 'response' event, where `completed` is set once the response was sent.
6
+ * A request the client abandoned has no `completed` but a `responded`, and either one is a better
7
+ * end than the time the event happens to run.
8
+ *
9
+ * @param {Object} info - Hapi request.info
10
+ * @returns {number|null} Seconds, or null when the request carries no usable timestamps
11
+ */
12
+ function apiCallDuration(info) {
13
+ if (!info || !Number.isFinite(info.received) || info.received <= 0) {
14
+ return null;
15
+ }
16
+ const end = [info.completed, info.responded].find(value => Number.isFinite(value) && value > 0);
17
+ if (!end || end < info.received) {
18
+ return null;
19
+ }
20
+ return (end - info.received) / 1000;
21
+ }
22
+
23
+ module.exports = { apiCallDuration };
@@ -11,6 +11,8 @@
11
11
  // stays up resets its own key immediately. server.js keys it by spawn slot (one per thread it
12
12
  // supervises), so exits of sibling workers of the same type do not add up.
13
13
 
14
+ const { setTimeout: setTimeoutPromise } = require('node:timers/promises');
15
+
14
16
  const DEFAULT_BASE_DELAY = 1000;
15
17
  const DEFAULT_MAX_DELAY = 60 * 1000;
16
18
 
@@ -88,8 +90,41 @@ class RespawnTracker {
88
90
  }
89
91
  }
90
92
 
93
+ /**
94
+ * Calls `fn` until it resolves, waiting `delayFor(attempt)` between failures. For the Redis reads
95
+ * a respawn has to make before it can start a thread (is the listener enabled): a failure there
96
+ * (Redis refusing commands under maxmemory, a failover) used to end the respawn chain for good,
97
+ * and the worker stayed down until the process restarted.
98
+ *
99
+ * @param {Function} fn - The read to make
100
+ * @param {Object} opts
101
+ * @param {Function} opts.delayFor - Delay before retry n (1 based), e.g. RespawnTracker#delayFor
102
+ * @param {Function} [opts.shouldStop] - True once the process is shutting down; the retries stop
103
+ * and the call resolves with undefined
104
+ * @param {Function} [opts.onError] - Called with the error and the delay before the retry
105
+ * @param {Function} [opts.sleep] - Waits the given milliseconds
106
+ * @returns {Promise<*>} What `fn` resolved with
107
+ */
108
+ async function retryWithBackoff(fn, opts) {
109
+ const { delayFor, shouldStop = () => false, onError = () => {}, sleep = setTimeoutPromise } = opts;
110
+
111
+ for (let attempt = 1; !shouldStop(); attempt++) {
112
+ try {
113
+ return await fn();
114
+ } catch (err) {
115
+ if (shouldStop()) {
116
+ throw err;
117
+ }
118
+ const delay = delayFor(attempt);
119
+ onError(err, delay);
120
+ await sleep(delay);
121
+ }
122
+ }
123
+ }
124
+
91
125
  module.exports = {
92
126
  RespawnTracker,
127
+ retryWithBackoff,
93
128
  DEFAULT_BASE_DELAY,
94
129
  DEFAULT_MAX_DELAY,
95
130
  DEFAULT_STABLE_UPTIME
@@ -3,64 +3,12 @@
3
3
  const Rewriter = require('@zone-eu/mailsplit/lib/node-rewriter');
4
4
  const Splitter = require('@zone-eu/mailsplit/lib/message-splitter');
5
5
  const Joiner = require('@zone-eu/mailsplit/lib/message-joiner');
6
- const encodingJapanese = require('encoding-japanese');
7
- const { Transform, pipeline } = require('stream');
8
- const iconv = require('iconv-lite');
6
+ const libmime = require('libmime');
7
+ const { pipeline } = require('stream');
9
8
  const LeWindows = require('nodemailer/lib/mime-node/le-windows');
10
9
  const { markParseFailure } = require('./smtp-message-processor');
11
10
  const logger = require('./logger').child({ component: 'rewrite-text-nodes' });
12
11
 
13
- class JPDecoder extends Transform {
14
- constructor(charset) {
15
- super();
16
-
17
- this.charset = charset;
18
- this.chunks = [];
19
- this.chunklen = 0;
20
- }
21
-
22
- _transform(chunk, encoding, done) {
23
- if (typeof chunk === 'string') {
24
- chunk = Buffer.from(chunk, encoding);
25
- }
26
-
27
- this.chunks.push(chunk);
28
- this.chunklen += chunk.length;
29
- done();
30
- }
31
-
32
- _flush(done) {
33
- let input = Buffer.concat(this.chunks, this.chunklen);
34
- try {
35
- let output = encodingJapanese.convert(input, {
36
- to: 'UNICODE', // to_encoding
37
- from: this.charset, // from_encoding
38
- type: 'string'
39
- });
40
- if (typeof output === 'string') {
41
- output = Buffer.from(output);
42
- }
43
- this.push(output);
44
- } catch (err) {
45
- logger.debug({ msg: 'Failed to convert Japanese charset, keeping original content', charset: this.charset, err });
46
- // keep as is on errors
47
- this.push(input);
48
- }
49
-
50
- done();
51
- }
52
- }
53
-
54
- const createDecodeStream = charset => {
55
- charset = (charset || 'ascii').toString().trim().toLowerCase();
56
- if (/^jis|^iso-?2022-?jp|^EUCJP/i.test(charset)) {
57
- // special case not supported by iconv-lite
58
- return new JPDecoder(charset);
59
- }
60
-
61
- return iconv.decodeStream(charset);
62
- };
63
-
64
12
  /**
65
13
  * Rewrites text content in email messages
66
14
  * @param {String|Buffer|ReadableStream} source RFC822 formatted email message
@@ -111,18 +59,24 @@ function rewriteTextNodes(source, options) {
111
59
  let encoded = !!data.node.charset;
112
60
  let decoder = data.decoder;
113
61
 
62
+ // A part in a charset that can not be decoded (unknown, or refused like UTF-7) is passed
63
+ // through untouched with its own label. It used to be relabelled utf-8 with the
64
+ // original bytes kept, which garbled it: a label as common as x-cp1251 failed that way,
65
+ // because the name reached iconv-lite without being normalized first
66
+ let decodable = true;
67
+
114
68
  if (encoded && !['ascii', 'usascii', 'utf8'].includes(data.node.charset.toLowerCase().replace(/[^a-z0-9]+/g, ''))) {
115
- try {
69
+ let decodeStream = libmime.createDecodeStream(data.node.charset);
70
+ if (decodeStream.supported) {
116
71
  let contentStream = decoder;
117
- let decodeStream = createDecodeStream(data.node.charset);
118
72
  contentStream.on('error', err => {
119
73
  decodeStream.emit('error', err);
120
74
  });
121
75
  contentStream.pipe(decodeStream);
122
76
  decoder = decodeStream;
123
- } catch (err) {
124
- logger.debug({ msg: 'Failed to create charset decode stream, keeping original charset', charset: data.node.charset, err });
125
- // do not decode charset
77
+ } else {
78
+ logger.debug({ msg: 'Unsupported charset, keeping the text part as it is', charset: data.node.charset });
79
+ decodable = false;
126
80
  }
127
81
  }
128
82
 
@@ -149,6 +103,12 @@ function rewriteTextNodes(source, options) {
149
103
 
150
104
  decoder.on('end', () => {
151
105
  const htmlBuf = Buffer.concat(chunks, chunklen);
106
+
107
+ if (!decodable) {
108
+ data.encoder.end(htmlBuf);
109
+ return;
110
+ }
111
+
152
112
  let html = htmlBuf.toString('utf-8');
153
113
 
154
114
  // enforce utf-8