emailengine-app 2.84.2 → 2.85.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 (86) hide show
  1. package/.ncurc.js +5 -3
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +33 -0
  6. package/Dockerfile +6 -0
  7. package/README.md +1 -1
  8. package/bin/emailengine.js +434 -408
  9. package/copy-static-files.sh +39 -14
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +16562 -0
  12. package/eslint.config.js +81 -99
  13. package/lib/account.js +36 -5
  14. package/lib/api-reference/format.js +4 -3
  15. package/lib/api-routes/account-routes.js +177 -12
  16. package/lib/api-routes/blocklist-routes.js +23 -2
  17. package/lib/api-routes/delivery-test-routes.js +26 -3
  18. package/lib/api-routes/export-routes.js +28 -2
  19. package/lib/api-routes/gateway-routes.js +28 -2
  20. package/lib/api-routes/mailbox-routes.js +41 -2
  21. package/lib/api-routes/message-routes.js +97 -3
  22. package/lib/api-routes/oauth2-app-routes.js +48 -15
  23. package/lib/api-routes/outbox-routes.js +45 -11
  24. package/lib/api-routes/permission-map.js +12 -1
  25. package/lib/api-routes/settings-routes.js +23 -2
  26. package/lib/api-routes/submit-routes.js +336 -309
  27. package/lib/api-routes/template-routes.js +38 -2
  28. package/lib/api-routes/token-routes.js +142 -96
  29. package/lib/api-routes/webhook-route-routes.js +13 -2
  30. package/lib/bounce-detect.js +397 -205
  31. package/lib/consts.js +5 -4
  32. package/lib/email-client/base-client.js +10 -31
  33. package/lib/email-client/gmail-client.js +9 -11
  34. package/lib/email-client/imap/mailbox.js +3 -19
  35. package/lib/email-client/imap/subconnection.js +1 -1
  36. package/lib/email-client/imap-client.js +1 -1
  37. package/lib/email-client/notification-handler.js +1 -2
  38. package/lib/gateway.js +2 -3
  39. package/lib/hapi-request-logger.js +107 -0
  40. package/lib/imapproxy/imap-core/README.md +6 -5
  41. package/lib/mcp/tools.js +37 -8
  42. package/lib/notify-attachments.js +17 -0
  43. package/lib/oauth/outlook-mailbox.js +35 -0
  44. package/lib/oauth/state.js +24 -0
  45. package/lib/oauth2-apps.js +1 -1
  46. package/lib/pbkdf2-phc.js +1 -1
  47. package/lib/schemas.js +1 -1
  48. package/lib/sso.js +1 -1
  49. package/lib/swagger-options.js +1 -1
  50. package/lib/thread-diagnostics.js +46 -0
  51. package/lib/timezones.js +109 -0
  52. package/lib/token-permission-view.js +3 -3
  53. package/lib/tools.js +40 -10
  54. package/lib/totp.js +2 -5
  55. package/lib/translations.js +1 -2
  56. package/lib/ui-routes/account-routes.js +475 -454
  57. package/lib/ui-routes/account-setup.js +99 -0
  58. package/lib/ui-routes/admin-config-routes.js +88 -10
  59. package/lib/ui-routes/admin-entities-routes.js +91 -7
  60. package/lib/ui-routes/auth-routes.js +90 -38
  61. package/lib/ui-routes/internals-routes.js +5 -0
  62. package/lib/ui-routes/oauth-config-routes.js +124 -82
  63. package/lib/ui-routes/route-helpers.js +19 -3
  64. package/lib/ui-routes/tls-config-routes.js +58 -15
  65. package/lib/utils/back-off.js +82 -0
  66. package/lib/utils/murmurhash3.js +66 -0
  67. package/lib/utils/public-suffix.js +122 -0
  68. package/lib/utils/random-id.js +26 -0
  69. package/lib/utils/version.js +74 -0
  70. package/lib/webhook-routing.js +27 -0
  71. package/lib/webhooks.js +41 -6
  72. package/package.json +27 -29
  73. package/sbom.json +7980 -1
  74. package/server.js +634 -441
  75. package/static/licenses.html +181 -1006
  76. package/translations/messages.pot +62 -63
  77. package/views/config/ai.hbs +1 -1
  78. package/views/config/security.hbs +2 -2
  79. package/views/config/service.hbs +3 -0
  80. package/views/internals/index.hbs +8 -0
  81. package/views/partials/webhook_form.hbs +1 -1
  82. package/views/suppression-lists/index.hbs +1 -1
  83. package/workers/api.js +738 -583
  84. package/workers/export.js +1 -1
  85. package/workers/submit.js +1 -1
  86. package/workers/webhooks.js +16 -32
