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/server.js CHANGED
@@ -20,19 +20,23 @@
20
20
  // same way. Set before anything can require bullmq; worker threads share this environment.
21
21
  process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED = 'true';
22
22
 
23
- // Load environment variables if not already loaded
24
- if (!process.env.EE_ENV_LOADED) {
25
- require('dotenv').config({ quiet: true });
26
- process.env.EE_ENV_LOADED = 'true';
27
- }
28
-
29
- // Attempt to change working directory to script location
23
+ // Attempt to change working directory to script location. Before anything reads a file by a
24
+ // relative path: `.env` below and the `config/` directory wild-config loads (including executable
25
+ // `.js` configuration files, run with the real require) are both resolved against the working
26
+ // directory, and the directory the operator happened to start from is not where this instance's
27
+ // configuration lives
30
28
  try {
31
29
  process.chdir(__dirname);
32
30
  } catch (err) {
33
31
  // ignore - may fail in some containerized environments
34
32
  }
35
33
 
34
+ // Load environment variables if not already loaded
35
+ if (!process.env.EE_ENV_LOADED) {
36
+ require('dotenv').config({ quiet: true });
37
+ process.env.EE_ENV_LOADED = 'true';
38
+ }
39
+
36
40
  // Set process title for easier identification in process lists
37
41
  process.title = 'emailengine';
38
42
 
@@ -71,7 +75,7 @@ const {
71
75
  getDuration,
72
76
  getByteSize,
73
77
  getBoolean,
74
- getWorkerCount,
78
+ workerPoolSize,
75
79
  selectRendezvousNode,
76
80
  checkLicense,
77
81
  checkForUpgrade,
@@ -123,7 +127,7 @@ const { packRpcError, unpackRpcError } = require('./lib/worker-rpc-error');
123
127
  const promClient = require('prom-client');
124
128
  const fs = require('fs').promises;
125
129
  const crypto = require('crypto');
126
- const { compare: cv } = require('compare-versions');
130
+ const { compareVersions, parseVersion } = require('./lib/utils/version');
127
131
  const Joi = require('joi');
128
132
  const { settingsSchema } = require('./lib/schemas');
129
133
  const settings = require('./lib/settings');
@@ -146,11 +150,12 @@ const {
146
150
  releaseWorkerAccounts,
147
151
  requeueFailedAccounts,
148
152
  forgetAccount,
149
- mapConcurrent,
150
153
  shouldRequeueFailedAssignment,
151
154
  planRebalance
152
155
  } = require('./lib/account-assignment');
156
+ const { mapConcurrent } = require('./lib/utils/map-concurrent');
153
157
  const { RespawnTracker } = require('./lib/respawn-backoff');
158
+ const { heartbeatDiagnostics, eventLoopDelaySeries } = require('./lib/thread-diagnostics');
154
159
 
155
160
  const msgpack = require('./lib/msgpack');
156
161
 
@@ -221,16 +226,14 @@ const CONNECTION_SETUP_DELAY = getDuration(readEnvValue('EENGINE_CONNECTION_SETU
221
226
  config.api.maxSize = getByteSize(readEnvValue('EENGINE_MAX_SIZE') || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
222
227
  config.dbs.redis = readEnvValue('EENGINE_REDIS') || readEnvValue('REDIS_URL') || config.dbs.redis;
223
228
 
224
- config.workers.imap = getWorkerCount(readEnvValue('EENGINE_WORKERS') || config.workers.imap) || 4;
225
- config.workers.webhooks = Number(readEnvValue('EENGINE_WORKERS_WEBHOOKS')) || config.workers.webhooks || 1;
226
- 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);
227
232
  // The Workers page has labelled this row EENGINE_WORKERS_EXPORT since the export worker shipped, while
228
233
  // only --workers.export and [workers] export were read, so an operator who set it saw no effect
229
- config.workers.export = Number(readEnvValue('EENGINE_WORKERS_EXPORT')) || config.workers.export || 1;
234
+ config.workers.export = workerPoolSize(readEnvValue('EENGINE_WORKERS_EXPORT'), config.workers.export);
230
235
  // API worker count. Values >1 require SO_REUSEPORT (Linux); on unsupported platforms it falls back to 1 at startup.
231
- // Uses getWorkerCount() for parity with EENGINE_WORKERS (supports "cpus"); Math.floor avoids a fractional
232
- // count over-spawning, Math.max keeps at least one API worker.
233
- 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);
234
237
 
235
238
  config.api.port =
236
239
  (hasEnvValue('EENGINE_PORT') && Number(readEnvValue('EENGINE_PORT'))) || (hasEnvValue('PORT') && Number(readEnvValue('PORT'))) || config.api.port;
@@ -660,6 +663,18 @@ const metrics = {
660
663
  help: 'Number of unresponsive worker threads'
661
664
  }),
662
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
+
663
678
  licenseDaysRemaining: new promClient.Gauge({
664
679
  name: 'license_days_remaining',
665
680
  help: 'Days until license expires (-1 for lifetime, 0 for no license)'
@@ -999,12 +1014,29 @@ async function getThreadsInfo() {
999
1014
  return threadsInfo;
1000
1015
  }
1001
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
+
1002
1033
  /**
1003
1034
  * Handle heartbeat from worker thread
1004
1035
  * @param {Worker} worker - The worker thread
1005
1036
  */
1006
1037
  function handleWorkerHeartbeat(worker) {
1007
1038
  const now = Date.now();
1039
+ const previousHeartbeat = workerHeartbeats.get(worker);
1008
1040
  workerHeartbeats.set(worker, now);
1009
1041
 
1010
1042
  // Mark as healthy if it was previously unhealthy
@@ -1013,7 +1045,9 @@ function handleWorkerHeartbeat(worker) {
1013
1045
  logger.info({
1014
1046
  msg: 'Worker recovered',
1015
1047
  threadId: worker.threadId,
1016
- 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)
1017
1051
  });
1018
1052
  }
1019
1053
  workerHealthStatus.set(worker, 'healthy');
@@ -1044,7 +1078,7 @@ async function checkWorkerHealth() {
1044
1078
  msg: 'Worker critically unresponsive, restarting',
1045
1079
  threadId: worker.threadId,
1046
1080
  type,
1047
- timeSinceHeartbeat: Math.round(timeSinceHeartbeat / 1000) + 's'
1081
+ ...workerHeartbeatDiagnostics(worker, now, lastHeartbeat)
1048
1082
  });
1049
1083
 
1050
1084
  workerHealthStatus.set(worker, 'restarting');
@@ -1066,7 +1100,7 @@ async function checkWorkerHealth() {
1066
1100
  msg: 'Worker unhealthy - no heartbeat',
1067
1101
  threadId: worker.threadId,
1068
1102
  type,
1069
- timeSinceHeartbeat: Math.round(timeSinceHeartbeat / 1000) + 's'
1103
+ ...workerHeartbeatDiagnostics(worker, now, lastHeartbeat)
1070
1104
  });
1071
1105
 
1072
1106
  workerHealthStatus.set(worker, 'unhealthy');
@@ -1111,7 +1145,7 @@ async function sendWebhook(account, event, data) {
1111
1145
  payload.data = data;
1112
1146
  }
1113
1147
 
1114
- await Webhooks.pushToQueue(event, await Webhooks.formatPayload(event, payload));
1148
+ await Webhooks.enqueue(event, payload);
1115
1149
  }
