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
package/server.js CHANGED
@@ -75,7 +75,7 @@ const {
75
75
  getDuration,
76
76
  getByteSize,
77
77
  getBoolean,
78
- getWorkerCount,
78
+ workerPoolSize,
79
79
  selectRendezvousNode,
80
80
  checkLicense,
81
81
  checkForUpgrade,
@@ -127,7 +127,7 @@ const { packRpcError, unpackRpcError } = require('./lib/worker-rpc-error');
127
127
  const promClient = require('prom-client');
128
128
  const fs = require('fs').promises;
129
129
  const crypto = require('crypto');
130
- const { compare: cv } = require('compare-versions');
130
+ const { compareVersions, parseVersion } = require('./lib/utils/version');
131
131
  const Joi = require('joi');
132
132
  const { settingsSchema } = require('./lib/schemas');
133
133
  const settings = require('./lib/settings');
@@ -155,6 +155,7 @@ const {
155
155
  } = require('./lib/account-assignment');
156
156
  const { mapConcurrent } = require('./lib/utils/map-concurrent');
157
157
  const { RespawnTracker } = require('./lib/respawn-backoff');
158
+ const { heartbeatDiagnostics, eventLoopDelaySeries } = require('./lib/thread-diagnostics');
158
159
 
159
160
  const msgpack = require('./lib/msgpack');
160
161
 
@@ -225,16 +226,14 @@ const CONNECTION_SETUP_DELAY = getDuration(readEnvValue('EENGINE_CONNECTION_SETU
225
226
  config.api.maxSize = getByteSize(readEnvValue('EENGINE_MAX_SIZE') || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
226
227
  config.dbs.redis = readEnvValue('EENGINE_REDIS') || readEnvValue('REDIS_URL') || config.dbs.redis;
227
228
 
228
- config.workers.imap = getWorkerCount(readEnvValue('EENGINE_WORKERS') || config.workers.imap) || 4;
229
- config.workers.webhooks = Number(readEnvValue('EENGINE_WORKERS_WEBHOOKS')) || config.workers.webhooks || 1;
230
- config.workers.submit = Number(readEnvValue('EENGINE_WORKERS_SUBMIT')) || config.workers.submit || 1;
229
+ config.workers.imap = workerPoolSize(readEnvValue('EENGINE_WORKERS'), config.workers.imap, 4);
230
+ config.workers.webhooks = workerPoolSize(readEnvValue('EENGINE_WORKERS_WEBHOOKS'), config.workers.webhooks);
231
+ config.workers.submit = workerPoolSize(readEnvValue('EENGINE_WORKERS_SUBMIT'), config.workers.submit);
231
232
  // The Workers page has labelled this row EENGINE_WORKERS_EXPORT since the export worker shipped, while
232
233
  // only --workers.export and [workers] export were read, so an operator who set it saw no effect
233
- config.workers.export = Number(readEnvValue('EENGINE_WORKERS_EXPORT')) || config.workers.export || 1;
234
+ config.workers.export = workerPoolSize(readEnvValue('EENGINE_WORKERS_EXPORT'), config.workers.export);
234
235
  // API worker count. Values >1 require SO_REUSEPORT (Linux); on unsupported platforms it falls back to 1 at startup.
235
- // Uses getWorkerCount() for parity with EENGINE_WORKERS (supports "cpus"); Math.floor avoids a fractional
236
- // count over-spawning, Math.max keeps at least one API worker.
237
- config.workers.api = Math.max(1, Math.floor(getWorkerCount(readEnvValue('EENGINE_WORKERS_API') || config.workers.api)));
236
+ config.workers.api = workerPoolSize(readEnvValue('EENGINE_WORKERS_API'), config.workers.api);
238
237
 
239
238
  config.api.port =
240
239
  (hasEnvValue('EENGINE_PORT') && Number(readEnvValue('EENGINE_PORT'))) || (hasEnvValue('PORT') && Number(readEnvValue('PORT'))) || config.api.port;
@@ -664,6 +663,18 @@ const metrics = {
664
663
  help: 'Number of unresponsive worker threads'
665
664
  }),
666
665
 
666
+ threadEventLoopDelayMax: new promClient.Gauge({
667
+ name: 'thread_event_loop_delay_max_seconds',
668
+ help: 'Longest event loop delay of a thread over the last collection window (15s)',
669
+ labelNames: ['type', 'thread']
670
+ }),
671
+
672
+ threadEventLoopDelayP99: new promClient.Gauge({
673
+ name: 'thread_event_loop_delay_p99_seconds',
674
+ help: '99th percentile event loop delay of a thread over the last collection window (15s)',
675
+ labelNames: ['type', 'thread']
676
+ }),
677
+
667
678
  licenseDaysRemaining: new promClient.Gauge({
668
679
  name: 'license_days_remaining',
669
680
  help: 'Days until license expires (-1 for lifetime, 0 for no license)'
@@ -1003,12 +1014,29 @@ async function getThreadsInfo() {
1003
1014
  return threadsInfo;
1004
1015
  }
1005
1016
 
1017
+ /**
1018
+ * The heartbeat log fields for a thread, see lib/thread-diagnostics.js
1019
+ * @param {Worker} worker - The worker thread
1020
+ * @param {number} now - Current time in milliseconds
1021
+ * @param {number} [lastHeartbeat] - When the thread last reported in
1022
+ * @returns {Object} Fields to add to the log entry
1023
+ */
1024
+ function workerHeartbeatDiagnostics(worker, now, lastHeartbeat) {
1025
+ return heartbeatDiagnostics({
1026
+ now,
1027
+ lastHeartbeat,
1028
+ accounts: workerAssigned.get(worker)?.size,
1029
+ threadInfo: metricsCollector?.cachedThreadsInfo?.find(threadInfo => threadInfo.threadId === worker.threadId)
1030
+ });
1031
+ }
1032
+
1006
1033
  /**
1007
1034
  * Handle heartbeat from worker thread
1008
1035
  * @param {Worker} worker - The worker thread
1009
1036
  */
1010
1037
  function handleWorkerHeartbeat(worker) {
1011
1038
  const now = Date.now();
1039
+ const previousHeartbeat = workerHeartbeats.get(worker);
1012
1040
  workerHeartbeats.set(worker, now);
1013
1041
 
1014
1042
  // Mark as healthy if it was previously unhealthy
@@ -1017,7 +1045,9 @@ function handleWorkerHeartbeat(worker) {
1017
1045
  logger.info({
1018
1046
  msg: 'Worker recovered',
1019
1047
  threadId: worker.threadId,
1020
- type: workersMeta.get(worker)?.type
1048
+ type: workersMeta.get(worker)?.type,
1049
+ // timeSinceHeartbeat here is how long the thread was blocked
1050
+ ...workerHeartbeatDiagnostics(worker, now, previousHeartbeat)
1021
1051
  });
1022
1052
  }
1023
1053
  workerHealthStatus.set(worker, 'healthy');
@@ -1048,7 +1078,7 @@ async function checkWorkerHealth() {
1048
1078
  msg: 'Worker critically unresponsive, restarting',
1049
1079
  threadId: worker.threadId,
1050
1080
  type,
1051
- timeSinceHeartbeat: Math.round(timeSinceHeartbeat / 1000) + 's'
1081
+ ...workerHeartbeatDiagnostics(worker, now, lastHeartbeat)
1052
1082
  });
1053
1083
 
1054
1084
  workerHealthStatus.set(worker, 'restarting');
@@ -1070,7 +1100,7 @@ async function checkWorkerHealth() {
1070
1100
  msg: 'Worker unhealthy - no heartbeat',
1071
1101
  threadId: worker.threadId,
1072
1102
  type,
1073
- timeSinceHeartbeat: Math.round(timeSinceHeartbeat / 1000) + 's'
1103
+ ...workerHeartbeatDiagnostics(worker, now, lastHeartbeat)
1074
1104
  });
1075
1105
 
1076
1106
  workerHealthStatus.set(worker, 'unhealthy');
@@ -1115,7 +1145,7 @@ async function sendWebhook(account, event, data) {
1115
1145
  payload.data = data;
1116
1146
  }
1117
1147
 
1118
- await Webhooks.pushToQueue(event, await Webhooks.formatPayload(event, payload));
1148
+ await Webhooks.enqueue(event, payload);
1119
1149
  }
1120
1150
 
1121
1151
  /**
@@ -2069,7 +2099,9 @@ let licenseCheckHandler = async opts => {
2069
2099
  // Check if we need to validate the license
2070
2100
  let kv = await redis.hget(`${REDIS_PREFIX}settings`, 'kv');
2071
2101
  let checkKv = true;
2072
- if (kv && typeof kv === 'string' && cv(packageData.version, Buffer.from(kv, 'hex').toString(), '<=')) {
2102
+ // an unreadable record means checking again, which also rewrites it
2103
+ let validatedVersion = kv && typeof kv === 'string' ? Buffer.from(kv, 'hex').toString() : null;
2104
+ if (parseVersion(validatedVersion) && compareVersions(packageData.version, validatedVersion) <= 0) {
2073
2105
  checkKv = false;
2074
2106
  }
2075
2107
 
@@ -2424,6 +2456,13 @@ async function updateQueueCounters() {
2424
2456
 
2425
2457
  let threadCounts = new Map();
2426
2458
  let unresponsiveCount = 0;
2459
+ // a replaced thread leaves with its thread id, so the series are rebuilt on every update
2460
+ metrics.threadEventLoopDelayMax.reset();
2461
+ metrics.threadEventLoopDelayP99.reset();
2462
+ for (let { labels, max, p99 } of eventLoopDelaySeries(threadsInfo)) {
2463
+ metrics.threadEventLoopDelayMax.set(labels, max);
2464
+ metrics.threadEventLoopDelayP99.set(labels, p99);
2465
+ }
2427
2466
  for (let workerThreadInfo of threadsInfo || []) {
2428
2467
  let key = workerThreadInfo.type;
2429
2468
  let metricKey = `${key}_total`;
@@ -2618,468 +2657,504 @@ async function withRequestDeadline(message, run) {
2618
2657
  }
2619
2658
  }
2620
2659
 
2621
- async function onCommand(worker, message) {
2622
- switch (message.cmd) {
2623
- case 'metrics':
2624
- // Return Prometheus metrics
2625
- await updateQueueCounters();
2626
- return promClient.register.metrics();
2627
-
2628
- case 'structuredMetrics': {
2629
- // Return structured metrics for API
2630
- let connections = {};
2631
-
2632
- for (let key of Object.keys(metrics.imapConnections.hashMap)) {
2633
- if (key.indexOf('status:') === 0) {
2634
- let metric = metrics.imapConnections.hashMap[key];
2635
- connections[metric.labels.status] = metric.value;
2636
- }
2637
- }
2660
+ // Handlers for the commands workers send to the main thread, dispatched by onCommand(). A command
2661
+ // with no handler, and a handler that answers NOT_HANDLED, both reply with 999
2662
+ const NOT_HANDLED = 999;
2638
2663
 
2639
- return { connections, redisPing: await getRedisPing() };
2640
- }
2664
+ async function commandMetrics() {
2665
+ // Return Prometheus metrics
2666
+ await updateQueueCounters();
2667
+ return promClient.register.metrics();
2668
+ }
2669
+
2670
+ async function commandStructuredMetrics() {
2671
+ // Return structured metrics for API
2672
+ let connections = {};
2641
2673
 
2642
- case 'imapWorkerCount': {
2643
- // Return number of available IMAP workers
2644
- return { workers: availableIMAPWorkers.size };
2674
+ for (let key of Object.keys(metrics.imapConnections.hashMap)) {
2675
+ if (key.indexOf('status:') === 0) {
2676
+ let metric = metrics.imapConnections.hashMap[key];
2677
+ connections[metric.labels.status] = metric.value;
2645
2678
  }
2679
+ }
2646
2680
 
2647
- case 'checkLicense':
2648
- // Force license check
2649
- try {
2650
- await licenseCheckHandler({
2651
- subscriptionCheckTimeout: 60 * 1000
2652
- });
2653
- } catch (err) {
2654
- // ignore
2655
- }
2656
- return licenseInfo;
2681
+ return { connections, redisPing: await getRedisPing() };
2682
+ }
2657
2683
 
2658
- case 'license':
2659
- // Return license info with suspension status
2660
- if (!licenseInfo.active && suspendedWorkerTypes.size) {
2661
- return Object.assign({}, licenseInfo, { suspended: true });
2662
- }
2663
- return licenseInfo;
2684
+ async function commandImapWorkerCount() {
2685
+ // Return number of available IMAP workers
2686
+ return { workers: availableIMAPWorkers.size };
2687
+ }
2664
2688
 
2665
- case 'updateLicense': {
2666
- // Update license from API
2667
- try {
2668
- const licenseFile = message.license;
2689
+ async function commandCheckLicense() {
2690
+ // Force license check
2691
+ try {
2692
+ await licenseCheckHandler({
2693
+ subscriptionCheckTimeout: 60 * 1000
2694
+ });
2695
+ } catch (err) {
2696
+ // ignore
2697
+ }
2698
+ return licenseInfo;
2699
+ }
2669
2700
 
2670
- let licenseData = await checkLicense(licenseFile);
2671
- if (!licenseData) {
2672
- throw new Error('Invalid license provided');
2673
- }
2701
+ async function commandLicense() {
2702
+ // Return license info with suspension status
2703
+ if (!licenseInfo.active && suspendedWorkerTypes.size) {
2704
+ return Object.assign({}, licenseInfo, { suspended: true });
2705
+ }
2706
+ return licenseInfo;
2707
+ }
2674
2708
 
2675
- logger.info({ msg: 'License updated', license: redactLicense(licenseData), source: 'API' });
2709
+ async function commandUpdateLicense(worker, message) {
2710
+ // Update license from API
2711
+ try {
2712
+ const licenseFile = message.license;
2676
2713
 
2677
- await setLicense(licenseData, licenseFile);
2714
+ let licenseData = await checkLicense(licenseFile);
2715
+ if (!licenseData) {
2716
+ throw new Error('Invalid license provided');
2717
+ }
2678
2718
 
2679
- licenseInfo.active = true;
2680
- licenseInfo.details = licenseData;
2681
- licenseInfo.type = 'EmailEngine License';
2719
+ logger.info({ msg: 'License updated', license: redactLicense(licenseData), source: 'API' });
2682
2720
 
2683
- // Re-enable workers
2684
- checkActiveLicense();
2721
+ await setLicense(licenseData, licenseFile);
2685
2722
 
2686
- return licenseInfo;
2687
- } catch (err) {
2688
- logger.warn({ msg: 'License update failed', source: 'API', err });
2689
- return false;
2690
- }
2691
- }
2723
+ licenseInfo.active = true;
2724
+ licenseInfo.details = licenseData;
2725
+ licenseInfo.type = 'EmailEngine License';
2692
2726
 
2693
- case 'removeLicense': {
2694
- // Remove existing license
2695
- try {
2696
- await settings.removeLicense();
2727
+ // Re-enable workers
2728
+ checkActiveLicense();
2729
+
2730
+ return licenseInfo;
2731
+ } catch (err) {
2732
+ logger.warn({ msg: 'License update failed', source: 'API', err });
2733
+ return false;
2734
+ }
2735
+ }
2697
2736
 
2698
- licenseInfo.active = false;
2699
- licenseInfo.details = false;
2700
- licenseInfo.type = packageData.license;
2737
+ async function commandRemoveLicense() {
2738
+ // Remove existing license
2739
+ try {
2740
+ await settings.removeLicense();
2701
2741
 
2702
- return licenseInfo;
2703
- } catch (err) {
2704
- logger.error({ msg: 'License removal failed', err });
2705
- return false;
2706
- }
2707
- }
2742
+ licenseInfo.active = false;
2743
+ licenseInfo.details = false;
2744
+ licenseInfo.type = packageData.license;
2708
2745
 
2709
- case 'kill-thread': {
2710
- // Terminate a specific thread
2711
- for (let [, workerSet] of workers) {
2712
- if (workerSet && workerSet.size) {
2713
- for (let worker of workerSet) {
2714
- if (worker.threadId === message.thread) {
2715
- logger.info({ msg: 'Thread termination requested', thread: message.thread });
2716
- return await worker.terminate();
2717
- }
2718
- }
2746
+ return licenseInfo;
2747
+ } catch (err) {
2748
+ logger.error({ msg: 'License removal failed', err });
2749
+ return false;
2750
+ }
2751
+ }
2752
+
2753
+ async function commandKillThread(worker, message) {
2754
+ // Terminate a specific thread
2755
+ for (let [, workerSet] of workers) {
2756
+ if (workerSet && workerSet.size) {
2757
+ for (let worker of workerSet) {
2758
+ if (worker.threadId === message.thread) {
2759
+ logger.info({ msg: 'Thread termination requested', thread: message.thread });
2760
+ return await worker.terminate();
2719
2761
  }
2720
2762
  }
2721
-
2722
- return false;
2723
2763
  }
2764
+ }
2724
2765
 
2725
- case 'snapshot-thread': {
2726
- // Get heap snapshot for debugging
2727
- if (message.thread === 0) {
2728
- // Main thread only - V8 operations should be done in main thread
2729
- try {
2730
- logger.info({ msg: 'Heap snapshot requested', thread: message.thread });
2731
- const stream = v8.getHeapSnapshot();
2732
- if (stream) {
2733
- return { _transfer: true, _response: await download(stream) };
2734
- }
2735
- } catch (err) {
2736
- logger.error({ msg: 'Failed to generate heap snapshot', thread: message.thread, err });
2737
- }
2738
- return false;
2766
+ return false;
2767
+ }
2768
+
2769
+ async function commandSnapshotThread(worker, message) {
2770
+ // Get heap snapshot for debugging
2771
+ if (message.thread === 0) {
2772
+ // Main thread only - V8 operations should be done in main thread
2773
+ try {
2774
+ logger.info({ msg: 'Heap snapshot requested', thread: message.thread });
2775
+ const stream = v8.getHeapSnapshot();
2776
+ if (stream) {
2777
+ return { _transfer: true, _response: await download(stream) };
2739
2778
  }
2779
+ } catch (err) {
2780
+ logger.error({ msg: 'Failed to generate heap snapshot', thread: message.thread, err });
2781
+ }
2782
+ return false;
2783
+ }
2740
2784
 
2741
- // Worker thread - use worker's built-in method which is safer
2742
- for (let [, workerSet] of workers) {
2743
- if (workerSet && workerSet.size) {
2744
- for (let worker of workerSet) {
2745
- if (worker.threadId === message.thread) {
2746
- try {
2747
- logger.info({ msg: 'Heap snapshot requested', thread: message.thread });
2748
- // Use worker's built-in getHeapSnapshot method instead of V8 API
2749
- const stream = await worker.getHeapSnapshot({ exposeInternals: true, exposeNumericValues: true });
2750
- if (stream) {
2751
- return { _transfer: true, _response: await download(stream) };
2752
- }
2753
- } catch (err) {
2754
- logger.error({ msg: 'Failed to generate heap snapshot for worker', thread: message.thread, err });
2755
- }
2756
- return false;
2785
+ // Worker thread - use worker's built-in method which is safer
2786
+ for (let [, workerSet] of workers) {
2787
+ if (workerSet && workerSet.size) {
2788
+ for (let worker of workerSet) {
2789
+ if (worker.threadId === message.thread) {
2790
+ try {
2791
+ logger.info({ msg: 'Heap snapshot requested', thread: message.thread });
2792
+ // Use worker's built-in getHeapSnapshot method instead of V8 API
2793
+ const stream = await worker.getHeapSnapshot({ exposeInternals: true, exposeNumericValues: true });
2794
+ if (stream) {
2795
+ return { _transfer: true, _response: await download(stream) };
2757
2796
  }
2797
+ } catch (err) {
2798
+ logger.error({ msg: 'Failed to generate heap snapshot for worker', thread: message.thread, err });
2758
2799
  }
2800
+ return false;
2759
2801
  }
2760
2802
  }
2761
-
2762
- return false;
2763
2803
  }
2804
+ }
2764
2805
 
2765
- case 'bounceClassify':
2766
- // Classify bounce response message
2767
- try {
2768
- return await bounceClassifier.classify(message.data.message);
2769
- } catch (err) {
2770
- // ignore
2771
- logger.warn({
2772
- msg: 'Failed to classify bounce response',
2773
- bounceResponse: message.data.message,
2774
- err
2775
- });
2776
- }
2777
- return false;
2806
+ return false;
2807
+ }
2778
2808
 
2779
- // OpenAI integration commands - run in the main process, where the metrics live
2780
- case 'generateSummary': {
2781
- const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
2782
- requestOpts.user = message.data.account;
2809
+ async function commandBounceClassify(worker, message) {
2810
+ // Classify bounce response message
2811
+ try {
2812
+ return await bounceClassifier.classify(message.data.message);
2813
+ } catch (err) {
2814
+ // ignore
2815
+ logger.warn({
2816
+ msg: 'Failed to classify bounce response',
2817
+ bounceResponse: message.data.message,
2818
+ err
2819
+ });
2820
+ }
2821
+ return false;
2822
+ }
2783
2823
 
2784
- // the configuration page's test runs are not production traffic
2785
- const counted = !message.data.options;
2786
- const model = requestOpts.gptModel;
2824
+ // OpenAI integration commands - run in the main process, where the metrics live
2825
+ async function commandGenerateSummary(worker, message) {
2826
+ const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
2827
+ requestOpts.user = message.data.account;
2787
2828
 
2788
- try {
2789
- const response = await withRequestDeadline(message, signal =>
2790
- generateSummary(message.data.message, openAiAPIKey, Object.assign(requestOpts, { signal }))
2791
- );
2792
- const { usage } = response;
2829
+ // the configuration page's test runs are not production traffic
2830
+ const counted = !message.data.options;
2831
+ const model = requestOpts.gptModel;
2793
2832
 
2794
- // the fitted email text the verbose mode adds stays out of the RPC and the log
2795
- delete usage.text;
2833
+ try {
2834
+ const response = await withRequestDeadline(message, signal =>
2835
+ generateSummary(message.data.message, openAiAPIKey, Object.assign(requestOpts, { signal }))
2836
+ );
2837
+ const { usage } = response;
2796
2838
 
2797
- if (counted) {
2798
- metrics.aiRequests.inc({ model, status: 'success' });
2799
- for (const type of ['prompt', 'completion']) {
2800
- const tokens = usage[`${type}Tokens`];
2801
- if (tokens) {
2802
- metrics.aiTokens.inc({ model, type }, tokens);
2803
- }
2804
- }
2805
- }
2839
+ // the fitted email text the verbose mode adds stays out of the RPC and the log
2840
+ delete usage.text;
2806
2841
 
2807
- return response;
2808
- } catch (err) {
2809
- if (counted) {
2810
- metrics.aiRequests.inc({ model, status: 'failure' });
2842
+ if (counted) {
2843
+ metrics.aiRequests.inc({ model, status: 'success' });
2844
+ for (const type of ['prompt', 'completion']) {
2845
+ const tokens = usage[`${type}Tokens`];
2846
+ if (tokens) {
2847
+ metrics.aiTokens.inc({ model, type }, tokens);
2811
2848
  }
2812
- throw err;
2813
2849
  }
2814
2850
  }
2815
2851
 
2816
- case 'openAiListModels': {
2817
- const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
2818
- return await withRequestDeadline(message, signal => openAiListModels(openAiAPIKey, Object.assign(requestOpts, { signal })));
2852
+ return response;
2853
+ } catch (err) {
2854
+ if (counted) {
2855
+ metrics.aiRequests.inc({ model, status: 'failure' });
2819
2856
  }
2857
+ throw err;
2858
+ }
2859
+ }
2820
2860
 
2821
- case 'threads': {
2822
- return await getThreadsInfo();
2823
- }
2861
+ async function commandOpenAiListModels(worker, message) {
2862
+ const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
2863
+ return await withRequestDeadline(message, signal => openAiListModels(openAiAPIKey, Object.assign(requestOpts, { signal })));
2864
+ }
2824
2865
 
2825
- case 'apiWorkerScaling': {
2826
- // Reported on /admin/internals so operators can see when EENGINE_WORKERS_API > 1
2827
- // was requested but only one worker started, and why (reason: 'platform' | 'port').
2828
- return {
2829
- requested: apiWorkersRequested,
2830
- fallback: apiWorkersRequested > 1 && !apiWorkerReusePort,
2831
- reason: apiWorkerReusePortFallbackReason
2832
- };
2833
- }
2866
+ async function commandThreads() {
2867
+ return await getThreadsInfo();
2868
+ }
2834
2869
 
2835
- case 'worker-accounts': {
2836
- // Get accounts assigned to a specific worker thread
2837
- const { threadId, page = 1, pageSize = 20 } = message;
2838
- const accounts = [];
2870
+ async function commandApiWorkerScaling() {
2871
+ // Reported on /admin/internals so operators can see when EENGINE_WORKERS_API > 1
2872
+ // was requested but only one worker started, and why (reason: 'platform' | 'port').
2873
+ return {
2874
+ requested: apiWorkersRequested,
2875
+ fallback: apiWorkersRequested > 1 && !apiWorkerReusePort,
2876
+ reason: apiWorkerReusePortFallbackReason
2877
+ };
2878
+ }
2839
2879
 
2840
- // Find worker by threadId and get its assigned accounts
2841
- for (const [account, worker] of assigned) {
2842
- if (worker.threadId === threadId) {
2843
- accounts.push(account);
2844
- }
2845
- }
2880
+ async function commandWorkerAccounts(worker, message) {
2881
+ // Get accounts assigned to a specific worker thread
2882
+ const { threadId, page = 1, pageSize = 20 } = message;
2883
+ const accounts = [];
2846
2884
 
2847
- // Sort accounts for consistent ordering
2848
- accounts.sort((a, b) => a.localeCompare(b));
2849
-
2850
- // Paginate
2851
- const totalAccounts = accounts.length;
2852
- const totalPages = Math.ceil(totalAccounts / pageSize) || 1;
2853
- const currentPage = Math.min(Math.max(1, page), totalPages);
2854
- const start = (currentPage - 1) * pageSize;
2855
- const pagedAccounts = accounts.slice(start, start + pageSize);
2856
-
2857
- return {
2858
- accounts: pagedAccounts,
2859
- total: totalAccounts,
2860
- page: currentPage,
2861
- pageSize,
2862
- pages: totalPages
2863
- };
2885
+ // Find worker by threadId and get its assigned accounts
2886
+ for (const [account, worker] of assigned) {
2887
+ if (worker.threadId === threadId) {
2888
+ accounts.push(account);
2864
2889
  }
2890
+ }
2865
2891
 
2866
- case 'rate-limit': {
2867
- return await checkRateLimit(message.key, message.count, message.allowed, message.windowSize);
2868
- }
2892
+ // Sort accounts for consistent ordering
2893
+ accounts.sort((a, b) => a.localeCompare(b));
2869
2894
 
2870
- case 'unsubscribe':
2871
- // Handle list unsubscribe
2872
- sendWebhook(message.account, LIST_UNSUBSCRIBE_NOTIFY, message.payload).catch(err =>
2873
- logger.error({ msg: 'Unsubscribe webhook failed', account: message.account, err })
2874
- );
2875
- return;
2895
+ // Paginate
2896
+ const totalAccounts = accounts.length;
2897
+ const totalPages = Math.ceil(totalAccounts / pageSize) || 1;
2898
+ const currentPage = Math.min(Math.max(1, page), totalPages);
2899
+ const start = (currentPage - 1) * pageSize;
2900
+ const pagedAccounts = accounts.slice(start, start + pageSize);
2876
2901
 
2877
- case 'subscribe':
2878
- // Handle list subscribe
2879
- sendWebhook(message.account, LIST_SUBSCRIBE_NOTIFY, message.payload).catch(err =>
2880
- logger.error({ msg: 'Subscribe webhook failed', account: message.account, err })
2881
- );
2882
- return;
2902
+ return {
2903
+ accounts: pagedAccounts,
2904
+ total: totalAccounts,
2905
+ page: currentPage,
2906
+ pageSize,
2907
+ pages: totalPages
2908
+ };
2909
+ }
2883
2910
 
2884
- case 'new':
2885
- // Handle new account.
2886
- //
2887
- // `unassigned` is `false` until assignAccounts() loads the account list from Redis on
2888
- // its first run, which waits for an IMAP worker to report ready. An account created
2889
- // before that used to throw here and fail the request with a 500. Skipping the add is
2890
- // safe rather than merely quiet: the account is already in `ia:accounts` by the time
2891
- // this message is sent, so the first load picks it up.
2892
- if (unassigned) {
2893
- unassigned.add(message.account);
2894
- }
2895
- assignAccounts()
2896
- .then(() => sendWebhook(message.account, ACCOUNT_ADDED_NOTIFY, { account: message.account }))
2897
- .catch(err => logger.error({ msg: 'Account assignment failed', err }));
2898
- return;
2911
+ async function commandRateLimit(worker, message) {
2912
+ return await checkRateLimit(message.key, message.count, message.allowed, message.windowSize);
2913
+ }
2899
2914
 
2900
- case 'delete':
2901
- // Handle account deletion
2902
- //
2903
- // Guarded for the same reason as the `new` branch above, and here the throw was
2904
- // answered with a 500 for a deletion that had in fact succeeded: the account was
2905
- // already gone from Redis by the time this message was sent.
2906
- {
2907
- let assignedWorker = forgetAccount({ workerAssigned, assigned, unassigned }, message.account);
2908
- if (assignedWorker) {
2909
- // Notify worker to clean up
2910
- call(assignedWorker, message)
2911
- .then(() => logger.debug('Account cleanup completed'))
2912
- .catch(err => logger.error({ msg: 'Account cleanup failed', account: message.account, err }));
2913
- }
2914
- }
2915
- sendWebhook(message.account, ACCOUNT_DELETED_NOTIFY, { account: message.account }).catch(err =>
2916
- logger.error({ msg: 'Account deletion webhook failed', account: message.account, err })
2917
- );
2918
- return;
2915
+ async function commandUnsubscribe(worker, message) {
2916
+ // Handle list unsubscribe
2917
+ sendWebhook(message.account, LIST_UNSUBSCRIBE_NOTIFY, message.payload).catch(err =>
2918
+ logger.error({ msg: 'Unsubscribe webhook failed', account: message.account, err })
2919
+ );
2920
+ }
2919
2921
 
2920
- case 'runIndex': {
2921
- return runIndex;
2922
- }
2923
-
2924
- case 'update':
2925
- case 'sync':
2926
- case 'pause':
2927
- case 'resume':
2928
- case 'reconnect':
2929
- // Forward to assigned worker
2930
- if (assigned.has(message.account)) {
2931
- let assignedWorker = assigned.get(message.account);
2932
- call(assignedWorker, message)
2933
- .then(() => logger.debug('Worker command completed'))
2934
- .catch(err => logger.error({ msg: 'Worker command failed', account: message.account, cmd: message.cmd, err }));
2935
- }
2936
- return;
2922
+ async function commandSubscribe(worker, message) {
2923
+ // Handle list subscribe
2924
+ sendWebhook(message.account, LIST_SUBSCRIBE_NOTIFY, message.payload).catch(err =>
2925
+ logger.error({ msg: 'Subscribe webhook failed', account: message.account, err })
2926
+ );
2927
+ }
2937
2928
 
2938
- case 'smtpReload':
2939
- case 'imapProxyReload':
2940
- {
2941
- // Reload proxy server
2942
- let type = message.cmd.replace(/Reload$/, '');
2943
- let hasWorkers = workers.has(type) && workers.get(type).size;
2944
- if (hasWorkers) {
2945
- // Kill existing workers
2946
- for (let worker of workers.get(type).values()) {
2947
- worker.terminate();
2948
- }
2949
- } else {
2950
- // Spawn new worker if enabled
2951
- let serverEnabled = await settings.get(`${type}ServerEnabled`);
2952
- if (serverEnabled) {
2953
- await spawnWorker(type);
2954
- }
2955
- }
2956
- }
2957
- break;
2929
+ async function commandNewAccount(worker, message) {
2930
+ // Handle new account.
2931
+ //
2932
+ // `unassigned` is `false` until assignAccounts() loads the account list from Redis on
2933
+ // its first run, which waits for an IMAP worker to report ready. An account created
2934
+ // before that used to throw here and fail the request with a 500. Skipping the add is
2935
+ // safe rather than merely quiet: the account is already in `ia:accounts` by the time
2936
+ // this message is sent, so the first load picks it up.
2937
+ if (unassigned) {
2938
+ unassigned.add(message.account);
2939
+ }
2940
+ assignAccounts()
2941
+ .then(() => sendWebhook(message.account, ACCOUNT_ADDED_NOTIFY, { account: message.account }))
2942
+ .catch(err => logger.error({ msg: 'Account assignment failed', err }));
2943
+ }
2958
2944
 
2959
- case 'apiReloadCertificates':
2960
- case 'smtpReloadCertificates':
2961
- case 'imapProxyReloadCertificates':
2962
- {
2963
- // A renewed certificate, handed to a running listener. Forwarded to the worker
2964
- // rather than terminating it: a restart would cut every session in flight, and
2965
- // every listener can swap its secure context between handshakes. Sent to every
2966
- // worker of the type, not just the one that ordered the certificate: the
2967
- // reconciler is a singleton but the listeners are not.
2968
- let type = message.cmd.replace(/ReloadCertificates$/, '');
2969
- for (let worker of (workers.get(type) || new Set()).values()) {
2970
- call(worker, message).catch(err => logger.error({ msg: 'Failed to reload certificates', type, worker: worker.threadId, err }));
2971
- }
2972
- }
2973
- break;
2974
-
2975
- // IMAP operations - forward to assigned worker
2976
- case 'submitMessage':
2977
- case 'queueMessage':
2978
- case 'listMessages':
2979
- case 'getRawMessage':
2980
- case 'getText':
2981
- case 'getMessage':
2982
- case 'getMessages':
2983
- case 'updateMessage':
2984
- case 'updateMessages':
2985
- case 'listMailboxes':
2986
- case 'moveMessage':
2987
- case 'moveMessages':
2988
- case 'deleteMessage':
2989
- case 'deleteMessages':
2990
- case 'getQuota':
2991
- case 'createMailbox':
2992
- case 'modifyMailbox':
2993
- case 'deleteMailbox':
2994
- case 'uploadMessage':
2995
- case 'getAttachment':
2996
- case 'listSignatures': {
2997
- if (!assigned.has(message.account)) {
2998
- throw NO_ACTIVE_HANDLER_RESP_ERR;
2999
- }
2945
+ async function commandDeleteAccount(worker, message) {
2946
+ // Handle account deletion
2947
+ //
2948
+ // Guarded for the same reason as commandNewAccount() above, and here the throw was
2949
+ // answered with a 500 for a deletion that had in fact succeeded: the account was
2950
+ // already gone from Redis by the time this message was sent.
2951
+ let assignedWorker = forgetAccount({ workerAssigned, assigned, unassigned }, message.account);
2952
+ if (assignedWorker) {
2953
+ // Notify worker to clean up
2954
+ call(assignedWorker, message)
2955
+ .then(() => logger.debug('Account cleanup completed'))
2956
+ .catch(err => logger.error({ msg: 'Account cleanup failed', account: message.account, err }));
2957
+ }
2958
+ sendWebhook(message.account, ACCOUNT_DELETED_NOTIFY, { account: message.account }).catch(err =>
2959
+ logger.error({ msg: 'Account deletion webhook failed', account: message.account, err })
2960
+ );
2961
+ }
3000
2962
 
3001
- let assignedWorker = assigned.get(message.account);
2963
+ async function commandRunIndex() {
2964
+ return runIndex;
2965
+ }
3002
2966
 
3003
- let transferList = [];
3004
- // Handle transferable objects
3005
- if (['getRawMessage', 'getAttachment'].includes(message.cmd) && message.port) {
3006
- transferList.push(message.port);
3007
- }
3008
- if (['submitMessage', 'queueMessage'].includes(message.cmd) && typeof message.raw === 'object') {
3009
- transferList.push(message.raw);
3010
- }
2967
+ async function commandForwardToAccountWorker(worker, message) {
2968
+ // Forward to assigned worker
2969
+ if (assigned.has(message.account)) {
2970
+ let assignedWorker = assigned.get(message.account);
2971
+ call(assignedWorker, message)
2972
+ .then(() => logger.debug('Worker command completed'))
2973
+ .catch(err => logger.error({ msg: 'Worker command failed', account: message.account, cmd: message.cmd, err }));
2974
+ }
2975
+ }
3011
2976
 
3012
- return await call(assignedWorker, message, transferList);
2977
+ async function commandReloadServer(worker, message) {
2978
+ // Reload proxy server
2979
+ let type = message.cmd.replace(/Reload$/, '');
2980
+ let hasWorkers = workers.has(type) && workers.get(type).size;
2981
+ if (hasWorkers) {
2982
+ // Kill existing workers
2983
+ for (let worker of workers.get(type).values()) {
2984
+ worker.terminate();
3013
2985
  }
2986
+ } else {
2987
+ // Spawn new worker if enabled
2988
+ let serverEnabled = await settings.get(`${type}ServerEnabled`);
2989
+ if (serverEnabled) {
2990
+ await spawnWorker(type);
2991
+ }
2992
+ }
2993
+ return NOT_HANDLED;
2994
+ }
3014
2995
 
3015
- case 'subconnections': {
3016
- // Get submission connections
3017
- if (!assigned.has(message.account)) {
3018
- return [];
3019
- }
2996
+ async function commandReloadCertificates(worker, message) {
2997
+ // A renewed certificate, handed to a running listener. Forwarded to the worker
2998
+ // rather than terminating it: a restart would cut every session in flight, and
2999
+ // every listener can swap its secure context between handshakes. Sent to every
3000
+ // worker of the type, not just the one that ordered the certificate: the
3001
+ // reconciler is a singleton but the listeners are not.
3002
+ let type = message.cmd.replace(/ReloadCertificates$/, '');
3003
+ for (let worker of (workers.get(type) || new Set()).values()) {
3004
+ call(worker, message).catch(err => logger.error({ msg: 'Failed to reload certificates', type, worker: worker.threadId, err }));
3005
+ }
3006
+ return NOT_HANDLED;
3007
+ }
3020
3008
 
3021
- let assignedWorker = assigned.get(message.account);
3022
- return await call(assignedWorker, message, []);
3023
- }
3009
+ // IMAP operations - forward to assigned worker
3010
+ async function commandAccountOperation(worker, message) {
3011
+ if (!assigned.has(message.account)) {
3012
+ throw NO_ACTIVE_HANDLER_RESP_ERR;
3013
+ }
3024
3014
 
3025
- case 'googlePubSub':
3026
- case 'googlePubSubRemove': {
3027
- // Notify all webhook workers about PubSub app changes
3028
- if (!workers.has('webhooks')) {
3029
- return true;
3030
- }
3031
- let proms = [];
3032
- for (let worker of workers.get('webhooks')) {
3033
- proms.push(
3034
- call(worker, message).catch(err => {
3035
- logger.error({ msg: 'Failed to notify webhook worker about PubSub change', cmd: message.cmd, err });
3036
- })
3037
- );
3038
- }
3039
- await Promise.all(proms);
3040
- return true;
3041
- }
3015
+ let assignedWorker = assigned.get(message.account);
3042
3016
 
3043
- case 'externalNotify': {
3044
- // External notification (e.g., Google Push)
3045
- let proms = [];
3046
- for (let account of message.accounts || []) {
3047
- if (!assigned.has(account)) {
3048
- continue;
3049
- }
3017
+ let transferList = [];
3018
+ // Handle transferable objects
3019
+ if (['getRawMessage', 'getAttachment'].includes(message.cmd) && message.port) {
3020
+ transferList.push(message.port);
3021
+ }
3022
+ if (['submitMessage', 'queueMessage'].includes(message.cmd) && typeof message.raw === 'object') {
3023
+ transferList.push(message.raw);
3024
+ }
3050
3025
 
3051
- let assignedWorker = assigned.get(account);
3052
- proms.push(
3053
- call(assignedWorker, { cmd: 'externalNotify', account, historyId: message.historyId }).catch(err => {
3054
- logger.error({ msg: 'External notification failed', cmd: 'externalNotify', account, historyId: message.historyId, err });
3055
- })
3056
- );
3057
- }
3058
- await Promise.all(proms);
3059
- return true;
3060
- }
3026
+ return await call(assignedWorker, message, transferList);
3027
+ }
3061
3028
 
3062
- case 'subscriptionLifecycle': {
3063
- // MS Graph subscription lifecycle event (reauthorizationRequired, subscriptionRemoved)
3064
- if (!assigned.has(message.account)) {
3065
- logger.warn({
3066
- msg: 'Subscription lifecycle event for unassigned account',
3067
- account: message.account,
3068
- event: message.event
3069
- });
3070
- return false;
3071
- }
3072
- let assignedWorker = assigned.get(message.account);
3073
- return await call(assignedWorker, {
3074
- cmd: 'subscriptionLifecycle',
3075
- account: message.account,
3076
- event: message.event,
3077
- timeout: message.timeout
3078
- });
3029
+ async function commandSubconnections(worker, message) {
3030
+ // Get submission connections
3031
+ if (!assigned.has(message.account)) {
3032
+ return [];
3033
+ }
3034
+
3035
+ let assignedWorker = assigned.get(message.account);
3036
+ return await call(assignedWorker, message, []);
3037
+ }
3038
+
3039
+ async function commandGooglePubSub(worker, message) {
3040
+ // Notify all webhook workers about PubSub app changes
3041
+ if (!workers.has('webhooks')) {
3042
+ return true;
3043
+ }
3044
+ let proms = [];
3045
+ for (let worker of workers.get('webhooks')) {
3046
+ proms.push(
3047
+ call(worker, message).catch(err => {
3048
+ logger.error({ msg: 'Failed to notify webhook worker about PubSub change', cmd: message.cmd, err });
3049
+ })
3050
+ );
3051
+ }
3052
+ await Promise.all(proms);
3053
+ return true;
3054
+ }
3055
+
3056
+ async function commandExternalNotify(worker, message) {
3057
+ // External notification (e.g., Google Push)
3058
+ let proms = [];
3059
+ for (let account of message.accounts || []) {
3060
+ if (!assigned.has(account)) {
3061
+ continue;
3079
3062
  }
3063
+
3064
+ let assignedWorker = assigned.get(account);
3065
+ proms.push(
3066
+ call(assignedWorker, { cmd: 'externalNotify', account, historyId: message.historyId }).catch(err => {
3067
+ logger.error({ msg: 'External notification failed', cmd: 'externalNotify', account, historyId: message.historyId, err });
3068
+ })
3069
+ );
3080
3070
  }
3071
+ await Promise.all(proms);
3072
+ return true;
3073
+ }
3081
3074
 
3082
- return 999;
3075
+ async function commandSubscriptionLifecycle(worker, message) {
3076
+ // MS Graph subscription lifecycle event (reauthorizationRequired, subscriptionRemoved)
3077
+ if (!assigned.has(message.account)) {
3078
+ logger.warn({
3079
+ msg: 'Subscription lifecycle event for unassigned account',
3080
+ account: message.account,
3081
+ event: message.event
3082
+ });
3083
+ return false;
3084
+ }
3085
+ let assignedWorker = assigned.get(message.account);
3086
+ return await call(assignedWorker, {
3087
+ cmd: 'subscriptionLifecycle',
3088
+ account: message.account,
3089
+ event: message.event,
3090
+ timeout: message.timeout
3091
+ });
3092
+ }
3093
+
3094
+ // A Map rather than an object literal, so a command name like `constructor` or `__proto__` is an
3095
+ // unknown command and not an inherited property
3096
+ const COMMAND_HANDLERS = new Map([
3097
+ ['metrics', commandMetrics],
3098
+ ['structuredMetrics', commandStructuredMetrics],
3099
+ ['imapWorkerCount', commandImapWorkerCount],
3100
+ ['checkLicense', commandCheckLicense],
3101
+ ['license', commandLicense],
3102
+ ['updateLicense', commandUpdateLicense],
3103
+ ['removeLicense', commandRemoveLicense],
3104
+ ['kill-thread', commandKillThread],
3105
+ ['snapshot-thread', commandSnapshotThread],
3106
+ ['bounceClassify', commandBounceClassify],
3107
+ ['generateSummary', commandGenerateSummary],
3108
+ ['openAiListModels', commandOpenAiListModels],
3109
+ ['threads', commandThreads],
3110
+ ['apiWorkerScaling', commandApiWorkerScaling],
3111
+ ['worker-accounts', commandWorkerAccounts],
3112
+ ['rate-limit', commandRateLimit],
3113
+ ['unsubscribe', commandUnsubscribe],
3114
+ ['subscribe', commandSubscribe],
3115
+ ['new', commandNewAccount],
3116
+ ['delete', commandDeleteAccount],
3117
+ ['runIndex', commandRunIndex],
3118
+ ...['update', 'sync', 'pause', 'resume', 'reconnect'].map(cmd => [cmd, commandForwardToAccountWorker]),
3119
+ ...['smtpReload', 'imapProxyReload'].map(cmd => [cmd, commandReloadServer]),
3120
+ ...['apiReloadCertificates', 'smtpReloadCertificates', 'imapProxyReloadCertificates'].map(cmd => [cmd, commandReloadCertificates]),
3121
+ ...[
3122
+ 'submitMessage',
3123
+ 'queueMessage',
3124
+ 'listMessages',
3125
+ 'getRawMessage',
3126
+ 'getText',
3127
+ 'getMessage',
3128
+ 'getMessages',
3129
+ 'updateMessage',
3130
+ 'updateMessages',
3131
+ 'listMailboxes',
3132
+ 'moveMessage',
3133
+ 'moveMessages',
3134
+ 'deleteMessage',
3135
+ 'deleteMessages',
3136
+ 'getQuota',
3137
+ 'createMailbox',
3138
+ 'modifyMailbox',
3139
+ 'deleteMailbox',
3140
+ 'uploadMessage',
3141
+ 'getAttachment',
3142
+ 'listSignatures'
3143
+ ].map(cmd => [cmd, commandAccountOperation]),
3144
+ ['subconnections', commandSubconnections],
3145
+ ['googlePubSub', commandGooglePubSub],
3146
+ ['googlePubSubRemove', commandGooglePubSub],
3147
+ ['externalNotify', commandExternalNotify],
3148
+ ['subscriptionLifecycle', commandSubscriptionLifecycle]
3149
+ ]);
3150
+
3151
+ async function onCommand(worker, message) {
3152
+ const handler = COMMAND_HANDLERS.get(message.cmd);
3153
+ if (handler) {
3154
+ return await handler(worker, message);
3155
+ }
3156
+
3157
+ return NOT_HANDLED;
3083
3158
  }
3084
3159
 
3085
3160
  // Metrics collection results
@@ -3286,13 +3361,11 @@ const settleWorkerFleet = async (label, promises, logFields) => {
3286
3361
  };
3287
3362
 
3288
3363
  /**
3289
- * Main application startup
3290
- * @returns {Promise<void>}
3364
+ * Loads the license from the configured license file and from EENGINE_PREPARED_LICENSE. Either one
3365
+ * failing is fatal: the process exits once the log is flushed
3366
+ * @returns {Promise<boolean>} true when startup has to stop
3291
3367
  */
3292
- const startApplication = async () => {
3293
- // Generate unique run index
3294
- runIndex = await redis.hincrby(`${REDIS_PREFIX}settings`, 'run', 1);
3295
-
3368
+ const importConfiguredLicenses = async () => {
3296
3369
  // Process license file if provided
3297
3370
  if (config.licensePath) {
3298
3371
  try {
@@ -3310,7 +3383,8 @@ const startApplication = async () => {
3310
3383
  await setLicense(licenseData, licenseFile);
3311
3384
  } catch (err) {
3312
3385
  logger.fatal({ msg: 'License verification failed', source: config.licensePath, err });
3313
- return logger.flush(() => process.exit(13));
3386
+ logger.flush(() => process.exit(13));
3387
+ return true;
3314
3388
  }
3315
3389
  }
3316
3390
 
@@ -3324,10 +3398,19 @@ const startApplication = async () => {
3324
3398
  }
3325
3399
  } catch (err) {
3326
3400
  logger.fatal({ msg: 'License import failed', source: 'import', err });
3327
- return logger.flush(() => process.exit(13));
3401
+ logger.flush(() => process.exit(13));
3402
+ return true;
3328
3403
  }
3329
3404
  }
3330
3405
 
3406
+ return false;
3407
+ };
3408
+
3409
+ /**
3410
+ * Activates the license stored in Redis, if there is a valid one
3411
+ * @returns {Promise<void>}
3412
+ */
3413
+ const loadStoredLicense = async () => {
3331
3414
  // Load license from database
3332
3415
  let licenseFile = await redis.hget(`${REDIS_PREFIX}settings`, 'license');
3333
3416
  if (licenseFile) {
@@ -3350,12 +3433,13 @@ const startApplication = async () => {
3350
3433
  if (!licenseInfo.active) {
3351
3434
  logger.error({ msg: 'No active license. Running in limited mode.' });
3352
3435
  }
3436
+ };
3353
3437
 
3354
- // Check for updates
3355
- processCheckUpgrade().catch(err => {
3356
- logger.warn({ msg: 'Update check failed', err });
3357
- });
3358
-
3438
+ /**
3439
+ * One-time data migrations that run before the workers spawn. None of them is fatal
3440
+ * @returns {Promise<void>}
3441
+ */
3442
+ const runStartupMigrations = async () => {
3359
3443
  // Move any settings-based OAuth2 configuration into the app registry before workers spawn.
3360
3444
  // A failure is not fatal: the source settings keys stay in place, so the migration retries
3361
3445
  // on the next startup (the legacy config is simply not visible until it succeeds).
@@ -3380,7 +3464,13 @@ const startApplication = async () => {
3380
3464
  } catch (err) {
3381
3465
  logger.error({ msg: 'Failed to sweep the retired bounce store', err });
3382
3466
  }
3467
+ };
3383
3468
 
3469
+ /**
3470
+ * Applies EENGINE_SETTINGS and records which keys it manages
3471
+ * @returns {Promise<void>}
3472
+ */
3473
+ const applyPreparedSettings = async () => {
3384
3474
  // Apply prepared settings
3385
3475
  if (preparedSettings) {
3386
3476
  logger.debug({ msg: 'Applying configuration', settingsKeys: Object.keys(preparedSettings) });
@@ -3396,13 +3486,13 @@ const startApplication = async () => {
3396
3486
  } else {
3397
3487
  await settings.clear('preparedSettingsKeys');
3398
3488
  }
3489
+ };
3399
3490
 
3400
- // Initialize required settings
3401
- let existingServiceId = await settings.get('serviceId');
3402
- if (existingServiceId === null) {
3403
- await settings.set('serviceId', crypto.randomBytes(16).toString('hex'));
3404
- }
3405
-
3491
+ /**
3492
+ * Seeds the SMTP server settings that have no stored value yet
3493
+ * @returns {Promise<void>}
3494
+ */
3495
+ const seedSmtpServerSettings = async () => {
3406
3496
  // SMTP server settings
3407
3497
  let existingSmtpEnabled = await settings.get('smtpServerEnabled');
3408
3498
  if (existingSmtpEnabled === null) {
@@ -3433,7 +3523,13 @@ const startApplication = async () => {
3433
3523
  if (existingSmtpProxy === null) {
3434
3524
  await settings.set('smtpServerProxy', SMTP_PROXY);
3435
3525
  }
3526
+ };
3436
3527
 
3528
+ /**
3529
+ * Seeds the IMAP proxy settings that have no stored value yet
3530
+ * @returns {Promise<void>}
3531
+ */
3532
+ const seedImapProxySettings = async () => {
3437
3533
  // IMAP proxy settings
3438
3534
  let existingImapProxyEnabled = await settings.get('imapProxyServerEnabled');
3439
3535
  if (existingImapProxyEnabled === null) {
@@ -3459,7 +3555,13 @@ const startApplication = async () => {
3459
3555
  if (existingImapProxyProxy === null) {
3460
3556
  await settings.set('imapProxyServerProxy', IMAP_PROXY_PROXY);
3461
3557
  }
3558
+ };
3462
3559
 
3560
+ /**
3561
+ * Seeds the API, service, webhook, script and token settings that have no stored value yet
3562
+ * @returns {Promise<void>}
3563
+ */
3564
+ const seedServiceSettings = async () => {
3463
3565
  // API proxy settings
3464
3566
  let existingEnableApiProxy = await settings.get('enableApiProxy');
3465
3567
  if (existingEnableApiProxy === null) {
@@ -3506,7 +3608,29 @@ const startApplication = async () => {
3506
3608
  // disableTokens is the inverse of REQUIRE_API_AUTH
3507
3609
  await settings.set('disableTokens', !REQUIRE_API_AUTH);
3508
3610
  }
3611
+ };
3612
+
3613
+ /**
3614
+ * Seeds every setting that has no stored value yet, in a fixed order
3615
+ * @returns {Promise<void>}
3616
+ */
3617
+ const seedDefaultSettings = async () => {
3618
+ // Initialize required settings
3619
+ let existingServiceId = await settings.get('serviceId');
3620
+ if (existingServiceId === null) {
3621
+ await settings.set('serviceId', crypto.randomBytes(16).toString('hex'));
3622
+ }
3623
+
3624
+ await seedSmtpServerSettings();
3625
+ await seedImapProxySettings();
3626
+ await seedServiceSettings();
3627
+ };
3509
3628
 
3629
+ /**
3630
+ * Imports EENGINE_PREPARED_TOKEN and EENGINE_PREPARED_PASSWORD. A failure is logged, not fatal
3631
+ * @returns {Promise<void>}
3632
+ */
3633
+ const importPreparedCredentials = async () => {
3510
3634
  // Import prepared token
3511
3635
  if (preparedToken) {
3512
3636
  try {
@@ -3544,7 +3668,13 @@ const startApplication = async () => {
3544
3668
  logger.error({ msg: 'Password import failed', err });
3545
3669
  }
3546
3670
  }
3671
+ };
3547
3672
 
3673
+ /**
3674
+ * Warns about a missing encryption secret and makes sure the admin session cookie key exists
3675
+ * @returns {Promise<void>}
3676
+ */
3677
+ const ensureInstanceSecrets = async () => {
3548
3678
  if (!(await getSecret())) {
3549
3679
  // Every consumer of the secret stores the value as it is when there is none, so without
3550
3680
  // it the account passwords, OAuth2 tokens, webhook secrets and TLS keys sit in Redis in
@@ -3560,16 +3690,13 @@ const startApplication = async () => {
3560
3690
  cookiePassword = crypto.randomBytes(32).toString('base64');
3561
3691
  await settings.set('cookiePassword', cookiePassword);
3562
3692
  }
3693
+ };
3563
3694
 
3564
- // Redis reconnection is now handled by workers themselves
3565
- // Workers will exit when Redis reconnects after disconnection,
3566
- // and the server will automatically restart them
3567
-
3568
- // Initialize HTTP proxy agent from settings/env vars before spawning workers
3569
- await reloadHttpProxyAgent();
3570
-
3571
- // -- START WORKER THREADS
3572
-
3695
+ /**
3696
+ * Starts the API workers, several sharing the listen port when SO_REUSEPORT allows it
3697
+ * @returns {Promise<void>}
3698
+ */
3699
+ const startApiWorkers = async () => {
3573
3700
  // Start API server first for health checks.
3574
3701
  // Optionally run several API workers that share the listen port via SO_REUSEPORT.
3575
3702
  apiWorkersRequested = config.workers.api;
@@ -3620,10 +3747,13 @@ const startApplication = async () => {
3620
3747
  // `attempted` can be below `requested` after the SO_REUSEPORT fallback above
3621
3748
  let apiReady = (await settleWorkerFleet('API', apiPromises, { requested: apiWorkersRequested, attempted: apiPromises.length })).length;
3622
3749
  logger.info({ msg: 'API workers started', requested: apiWorkersRequested, ready: apiReady });
3750
+ };
3623
3751
 
3624
- // Small delay to allow API to start
3625
- await new Promise(r => setTimeout(r, 100));
3626
-
3752
+ /**
3753
+ * Starts the IMAP workers and assigns the accounts to them
3754
+ * @returns {Promise<void>}
3755
+ */
3756
+ const startImapWorkers = async () => {
3627
3757
  // Start IMAP workers
3628
3758
  let workerPromises = [];
3629
3759
  for (let i = 0; i < config.workers.imap; i++) {
@@ -3646,7 +3776,14 @@ const startApplication = async () => {
3646
3776
  } catch (err) {
3647
3777
  logger.error({ msg: 'Initial account assignment failed', err });
3648
3778
  }
3779
+ };
3649
3780
 
3781
+ /**
3782
+ * Starts the webhook, submission and export workers, then the SMTP server and the IMAP proxy if
3783
+ * they are enabled
3784
+ * @returns {Promise<void>}
3785
+ */
3786
+ const startBackgroundWorkers = async () => {
3650
3787
  // Start webhook workers
3651
3788
  for (let i = 0; i < config.workers.webhooks; i++) {
3652
3789
  await spawnWorker('webhooks');
@@ -3681,7 +3818,12 @@ const startApplication = async () => {
3681
3818
  if (await settings.get('imapProxyServerEnabled')) {
3682
3819
  await spawnWorker('imapProxy');
3683
3820
  }
3821
+ };
3684
3822
 
3823
+ /**
3824
+ * Creates and starts the background metrics collector
3825
+ */
3826
+ const startMetricsCollector = () => {
3685
3827
  // Initialize and start the metrics collector after all workers are ready
3686
3828
  metricsCollector = new MetricsCollector({
3687
3829
  logger,
@@ -3725,6 +3867,57 @@ const startApplication = async () => {
3725
3867
  logger.info({ msg: 'Background metrics collector initialized and started' });
3726
3868
  };
3727
3869
 
3870
+ /**
3871
+ * Main application startup
3872
+ * @returns {Promise<void>}
3873
+ */
3874
+ const startApplication = async () => {
3875
+ // Generate unique run index
3876
+ runIndex = await redis.hincrby(`${REDIS_PREFIX}settings`, 'run', 1);
3877
+
3878
+ // A license that was explicitly configured but cannot be loaded stops the startup
3879
+ if (await importConfiguredLicenses()) {
3880
+ return;
3881
+ }
3882
+
3883
+ await loadStoredLicense();
3884
+
3885
+ // Check for updates
3886
+ processCheckUpgrade().catch(err => {
3887
+ logger.warn({ msg: 'Update check failed', err });
3888
+ });
3889
+
3890
+ await runStartupMigrations();
3891
+
3892
+ await applyPreparedSettings();
3893
+
3894
+ await seedDefaultSettings();
3895
+
3896
+ await importPreparedCredentials();
3897
+
3898
+ await ensureInstanceSecrets();
3899
+
3900
+ // Redis reconnection is now handled by workers themselves
3901
+ // Workers will exit when Redis reconnects after disconnection,
3902
+ // and the server will automatically restart them
3903
+
3904
+ // Initialize HTTP proxy agent from settings/env vars before spawning workers
3905
+ await reloadHttpProxyAgent();
3906
+
3907
+ // -- START WORKER THREADS
3908
+
3909
+ await startApiWorkers();
3910
+
3911
+ // Small delay to allow API to start
3912
+ await new Promise(r => setTimeout(r, 100));
3913
+
3914
+ await startImapWorkers();
3915
+
3916
+ await startBackgroundWorkers();
3917
+
3918
+ startMetricsCollector();
3919
+ };
3920
+
3728
3921
  // Start the application
3729
3922
  startApplication()
3730
3923
  .then(bounceClassifier.initialize)