@@ -110,12 +110,10 @@ async function assertConfiguredHostname(hostname) {
110
110
  return name;
111
111
  }
112
112
 
113
- function init(args) {
114
- const { server, call } = args;
115
-
116
- // The path Let's Encrypt fetches to validate a domain, and the only unauthenticated route on
117
- // this module. It lives here rather than in the routes-ui monolith because it is part of the
118
- // certificate story, and because the preflight probe below shares its token store.
113
+ // The path Let's Encrypt fetches to validate a domain, and the only unauthenticated route on
114
+ // this module. It lives here rather than in the routes-ui monolith because it is part of the
115
+ // certificate story, and because the preflight probe below shares its token store.
116
+ function registerAcmeChallenge(server) {
119
117
  server.route({
120
118
  method: 'GET',
121
119
  path: '/.well-known/acme-challenge/{token}',
@@ -157,6 +155,10 @@ Token: ${JSON.stringify(request.params.token)}`
157
155
  auth: false
158
156
  }
159
157
  });
158
+ }
159
+
160
+ function registerTlsSettingsPage(server, args) {
161
+ const { call } = args;
160
162
 
161
163
  registerSettingsPage(server, {
162
164
  path: TLS_PAGE,
@@ -185,12 +187,16 @@ Token: ${JSON.stringify(request.params.token)}`
185
187
  await maybeReloadTlsCertificates(call, request.logger, changed ? ['tlsProvisioning'] : [], { action: 'settings' });
186
188
  }
187
189
  });
190
+ }
191
+
192
+ // Hostnames are rows of the certificate table, added and removed one at a time. Each write
193
+ // reloads the listeners: they resolve their material against the hostname list, and the
194
+ // self-signed fallback is regenerated when that list no longer matches what it covers. Without
195
+ // the reload a name added here is served the previous certificate until something else restarts
196
+ // the worker, and the page would report a certificate the listener is not using.
197
+ function registerPostConfigTlsHostnames(server, args) {
198
+ const { call } = args;
188
199
 
189
- // Hostnames are rows of the certificate table, added and removed one at a time. Each write
190
- // reloads the listeners: they resolve their material against the hostname list, and the
191
- // self-signed fallback is regenerated when that list no longer matches what it covers. Without
192
- // the reload a name added here is served the previous certificate until something else restarts
193
- // the worker, and the page would report a certificate the listener is not using.
194
200
  server.route({
195
201
  method: 'POST',
196
202
  path: '/admin/config/tls/hostnames',
@@ -235,6 +241,10 @@ Token: ${JSON.stringify(request.params.token)}`
235
241
  }
236
242
  }
237
243
  });
244
+ }
245
+
246
+ function registerPostConfigTlsHostnamesDelete(server, args) {
247
+ const { call } = args;
238
248
 
239
249
  server.route({
240
250
  method: 'POST',
@@ -290,11 +300,15 @@ Token: ${JSON.stringify(request.params.token)}`
290
300
  }
291
301
  }
292
302
  });
303
+ }
304
+
305
+ // Which certificate each listener presents by default. One form for the three listeners,
306
+ // posted with a Save button rather than on change: a wrong default is what a client sees on
307
+ // its next handshake, and three dropdowns that each reload every listener the moment they are
308
+ // touched is three chances to do that by accident.
309
+ function registerPostConfigTlsListeners(server, args) {
310
+ const { call } = args;
293
311
 
294
- // Which certificate each listener presents by default. One form for the three listeners,
295
- // posted with a Save button rather than on change: a wrong default is what a client sees on
296
- // its next handshake, and three dropdowns that each reload every listener the moment they are
297
- // touched is three chances to do that by accident.
298
312
  server.route({
299
313
  method: 'POST',
300
314
  path: '/admin/config/tls/listeners',
@@ -358,7 +372,9 @@ Token: ${JSON.stringify(request.params.token)}`
358
372
  }
359
373
  }
360
374
  });
375
+ }
361
376
 
377
+ function registerGetUploadPage(server) {
362
378
  server.route({
363
379
  method: 'GET',
364
380
  path: UPLOAD_PAGE,
@@ -375,7 +391,9 @@ Token: ${JSON.stringify(request.params.token)}`
375
391
  );
376
392
  }
377
393
  });
