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
@@ -0,0 +1,82 @@
1
+ 'use strict';
2
+
3
+ // Retries an async operation with capped exponential delays. Replaces the exponential-backoff
4
+ // package and keeps its semantics for the options EmailEngine uses:
5
+ //
6
+ // - the delay before attempt n (0-based) is startingDelay * timeMultiple^(n - 1), capped at
7
+ // maxDelay, and the first attempt runs immediately. With delayFirstAttempt the exponent is n
8
+ // instead, so the first attempt waits startingDelay as well.
9
+ // - after each failure retry(err, failures) is awaited; a falsy answer rethrows that error.
10
+ // - numOfAttempts bounds the total number of attempts (Infinity keeps going); the last error is
11
+ // rethrown once it is reached.
12
+ //
13
+ // The wait is node:timers/promises setTimeout, looked up at call time, so a suite can drive the
14
+ // loop with test/helpers/instant-timers.js like the other retry loops.
15
+
16
+ const timers = require('node:timers/promises');
17
+
18
+ // setTimeout() fires after 1 ms for any delay above this, which would turn an uncapped backoff
19
+ // into a busy loop
20
+ const MAX_TIMER_DELAY = 2 ** 31 - 1;
21
+
22
+ const DEFAULTS = {
23
+ delayFirstAttempt: false,
24
+ maxDelay: Infinity,
25
+ numOfAttempts: 10,
26
+ retry: () => true,
27
+ startingDelay: 100,
28
+ timeMultiple: 2
29
+ };
30
+
31
+ function getDelay(options, attempt) {
32
+ const exponent = options.delayFirstAttempt ? attempt : attempt - 1;
33
+ if (exponent < 0) {
34
+ return 0;
35
+ }
36
+ const delay = Math.min(options.startingDelay * Math.pow(options.timeMultiple, exponent), options.maxDelay);
37
+ return Math.min(delay, MAX_TIMER_DELAY);
38
+ }
39
+
40
+ /**
41
+ * @template T
42
+ * @param {() => Promise<T>} request The operation to run
43
+ * @param {Object} [options]
44
+ * @param {boolean} [options.delayFirstAttempt=false] Wait startingDelay before the first attempt too
45
+ * @param {number} [options.startingDelay=100] First delay in ms
46
+ * @param {number} [options.timeMultiple=2] Growth factor between delays
47
+ * @param {number} [options.maxDelay=Infinity] Upper bound for a single delay in ms
48
+ * @param {number} [options.numOfAttempts=10] Maximum number of attempts, at least 1
49
+ * @param {(err: Error, failures: number) => boolean|Promise<boolean>} [options.retry] Whether to try again after a failure
50
+ * @returns {Promise<T>}
51
+ */
52
+ async function backOff(request, options) {
53
+ // an option passed as undefined keeps its default instead of turning the delay into NaN
54
+ const settings = Object.assign({}, DEFAULTS);
55
+ for (const [key, value] of Object.entries(options || {})) {
56
+ if (value !== undefined) {
57
+ settings[key] = value;
58
+ }
59
+ }
60
+ options = settings;
61
+
62
+ const maxAttempts = Math.max(options.numOfAttempts, 1);
63
+
64
+ for (let attempt = 0; ; attempt++) {
65
+ const delay = getDelay(options, attempt);
66
+ if (delay > 0) {
67
+ await timers.setTimeout(delay);
68
+ }
69
+
70
+ try {
71
+ return await request();
72
+ } catch (err) {
73
+ const failures = attempt + 1;
74
+ const shouldRetry = await options.retry(err, failures);
75
+ if (!shouldRetry || failures >= maxAttempts) {
76
+ throw err;
77
+ }
78
+ }
79
+ }
80
+ }
81
+
82
+ module.exports = { backOff, getDelay };
@@ -1,7 +1,6 @@
1
1
  'use strict';
2
2
 
3
3
  const libmime = require('libmime');
4
- const { UNSAFE_KEYS } = require('./unsafe-key');
5
4
 
6
5
  // Largest header block handed to libmime. Its line unfolding used to be quadratic in the line
7
6
  // count, and the bounce and complaint detectors decode blocks taken from attachments any sender