1116
1150
 
1117
1151
  /**
@@ -2065,7 +2099,9 @@ let licenseCheckHandler = async opts => {
2065
2099
  // Check if we need to validate the license
2066
2100
  let kv = await redis.hget(`${REDIS_PREFIX}settings`, 'kv');
2067
2101
  let checkKv = true;
2068
- 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) {
2069
2105
  checkKv = false;
2070
2106
  }
2071
2107
 
@@ -2420,6 +2456,13 @@ async function updateQueueCounters() {
2420
2456
 
2421
2457
  let threadCounts = new Map();
2422
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
+ }
2423
2466
  for (let workerThreadInfo of threadsInfo || []) {
2424
2467
  let key = workerThreadInfo.type;
2425
2468
  let metricKey = `${key}_total`;
@@ -2548,10 +2591,15 @@ const openAiRequestOpts = () => ({
2548
2591
 
2549
2592
  const aiValueSet = value => value !== undefined && value !== null && value !== '';
2550
2593
 
2594
+ const aiUrlValue = value => (value === undefined || value === null ? '' : String(value).trim());
2595
+
2551
2596
  /**
2552
2597
  * Options for one request to the AI provider. The configuration page's test sends every field as
2553
2598
  * its form shows it, so the test runs with what the page shows; the sync path sends none and gets
2554
- * the stored settings. The key is the exception: the form leaves it blank to keep the stored one
2599
+ * the stored settings. The key is the exception: the form leaves it blank to keep the stored one,
2600
+ * and a request made with the stored key goes to the stored URL, since a write-only secret must
2601
+ * not be extractable by pointing a request that falls back to it at a server of one's own. The
2602
+ * rule is here rather than on the page's routes so every request the form can make is under it
2555
2603
  * @param {Object} data - The command's data
2556
2604
  * @returns {Promise<{openAiAPIKey: string, requestOpts: Object}>}
2557
2605
  */
@@ -2563,6 +2611,9 @@ async function aiRequestOptions(data) {
2563
2611
  if (!openAiAPIKey) {
2564
2612
  throw new Error(`OpenAI API key is not configured`);
2565
2613
  }
2614
+ if (data.options && !data.options.openAiAPIKey && aiUrlValue(data.options.openAiAPIUrl) !== aiUrlValue(stored.openAiAPIUrl)) {
2615
+ throw new Error('Enter the API key to use a different API URL');
2616
+ }
2566
2617
 
2567
2618
  const requestOpts = openAiRequestOpts();
2568
2619
  requestOpts.gptModel = aiValueSet(values.openAiModel) ? values.openAiModel : openAiDefaultModel;
@@ -2606,468 +2657,504 @@ async function withRequestDeadline(message, run) {
2606
2657
  }
2607
2658
  }
2608
2659
 