394
+ }
378
395
 
396
+ function registerPostConfigTlsRequest(server) {
379
397
  server.route({
380
398
  method: 'POST',
381
399
  path: '/admin/config/tls/request',
@@ -410,7 +428,9 @@ Token: ${JSON.stringify(request.params.token)}`
410
428
  }
411
429
  }
412
430
  });
431
+ }
413
432
 
433
+ function registerPostConfigTlsPreflight(server) {
414
434
  server.route({
415
435
  method: 'POST',
416
436
  path: '/admin/config/tls/preflight',
@@ -434,6 +454,10 @@ Token: ${JSON.stringify(request.params.token)}`
434
454
  }
435
455
  }
436
456
  });
457
+ }
458
+
459
+ function registerPostConfigTlsUpload(server, args) {
460
+ const { call } = args;
437
461
 
438
462
  server.route({
439
463
  method: 'POST',
@@ -488,6 +512,10 @@ Token: ${JSON.stringify(request.params.token)}`
488
512
  }
489
513
  }
490
514
  });
515
+ }
516
+
517
+ function registerPostConfigTlsDelete(server, args) {
518
+ const { call } = args;
491
519
 
492
520
  server.route({
493
521
  method: 'POST',
@@ -549,6 +577,21 @@ Token: ${JSON.stringify(request.params.token)}`
549
577
  });
550
578
  }
551
579
 