@@ -53,17 +52,9 @@ function capHeaderBlock(content) {
53
52
  * @returns {Object} Map of lowercased header name to array of values
54
53
  */
55
54
  function decodeHeaders(headers) {
56
- let parsed = libmime.decodeHeaders(capHeaderBlock(headers));
57
-
58
- for (let name of UNSAFE_KEYS) {
59
- // Probing first is not needed for correctness, deleting a missing key is a no-op, but it is
60
- // the cheaper no-op and almost every message takes this path
61
- if (Object.hasOwn(parsed, name)) {
62
- delete parsed[name];
63
- }
64
- }
65
-
66
- return parsed;
55
+ // libmime drops the names that exist on Object.prototype itself; as header names are lowercased
56
+ // those are exactly __proto__ and constructor, the UNSAFE_KEYS this module used to delete
57
+ return libmime.decodeHeaders(capHeaderBlock(headers), { skipPrototypeKeys: true });
67
58
  }
68
59
 
69
60
  module.exports = { decodeHeaders, capHeaderBlock, MAX_HEADER_BLOCK_SIZE };
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+
3
+ // Dependency-free, so pure modules can use it without the Redis connection lib/tools.js opens
4
+
5
+ /**
6
+ * A copy of an object with only the keys whose value is set (truthy)
7
+ * @param {Object} obj
8
+ * @returns {Object}
9
+ */
10
+ function filterEmptyObjectValues(obj) {
11
+ let res = {};
12
+ for (let key of Object.keys(obj)) {
13
+ if (obj[key]) {
14
+ res[key] = obj[key];
15
+ }
16
+ }
17
+ return res;
18
+ }
19
+
20
+ module.exports = { filterEmptyObjectValues };
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ // Readers for whole-number settings and environment values. Dependency-free, so pure modules can
4
+ // share them: the overridable settings, the token audit log and the webhook retry policy each had
5
+ // a parser of their own, and they disagreed on blank values, zero and fractions.
6
+
7
+ /**
8
+ * A whole number of at least 1, or undefined for anything else. Fractions are floored.
9
+ * @param {*} value
10
+ * @returns {number|undefined}
11
+ */
12
+ function asPositiveInt(value) {
13
+ const parsed = Math.floor(Number(value));
14
+ return Number.isFinite(parsed) && parsed >= 1 ? parsed : undefined;
15
+ }
16
+
17
+ /**
18
+ * A whole number of at least 0, or undefined for anything else, blank values included (Number('')
19
+ * would read as 0). Fractions are floored.
20
+ * @param {*} value
21
+ * @returns {number|undefined}
22
+ */
23
+ function asNonNegativeInt(value) {
24
+ if (value === '' || value === null || value === undefined) {
25
+ return undefined;
26
+ }
27
+ const parsed = Math.floor(Number(value));
28
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
29
+ }
30
+
31
+ /**
32
+ * A whole number clamped into [min, max], or the default for anything that is not one: a setting
33
+ * that is unset, cleared, or written by an older version without validation
34
+ * @param {*} value
35
+ * @param {number} defaultValue
36
+ * @param {number} min
37
+ * @param {number} max
38
+ * @returns {number}
39
+ */
40
+ function boundedInt(value, defaultValue, min, max) {
41
+ const number = Number(value);
42
+ if (value === null || value === undefined || value === '' || !Number.isInteger(number)) {
43
+ return defaultValue;
44
+ }
45
+ return Math.min(Math.max(number, min), max);
46
+ }
47
+
48
+ module.exports = { asPositiveInt, asNonNegativeInt, boundedInt };
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ // MurmurHash3, the x86 32-bit variant, over the UTF-8 bytes of a string.
4
+ //
5
+ // The output is load-bearing: tools.getRendezvousScore() ranks IMAP workers and local addresses
6
+ // with it, so the hash decides which worker owns an account and which source address it connects
7
+ // from. A different hash would move every account to another worker and another source IP on
8
+ // upgrade. The result must stay bit-identical to the `murmurhash` package's v3() this replaced,
9
+ // which test/murmurhash3-test.js pins with vectors recorded from that package.
10
+
11
+ const C1 = 0xcc9e2d51;
12
+ const C2 = 0x1b873593;
13
+
14
+ function rotl32(x, r) {
15
+ return (x << r) | (x >>> (32 - r));
16
+ }
17
+
18
+ function mixK1(k1) {
19
+ k1 = Math.imul(k1, C1);
20
+ k1 = rotl32(k1, 15);
21
+ return Math.imul(k1, C2);
22
+ }
23
+
24
+ /**
25
+ * @param {string|Uint8Array} key Input, strings are hashed as UTF-8
26
+ * @param {number} [seed=0] 32-bit seed
27
+ * @returns {number} Unsigned 32-bit hash
28
+ */
29
+ function murmurhash3(key, seed) {
30
+ const bytes = typeof key === 'string' ? Buffer.from(key, 'utf-8') : key;
31
+ const length = bytes.length;
32
+ const tail = length & ~3;
33
+
34
+ let h1 = seed >>> 0;
35
+
36
+ for (let i = 0; i < tail; i += 4) {
37
+ const k1 = bytes[i] | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24);
38
+ h1 ^= mixK1(k1);
39
+ h1 = rotl32(h1, 13);
40
+ h1 = (Math.imul(h1, 5) + 0xe6546b64) | 0;
41
+ }
42
+
43
+ let k1 = 0;
44
+ switch (length & 3) {
45
+ case 3:
46
+ k1 ^= bytes[tail + 2] << 16;
47
+ // falls through
48
+ case 2:
49
+ k1 ^= bytes[tail + 1] << 8;
50
+ // falls through
51
+ case 1:
52
+ k1 ^= bytes[tail];
53
+ h1 ^= mixK1(k1);
54
+ }
55
+
56
+ h1 ^= length;
57
+ h1 ^= h1 >>> 16;
58
+ h1 = Math.imul(h1, 0x85ebca6b);
59
+ h1 ^= h1 >>> 13;
60
+ h1 = Math.imul(h1, 0xc2b2ae35);
61
+ h1 ^= h1 >>> 16;
62
+
63
+ return h1 >>> 0;
64
+ }
65
+
66
+ module.exports = { murmurhash3 };
@@ -0,0 +1,122 @@
1
+ 'use strict';
2
+
3
+ // Registrable-domain lookup against the Public Suffix List (https://publicsuffix.org/list/), in
4
+ // place of the psl package, whose bundled copy of the list had not been refreshed since its last
5
+ // release. The list itself lives in data/public_suffix_list.dat and is refreshed by
6
+ // copy-static-files.sh on every `npm run update`.
7
+ //
8
+ // The matching follows the list's own algorithm (https://github.com/publicsuffix/list/wiki/Format):
9
+ // an exception rule wins outright, otherwise the matching rule with the most labels does, and a
10
+ // name no rule covers falls back to the implicit "*" rule (its last label is the suffix). Both the
11
+ // ICANN and the private section are used, as psl did.
12
+
13
+ const fs = require('fs');
14
+ const pathlib = require('path');
15
+ const net = require('net');
16
+ const { domainToASCII } = require('url');
17
+
18
+ const LIST_PATH = pathlib.join(__dirname, '..', '..', 'data', 'public_suffix_list.dat');
19
+
20
+ /**
21
+ * @param {string} text The list in its published format
22
+ * @returns {{ exact: Set<string>, wildcard: Set<string>, exception: Set<string> }} Rules in ASCII
23
+ * (punycode) form; `wildcard` holds the parent of each "*." rule, which `exact` holds as well
24
+ */
25
+ function parseList(text) {
26
+ const rules = { exact: new Set(), wildcard: new Set(), exception: new Set() };
27
+
28
+ for (let line of text.split('\n')) {
29
+ // a rule is the first whitespace-delimited token of a line that is not a comment
30
+ line = line.trim().split(/\s/)[0];
31
+ if (!line || line.startsWith('//')) {
32
+ continue;
33
+ }
34
+
35
+ let set = rules.exact;
36
+ if (line.startsWith('!')) {
37
+ set = rules.exception;
38
+ line = line.slice(1);
39
+ } else if (line.startsWith('*.')) {
40
+ set = rules.wildcard;
41
+ line = line.slice(2);
42
+ }
43
+
44
+ const rule = domainToASCII(line) || line.toLowerCase();
45
+ set.add(rule);
46
+
47
+ // The parent of a wildcard rule counts as a public suffix of its own, as it does in psl and
48
+ // libpsl: "*.kawasaki.jp" makes "kawasaki.jp" no more registrable than "foo.kawasaki.jp"
49
+ if (set === rules.wildcard) {
50
+ rules.exact.add(rule);
51
+ }
52
+ }
53
+
54
+ return rules;
55
+ }
56
+
57
+ let defaultRules = null;
58
+
59
+ /**
60
+ * Returns the registrable domain of a host name: the public suffix plus one label, e.g.
61
+ * "example.co.uk" for "imap.mail.example.co.uk".
62
+ *
63
+ * @param {string} host
64
+ * @param {Object} [rules] Parsed rules, the bundled list when omitted
65
+ * @returns {string|null} The registrable domain in the spelling of the input (lower-cased), or null
66
+ * for an IP address, an invalid name, or a name that is itself a public suffix
67
+ */
68
+ function getRegistrableDomain(host, rules) {
69
+ if (typeof host !== 'string') {
70
+ return null;
71
+ }
72
+
73
+ host = host.trim().toLowerCase().replace(/\.$/, '');
74
+ if (!host || net.isIP(host.replace(/^\[|\]$/g, ''))) {
75
+ return null;
76
+ }
77
+
78
+ const ascii = domainToASCII(host);
79
+ if (!ascii) {
80
+ return null;
81
+ }
82
+
83
+ const labels = ascii.split('.');
84
+ if (labels.some(label => !label)) {
85
+ return null;
86
+ }
87
+
88
+ if (!rules) {
89
+ defaultRules = defaultRules || parseList(fs.readFileSync(LIST_PATH, 'utf-8'));
90
+ rules = defaultRules;
91
+ }
92
+
93
+ // number of labels in the public suffix
94
+ let suffixLength = 0;
95
+
96
+ for (let i = 0; i < labels.length && !suffixLength; i++) {
97
+ // an exception marks its own name as registrable: the suffix is one label shorter
98
+ if (rules.exception.has(labels.slice(i).join('.'))) {
99
+ suffixLength = labels.length - i - 1;
100
+ }
101
+ }
102
+
103
+ for (let i = 0; i < labels.length && !suffixLength; i++) {
104
+ if (rules.exact.has(labels.slice(i).join('.')) || (i + 1 < labels.length && rules.wildcard.has(labels.slice(i + 1).join('.')))) {
105
+ suffixLength = labels.length - i;
106
+ }
107
+ }
108
+
109
+ suffixLength = suffixLength || 1;
110
+
111
+ if (labels.length <= suffixLength) {
112
+ return null;
113
+ }
114
+
115
+ // Answer in the caller's spelling (an IDN stays in Unicode) when the label counts line up, which
116
+ // they do unless the input used an ideographic full stop that domainToASCII folded into a dot
117
+ const original = host.split('.');
118
+ const source = original.length === labels.length ? original : labels;
119
+ return source.slice(-(suffixLength + 1)).join('.');
120
+ }
121
+
122
+ module.exports = { getRegistrableDomain, parseList, LIST_PATH };
@@ -0,0 +1,26 @@
1
+ 'use strict';
2
+
3
+ const { randomInt } = require('crypto');
4
+
5
+ // The alphabet and length of generated account and gateway ids. Kept identical to the nanoid
6
+ // customAlphabet() call this replaced, so new ids look like the ones already stored.
7
+ const ID_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
8
+ const ID_LENGTH = 16;
9
+
10
+ /**
11
+ * Generates a random string from a CSPRNG. Every character is drawn uniformly from the alphabet
12
+ * (crypto.randomInt rejects out-of-range values instead of taking a biased modulo).
13
+ *
14
+ * @param {string} [alphabet] Characters to draw from
15
+ * @param {number} [size] Length of the result
16
+ * @returns {string}
17
+ */
18
+ function randomId(alphabet = ID_ALPHABET, size = ID_LENGTH) {
19
+ let id = '';
20
+ for (let i = 0; i < size; i++) {
21
+ id += alphabet[randomInt(alphabet.length)];
22
+ }
23
+ return id;
24
+ }
25
+
26
+ module.exports = { randomId, ID_ALPHABET, ID_LENGTH };
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ // Which kinds of tracking a sent message gets. The message's own flags win, the instance
4
+ // settings fill in what it leaves open, and open and click tracking follow trackSentMessages
5
+ // unless set on their own.
6
+
7
+ const TRACKING_SETTINGS = ['trackSentMessages', 'trackClicks', 'trackOpens'];
8
+
9
+ const isBoolean = value => typeof value === 'boolean';
10
+
11
+ /**
12
+ * Whether the message leaves anything to the instance settings, so the caller can skip the read
13
+ * @param {Object} message - trackingEnabled, trackClicks, trackOpens as the message set them
14
+ * @returns {boolean}
15
+ */
16
+ function needsTrackingSettings(message) {
17
+ return !isBoolean(message.trackingEnabled) || !isBoolean(message.trackClicks) || !isBoolean(message.trackOpens);
18
+ }
19
+
20
+ /**
21
+ * @param {Object} message - trackingEnabled, trackClicks, trackOpens as the message set them
22
+ * @param {Object} [stored] - The TRACKING_SETTINGS values; needed only when needsTrackingSettings()
23
+ * @returns {{trackingEnabled: *, trackClicks: boolean, trackOpens: boolean}}
24
+ */
25
+ function resolveTracking(message, stored = {}) {
26
+ const trackingEnabled = isBoolean(message.trackingEnabled) ? message.trackingEnabled : stored.trackSentMessages || false;
27
+ const pick = (own, setting) => [own, setting].find(isBoolean) ?? trackingEnabled;
28
+ return {
29
+ trackingEnabled,
30
+ trackClicks: pick(message.trackClicks, stored.trackClicks),
31
+ trackOpens: pick(message.trackOpens, stored.trackOpens)
32
+ };
33
+ }
34
+
35
+ module.exports = { TRACKING_SETTINGS, needsTrackingSettings, resolveTracking };
@@ -0,0 +1,74 @@
1
+ 'use strict';
2
+
3
+ // Semantic version parsing and precedence (semver 2.0.0, section 11) for the two places EmailEngine
4
+ // compares versions: the update check against the latest GitHub release tag, and the license
5
+ // check's record of which version last validated. Both only ever see MAJOR.MINOR.PATCH with an
6
+ // optional pre-release, so ranges, wildcards and partial versions are deliberately not accepted.
7
+
8
+ const VERSION_RE = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
9
+
10
+ /**
11
+ * @param {string} version A version such as `2.84.2`, `v2.84.2` or `3.0.0-beta.1`
12
+ * @returns {{ core: number[], prerelease: string[] } | null} The parsed version, or null if it is not one
13
+ */
14
+ function parseVersion(version) {
15
+ const match = typeof version === 'string' ? version.match(VERSION_RE) : null;
16
+ if (!match) {
17
+ return null;
18
+ }
19
+ return {
20
+ core: [Number(match[1]), Number(match[2]), Number(match[3])],
21
+ prerelease: match[4] ? match[4].split('.') : []
22
+ };
23
+ }
24
+
25
+ function compareIdentifiers(a, b) {
26
+ const aNumeric = /^\d+$/.test(a);
27
+ const bNumeric = /^\d+$/.test(b);
28
+ if (aNumeric && bNumeric) {
29
+ return Math.sign(Number(a) - Number(b));
30
+ }
31
+ if (aNumeric !== bNumeric) {
32
+ // numeric identifiers have lower precedence than alphanumeric ones
33
+ return aNumeric ? -1 : 1;
34
+ }
35
+ return a < b ? -1 : a > b ? 1 : 0;
36
+ }
37
+
38
+ /**
39
+ * Compares two versions by semver precedence. Build metadata is ignored.
40
+ *
41
+ * @param {string} a
42
+ * @param {string} b
43
+ * @returns {number} -1 when a is lower than b, 0 when equal, 1 when higher
44
+ * @throws {TypeError} when either argument is not a version
45
+ */
46
+ function compareVersions(a, b) {
47
+ const va = parseVersion(a);
48
+ const vb = parseVersion(b);
49
+ if (!va || !vb) {
50
+ throw new TypeError(`Invalid version: ${JSON.stringify(va ? b : a)}`);
51
+ }
52
+
53
+ for (let i = 0; i < 3; i++) {
54
+ if (va.core[i] !== vb.core[i]) {
55
+ return va.core[i] < vb.core[i] ? -1 : 1;
56
+ }
57
+ }
58
+
59
+ // a version without a pre-release ranks above any pre-release of the same core version
60
+ if (!va.prerelease.length || !vb.prerelease.length) {
61
+ return Math.sign(vb.prerelease.length - va.prerelease.length);
62
+ }
63
+
64
+ const length = Math.min(va.prerelease.length, vb.prerelease.length);
65
+ for (let i = 0; i < length; i++) {
66
+ const result = compareIdentifiers(va.prerelease[i], vb.prerelease[i]);
67
+ if (result) {
68
+ return result;
69
+ }
70
+ }
71
+ return Math.sign(va.prerelease.length - vb.prerelease.length);
72
+ }
73
+
74
+ module.exports = { parseVersion, compareVersions };
@@ -1,11 +1,12 @@
1
1
  'use strict';