2609
- async function onCommand(worker, message) {
2610
- switch (message.cmd) {
2611
- case 'metrics':
2612
- // Return Prometheus metrics
2613
- await updateQueueCounters();
2614
- return promClient.register.metrics();
2615
-
2616
- case 'structuredMetrics': {
2617
- // Return structured metrics for API
2618
- let connections = {};
2619
-
2620
- for (let key of Object.keys(metrics.imapConnections.hashMap)) {
2621
- if (key.indexOf('status:') === 0) {
2622
- let metric = metrics.imapConnections.hashMap[key];
2623
- connections[metric.labels.status] = metric.value;
2624
- }
2625
- }
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;
2626
2663
 
2627
- return { connections, redisPing: await getRedisPing() };
2628
- }
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 = {};
2629
2673
 
2630
- case 'imapWorkerCount': {
2631
- // Return number of available IMAP workers
2632
- 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;
2633
2678
  }
2679
+ }
2634
2680
 
2635
- case 'checkLicense':
2636
- // Force license check
2637
- try {
2638
- await licenseCheckHandler({
2639
- subscriptionCheckTimeout: 60 * 1000
2640
- });
2641
- } catch (err) {
2642
- // ignore
2643
- }
2644
- return licenseInfo;
2681
+ return { connections, redisPing: await getRedisPing() };
2682
+ }
2645
2683
 
2646
- case 'license':
2647
- // Return license info with suspension status
2648
- if (!licenseInfo.active && suspendedWorkerTypes.size) {
2649
- return Object.assign({}, licenseInfo, { suspended: true });
2650
- }
2651
- return licenseInfo;
2684
+ async function commandImapWorkerCount() {
2685
+ // Return number of available IMAP workers
2686
+ return { workers: availableIMAPWorkers.size };
2687
+ }
2652
2688
 
2653
- case 'updateLicense': {
2654
- // Update license from API
2655
- try {
2656
- 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
+ }
2657
2700
 
2658
- let licenseData = await checkLicense(licenseFile);
2659
- if (!licenseData) {
2660
- throw new Error('Invalid license provided');
2661
- }
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
+ }
2662
2708
 
2663
- 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;
2664
2713
 
2665
- await setLicense(licenseData, licenseFile);
2714
+ let licenseData = await checkLicense(licenseFile);
2715
+ if (!licenseData) {
2716
+ throw new Error('Invalid license provided');
2717
+ }
2666
2718
 
2667
- licenseInfo.active = true;
2668
- licenseInfo.details = licenseData;
2669
- licenseInfo.type = 'EmailEngine License';
2719
+ logger.info({ msg: 'License updated', license: redactLicense(licenseData), source: 'API' });
2670
2720
 
2671
- // Re-enable workers
2672
- checkActiveLicense();
2721
+ await setLicense(licenseData, licenseFile);
2673
2722
 
2674
- return licenseInfo;
2675
- } catch (err) {
2676
- logger.warn({ msg: 'License update failed', source: 'API', err });
2677
- return false;
2678
- }
2679
- }
2723
+ licenseInfo.active = true;
2724
+ licenseInfo.details = licenseData;
2725
+ licenseInfo.type = 'EmailEngine License';
2680
2726
 
2681
- case 'removeLicense': {
2682
- // Remove existing license
2683
- try {
2684
- 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
+ }
2685
2736
 
2686
- licenseInfo.active = false;
2687
- licenseInfo.details = false;
2688
- licenseInfo.type = packageData.license;
2737
+ async function commandRemoveLicense() {
2738
+ // Remove existing license
2739
+ try {
2740
+ await settings.removeLicense();
2689
2741
 
2690
- return licenseInfo;
2691
- } catch (err) {
2692
- logger.error({ msg: 'License removal failed', err });
2693
- return false;
2694
- }
2695
- }
2742
+ licenseInfo.active = false;
2743
+ licenseInfo.details = false;
2744
+ licenseInfo.type = packageData.license;
2696
2745
 
2697
- case 'kill-thread': {
2698
- // Terminate a specific thread
2699
- for (let [, workerSet] of workers) {
2700
- if (workerSet && workerSet.size) {
2701
- for (let worker of workerSet) {
2702
- if (worker.threadId === message.thread) {
2703
- logger.info({ msg: 'Thread termination requested', thread: message.thread });
2704
- return await worker.terminate();
2705
- }
2706
- }
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();
2707
2761
  }
2708
2762
  }
2709
-
2710
- return false;
2711
2763
  }
2764
+ }
2712
2765
 
2713
- case 'snapshot-thread': {
2714
- // Get heap snapshot for debugging
2715
- if (message.thread === 0) {
2716
- // Main thread only - V8 operations should be done in main thread
2717
- try {
2718
- logger.info({ msg: 'Heap snapshot requested', thread: message.thread });
2719
- const stream = v8.getHeapSnapshot();
2720
- if (stream) {
2721
- return { _transfer: true, _response: await download(stream) };
2722
- }
2723
- } catch (err) {
2724
- logger.error({ msg: 'Failed to generate heap snapshot', thread: message.thread, err });
2725
- }
2726
- 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) };
2727
2778
  }
