emailengine-app 2.84.1 → 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 (147) hide show
  1. package/.dockerignore +6 -0
  2. package/.ncurc.js +5 -3
  3. package/.prettierignore +5 -1
  4. package/.prettierrc.js +2 -0
  5. package/.release-please-manifest.json +1 -1
  6. package/CHANGELOG.md +61 -0
  7. package/Dockerfile +8 -2
  8. package/README.md +1 -1
  9. package/bin/emailengine.js +444 -403
  10. package/copy-static-files.sh +39 -14
  11. package/data/google-crawlers.json +1 -1
  12. package/data/public_suffix_list.dat +16562 -0
  13. package/docker-compose.yml +1 -1
  14. package/eslint.config.js +81 -99
  15. package/lib/account/own-account-key.js +42 -0
  16. package/lib/account-assignment.js +1 -33
  17. package/lib/account.js +68 -24
  18. package/lib/add-trackers.js +11 -4
  19. package/lib/api-reference/format.js +4 -3
  20. package/lib/api-routes/account-routes.js +244 -26
  21. package/lib/api-routes/blocklist-routes.js +23 -2
  22. package/lib/api-routes/delivery-test-routes.js +26 -3
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +37 -5
  25. package/lib/api-routes/mailbox-routes.js +41 -2
  26. package/lib/api-routes/message-routes.js +104 -4
  27. package/lib/api-routes/mint-bounds.js +11 -0
  28. package/lib/api-routes/oauth2-app-routes.js +48 -15
  29. package/lib/api-routes/outbox-routes.js +45 -11
  30. package/lib/api-routes/permission-map.js +12 -1
  31. package/lib/api-routes/route-helpers.js +125 -3
  32. package/lib/api-routes/settings-routes.js +23 -2
  33. package/lib/api-routes/submit-routes.js +338 -309
  34. package/lib/api-routes/template-routes.js +38 -2
  35. package/lib/api-routes/token-routes.js +142 -96
  36. package/lib/api-routes/webhook-route-routes.js +13 -2
  37. package/lib/auth-token.js +23 -10
  38. package/lib/bounce-detect.js +414 -210
  39. package/lib/consts.js +39 -4
  40. package/lib/create-imap-client.js +41 -2
  41. package/lib/email-client/base-client.js +30 -41
  42. package/lib/email-client/gmail-client.js +30 -18
  43. package/lib/email-client/imap/mailbox.js +13 -23
  44. package/lib/email-client/imap/response-metrics.js +75 -0
  45. package/lib/email-client/imap/subconnection.js +1 -1
  46. package/lib/email-client/imap-client.js +6 -3
  47. package/lib/email-client/message-builder.js +7 -2
  48. package/lib/email-client/notification-handler.js +1 -2
  49. package/lib/email-client/outlook/graph-api.js +17 -2
  50. package/lib/email-client/outlook-client.js +6 -3
  51. package/lib/email-client/smtp-pool-manager.js +6 -0
  52. package/lib/encrypt.js +9 -0
  53. package/lib/export.js +3 -1
  54. package/lib/gateway.js +2 -3
  55. package/lib/get-raw-email.js +4 -2
  56. package/lib/hapi-request-logger.js +107 -0
  57. package/lib/imap-proxy-auth.js +14 -1
  58. package/lib/imapproxy/imap-core/README.md +6 -5
  59. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  60. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  61. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  62. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  63. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  64. package/lib/mcp/listen.js +10 -1
  65. package/lib/mcp/tools.js +37 -8
  66. package/lib/notify-attachments.js +17 -0
  67. package/lib/oauth/external-account-config.js +3 -1
  68. package/lib/oauth/gmail.js +21 -48
  69. package/lib/oauth/mail-ru.js +5 -38
  70. package/lib/oauth/outlook-mailbox.js +35 -0
  71. package/lib/oauth/outlook.js +26 -44
  72. package/lib/oauth/state.js +24 -0
  73. package/lib/oauth2-apps.js +1 -1
  74. package/lib/pbkdf2-phc.js +19 -2
  75. package/lib/privileged-settings.js +6 -3
  76. package/lib/redis-scan-delete.js +15 -1
  77. package/lib/schemas.js +79 -33
  78. package/lib/settings.js +13 -1
  79. package/lib/smtp-auth.js +23 -0
  80. package/lib/sso.js +1 -1
  81. package/lib/swagger-options.js +1 -1
  82. package/lib/thread-diagnostics.js +46 -0
  83. package/lib/timezones.js +109 -0
  84. package/lib/token-permission-view.js +3 -3
  85. package/lib/tools.js +285 -66
  86. package/lib/totp.js +2 -5
  87. package/lib/translations.js +1 -2
  88. package/lib/ui-routes/account-routes.js +491 -491
  89. package/lib/ui-routes/account-setup.js +99 -0
  90. package/lib/ui-routes/admin-config-routes.js +98 -48
  91. package/lib/ui-routes/admin-entities-routes.js +113 -31
  92. package/lib/ui-routes/auth-routes.js +137 -62
  93. package/lib/ui-routes/connection-security-form.js +74 -0
  94. package/lib/ui-routes/form-lists.js +46 -0
  95. package/lib/ui-routes/internals-routes.js +5 -0
  96. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  97. package/lib/ui-routes/oauth-config-routes.js +133 -100
  98. package/lib/ui-routes/route-helpers.js +19 -3
  99. package/lib/ui-routes/sign-in-helpers.js +59 -0
  100. package/lib/ui-routes/tls-config-routes.js +58 -15
  101. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  102. package/lib/utils/back-off.js +82 -0
  103. package/lib/utils/map-concurrent.js +36 -0
  104. package/lib/utils/murmurhash3.js +66 -0
  105. package/lib/utils/network.js +28 -0
  106. package/lib/utils/provider-id.js +27 -0
  107. package/lib/utils/public-suffix.js +122 -0
  108. package/lib/utils/random-id.js +26 -0
  109. package/lib/utils/require-tls.js +33 -0
  110. package/lib/utils/version.js +74 -0
  111. package/lib/web-safe-html.js +5 -6
  112. package/lib/webhook-penalty.js +75 -0
  113. package/lib/webhook-routing.js +49 -2
  114. package/lib/webhooks.js +41 -6
  115. package/package.json +37 -39
  116. package/sbom.json +7980 -1
  117. package/server.js +659 -455
  118. package/static/js/ace/ace.js +1 -1
  119. package/static/js/ace/mode-handlebars.js +1 -1
  120. package/static/js/ace/mode-html.js +1 -1
  121. package/static/js/ace/mode-javascript.js +1 -1
  122. package/static/js/ace/mode-markdown.js +1 -1
  123. package/static/js/ace/worker-html.js +1 -1
  124. package/static/js/ace/worker-javascript.js +1 -1
  125. package/static/js/ace/worker-json.js +1 -1
  126. package/static/js/ee-client.js +5 -0
  127. package/static/licenses.html +191 -1016
  128. package/translations/messages.pot +70 -71
  129. package/views/account/security.hbs +10 -0
  130. package/views/accounts/account.hbs +11 -11
  131. package/views/accounts/edit.hbs +6 -2
  132. package/views/config/ai.hbs +1 -1
  133. package/views/config/security.hbs +2 -2
  134. package/views/config/service.hbs +3 -0
  135. package/views/internals/index.hbs +8 -0
  136. package/views/partials/gateway_form.hbs +3 -1
  137. package/views/partials/webhook_form.hbs +1 -1
  138. package/views/suppression-lists/index.hbs +1 -1
  139. package/workers/api.js +780 -585
  140. package/workers/export.js +1 -1
  141. package/workers/submit.js +1 -1
  142. package/workers/webhooks.js +54 -34
  143. package/config/test.toml +0 -46
  144. package/install.sh +0 -428
  145. package/setup-production.sh +0 -215
  146. package/systemd/emailengine.service +0 -97
  147. package/systemd/nginx-proxy.conf +0 -77