2
2
 
3
- const { analyze } = require('@postalsys/email-content');
3
+ const { analyze, canonicalisePlainText } = require('@postalsys/email-content');
4
4
  // Resolved at call time rather than destructured here: the package exposes mimeHtml through a
5
5
  // lazy getter, and touching it loads jsdom (tens of MB of heap) into every process that merely
6
6
  // requires this module, the main process included.
7
7
  const textTools = require('@postalsys/email-text-tools');
8
- const { getBoolean, readEnvValue, attributeValueRegex } = require('./tools');
8
+ const { attributeValueRegex } = require('./tools');
9
+ const { getOverridableSettings } = require('./env-setting-overrides');
9
10
  const { COLLAPSE_CLASS, COLLAPSE_TOGGLE_CLASS } = require('./consts');
10
11
  const logger = require('./logger');
11
12
  const he = require('he');
@@ -53,54 +54,16 @@ const MIN_COLLAPSE_CHARS = 120;
53
54
  const MAX_ANALYZE_CHARS = 256 * 1024;
54
55
 
55
56
  // Opt-out for operators who need the previous output shape, or who do not want to pay for
56
- // extraction on every notified message.
57
- const DISABLE_THREAD_COLLAPSE = getBoolean(readEnvValue('EENGINE_DISABLE_THREAD_COLLAPSE'));
57
+ // extraction on every notified message: the disableThreadCollapse setting, or
58
+ // EENGINE_DISABLE_THREAD_COLLAPSE, which wins when set (lib/env-setting-overrides.js). Read per
59
+ // message through that module's short cache, so a change applies without a restart.
58
60
 