2779
+ } catch (err) {
2780
+ logger.error({ msg: 'Failed to generate heap snapshot', thread: message.thread, err });
2781
+ }
2782
+ return false;
2783
+ }
2728
2784
 
2729
- // Worker thread - use worker's built-in method which is safer
2730
- for (let [, workerSet] of workers) {
2731
- if (workerSet && workerSet.size) {
2732
- for (let worker of workerSet) {
2733
- if (worker.threadId === message.thread) {
2734
- try {
2735
- logger.info({ msg: 'Heap snapshot requested', thread: message.thread });
2736
- // Use worker's built-in getHeapSnapshot method instead of V8 API
2737
- const stream = await worker.getHeapSnapshot({ exposeInternals: true, exposeNumericValues: true });
2738
- if (stream) {
2739
- return { _transfer: true, _response: await download(stream) };
2740
- }
2741
- } catch (err) {
2742
- logger.error({ msg: 'Failed to generate heap snapshot for worker', thread: message.thread, err });
2743
- }
2744
- 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) };
2745
2796
  }
2797
+ } catch (err) {
2798
+ logger.error({ msg: 'Failed to generate heap snapshot for worker', thread: message.thread, err });
2746
2799
  }
2800
+ return false;
2747
2801
  }
2748
2802
  }
2749
-
2750
- return false;
2751
2803
  }
2804
+ }
2752
2805
 
2753
- case 'bounceClassify':
2754
- // Classify bounce response message
2755
- try {
2756
- return await bounceClassifier.classify(message.data.message);
2757
- } catch (err) {
2758
- // ignore
2759
- logger.warn({
2760
- msg: 'Failed to classify bounce response',
2761
- bounceResponse: message.data.message,
2762
- err
2763
- });
2764
- }
2765
- return false;
2806
+ return false;
2807
+ }
2766
2808
 
2767
- // OpenAI integration commands - run in the main process, where the metrics live
2768
- case 'generateSummary': {
2769
- const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
2770
- 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
+ }
2771
2823
 
2772
- // the configuration page's test runs are not production traffic
2773
- const counted = !message.data.options;
2774
- 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;
2775
2828
 
2776
- try {
2777
- const response = await withRequestDeadline(message, signal =>
2778
- generateSummary(message.data.message, openAiAPIKey, Object.assign(requestOpts, { signal }))
2779
- );
2780
- 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;
2781
2832
 
2782
- // the fitted email text the verbose mode adds stays out of the RPC and the log
2783
- 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;
2784
2838
 
2785
- if (counted) {
2786
- metrics.aiRequests.inc({ model, status: 'success' });
2787
- for (const type of ['prompt', 'completion']) {
2788
- const tokens = usage[`${type}Tokens`];
2789
- if (tokens) {
2790
- metrics.aiTokens.inc({ model, type }, tokens);
2791
- }
2792
- }
2793
- }
2839
+ // the fitted email text the verbose mode adds stays out of the RPC and the log
2840
+ delete usage.text;
2794
2841
 
2795
- return response;
2796
- } catch (err) {
2797
- if (counted) {
2798
- 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);
2799
2848
  }
2800
- throw err;
2801
2849
  }
2802
2850
  }
2803
2851
 
2804
- case 'openAiListModels': {
2805
- const { openAiAPIKey, requestOpts } = await aiRequestOptions(message.data);
2806
- 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' });
2807
2856
  }
2857
+ throw err;
2858
+ }
2859
+ }
2808
2860
 
2809
- case 'threads': {
2810
- return await getThreadsInfo();
2811
- }
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
+ }
2812
2865
 
2813
- case 'apiWorkerScaling': {
2814
- // Reported on /admin/internals so operators can see when EENGINE_WORKERS_API > 1
2815
- // was requested but only one worker started, and why (reason: 'platform' | 'port').
2816
- return {
2817
- requested: apiWorkersRequested,
2818
- fallback: apiWorkersRequested > 1 && !apiWorkerReusePort,
2819
- reason: apiWorkerReusePortFallbackReason
2820
- };
2821
- }
2866
+ async function commandThreads() {
2867
+ return await getThreadsInfo();
2868
+ }
2822
2869
 
2823
- case 'worker-accounts': {
2824
- // Get accounts assigned to a specific worker thread
2825
- const { threadId, page = 1, pageSize = 20 } = message;
2826
- 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
+ }
2827
2879
 
2828
- // Find worker by threadId and get its assigned accounts
2829
- for (const [account, worker] of assigned) {
2830
- if (worker.threadId === threadId) {
2831
- accounts.push(account);
2832
- }
2833
- }
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 = [];
2834
2884
 
2835
- // Sort accounts for consistent ordering
2836
- accounts.sort((a, b) => a.localeCompare(b));
2837
-
2838
- // Paginate
2839
- const totalAccounts = accounts.length;
2840
- const totalPages = Math.ceil(totalAccounts / pageSize) || 1;
2841
- const currentPage = Math.min(Math.max(1, page), totalPages);
2842
- const start = (currentPage - 1) * pageSize;
2843
- const pagedAccounts = accounts.slice(start, start + pageSize);
2844
-
2845
- return {
2846
- accounts: pagedAccounts,
2847
- total: totalAccounts,
2848
- page: currentPage,
2849
- pageSize,
2850
- pages: totalPages
2851
- };
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);
2852
2889
  }