580
+ function init(args) {
581
+ const { server } = args;
582
+
583
+ registerAcmeChallenge(server);
584
+ registerTlsSettingsPage(server, args);
585
+ registerPostConfigTlsHostnames(server, args);
586
+ registerPostConfigTlsHostnamesDelete(server, args);
587
+ registerPostConfigTlsListeners(server, args);
588
+ registerGetUploadPage(server);
589
+ registerPostConfigTlsRequest(server);
590
+ registerPostConfigTlsPreflight(server);
591
+ registerPostConfigTlsUpload(server, args);
592
+ registerPostConfigTlsDelete(server, args);
593
+ }
594
+
552
595
  /**
553
596
  * The whole page model: the certificate for every configured name, every certificate the instance
554
597
  * holds, and the listeners with the default each is set to and what each is serving right now.
@@ -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 };
@@ -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,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 };
@@ -4,6 +4,8 @@
4
4
  // and the admin account page's routing card resolve targets and gates through the helpers
5
5
  // here, so the debug view cannot drift from what the worker actually does.
6
6
 
7
+ const { MESSAGE_NEW_NOTIFY } = require('./consts');
8
+
7
9
  // Precedence: custom route target, then the per-account webhooks override, then the global
8
10
  // webhooks setting. Returns the winning URL and which configuration level provided it.
9
11
  function resolveTargetUrl(customRouteTargetUrl, accountWebhooks, globalWebhooks) {
@@ -30,6 +32,30 @@ function eventAllowed(webhookEvents, eventName) {
30
32
  return events.includes('*') || events.includes(eventName);
31
33
  }
32
34
 
35
+ // A messageNew counts as an Inbox message when any of the ways the clients report the folder says so:
36
+ // the IMAP path, the folder's special use, or the message's own special use or Gmail label
37
+ function isInboxPayload(payload) {
38
+ return !!(
39
+ (payload.account && payload.path === 'INBOX') ||
40
+ payload.specialUse === '\\Inbox' ||
41
+ (payload.data && payload.data.messageSpecialUse === '\\Inbox') ||
42
+ (payload.data && payload.data.labels && payload.data.labels.includes('\\Inbox'))
43
+ );
44
+ }
45
+
46
+ // Whether the default route takes an event: the webhookEvents allowlist, then inboxNewOnly for
47
+ // messageNew. The worker asks this at delivery, and lib/webhooks.js asks it before queueing so an
48
+ // event the default route would drop is not written to Redis only for the worker to drop it.
49
+ function defaultRouteTakes(eventName, payload, { webhookEvents, inboxNewOnly }) {
50
+ if (!eventAllowed(webhookEvents, eventName)) {
51
+ return false;
52
+ }
53
+ if (eventName === MESSAGE_NEW_NOTIFY && inboxNewOnly && !isInboxPayload(payload)) {
54
+ return false;
55
+ }
56
+ return true;
57
+ }
58
+
33
59
  // Which custom header lists travel with a delivery, by the configuration level whose target won
34
60
  // (`source`, from resolveTargetUrl), in the order they are merged (later lists override earlier):
35
61
  //
@@ -145,6 +171,7 @@ module.exports = {
145
171
  resolveTargetUrl,
146
172
  isDeliverableRoute,
147
173
  eventAllowed,
174
+ defaultRouteTakes,
148
175
  describeEffectiveRouting,
149
176
  headerLevels,
150
177
  deliveryCustomHeaders,
package/lib/webhooks.js CHANGED
@@ -9,7 +9,11 @@ const { SubScript } = require('./sub-script');
9
9
  const settings = require('./settings');
10
10
  const { filterListPage, truncateTextContents } = require('./tools');
11
11
  const { buildRetentionPolicy } = require('./queue-retention');
12
- const { isDeliverableRoute } = require('./webhook-routing');
12
+ const { isDeliverableRoute, defaultRouteTakes } = require('./webhook-routing');
13
+ const { withinNotifyAttachmentSize } = require('./notify-attachments');
14
+
15
+ // Every setting pushToQueue() decides by, read in one round trip per event
16
+ const QUEUE_SETTINGS = ['webhooksEnabled', 'queueKeep', 'webhookEvents', 'inboxNewOnly'];
13
17
  const { encryptField, decryptField } = require('./encrypt');
14
18
  const getSecret = require('./get-secret');
15
19
 
@@ -643,7 +647,7 @@ class WebhooksHandler {
643
647
 
644
648
  for (let attachment of payload.data.attachments) {
645
649
  if (attachment.content) {
646
- if (notifyAttachments && (!notifyAttachmentSize || notifyAttachmentSize > (attachment.content.length / 4) * 3)) {
650
+ if (notifyAttachments && withinNotifyAttachmentSize(attachment, notifyAttachmentSize)) {
647
651
  // keep the attachment
648
652
  continue;
649
653
  }
@@ -661,10 +665,38 @@ class WebhooksHandler {
661
665
  return payload;
662
666
  }
663
667
 
664
- async pushToQueue(event, originalPayload) {
668
+ /**
669
+ * Formats an event and queues it for delivery. The entry point for every producer of webhook
670
+ * events: with delivery switched off it returns before the payload is cloned and formatted.
671
+ * @param {string} event - Event name
672
+ * @param {Object} payload - Unformatted event payload
673
+ */
674
+ async enqueue(event, payload) {
675
+ let queueSettings = await settings.getMulti(...QUEUE_SETTINGS);
676
+ if (!queueSettings.webhooksEnabled) {
677
+ return;
678
+ }
679
+ await this.pushToQueue(event, await this.formatPayload(event, payload), queueSettings);
680
+ }
681
+
682
+ /**
683
+ * Queues a formatted event for the custom routes that take it and for the default route.
684
+ * @param {string} event - Event name
685
+ * @param {Object} originalPayload - Payload as formatPayload() returned it
686
+ * @param {Object} [queueSettings] - QUEUE_SETTINGS values when the caller has read them already
687
+ */
688
+ async pushToQueue(event, originalPayload, queueSettings) {
689
+ queueSettings = queueSettings || (await settings.getMulti(...QUEUE_SETTINGS));
690
+
691
+ // With delivery switched off the worker drops every job before looking at its target,
692
+ // custom routes included, so nothing is queued and no route script runs
693
+ if (!queueSettings.webhooksEnabled) {
694
+ return;
695
+ }
696
+
665
697
  // custom webhook routes
666
698
  let webhookRoutes = await this.getWebhookHandlers();
667
- let queueKeep = (await settings.get('queueKeep')) ?? true;
699
+ let queueKeep = queueSettings.queueKeep ?? true;
668
700
 
669
701
  let jobOpts = {
670
702
  ...buildRetentionPolicy(queueKeep),
@@ -724,8 +756,11 @@ class WebhooksHandler {
724
756
  }
725
757
  }
726
758
 
727
- // MAIN webhook
728
- await notifyQueue.add(event, originalPayload, jobOpts);
759
+ // MAIN webhook, unless its allowlist or inboxNewOnly already rules the event out. The worker
760
+ // asks the same again at delivery, since either setting can change while a job waits
761
+ if (defaultRouteTakes(event, originalPayload, queueSettings)) {
762
+ await notifyQueue.add(event, originalPayload, jobOpts);
763
+ }
729
764
  }
730
765
  }
731
766