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
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ // What the main thread reports about its worker threads beyond their counts: the fields the
4
+ // heartbeat log lines carry and the per-thread event loop delay gauges. Kept free of server.js
5
+ // state so both can be tested without starting the process.
6
+
7
+ /**
8
+ * Fields for a heartbeat log line (unhealthy, restarting, recovered).
9
+ * @param {Object} args
10
+ * @param {number} args.now - Current time in milliseconds
11
+ * @param {number} [args.lastHeartbeat] - When the thread last reported in
12
+ * @param {number} [args.accounts] - Accounts assigned to the thread, for an account worker
13
+ * @param {Object} [args.threadInfo] - The thread's last resource reading. A thread that has gone quiet
14
+ * cannot answer, so this is the one taken before that, at most one collection interval earlier.
15
+ * @returns {Object} Fields to spread into the log entry
16
+ */
17
+ function heartbeatDiagnostics({ now, lastHeartbeat, accounts, threadInfo }) {
18
+ let details = {};
19
+ if (typeof lastHeartbeat === 'number') {
20
+ details.timeSinceHeartbeat = Math.round((now - lastHeartbeat) / 1000) + 's';
21
+ }
22
+ if (typeof accounts === 'number') {
23
+ details.accounts = accounts;
24
+ }
25
+ if (threadInfo?.eventLoopDelay) {
26
+ details.lastEventLoopDelay = Math.round(threadInfo.eventLoopDelay.max) + 'ms';
27
+ }
28
+ return details;
29
+ }
30
+
31
+ /**
32
+ * The per-thread event loop delay gauge values, in seconds, for every thread that has a reading.
33
+ * @param {Array<Object>} threadsInfo - Thread readings as the metrics collector returns them
34
+ * @returns {Array<{labels: Object, max: number, p99: number}>}
35
+ */
36
+ function eventLoopDelaySeries(threadsInfo) {
37
+ return (threadsInfo || [])
38
+ .filter(threadInfo => threadInfo.eventLoopDelay)
39
+ .map(threadInfo => ({
40
+ labels: { type: threadInfo.type, thread: String(threadInfo.threadId) },
41
+ max: threadInfo.eventLoopDelay.max / 1000,
42
+ p99: threadInfo.eventLoopDelay.p99 / 1000
43
+ }));
44
+ }
45
+
46
+ module.exports = { heartbeatDiagnostics, eventLoopDelaySeries };
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+
3
+ // The timezone choices on the admin Service page, built from the runtime's own ICU data instead of
4
+ // a static package. Node (and the pkg binaries, which carry full ICU) list zones under their CLDR
5
+ // ids, and CLDR keeps the old spelling for zones IANA has since renamed: Intl answers
6
+ // "Europe/Kiev" and "Asia/Calcutta", never "Europe/Kyiv" or "Asia/Kolkata". Those are shown and
7
+ // stored under their IANA names, which is also what the replaced timezones-list package offered, so
8
+ // a value saved from the old list stays selected. Intl accepts both spellings as a timeZone.
9
+
10
+ // CLDR id -> current IANA name, for every id Intl.supportedValuesOf('timeZone') returns in its
11
+ // legacy form (checked on Node 20, 24 and 26, all ICU 78)
12
+ const IANA_NAMES = new Map([
13
+ ['Africa/Asmera', 'Africa/Asmara'],
14
+ ['America/Buenos_Aires', 'America/Argentina/Buenos_Aires'],
15
+ ['America/Catamarca', 'America/Argentina/Catamarca'],
16
+ ['America/Coral_Harbour', 'America/Atikokan'],
17
+ ['America/Cordoba', 'America/Argentina/Cordoba'],
18
+ ['America/Indianapolis', 'America/Indiana/Indianapolis'],
19
+ ['America/Jujuy', 'America/Argentina/Jujuy'],
20
+ ['America/Louisville', 'America/Kentucky/Louisville'],
21
+ ['America/Mendoza', 'America/Argentina/Mendoza'],
22
+ ['Asia/Calcutta', 'Asia/Kolkata'],
23
+ ['Asia/Katmandu', 'Asia/Kathmandu'],
24
+ ['Asia/Rangoon', 'Asia/Yangon'],
25
+ ['Asia/Saigon', 'Asia/Ho_Chi_Minh'],
26
+ ['Atlantic/Faeroe', 'Atlantic/Faroe'],
27
+ ['Europe/Kiev', 'Europe/Kyiv'],
28
+ ['Pacific/Ponape', 'Pacific/Pohnpei'],
29
+ ['Pacific/Truk', 'Pacific/Chuuk']
30
+ ]);
31
+
32
+ // Offsets are read on these dates so the label shows the standard offset all year round instead
33
+ // of moving with daylight saving time: the smaller of a January and a July offset is the standard
34
+ // one in both hemispheres
35
+ const SAMPLE_DATES = [new Date(Date.UTC(2026, 0, 1)), new Date(Date.UTC(2026, 6, 1))];
36
+
37
+ /**
38
+ * @param {string} timeZone
39
+ * @param {Date} date
40
+ * @returns {number|null} UTC offset in minutes, or null for an unknown zone
41
+ */
42
+ function getOffsetMinutes(timeZone, date) {
43
+ let name;
44
+ try {
45
+ name = new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' }).formatToParts(date).find(part => part.type === 'timeZoneName').value;
46
+ } catch {
47
+ return null;
48
+ }
49
+ // "GMT" alone is UTC, otherwise "GMT+05:30" / "GMT-03:00"
50
+ const match = name.match(/^GMT(?:([+-])(\d{2}):(\d{2}))?$/);
51
+ if (!match) {
52
+ return null;
53
+ }
54
+ return match[1] ? (match[1] === '-' ? -1 : 1) * (Number(match[2]) * 60 + Number(match[3])) : 0;
55
+ }
56
+
57
+ // The standard offset of a zone, null when the runtime does not know it
58
+ function getStandardOffset(timeZone) {
59
+ const offsets = SAMPLE_DATES.map(date => getOffsetMinutes(timeZone, date)).filter(offset => offset !== null);
60
+ return offsets.length ? Math.min(...offsets) : null;
61
+ }
62
+
63
+ function formatOffset(minutes) {
64
+ const sign = minutes < 0 ? '-' : '+';
65
+ const abs = Math.abs(minutes);
66
+ return `GMT${sign}${String(Math.floor(abs / 60)).padStart(2, '0')}:${String(abs % 60).padStart(2, '0')}`;
67
+ }
68
+
69
+ let cachedZones = null;
70
+
71
+ /**
72
+ * Every zone the runtime knows under its IANA name, ordered by standard offset and then by name.
73
+ *
74
+ * @returns {{ timezone: string, offset: number, label: string }[]}
75
+ */
76
+ function listTimezones() {
77
+ if (!cachedZones) {
78
+ const zones = new Map();
79
+ for (const id of Intl.supportedValuesOf('timeZone')) {
80
+ const timezone = IANA_NAMES.get(id) || id;
81
+ const offset = getStandardOffset(id);
82
+ if (offset === null || zones.has(timezone)) {
83
+ continue;
84
+ }
85
+ zones.set(timezone, { timezone, offset, label: `${timezone} (${formatOffset(offset)})` });
86
+ }
87
+ cachedZones = [...zones.values()].sort((a, b) => a.offset - b.offset || a.timezone.localeCompare(b.timezone));
88
+ }
89
+ return cachedZones;
90
+ }
91
+
92
+ /**
93
+ * Options for the timezone select. A stored value the runtime does not list (a zone IANA has
94
+ * since merged into another, like America/Yellowknife) is kept as an option of its own, so opening
95
+ * and saving the page never changes it.
96
+ *
97
+ * @param {string|false|null|undefined} selected The stored timezone
98
+ * @returns {{ name: string, timezone: string, selected: boolean }[]}
99
+ */
100
+ function timezoneOptions(selected) {
101
+ const options = listTimezones().map(zone => ({ name: zone.label, timezone: zone.timezone, selected: zone.timezone === selected }));
102
+ if (selected && !options.some(option => option.selected)) {
103
+ const offset = getStandardOffset(selected);
104
+ options.unshift({ name: offset === null ? selected : `${selected} (${formatOffset(offset)})`, timezone: selected, selected: true });
105
+ }
106
+ return options;
107
+ }
108
+
109
+ module.exports = { listTimezones, timezoneOptions, IANA_NAMES };
@@ -205,14 +205,14 @@ const MCP_SECTIONS = {
205
205
  {
206
206
  value: 'mail',
207
207
  label: 'Mail agent',
208
- hint: 'Read, organize, draft and send mail - everything except the delete tool.',
209
- caveat: 'Everything except the delete tool. Instructions inside received mail are a real prompt-injection risk once sending is granted.',
208
+ hint: 'Read, organize, draft and send mail, and create and rename folders - everything except deleting.',
209
+ caveat: 'Everything except deleting messages and folders. Instructions inside received mail are a real prompt-injection risk once sending is granted.',
210
210
  pairs: pairsOf(MCP_SCOPES.mail, grant => grant.action !== ACTION.DESTRUCTIVE)
211
211
  },
212
212
  {
213
213
  value: 'full',
214
214
  label: 'Full access',
215
- hint: 'Every mail tool, including deleting messages.',
215
+ hint: 'Every mail tool, including deleting messages and folders.',
216
216
  caveat: 'Instructions inside received mail are a real prompt-injection risk once sending is granted.',
217
217
  pairs: pairsOf(MCP_SCOPES.mail, () => true)
218
218
  }
package/lib/tools.js CHANGED
@@ -27,17 +27,18 @@ 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
40
  const { applyRequireTls } = require('./utils/require-tls');
40
- const { compare: compareVersions, validate: validateVersion } = require('compare-versions');
41
+ const { compareVersions, parseVersion } = require('./utils/version');
41
42
 
42
43
  // Largest decompressed license blob accepted, well above any real license
43
44
  const MAX_LICENSE_SIZE = 1024 * 1024;
@@ -1304,6 +1305,13 @@ module.exports = {
1304
1305
  return processCount;
1305
1306
  },
1306
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
+
1307
1315
  getDuration(val, opts = {}) {
1308
1316
  val = (val || '').toString().replace(/^([\d.]+)\s*([smhdy][a-z]*)$/i, (o, num, m) => {
1309
1317
  if (!num || isNaN(num)) {
@@ -1564,7 +1572,7 @@ module.exports = {
1564
1572
  },
1565
1573
 
1566
1574
  getRendezvousScore(key, shardId) {
1567
- return murmurhash(`${(shardId || '').toString()}\x00${key}`);
1575
+ return murmurhash3(`${(shardId || '').toString()}\x00${key}`);
1568
1576
  },
1569
1577
 
1570
1578
  selectRendezvousNode(key, workers) {
@@ -2383,11 +2391,11 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2383
2391
  }
2384
2392
 
2385
2393
  let releaseVersion = (releaseData.tag_name || '').toString().replace(/^v/, '');
2386
- if (!validateVersion(releaseVersion)) {
2394
+ if (!parseVersion(releaseVersion)) {
2387
2395
  return { current: packageData.version, available: false, canUpgrade: false };
2388
2396
  }
2389
2397
 
2390
- if (compareVersions(releaseVersion, packageData.version, '>')) {
2398
+ if (compareVersions(releaseVersion, packageData.version) > 0) {
2391
2399
  return { current: packageData.version, available: releaseVersion, canUpgrade: true };
2392
2400
  }
2393
2401
 
@@ -2698,8 +2706,8 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2698
2706
  },
2699
2707
 
2700
2708
  // Redis key for a hosted-form single-use nonce (`n` inside the signed blob). Built in one place so
2701
- // the sites that must agree on it - the consumed-nonce check below, the IMAP-arm claim
2702
- // (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.
2703
2711
  formNonceKey(n) {
2704
2712
  return `${REDIS_PREFIX}account:form:${n}`;
2705
2713
  },
@@ -2707,8 +2715,8 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2707
2715
  // Atomically claim a hosted-form single-use nonce (SET NX). Returns true when THIS caller won the
2708
2716
  // claim, false when the key already existed (the signed URL was already used). Throws on a Redis error
2709
2717
  // - a Redis failure is NOT a consumed nonce, so callers must map it to a retryable 5xx, not a 403.
2710
- // Shared by the IMAP-arm submit and the OAuth callback so the EX/NX/TTL semantics of the double-spend
2711
- // 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.
2712
2720
  async claimFormNonce(redis, n, t) {
2713
2721
  const claimed = await redis.set(module.exports.formNonceKey(n), (t || '0').toString(), 'EX', Math.floor(MAX_FORM_TTL / 1000), 'NX');
2714
2722
  return !!claimed;
@@ -2919,8 +2927,30 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2919
2927
  heapTotal: memUsage.heapTotal,
2920
2928
  external: memUsage.external,
2921
2929
  rss: memUsage.rss,
2922
- arrayBuffers: memUsage.arrayBuffers || 0
2930
+ arrayBuffers: memUsage.arrayBuffers || 0,
2931
+ eventLoopDelay: this.readEventLoopDelay()
2923
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;
2924
2954
  }
2925
2955
  },
2926
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
  }