2890
+ }
2853
2891
 
2854
- case 'rate-limit': {
2855
- return await checkRateLimit(message.key, message.count, message.allowed, message.windowSize);
2856
- }
2892
+ // Sort accounts for consistent ordering
2893
+ accounts.sort((a, b) => a.localeCompare(b));
2857
2894
 
2858
- case 'unsubscribe':
2859
- // Handle list unsubscribe
2860
- sendWebhook(message.account, LIST_UNSUBSCRIBE_NOTIFY, message.payload).catch(err =>
2861
- logger.error({ msg: 'Unsubscribe webhook failed', account: message.account, err })
2862
- );
2863
- 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);
2864
2901
 
2865
- case 'subscribe':
2866
- // Handle list subscribe
2867
- sendWebhook(message.account, LIST_SUBSCRIBE_NOTIFY, message.payload).catch(err =>
2868
- logger.error({ msg: 'Subscribe webhook failed', account: message.account, err })
2869
- );
2870
- return;
2902
+ return {
2903
+ accounts: pagedAccounts,
2904
+ total: totalAccounts,
2905
+ page: currentPage,
2906
+ pageSize,
2907
+ pages: totalPages
2908
+ };
2909
+ }
2871
2910
 
2872
- case 'new':
2873
- // Handle new account.
2874
- //
2875
- // `unassigned` is `false` until assignAccounts() loads the account list from Redis on
2876
- // its first run, which waits for an IMAP worker to report ready. An account created
2877
- // before that used to throw here and fail the request with a 500. Skipping the add is
2878
- // safe rather than merely quiet: the account is already in `ia:accounts` by the time
2879
- // this message is sent, so the first load picks it up.
2880
- if (unassigned) {
2881
- unassigned.add(message.account);
2882
- }
2883
- assignAccounts()
2884
- .then(() => sendWebhook(message.account, ACCOUNT_ADDED_NOTIFY, { account: message.account }))
2885
- .catch(err => logger.error({ msg: 'Account assignment failed', err }));
2886
- return;
2911
+ async function commandRateLimit(worker, message) {
2912
+ return await checkRateLimit(message.key, message.count, message.allowed, message.windowSize);
2913
+ }
2887
2914
 
2888
- case 'delete':
2889
- // Handle account deletion
2890
- //
2891
- // Guarded for the same reason as the `new` branch above, and here the throw was
2892
- // answered with a 500 for a deletion that had in fact succeeded: the account was
2893
- // already gone from Redis by the time this message was sent.
2894
- {
2895
- let assignedWorker = forgetAccount({ workerAssigned, assigned, unassigned }, message.account);
2896
- if (assignedWorker) {
2897
- // Notify worker to clean up
2898
- call(assignedWorker, message)
2899
- .then(() => logger.debug('Account cleanup completed'))
2900
- .catch(err => logger.error({ msg: 'Account cleanup failed', account: message.account, err }));
2901
- }
2902
- }
2903
- sendWebhook(message.account, ACCOUNT_DELETED_NOTIFY, { account: message.account }).catch(err =>
2904
- logger.error({ msg: 'Account deletion webhook failed', account: message.account, err })
2905
- );
2906
- 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
+ }
2907
2921
 
2908
- case 'runIndex': {
2909
- return runIndex;
2910
- }
2911
-
2912
- case 'update':
2913
- case 'sync':
2914
- case 'pause':
2915
- case 'resume':
2916
- case 'reconnect':
2917
- // Forward to assigned worker
2918
- if (assigned.has(message.account)) {
2919
- let assignedWorker = assigned.get(message.account);
2920
- call(assignedWorker, message)
2921
- .then(() => logger.debug('Worker command completed'))
2922
- .catch(err => logger.error({ msg: 'Worker command failed', account: message.account, cmd: message.cmd, err }));
2923
- }
2924
- 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
+ }
2925
2928
 
2926
- case 'smtpReload':
2927
- case 'imapProxyReload':
2928
- {
2929
- // Reload proxy server
2930
- let type = message.cmd.replace(/Reload$/, '');
2931
- let hasWorkers = workers.has(type) && workers.get(type).size;
2932
- if (hasWorkers) {
2933
- // Kill existing workers
2934
- for (let worker of workers.get(type).values()) {
2935
- worker.terminate();
2936
- }
2937
- } else {
2938
- // Spawn new worker if enabled
2939
- let serverEnabled = await settings.get(`${type}ServerEnabled`);
2940
- if (serverEnabled) {
2941
- await spawnWorker(type);
2942
- }
2943
- }
2944
- }
2945
- 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
+ }
2946
2944
 