package/lib/tools.js CHANGED
@@ -27,18 +27,27 @@ const punycode = require('punycode.js');
27
27
  const { PassThrough } = require('stream');
28
28
  const socks = require('socks');
29
29
  const os = require('os');
30
+ const { monitorEventLoopDelay } = require('perf_hooks');
30
31
  const Fs = require('fs');
31
32
  const fs = Fs.promises;
32
33
  const pathlib = require('path');
33
34
  const { randomUUID: uuid } = require('crypto');
34
35
  const mimeTypes = require('nodemailer/lib/mime-funcs/mime-types');
35
- const { v3: murmurhash } = require('murmurhash');
36
+ const { murmurhash3 } = require('./utils/murmurhash3');
36
37
  const { isEmail } = require('./utils/is-email');
37
38
  const { toCamelCase } = require('./utils/to-camel-case');
38
39
  const { normalizePath } = require('./utils/mailbox-path');
39
- const { compare: compareVersions, validate: validateVersion } = require('compare-versions');
40
+ const { applyRequireTls } = require('./utils/require-tls');
41
+ const { compareVersions, parseVersion } = require('./utils/version');
42
+
43
+ // Largest decompressed license blob accepted, well above any real license
44
+ const MAX_LICENSE_SIZE = 1024 * 1024;
45
+
46
+ // deriveSigningKey() results, by purpose
47
+ const derivedSigningKeys = new Map();
40
48
  const {
41
49
  REDIS_PREFIX,
50
+ ADMIN_SESSION_MAX_AGE,
42
51
  TLS_DEFAULTS,
43
52
  URL_FETCH_TIMEOUT,
44
53
  MAX_FORM_TTL,
@@ -204,7 +213,9 @@ function createSocksAgent(proxyUrl, agentOpts) {
204
213
 
205
214
  if (useTls) {
206
215
  let rawSocket = socket;
207
- socket = tls.connect(Object.assign({ socket: rawSocket, servername: servername || hostname }, TLS_DEFAULTS));
216
+ // Node's own TLS defaults, not TLS_DEFAULTS: those (TLSv1, SECLEVEL=0) exist for old
217
+ // mail servers, and this is an HTTPS request to an API or a webhook target
218
+ socket = tls.connect({ socket: rawSocket, servername: servername || hostname });
208
219
  // The SOCKS timeout above only covers the proxy negotiation. A proxy (or a target
209
220
  // behind it) that accepts the tunnel and then never answers the ClientHello would
210
221
  // otherwise hold the request, and whatever awaits it (a token refresh, a Gmail or
@@ -326,7 +337,8 @@ httpAgent.forRoute = dispatchersForRoute;
326
337
  try {
327
338
  installDispatchers((workerData && workerData.httpProxyUrl) || null, null);
328
339
  } catch (err) {
329
- logger.error({ msg: 'Failed to create HTTP proxy agent, using direct connections', err });
340
+ // the URL error carries the proxy URL, credentials included, as its input
341
+ logger.error({ msg: 'Failed to create HTTP proxy agent, using direct connections', err: module.exports.sanitizeUrlError(err) });
330
342
  installDispatchers(null, null);
331
343
  }
332
344
 
@@ -454,7 +466,11 @@ async function _doReloadHttpProxyAgent() {
454
466
  .map(([stale]) => stale.close().catch(() => false))
455
467
  );
456
468
  } catch (err) {
457
- logger.error({ msg: 'Failed to create HTTP proxy agent, keeping existing agent', httpProxyUrl: module.exports.redactUrlCredentials(proxyUrl), err });
469
+ logger.error({
470
+ msg: 'Failed to create HTTP proxy agent, keeping existing agent',
471
+ httpProxyUrl: module.exports.redactUrlCredentials(proxyUrl),
472
+ err: module.exports.sanitizeUrlError(err)
473
+ });
458
474
  }
459
475
  }
460
476
 
@@ -580,10 +596,11 @@ function redactValidationError(err) {
580
596
  }
581
597
 
582
598
  // Shared token grammar for cid: references in HTML. Collection
583
- // (collectCidReferences) and every cid: to data URI replace step must tokenize
584
- // identically, otherwise the attachments fetched drift from the references
585
- // replaced and inline images silently disappear. Exposed as a factory rather
586
- // than one regex instance so no lastIndex state can leak between callers.
599
+ // (collectCidReferences) and the data URI replace step (embedCidImages) tokenize
600
+ // a reference identically, so everything the replace step rewrites was collected
601
+ // and fetched first, otherwise inline images would silently disappear. Exposed as
602
+ // a factory rather than one regex instance so no lastIndex state can leak
603
+ // between callers.
587
604
  const CID_REFERENCE_SOURCE = String.raw`\bcid:([^"'\s>]+)`;
588
605
 
589
606
  function cidReferenceRegex() {
@@ -595,13 +612,6 @@ function cidReferenceRegex() {
595
612
  // break out of the src attribute of HTML that is served as web safe
596
613
  const DATA_URL_CONTENT_TYPE = /^[\w.+-]+\/[\w.+-]+$/;
597
614
 
598
- /**
599
- * Replaces cid: references in HTML with data: URLs for the attachments that have content
600
- *
601
- * @param {String} html
602
- * @param {Function} lookup - called with the content id, returns { contentType, content } (content as base64) or a falsy value
603
- * @returns {String}
604
- */
605
615
  /**
606
616
  * Reads a Retry-After header as seconds. Accepts a fetch Headers object (or anything with get())
607
617
  * and a plain header object with keys in any casing, which is how the items of a Graph $batch
@@ -643,17 +653,51 @@ function parseRetryAfter(headers) {
643
653
  return Math.max(0, Math.ceil((date - Date.now()) / 1000));
644
654
  }
645
655
 
656
+ /**
657
+ * Builds a regex for the named HTML attributes with their value in any of the three syntaxes:
658
+ * group 1 is everything up to the value, group 2 the value as written, quotes included. The HTML
659
+ * parser treats '/' between attributes like whitespace, hence [\s/] rather than \s, and a new
660
+ * attribute name may start right after a quoted value (`open=""class="..."`), so a quote counts as
661
+ * a boundary too
662
+ *
663
+ * @param {String[]} names - attribute names
664
+ * @returns {RegExp} global, case-insensitive
665
+ */
666
+ function attributeValueRegex(names) {
667
+ return new RegExp(`([\\s/"'](?:${names.join('|')})\\s*=\\s*)("[^"]*"|'[^']*'|[^\\s"'>]+)`, 'gi');
668
+ }
669
+
670
+ // The attributes a cid: reference is embedded in. A reference anywhere else (an href, the text
671
+ // of the message) is left as it is: this runs after the sanitizer, which refuses a data: URL on a
672
+ // link, and rewriting a cid: link into one would hand the sender exactly what was refused
673
+ const CID_EMBED_ATTRIBUTE = attributeValueRegex(['src', 'srcset', 'background']);
674
+
675
+ /**
676
+ * Replaces the cid: references in the image attributes of an HTML string with data: URLs for the
677
+ * attachments that have content
678
+ *
679
+ * @param {String} html
680
+ * @param {Function} lookup - called with the content id, returns { contentType, content } (content as base64) or a falsy value
681
+ * @returns {String}
682
+ */
646
683
  function embedCidImages(html, lookup) {
647
- if (!html) {
684
+ if (!html || !html.includes('cid:')) {
648
685
  return html;
649
686
  }
650
- return html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
651
- let attachment = lookup(cidMatch);
652
- if (!attachment || !attachment.content) {
653
- return fullMatch;
654
- }
655
- let contentType = DATA_URL_CONTENT_TYPE.test(attachment.contentType || '') ? attachment.contentType : 'application/octet-stream';
656
- return `data:${contentType};base64,${attachment.content}`;
687
+ let references = cidReferenceRegex();
688
+ return html.replace(CID_EMBED_ATTRIBUTE, (attribute, prefix, value) => {
689
+ if (!value.includes('cid:')) {
690
+ return attribute;
691
+ }
692
+ let embedded = value.replace(references, (reference, cid) => {
693
+ let attachment = lookup(cid);
694
+ if (!attachment || !attachment.content) {
695
+ return reference;
696
+ }
697
+ let contentType = DATA_URL_CONTENT_TYPE.test(attachment.contentType || '') ? attachment.contentType : 'application/octet-stream';
698
+ return `data:${contentType};base64,${attachment.content}`;
699
+ });
700
+ return prefix + embedded;
657
701
  });
658
702
  }
659
703
 
@@ -718,6 +762,7 @@ module.exports = {
718
762
  TLS_MATERIAL_SETTINGS,
719
763
 
720
764
  cidReferenceRegex,
765
+ attributeValueRegex,
721
766
  embedCidImages,
722
767
  parseRetryAfter,
723
768
 
@@ -734,7 +779,9 @@ module.exports = {
734
779
  * @param {Object} sessionData Session payload (user/profile/etc, no sid)
735
780
  */
736
781
  setAdminSession(request, sessionData) {
737
- request.cookieAuth.set(Object.assign({}, sessionData, { sid: randomBytes(32).toString('hex') }));
782
+ // issuedAt is what isEndedSession() ages the session by; a caller re-stamping a session
783
+ // it means to keep may carry the old value over
784
+ request.cookieAuth.set(Object.assign({ issuedAt: Date.now() }, sessionData, { sid: randomBytes(32).toString('hex') }));
738
785
  },
739
786
 
740
787
  /**
@@ -754,12 +801,28 @@ module.exports = {
754
801
  * password exists (an unsecured instance), or nobody has ever bumped it,
755
802
  * and a session stamped before the field existed must not be force-expired.
756
803
  *
804
+ * A session is also over once it is older than ADMIN_SESSION_MAX_AGE, by
805
+ * the issuedAt setAdminSession() stamps. The sealed cookie has no expiry of
806
+ * its own, so a cookie captured once used to stay valid until the next
807
+ * password change, however long ago it was issued. A session carrying no
808
+ * issuedAt was issued before the stamp existed and is over too: that is one
809
+ * sign-in at upgrade time for whoever is logged in, against never ageing
810
+ * out a cookie whose age nobody can tell.
811
+ *
757
812
  * @param {Number} currentPasswordVersion authData.passwordVersion, or 0
758
813
  * @param {Object} session decoded session cookie
814
+ * @param {Number} [now] the current time, for tests
759
815
  * @returns {Boolean} true when the session is over
760
816
  */
761
- isEndedSession(currentPasswordVersion, session) {
762
- return !!currentPasswordVersion && currentPasswordVersion !== (session && session.passwordVersion);
817
+ isEndedSession(currentPasswordVersion, session, now) {
818
+ if (!currentPasswordVersion) {
819
+ return false;
820
+ }
821
+ if (currentPasswordVersion !== (session && session.passwordVersion)) {
822
+ return true;
823
+ }
824
+ let issuedAt = Number(session.issuedAt);
825
+ return !issuedAt || (now || Date.now()) - issuedAt > ADMIN_SESSION_MAX_AGE;
763
826
  },
764
827
 
765
828
  /**
@@ -796,12 +859,14 @@ module.exports = {
796
859
  * lookup per attachment instead of scanning the full HTML once per attachment:
797
860
  * the repeated synchronous scans cost attachment count times body size, which
798
861
  * on a crafted message blocks the worker event loop past the heartbeat
799
- * restart timeout. Tokenizes with the same grammar as the cid: replace steps
862
+ * restart timeout. Tokenizes with the same grammar as the replace step
800
863
  * (cidReferenceRegex), so a content id that is only a prefix of a referenced
801
- * id, or that appears outside a cid: link, does not match. Each token is
802
- * additionally added truncated at a closing parenthesis: the replace grammar
803
- * does not stop at ")" and so never embeds CSS url(cid:...) references, but
804
- * the attachment content they point at should still be fetched.
864
+ * id, or that appears outside a cid: link, does not match. The set answers
865
+ * which attachments the HTML refers to at all, which is also what decides
866
+ * whether an attachment is inline, so it looks at every reference, while
867
+ * embedCidImages() rewrites only the image attributes among them. Each token
868
+ * is additionally added truncated at a closing parenthesis, so that a CSS
869
+ * url(cid:...) reference counts as a reference to its attachment.
805
870
  * @param {String} html HTML content to scan
806
871
  * @returns {Set<String>} Content ids referenced in the HTML
807
872
  */
@@ -1240,6 +1305,13 @@ module.exports = {
1240
1305
  return processCount;
1241
1306
  },
1242
1307
 
1308
+ // A worker pool size: the environment value if it gives one, else the configuration file's, else
1309
+ // the pool's default. Both accept "cpus", and a fraction is rounded down so a pool never gets
1310
+ // more threads than asked for.
1311
+ workerPoolSize(envValue, configValue, defaultCount = 1) {
1312
+ return Math.floor(module.exports.getWorkerCount(envValue)) || Math.floor(module.exports.getWorkerCount(configValue)) || defaultCount;
1313
+ },
1314
+
1243
1315
  getDuration(val, opts = {}) {
1244
1316
  val = (val || '').toString().replace(/^([\d.]+)\s*([smhdy][a-z]*)$/i, (o, num, m) => {
1245
1317
  if (!num || isNaN(num)) {
@@ -1500,7 +1572,7 @@ module.exports = {
1500
1572
  },
1501
1573
 
1502
1574
  getRendezvousScore(key, shardId) {
1503
- return murmurhash(`${(shardId || '').toString()}\x00${key}`);
1575
+ return murmurhash3(`${(shardId || '').toString()}\x00${key}`);
1504
1576
  },
1505
1577
 
1506
1578
  selectRendezvousNode(key, workers) {
@@ -1568,7 +1640,9 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1568
1640
  );
1569
1641
  }
1570
1642
 
1571
- let signedLicense = await brotliDecompressAsync(encodedLicense);
1643
+ // bounded: the blob is caller-supplied and brotli expands a few hundred bytes into
1644
+ // hundreds of megabytes; a license is a few kilobytes
1645
+ let signedLicense = await brotliDecompressAsync(encodedLicense, { maxOutputLength: MAX_LICENSE_SIZE });
1572
1646
 
1573
1647
  let { l: licenseRaw, s: signature } = msgpack.decode(signedLicense);
1574
1648
 
@@ -1829,6 +1903,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1829
1903
  smtpConfig.tls[key] = TLS_DEFAULTS[key];
1830
1904
  }
1831
1905
  }
1906
+ applyRequireTls(smtpConfig);
1832
1907
 
1833
1908
  for (let level of ['trace', 'debug', 'info', 'warn', 'error', 'fatal']) {
1834
1909
  smtpLogger[level] = (data, message, ...args) => {
@@ -1923,7 +1998,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1923
1998
  );
1924
1999
  }
1925
2000
 
1926
- let signedContent = await brotliDecompressAsync(encodedContent);
2001
+ let signedContent = await brotliDecompressAsync(encodedContent, { maxOutputLength: MAX_LICENSE_SIZE });
1927
2002
  let { l: contentRaw, s: signature } = msgpack.decode(signedContent);
1928
2003
  for (let rootItem of rootList) {
1929
2004
  try {
@@ -2316,11 +2391,11 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2316
2391
  }
2317
2392
 
2318
2393
  let releaseVersion = (releaseData.tag_name || '').toString().replace(/^v/, '');
2319
- if (!validateVersion(releaseVersion)) {
2394
+ if (!parseVersion(releaseVersion)) {
2320
2395
  return { current: packageData.version, available: false, canUpgrade: false };
2321
2396
  }
2322
2397
 
2323
- if (compareVersions(releaseVersion, packageData.version, '>')) {
2398
+ if (compareVersions(releaseVersion, packageData.version) > 0) {
2324
2399
  return { current: packageData.version, available: releaseVersion, canUpgrade: true };
2325
2400
  }
2326
2401
 
@@ -2331,6 +2406,65 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2331
2406
  return secretKey.replace(/^(.{8}).*$/, `$1... (${secretKey.length}B)`);
2332
2407
  },
2333
2408
 
2409
+ // What an operator needs to tell which client secret the instance holds when the provider says
2410
+ // it is wrong: the length and the first few characters. Carried on the token error as
2411
+ // `clientSecretHint`, where the log serializer picks it up and nothing that builds an API
2412
+ // payload or a webhook out of `err.tokenRequest` does. Shorter than formatPartialSecretKey()
2413
+ // all the same, since eight characters of a thirty-character secret is a quarter of it
2414
+ formatSecretHint(secretKey) {
2415
+ secretKey = (secretKey || '').toString();
2416
+ return `${secretKey.slice(0, 3)}... (${secretKey.length}B)`;
2417
+ },
2418
+
2419
+ // The body of a token request and the token response as they may go to the log. The secrets
2420
+ // in them are masked whether or not raw logging is on: EENGINE_LOG_RAW is for the protocol
2421
+ // traffic, and the application's client secret and the refresh tokens of every account are
2422
+ // not something a debug switch should put in the log in full
2423
+ formatOAuthRequestBody(searchParams) {
2424
+ let entries = typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
2425
+ let data = Object.fromEntries(entries);
2426
+
2427
+ for (let key of ['refresh_token', 'client_secret', 'code']) {
2428
+ if (data[key]) {
2429
+ data[key] = module.exports.formatPartialSecretKey(data[key]);
2430
+ }
2431
+ }
2432
+
2433
+ if (data.assertion) {
2434
+ // a signed JWT
2435
+ let [payload, signature] = data.assertion.toString().split('.');
2436
+ data.assertion = [payload, module.exports.formatPartialSecretKey(signature)].join('.');
2437
+ }
2438
+
2439
+ return data;
2440
+ },
2441
+
2442
+ formatOAuthResponse(responseObj) {
2443
+ if (!responseObj || typeof responseObj !== 'object') {
2444
+ return responseObj;
2445
+ }
2446
+
2447
+ let data = module.exports.structuredClone(responseObj);
2448
+ for (let key of ['access_token', 'refresh_token', 'id_token']) {
2449
+ if (data[key]) {
2450
+ data[key] = module.exports.formatPartialSecretKey(data[key]);
2451
+ }
2452
+ }
2453
+
2454
+ return data;
2455
+ },
2456
+
2457
+ // An error from `new URL()` carries the string it failed on as `err.input`, and when that
2458
+ // string is a proxy URL it carries the proxy credentials. The logger redacts that field on its
2459
+ // own (REDACTED_LOG_KEYS), but the error object also reaches Sentry whole, so the string itself
2460
+ // is rewritten. Returns the same error with the credentials redacted
2461
+ sanitizeUrlError(err) {
2462
+ if (err && typeof err === 'object' && typeof err.input === 'string') {
2463
+ err.input = module.exports.redactUrlCredentials(err.input);
2464
+ }
2465
+ return err;
2466
+ },
2467
+
2334
2468
  // Returns the URL with any embedded basic auth credentials removed, safe for logging. Never
2335
2469
  // throws: an unparseable value is replaced with a static placeholder rather than echoed back,
2336
2470
  // because the raw string could itself carry the credentials that made it unparseable.
@@ -2406,9 +2540,21 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2406
2540
  if (stored) {
2407
2541
  serviceSecret = stored;
2408
2542
  } else {
2409
- // The field exists but reads back empty/undecryptable (e.g. explicitly blanked
2410
- // via the settings API): HSETNX cannot heal it, so overwrite - same healing the
2411
- // previous read-then-write implementation performed.
2543
+ // The field exists but reads back empty. Two cases, and they must not be
2544
+ // treated the same. A legacy blank (the settings API used to allow it) is
2545
+ // healed by overwriting, which HSETNX cannot do. A value that is present but
2546
+ // does not decrypt is the instance running with the wrong EENGINE_SECRET, and
2547
+ // overwriting it would destroy a secret the rotation CLI can still recover
2548
+ // once the right one is back, so that one is an error here: links stop
2549
+ // verifying until the operator fixes the secret, the same as every stored
2550
+ // credential already does.
2551
+ let raw = await settings.getRaw('serviceSecret');
2552
+ if (raw) {
2553
+ let error = new Error('The stored service secret can not be decrypted; check EENGINE_SECRET');
2554
+ error.code = 'EServiceSecretUnreadable';
2555
+ error.statusCode = 500;
2556
+ throw error;
2557
+ }
2412
2558
  await settings.set('serviceSecret', serviceSecret);
2413
2559
  }
2414
2560
  }
@@ -2416,6 +2562,40 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2416
2562
  return serviceSecret;
2417
2563
  },
2418
2564
 
2565
+ // One service secret signs several unrelated things: webhook bodies, hosted setup-form blobs,
2566
+ // tracking links and unsubscribe links. Each is HMAC-SHA256 of some bytes, so without a purpose
2567
+ // in the key a signature made for one is a valid signature for the others - a webhook body and
2568
+ // its X-EE-Wh-Signature header was a valid setup blob for the account the delivery named. The
2569
+ // key for each purpose is derived from the service secret, so a signature only verifies where
2570
+ // it was minted. The webhook signature itself keeps the raw secret: its format is documented
2571
+ // and verified by customer code.
2572
+ SIGNING_PURPOSE: {
2573
+ FORM: 'form',
2574
+ TRACKING: 'tracking',
2575
+ UNSUBSCRIBE: 'unsubscribe'
2576
+ },
2577
+
2578
+ // Derived once per purpose and kept while the secret is the one it was derived from: a
2579
+ // tracked message signs one blob per link, and the key is the same for all of them
2580
+ deriveSigningKey(serviceSecret, purpose) {
2581
+ if (!Object.values(module.exports.SIGNING_PURPOSE).includes(purpose)) {
2582
+ throw new Error(`Unknown signing purpose ${JSON.stringify(purpose)}`);
2583
+ }
2584
+ let cached = derivedSigningKeys.get(purpose);
2585
+ if (cached && cached.serviceSecret === serviceSecret) {
2586
+ return cached.key;
2587
+ }
2588
+ let key = createHmac('sha256', serviceSecret).update(`emailengine:signing:${purpose}:v1`).digest();
2589
+ derivedSigningKeys.set(purpose, { serviceSecret, key });
2590
+ return key;
2591
+ },
2592
+
2593
+ signServiceData(serviceSecret, data, purpose) {
2594
+ let hmac = createHmac('sha256', module.exports.deriveSigningKey(serviceSecret, purpose));
2595
+ hmac.update(data);
2596
+ return hmac.digest('base64url');
2597
+ },
2598
+
2419
2599
  async getSignedFormData(opts) {
2420
2600
  const serviceSecret = await module.exports.getServiceSecret();
2421
2601
  return module.exports.getSignedFormDataSync(serviceSecret, opts);
@@ -2431,8 +2611,11 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2431
2611
  return res;
2432
2612
  },
2433
2613
 
2434
- getSignedFormDataSync(serviceSecret, opts, asIs) {
2614
+ // Signs a hosted setup-form blob (the default purpose), a tracking blob or an unsubscribe
2615
+ // blob; the purpose picks the derived key the matching verifier checks against
2616
+ getSignedFormDataSync(serviceSecret, opts, asIs, purpose) {
2435
2617
  opts = opts || {};
2618
+ purpose = purpose || module.exports.SIGNING_PURPOSE.FORM;
2436
2619
 
2437
2620
  let data = Buffer.from(
2438
2621
  JSON.stringify(
@@ -2455,11 +2638,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2455
2638
  )
2456
2639
  );
2457
2640
 
2458
- let signature;
2459
-
2460
- let hmac = createHmac('sha256', serviceSecret);
2461
- hmac.update(data);
2462
- signature = hmac.digest('base64url');
2641
+ let signature = module.exports.signServiceData(serviceSecret, data, purpose);
2463
2642
 
2464
2643
  return { data: data.toString('base64url'), signature };
2465
2644
  },
@@ -2483,7 +2662,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2483
2662
  payload.msg = opts.messageId;
2484
2663
  }
2485
2664
 
2486
- let { data: signedData, signature } = module.exports.getSignedFormDataSync(serviceSecret, payload, true);
2665
+ let { data: signedData, signature } = module.exports.getSignedFormDataSync(serviceSecret, payload, true, module.exports.SIGNING_PURPOSE.UNSUBSCRIBE);
2487
2666
 
2488
2667
  let unsubscribeUrlObj = new URL('/unsubscribe', baseUrl || 'http://localhost');
2489
2668
  unsubscribeUrlObj.searchParams.append('data', signedData);
@@ -2499,24 +2678,36 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2499
2678
  // silently skipped (an empty secret would otherwise accept forged, unsigned data). Returns true
2500
2679
  // only when `sig` matches `data`.
2501
2680
  //
2502
- // Reviewed compat note (accepted, do not revert to skip-when-empty): fail-closed means an install
2503
- // whose stored serviceSecret is currently blank will 403 tracking/unsubscribe links in
2504
- // already-delivered mail (the old code skipped verification and resolved them, which also accepted
2505
- // FORGED blobs - the hole this closes). This is documented in the release notes; an operator can
2506
- // restore the previous secret via the settings API to revive old links. The separate hazard of an
2507
- // undecryptable-but-present secret being overwritten is PRE-EXISTING (server.js startApplication
2508
- // re-mints a null-reading secret at boot, before any request), not introduced by this change - so
2509
- // do not treat it as a regression of this refactor.
2510
- async verifyServiceSignature(data, sig) {
2681
+ // Fail-closed on purpose: an install whose stored serviceSecret is blank answers 403 to the
2682
+ // tracking and unsubscribe links in already-delivered mail (skipping the check resolved them,
2683
+ // and accepted forged blobs with them). An operator can restore the previous secret through
2684
+ // the settings API to revive old links.
2685
+ //
2686
+ // `purpose` names the derived key (SIGNING_PURPOSE; the setup form when omitted). Tracking and
2687
+ // unsubscribe links live in mail that was sent before the keys were derived, so for those two
2688
+ // purposes a signature made with the raw secret is still accepted; a setup blob is not, since
2689
+ // a nonce-less one is exactly what a replayed webhook body or tracking blob used to pass as.
2690
+ async verifyServiceSignature(data, sig, purpose) {
2691
+ purpose = purpose || module.exports.SIGNING_PURPOSE.FORM;
2511
2692
  const serviceSecret = await module.exports.getServiceSecret();
2512
- const hmac = createHmac('sha256', serviceSecret);
2513
- hmac.update(data);
2514
- return module.exports.constantTimeEqual(hmac.digest('base64url'), sig);
2693
+
2694
+ if (module.exports.constantTimeEqual(module.exports.signServiceData(serviceSecret, data, purpose), sig)) {
2695
+ return true;
2696
+ }
2697
+
2698
+ if (purpose === module.exports.SIGNING_PURPOSE.TRACKING || purpose === module.exports.SIGNING_PURPOSE.UNSUBSCRIBE) {
2699
+ // a link minted before the keys were derived
2700
+ const legacy = createHmac('sha256', serviceSecret);
2701
+ legacy.update(data);
2702
+ return module.exports.constantTimeEqual(legacy.digest('base64url'), sig);
2703
+ }
2704
+
2705
+ return false;
2515
2706
  },
2516
2707
 
2517
2708
  // Redis key for a hosted-form single-use nonce (`n` inside the signed blob). Built in one place so
2518
- // the sites that must agree on it - the consumed-nonce check below, the IMAP-arm claim
2519
- // (lib/ui-routes/account-routes.js) and the OAuth callback claim (workers/api.js) - cannot drift.
2709
+ // the sites that must agree on it - the consumed-nonce check below and the claim both setup arms
2710
+ // make through lib/ui-routes/account-setup.js - cannot drift.
2520
2711
  formNonceKey(n) {
2521
2712
  return `${REDIS_PREFIX}account:form:${n}`;
2522
2713
  },
@@ -2524,8 +2715,8 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2524
2715
  // Atomically claim a hosted-form single-use nonce (SET NX). Returns true when THIS caller won the
2525
2716
  // claim, false when the key already existed (the signed URL was already used). Throws on a Redis error
2526
2717
  // - a Redis failure is NOT a consumed nonce, so callers must map it to a retryable 5xx, not a 403.
2527
- // Shared by the IMAP-arm submit and the OAuth callback so the EX/NX/TTL semantics of the double-spend
2528
- // guard cannot drift between the two arms; each caller keeps its own Boom 403/500 messages.
2718
+ // Called from lib/ui-routes/account-setup.js, which both setup arms complete through, and which maps
2719
+ // the outcome to its 403/500 refusals.
2529
2720
  async claimFormNonce(redis, n, t) {
2530
2721
  const claimed = await redis.set(module.exports.formNonceKey(n), (t || '0').toString(), 'EX', Math.floor(MAX_FORM_TTL / 1000), 'NX');
2531
2722
  return !!claimed;
@@ -2545,11 +2736,13 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2545
2736
  }
2546
2737
  },
2547
2738
 
2739
+ // `opts.purpose` selects the signing key (SIGNING_PURPOSE; the setup form when omitted), see
2740
+ // verifyServiceSignature()
2548
2741
  async parseSignedFormData(redis, payload, gt, opts) {
2549
2742
  opts = opts || {};
2550
2743
 
2551
2744
  let data = Buffer.from(payload.data, 'base64url').toString();
2552
- if (!(await module.exports.verifyServiceSignature(data, payload.sig))) {
2745
+ if (!(await module.exports.verifyServiceSignature(data, payload.sig, opts.purpose))) {
2553
2746
  let error = Boom.boomify(new Error(gt.gettext('Signature validation failed')), { statusCode: 403 });
2554
2747
  throw error;
2555
2748
  }
@@ -2695,7 +2888,11 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2695
2888
  convertDataUrisToAttachments(data) {
2696
2889
  if (data.html) {
2697
2890
  let cidCounter = 0;
2698
- let html = data.html.replace(/(<img\b[^>]* src\s*=[\s"']*)(data:([^;]+);[^"'>\s]+)/gi, (match, prefix, dataUri, mimeType) => {
2891
+ // `[^<>]*` before src and a bounded media type: an `<img` that is never closed used to
2892
+ // let the scan run to the end of the body from every image tag and backtrack over it
2893
+ // (80 KB of `<img ` took half a second, the 5 MB schema cap would have taken minutes).
2894
+ // A tag never contains `<`, so well-formed markup is unaffected
2895
+ let html = data.html.replace(/(<img\b[^<>]* src\s*=[\s"']*)(data:([^;"'>\s]{1,256});[^"'>\s]+)/gi, (match, prefix, dataUri, mimeType) => {
2699
2896
  let cid = `${uuid()}@emailengine`;
2700
2897
  if (!data.attachments) {
2701
2898
  data.attachments = [];
@@ -2730,8 +2927,30 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2730
2927
  heapTotal: memUsage.heapTotal,
2731
2928
  external: memUsage.external,
2732
2929
  rss: memUsage.rss,
2733
- arrayBuffers: memUsage.arrayBuffers || 0
2930
+ arrayBuffers: memUsage.arrayBuffers || 0,
2931
+ eventLoopDelay: this.readEventLoopDelay()
2734
2932
  };
2933
+ },
2934
+
2935
+ // How late this thread's event loop ran since the previous reading, in milliseconds. The
2936
+ // main thread's metrics collector reads every thread every 15 seconds, so a reading covers
2937
+ // that window. The histogram starts with the first reading, which therefore has nothing
2938
+ // to report.
2939
+ readEventLoopDelay() {
2940
+ if (!this.delayHistogram) {
2941
+ this.delayHistogram = monitorEventLoopDelay({ resolution: 20 });
2942
+ this.delayHistogram.enable();
2943
+ return null;
2944
+ }
2945
+ let histogram = this.delayHistogram;
2946
+ let reading = histogram.count
2947
+ ? {
2948
+ max: histogram.max / 1e6,
2949
+ p99: histogram.percentile(99) / 1e6
2950
+ }
2951
+ : null;
2952
+ histogram.reset();
2953
+ return reading;
2735
2954
  }
2736
2955
  },
2737
2956
 
package/lib/totp.js CHANGED
@@ -3,6 +3,7 @@
3
3
  const crypto = require('crypto');
4
4
  const { base32Encode } = require('./base32');
5
5
  const qrcode = require('qrcode-generator');
6
+ const { randomId } = require('./utils/random-id');
6
7
 
7
8
  // The otpauth URL is percent-encoded ASCII, but the encoder qrcode-generator selects by default
8
9
  // keeps one byte per character, so it is switched to UTF-8 once here rather than relied on
@@ -32,11 +33,7 @@ function hotp(secret, counter) {
32
33
  }
33
34
 
34
35
  function generateTotpSeed() {
35
- let seed = '';
36
- for (let i = 0; i < SEED_LENGTH; i++) {
37
- seed += SEED_CHARSET[crypto.randomInt(SEED_CHARSET.length)];
38
- }
39
- return seed;
36
+ return randomId(SEED_CHARSET, SEED_LENGTH);
40
37
  }
41
38
 
42
39
  function verifyTotp(seed, token, options) {
@@ -3,7 +3,6 @@
3
3
  const fs = require('fs').promises;
4
4
  const Path = require('path');
5
5
  const Gettext = require('@postalsys/gettext');
6
- const { mo } = require('gettext-parser');
7
6
  const locales = require('../translations/locales.json');
8
7
  const joiMessages = require('@postalsys/joi-messages');
9
8
 
@@ -25,7 +24,7 @@ async function loadTranslations() {
25
24
  // Gettext translations
26
25
  for (let locale of locales) {
27
26
  let fContent = await fs.readFile(Path.join(translationsDir, locale.file || `${locale.locale}.mo`));
28
- let parsedTranslations = mo.parse(fContent);
27
+ let parsedTranslations = Gettext.parseMo(fContent);
29
28
  gt.addTranslations(locale.locale, domain, parsedTranslations);
30
29
  }
31
30
  }