emailengine-app 2.85.0 → 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 (128) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +74 -0
  4. package/Dockerfile +14 -1
  5. package/ENVIRONMENT.md +139 -0
  6. package/README.md +1 -1
  7. package/config/default.toml +2 -0
  8. package/copy-static-files.sh +4 -2
  9. package/data/google-crawlers.json +1 -1
  10. package/data/public_suffix_list.dat +4 -3
  11. package/lib/account-assignment.js +19 -0
  12. package/lib/account.js +194 -165
  13. package/lib/api-error-codes.js +49 -0
  14. package/lib/api-reference/model.js +6 -1
  15. package/lib/api-routes/account-routes.js +78 -26
  16. package/lib/api-routes/blocklist-routes.js +68 -2
  17. package/lib/api-routes/delivery-test-routes.js +1 -1
  18. package/lib/api-routes/gateway-routes.js +82 -10
  19. package/lib/api-routes/index.js +4 -0
  20. package/lib/api-routes/license-routes.js +2 -2
  21. package/lib/api-routes/mailbox-routes.js +3 -3
  22. package/lib/api-routes/message-routes.js +15 -7
  23. package/lib/api-routes/oauth2-app-routes.js +15 -8
  24. package/lib/api-routes/outbox-routes.js +77 -66
  25. package/lib/api-routes/permission-map.js +55 -6
  26. package/lib/api-routes/scoped-routes.js +74 -0
  27. package/lib/api-routes/settings-routes.js +11 -4
  28. package/lib/api-routes/stats-routes.js +5 -1
  29. package/lib/api-routes/submit-routes.js +4 -3
  30. package/lib/api-routes/template-routes.js +7 -6
  31. package/lib/api-routes/token-routes.js +11 -5
  32. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  33. package/lib/api-routes/webhook-route-routes.js +119 -4
  34. package/lib/calendar-event.js +81 -1
  35. package/lib/consts.js +38 -46
  36. package/lib/db.js +14 -6
  37. package/lib/delivery-error.js +6 -0
  38. package/lib/deprecations.js +270 -0
  39. package/lib/email-client/base-client.js +130 -156
  40. package/lib/email-client/fallback-poll.js +62 -0
  41. package/lib/email-client/gmail-client.js +51 -11
  42. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  43. package/lib/email-client/imap/adaptive-idle.js +278 -0
  44. package/lib/email-client/imap/connection-errors.js +14 -1
  45. package/lib/email-client/imap/idle-settings.js +31 -5
  46. package/lib/email-client/imap/listing-diff.js +37 -0
  47. package/lib/email-client/imap/mailbox.js +372 -226
  48. package/lib/email-client/imap/subconnection.js +7 -29
  49. package/lib/email-client/imap/sync-operations.js +220 -127
  50. package/lib/email-client/imap-client.js +227 -163
  51. package/lib/email-client/message-builder.js +14 -79
  52. package/lib/email-client/outlook-client.js +372 -338
  53. package/lib/email-client/smtp-pool-manager.js +16 -13
  54. package/lib/email-client/sync-state-fields.js +19 -0
  55. package/lib/encrypt.js +157 -41
  56. package/lib/enum-descriptions.js +3 -1
  57. package/lib/env-setting-overrides.js +288 -0
  58. package/lib/export-worker.js +751 -0
  59. package/lib/export.js +64 -15
  60. package/lib/gateway.js +17 -1
  61. package/lib/get-raw-email.js +25 -107
  62. package/lib/health.js +75 -0
  63. package/lib/lock-run.js +119 -0
  64. package/lib/logger-consts.js +48 -0
  65. package/lib/logger.js +1 -1
  66. package/lib/lua/z-head-scores.lua +28 -0
  67. package/lib/network-errors.js +1 -1
  68. package/lib/node-version.js +24 -0
  69. package/lib/notify-attachments.js +20 -1
  70. package/lib/oauth2-apps.js +630 -655
  71. package/lib/outbox.js +184 -54
  72. package/lib/parse-message.js +3 -3
  73. package/lib/privileged-settings.js +2 -2
  74. package/lib/queue-browser/definitions.js +11 -0
  75. package/lib/queue-browser/index.js +68 -19
  76. package/lib/queue-job-actions.js +18 -1
  77. package/lib/queue-retention.js +48 -12
  78. package/lib/queue-stats.js +11 -2
  79. package/lib/read-env-value.js +3 -0
  80. package/lib/redis-memory-warnings.js +99 -0
  81. package/lib/redis-reconnect.js +29 -0
  82. package/lib/request-timing.js +23 -0
  83. package/lib/respawn-backoff.js +35 -0
  84. package/lib/rewrite-text-nodes.js +19 -59
  85. package/lib/schemas.js +163 -39
  86. package/lib/settings.js +6 -2
  87. package/lib/smtp-auth.js +19 -1
  88. package/lib/thread-diagnostics.js +18 -1
  89. package/lib/tls/provision.js +6 -3
  90. package/lib/token-audit-log.js +19 -20
  91. package/lib/token-permission-view.js +4 -3
  92. package/lib/tools.js +8 -41
  93. package/lib/ui-routes/admin-config-routes.js +64 -90
  94. package/lib/ui-routes/admin-entities-routes.js +2 -14
  95. package/lib/ui-routes/imap-idle-field.js +1 -1
  96. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  97. package/lib/ui-routes/overridable-fields.js +84 -0
  98. package/lib/ui-routes/queue-routes.js +8 -5
  99. package/lib/ui-routes/settings-page.js +6 -0
  100. package/lib/utils/decode-headers.js +3 -12
  101. package/lib/utils/filter-empty.js +20 -0
  102. package/lib/utils/int-setting.js +48 -0
  103. package/lib/utils/tracking-settings.js +35 -0
  104. package/lib/web-safe-html.js +18 -105
  105. package/lib/webhook-delivery.js +461 -0
  106. package/lib/webhook-failures.js +132 -0
  107. package/lib/webhook-request.js +29 -1
  108. package/lib/webhook-routing.js +30 -1
  109. package/lib/webhook-test.js +88 -0
  110. package/lib/webhooks.js +54 -41
  111. package/lib/worker-rpc-error.js +2 -1
  112. package/package.json +21 -20
  113. package/sbom.json +304 -382
  114. package/server.js +149 -76
  115. package/static/js/ace/ace.js +1 -1
  116. package/static/licenses.html +21 -31
  117. package/translations/messages.pot +26 -26
  118. package/views/config/security.hbs +22 -0
  119. package/views/config/service.hbs +44 -0
  120. package/views/config/webhooks.hbs +36 -0
  121. package/views/partials/queue_retention_note.hbs +12 -8
  122. package/views/partials/ui/env-managed-alert.hbs +16 -7
  123. package/workers/api.js +102 -28
  124. package/workers/export.js +16 -631
  125. package/workers/imap.js +13 -0
  126. package/workers/smtp.js +9 -11
  127. package/workers/webhooks.js +18 -432
  128. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -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