2947
- case 'apiReloadCertificates':
2948
- case 'smtpReloadCertificates':
2949
- case 'imapProxyReloadCertificates':
2950
- {
2951
- // A renewed certificate, handed to a running listener. Forwarded to the worker
2952
- // rather than terminating it: a restart would cut every session in flight, and
2953
- // every listener can swap its secure context between handshakes. Sent to every
2954
- // worker of the type, not just the one that ordered the certificate: the
2955
- // reconciler is a singleton but the listeners are not.
2956
- let type = message.cmd.replace(/ReloadCertificates$/, '');
2957
- for (let worker of (workers.get(type) || new Set()).values()) {
2958
- call(worker, message).catch(err => logger.error({ msg: 'Failed to reload certificates', type, worker: worker.threadId, err }));
2959
- }
2960
- }
2961
- break;
2962
-
2963
- // IMAP operations - forward to assigned worker
2964
- case 'submitMessage':
2965
- case 'queueMessage':
2966
- case 'listMessages':
2967
- case 'getRawMessage':
2968
- case 'getText':
2969
- case 'getMessage':
2970
- case 'getMessages':
2971
- case 'updateMessage':
2972
- case 'updateMessages':
2973
- case 'listMailboxes':
2974
- case 'moveMessage':
2975
- case 'moveMessages':
2976
- case 'deleteMessage':
2977
- case 'deleteMessages':
2978
- case 'getQuota':
2979
- case 'createMailbox':
2980
- case 'modifyMailbox':
2981
- case 'deleteMailbox':
2982
- case 'uploadMessage':
2983
- case 'getAttachment':
2984
- case 'listSignatures': {
2985
- if (!assigned.has(message.account)) {
2986
- throw NO_ACTIVE_HANDLER_RESP_ERR;
2987
- }
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
+ }
2988
2962
 
2989
- let assignedWorker = assigned.get(message.account);
2963
+ async function commandRunIndex() {
2964
+ return runIndex;
2965
+ }
2990
2966
 
2991
- let transferList = [];
2992
- // Handle transferable objects
2993
- if (['getRawMessage', 'getAttachment'].includes(message.cmd) && message.port) {
2994
- transferList.push(message.port);
2995
- }
2996
- if (['submitMessage', 'queueMessage'].includes(message.cmd) && typeof message.raw === 'object') {
2997
- transferList.push(message.raw);
2998
- }
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
+ }
2999
2976
 
3000
- 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();
2985
+ }
2986
+ } else {
2987
+ // Spawn new worker if enabled
2988
+ let serverEnabled = await settings.get(`${type}ServerEnabled`);
2989
+ if (serverEnabled) {
2990
+ await spawnWorker(type);
3001
2991
  }
2992
+ }
2993
+ return NOT_HANDLED;
2994
+ }
3002
2995
 
3003
- case 'subconnections': {
3004
- // Get submission connections
3005
- if (!assigned.has(message.account)) {
3006
- return [];
3007
- }
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
+ }
3008
3008
 
3009
- let assignedWorker = assigned.get(message.account);
3010
- return await call(assignedWorker, message, []);
3011
- }
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
+ }
3012
3014
 
3013
- case 'googlePubSub':
3014
- case 'googlePubSubRemove': {
3015
- // Notify all webhook workers about PubSub app changes
3016
- if (!workers.has('webhooks')) {
3017
- return true;
3018
- }
3019
- let proms = [];
3020
- for (let worker of workers.get('webhooks')) {
3021
- proms.push(
3022
- call(worker, message).catch(err => {
3023
- logger.error({ msg: 'Failed to notify webhook worker about PubSub change', cmd: message.cmd, err });
3024
- })
3025
- );
3026
- }
3027
- await Promise.all(proms);
3028
- return true;
3029
- }
3015
+ let assignedWorker = assigned.get(message.account);
3030
3016
 
3031
- case 'externalNotify': {
3032
- // External notification (e.g., Google Push)
3033
- let proms = [];
3034
- for (let account of message.accounts || []) {
3035
- if (!assigned.has(account)) {
3036
- continue;
3037
- }
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
+ }
3038
3025
 
3039
- let assignedWorker = assigned.get(account);
3040
- proms.push(
3041
- call(assignedWorker, { cmd: 'externalNotify', account, historyId: message.historyId }).catch(err => {
3042
- logger.error({ msg: 'External notification failed', cmd: 'externalNotify', account, historyId: message.historyId, err });
3043
- })
3044
- );
3045
- }
3046
- await Promise.all(proms);
3047
- return true;
3048
- }
3026
+ return await call(assignedWorker, message, transferList);
3027
+ }
3049
3028
 
3050
- case 'subscriptionLifecycle': {
3051
- // MS Graph subscription lifecycle event (reauthorizationRequired, subscriptionRemoved)
3052
- if (!assigned.has(message.account)) {
3053
- logger.warn({
3054
- msg: 'Subscription lifecycle event for unassigned account',
3055
- account: message.account,
3056
- event: message.event
3057
- });
3058
- return false;
3059
- }
3060
- let assignedWorker = assigned.get(message.account);
3061
- return await call(assignedWorker, {
3062
- cmd: 'subscriptionLifecycle',
3063
- account: message.account,
3064
- event: message.event,
3065
- timeout: message.timeout
3066
- });
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;
3067
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
+ );
3068
3070
  }