59
- /**
60
- * Base styles for messages that only have a plain text body.
61
- *
62
- * mimeHtml() applies its own copy of these whenever it converts text to HTML itself. Once a
63
- * collapse marker is involved the conversion happens here instead, so the styling has to travel
64
- * with it, otherwise a plain text reply would lose its quote colouring the moment it became
65
- * collapsible. juice inlines the block and the sanitizer then drops the tag.
66
- *
67
- * Kept byte for byte identical to INLINE_STYLE_BLOCK in @postalsys/email-text-tools, so the two
68
- * can be diffed when that package restyles quoted text.
69
- */
70
- const PLAINTEXT_STYLE_BLOCK = `<style>
71
-
72
- body, td, th, p {
73
- font-family: sans-serif;
74
- font-size: 12px;
75
- }
76
-
77
- blockquote {
78
- border-left-width: 2px;
79
- border-left-style: solid;
80
-
81
- border-left-color: darkblue;
82
- color: darkblue;
83
-
84
- margin: 1rem 0;
85
- padding-left: 1rem;
86
- }
87
-
88
- blockquote blockquote{
89
- border-left-color: royalblue;
90
- color: royalblue;
91
- }
92
-
93
- blockquote blockquote blockquote{
94
- border-left-color: dodgerblue;
95
- color: dodgerblue;
96
- }
97
-
98
- blockquote blockquote blockquote blockquote{
99
- border-left-color: darkblue;
100
- color: darkblue;
101
- }
102
-
103
- </style>`;
61
+ // Base styles for messages that only have a plain text body. mimeHtml() applies the same block
62
+ // whenever it converts text to HTML itself; once a collapse marker is involved the conversion happens
63
+ // here instead, so the styling has to travel with it, or a plain text reply would lose its quote
64
+ // colouring the moment it became collapsible. juice inlines the block and the sanitizer drops the tag.
65
+ // Taken from the package rather than kept as a copy, which had already drifted from it.
66
+ const PLAINTEXT_STYLE_BLOCK = textTools.INLINE_STYLE_BLOCK;
104
67
 