3071
+ await Promise.all(proms);
3072
+ return true;
3073
+ }
3069
3074
 
3070
- 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;
3071
3158
  }
3072
3159
 
3073
3160
  // Metrics collection results
@@ -3274,13 +3361,11 @@ const settleWorkerFleet = async (label, promises, logFields) => {
3274
3361
  };
3275
3362
 
3276
3363
  /**
3277
- * Main application startup
3278
- * @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
3279
3367
  */
3280
- const startApplication = async () => {
3281
- // Generate unique run index
3282
- runIndex = await redis.hincrby(`${REDIS_PREFIX}settings`, 'run', 1);
3283
-
3368
+ const importConfiguredLicenses = async () => {
3284
3369
  // Process license file if provided
3285
3370
  if (config.licensePath) {
3286
3371
  try {
@@ -3298,7 +3383,8 @@ const startApplication = async () => {
3298
3383
  await setLicense(licenseData, licenseFile);
3299
3384
  } catch (err) {
3300
3385
  logger.fatal({ msg: 'License verification failed', source: config.licensePath, err });
3301
- return logger.flush(() => process.exit(13));
3386
+ logger.flush(() => process.exit(13));
3387
+ return true;
3302
3388
  }
3303
3389
  }
3304
3390
 
@@ -3312,10 +3398,19 @@ const startApplication = async () => {
3312
3398
  }
3313
3399
  } catch (err) {
3314
3400
  logger.fatal({ msg: 'License import failed', source: 'import', err });
3315
- return logger.flush(() => process.exit(13));
3401
+ logger.flush(() => process.exit(13));
3402
+ return true;
3316
3403
  }
3317
3404
  }
3318
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 () => {
3319
3414
  // Load license from database
3320
3415
  let licenseFile = await redis.hget(`${REDIS_PREFIX}settings`, 'license');
3321
3416
  if (licenseFile) {
@@ -3338,12 +3433,13 @@ const startApplication = async () => {
3338
3433
  if (!licenseInfo.active) {
3339
3434
  logger.error({ msg: 'No active license. Running in limited mode.' });
3340
3435
  }
3436
+ };
3341
3437
 
3342
- // Check for updates
3343
- processCheckUpgrade().catch(err => {
3344
- logger.warn({ msg: 'Update check failed', err });
3345
- });
3346
-
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 () => {
3347
3443
  // Move any settings-based OAuth2 configuration into the app registry before workers spawn.
3348
3444
  // A failure is not fatal: the source settings keys stay in place, so the migration retries
3349
3445
  // on the next startup (the legacy config is simply not visible until it succeeds).
@@ -3368,7 +3464,13 @@ const startApplication = async () => {
3368
3464
  } catch (err) {
3369
3465
  logger.error({ msg: 'Failed to sweep the retired bounce store', err });
3370
3466
  }
3467
+ };
3371
3468
 
3469
+ /**
3470
+ * Applies EENGINE_SETTINGS and records which keys it manages
3471
+ * @returns {Promise<void>}
3472
+ */
3473
+ const applyPreparedSettings = async () => {
3372
3474
  // Apply prepared settings
3373
3475
  if (preparedSettings) {
3374
3476
  logger.debug({ msg: 'Applying configuration', settingsKeys: Object.keys(preparedSettings) });
@@ -3384,13 +3486,13 @@ const startApplication = async () => {
3384
3486
  } else {
3385
3487
  await settings.clear('preparedSettingsKeys');
3386
3488
  }
3489
+ };
3387
3490
 
3388
- // Initialize required settings
3389
- let existingServiceId = await settings.get('serviceId');
3390
- if (existingServiceId === null) {
3391
- await settings.set('serviceId', crypto.randomBytes(16).toString('hex'));
3392
- }
3393
-
3491
+ /**
3492
+ * Seeds the SMTP server settings that have no stored value yet
3493
+ * @returns {Promise<void>}
3494
+ */
3495
+ const seedSmtpServerSettings = async () => {
3394
3496
  // SMTP server settings
3395
3497
  let existingSmtpEnabled = await settings.get('smtpServerEnabled');
3396
3498
  if (existingSmtpEnabled === null) {
@@ -3421,7 +3523,13 @@ const startApplication = async () => {
3421
3523
  if (existingSmtpProxy === null) {
3422
3524
  await settings.set('smtpServerProxy', SMTP_PROXY);
3423
3525
  }
3526
+ };
3424
3527
 
3528
+ /**
3529
+ * Seeds the IMAP proxy settings that have no stored value yet
3530
+ * @returns {Promise<void>}
3531
+ */
3532
+ const seedImapProxySettings = async () => {
3425
3533
  // IMAP proxy settings
3426
3534
  let existingImapProxyEnabled = await settings.get('imapProxyServerEnabled');
3427
3535
  if (existingImapProxyEnabled === null) {
@@ -3447,18 +3555,23 @@ const startApplication = async () => {
3447
3555
  if (existingImapProxyProxy === null) {
3448
3556
  await settings.set('imapProxyServerProxy', IMAP_PROXY_PROXY);
3449
3557
  }
3558
+ };
3450
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 () => {
3451
3565
  // API proxy settings
3452
3566
  let existingEnableApiProxy = await settings.get('enableApiProxy');
3453
3567
  if (existingEnableApiProxy === null) {
3454
3568
  await settings.set('enableApiProxy', HAS_API_PROXY_SET ? API_PROXY : true);
3455
3569
  }
3456
3570
 
3457
- // Service settings
3458
- let existingServiceSecret = await settings.get('serviceSecret');
3459
- if (existingServiceSecret === null) {
3460
- await settings.set('serviceSecret', crypto.randomBytes(16).toString('hex'));
3461
- }
3571
+ // Service settings. HSETNX rather than read-then-write: a stored secret that does not decrypt
3572
+ // (the wrong EENGINE_SECRET) reads as null, and overwriting it would destroy a value the
3573
+ // rotation CLI can still recover once the right secret is back
3574
+ await settings.setIfMissing('serviceSecret', crypto.randomBytes(16).toString('hex'));
3462
3575
 
3463
3576
  let existingQueueKeep = await settings.get('queueKeep');
3464
3577
  if (existingQueueKeep === null) {
@@ -3495,7 +3608,29 @@ const startApplication = async () => {
3495
3608
  // disableTokens is the inverse of REQUIRE_API_AUTH
3496
3609
  await settings.set('disableTokens', !REQUIRE_API_AUTH);
3497
3610
  }
3611
+ };
3498
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
+ };
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 () => {
3499
3634
  // Import prepared token
3500
3635
  if (preparedToken) {
3501
3636
  try {
@@ -3533,7 +3668,13 @@ const startApplication = async () => {
3533
3668
  logger.error({ msg: 'Password import failed', err });
3534
3669
  }
3535
3670
  }
3671
+ };
3536
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 () => {
3537
3678
  if (!(await getSecret())) {
3538
3679
  // Every consumer of the secret stores the value as it is when there is none, so without
3539
3680
  // it the account passwords, OAuth2 tokens, webhook secrets and TLS keys sit in Redis in
@@ -3549,16 +3690,13 @@ const startApplication = async () => {
3549
3690
  cookiePassword = crypto.randomBytes(32).toString('base64');
3550
3691
  await settings.set('cookiePassword', cookiePassword);
3551
3692
  }
3693
+ };
3552
3694
 
3553
- // Redis reconnection is now handled by workers themselves
3554
- // Workers will exit when Redis reconnects after disconnection,
3555
- // and the server will automatically restart them
3556
-
3557
- // Initialize HTTP proxy agent from settings/env vars before spawning workers
3558
- await reloadHttpProxyAgent();
3559
-
3560
- // -- START WORKER THREADS
3561
-
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 () => {
3562
3700
  // Start API server first for health checks.
3563
3701
  // Optionally run several API workers that share the listen port via SO_REUSEPORT.
3564
3702
  apiWorkersRequested = config.workers.api;
@@ -3609,10 +3747,13 @@ const startApplication = async () => {
3609
3747
  // `attempted` can be below `requested` after the SO_REUSEPORT fallback above
3610
3748
  let apiReady = (await settleWorkerFleet('API', apiPromises, { requested: apiWorkersRequested, attempted: apiPromises.length })).length;
3611
3749
  logger.info({ msg: 'API workers started', requested: apiWorkersRequested, ready: apiReady });
3750
+ };
3612
3751
 
3613
- // Small delay to allow API to start
3614
- await new Promise(r => setTimeout(r, 100));
3615
-
3752
+ /**
3753
+ * Starts the IMAP workers and assigns the accounts to them
3754
+ * @returns {Promise<void>}
3755
+ */
3756
+ const startImapWorkers = async () => {
3616
3757
  // Start IMAP workers
3617
3758
  let workerPromises = [];
3618
3759
  for (let i = 0; i < config.workers.imap; i++) {
@@ -3635,7 +3776,14 @@ const startApplication = async () => {
3635
3776
  } catch (err) {
3636
3777
  logger.error({ msg: 'Initial account assignment failed', err });
3637
3778
  }
3779
+ };
3638
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 () => {
3639
3787
  // Start webhook workers
3640
3788
  for (let i = 0; i < config.workers.webhooks; i++) {
3641
3789
  await spawnWorker('webhooks');
@@ -3670,7 +3818,12 @@ const startApplication = async () => {
3670
3818
  if (await settings.get('imapProxyServerEnabled')) {
3671
3819
  await spawnWorker('imapProxy');
3672
3820
  }
3821
+ };
3673
3822
 
3823
+ /**
3824
+ * Creates and starts the background metrics collector
3825
+ */
3826
+ const startMetricsCollector = () => {
3674
3827
  // Initialize and start the metrics collector after all workers are ready
3675
3828
  metricsCollector = new MetricsCollector({
3676
3829
  logger,
@@ -3714,6 +3867,57 @@ const startApplication = async () => {
3714
3867
  logger.info({ msg: 'Background metrics collector initialized and started' });
3715
3868
  };
3716
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
+
3717
3921
  // Start the application
3718
3922
  startApplication()
3719
3923
  .then(bounceClassifier.initialize)