105
68
  // Table internals can not host a wrapper element. A <details> opened between table cells is
106
69
  // foster-parented out of the table by the HTML parser, which would leave the content behind and
@@ -136,36 +99,6 @@ function formatSender(from) {
136
99
  return address || name || null;
137
100
  }
138
101
 
139
- /**
140
- * Normalizes text the same way the extractor does, so the offsets it reports index this string.
141
- *
142
- * Mirrors canonicaliseText() in @postalsys/email-content: BOM removal, LF line endings, NUL
143
- * removal and NFC normalization. Anything else would shift the offsets.
144
- *
145
- * There is no HTML counterpart on purpose. HTML offsets come from source ranges over the string
146
- * exactly as it was handed to the extractor, so HTML must not be normalized before slicing it.
147
- *
148
- * @param {string} text - Decoded plain text body
149
- * @returns {string} Canonical text
150
- */
151
- function canonicaliseText(text) {
152
- let canonical = text;
153
-
154
- if (canonical.charCodeAt(0) === 0xfeff) {
155
- canonical = canonical.slice(1);
156
- }
157
-
158
- canonical = canonical.replace(/\r\n?/g, '\n').replace(/\0/g, '');
159
-
160
- try {
161
- canonical = canonical.normalize('NFC');
162
- } catch (_err) {
163
- // Extremely long or malformed input can defeat NFC. Unnormalized text still slices.
164
- }
165
-
166
- return canonical;
167
- }
168
-
169
102
  /**
170
103
  * Finds the offset where the quoted tail of a message starts.
171
104
  *
@@ -375,7 +308,7 @@ async function collapseThreadHistory(messageData) {
375
308
  // Text offsets index the extractor's canonical form, so the same normalization has to be
376
309
  // applied before slicing. It is done here rather than up front because the HTML path,
377
310
  // which is the common one, has no use for it.
378
- collapsed = collapseText(canonicaliseText(text), cut.offset);
311
+ collapsed = collapseText(canonicalisePlainText(text), cut.offset);
379
312
  }
380
313
 
381
314
  return collapsed ? { html: collapsed } : null;
@@ -415,24 +348,6 @@ function stripReservedClasses(html) {
415
348
  });
416
349
  }
417
350
 
418
- /**
419
- * Last-resort rendering when the sanitizer itself fails.
420
- *
421
- * mimeHtml() throws RangeError on hostile nesting (a few thousand nested elements or quote
422
- * levels). The message is still delivered and still has to be readable, so it is shown as escaped
423
- * text rather than dropped. Never the unconverted HTML: that has not been sanitized.
424
- *
425
- * @param {Object} source - `{ html, text }` as handed to mimeHtml()
426
- * @returns {string} Escaped text in a wrapper
427
- */
428
- function escapedTextFallback(source) {
429
- let text = source.text || '';
430
- if (!text && source.html) {
431
- text = he.decode(source.html.toString().replace(/<[^>]*>/g, ' '));
432
- }
433
- return `<div style="overflow: auto; white-space: pre-wrap;">${he.escape(text.toString())}</div>`;
434
- }
435
-
436
351
  /**
437
352
  * Converts the bodies of a message object into sanitized, web-safe HTML.
438
353
  *
@@ -447,7 +362,8 @@ async function messageWebSafeHtml(messageData) {
447
362
 
448
363
  let source = { html, text: messageData.text.plain };
449
364
 
450
- if (!DISABLE_THREAD_COLLAPSE) {
365
+ const { disableThreadCollapse } = await getOverridableSettings('disableThreadCollapse');
366
+ if (!disableThreadCollapse) {
451
367
  try {
452
368
  let collapsed = await collapseThreadHistory(messageData);
453
369
  if (collapsed) {
@@ -459,12 +375,9 @@ async function messageWebSafeHtml(messageData) {
459
375
  }
460
376
  }
461
377
 
462
- try {
463
- return textTools.mimeHtml(source);
464
- } catch (err) {
465
- logger.warn({ msg: 'Failed to convert message to web-safe HTML, rendering it as text', err });
466
- return escapedTextFallback({ html: messageData.text.html, text: messageData.text.plain });
467
- }
378
+ // mimeHtml() does not throw: on hostile input (thousands of nested elements or quote levels)
379
+ // it falls back to escaped text itself, which is what the catch that used to be here did
380
+ return textTools.mimeHtml(source);
468
381
  }
469
382
 
470
383
  /**