emailengine-app 2.74.1 → 2.75.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 (60) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/data/google-crawlers.json +1 -1
  3. package/lib/account.js +117 -63
  4. package/lib/api-routes/changes-routes.js +51 -0
  5. package/lib/api-routes/index.js +160 -0
  6. package/lib/api-routes/message-routes.js +3 -1
  7. package/lib/consts.js +21 -0
  8. package/lib/db.js +4 -1
  9. package/lib/egress-filter.js +220 -0
  10. package/lib/email-client/base-client.js +5 -8
  11. package/lib/email-client/gmail/send-request.js +69 -0
  12. package/lib/email-client/gmail-client.js +6 -46
  13. package/lib/email-client/imap/detach-client.js +27 -0
  14. package/lib/email-client/imap/listing-diff.js +165 -0
  15. package/lib/email-client/imap/mailbox.js +35 -22
  16. package/lib/email-client/imap/subconnection.js +2 -4
  17. package/lib/email-client/imap/sync-operations.js +5 -3
  18. package/lib/email-client/imap-client.js +50 -84
  19. package/lib/email-client/notification-handler.js +11 -12
  20. package/lib/email-client/outlook/send-request.js +48 -0
  21. package/lib/email-client/outlook-client.js +7 -19
  22. package/lib/export.js +97 -21
  23. package/lib/imapproxy/imap-core/README.md +69 -0
  24. package/lib/imapproxy/imap-core/lib/imap-connection.js +1 -1
  25. package/lib/logger.js +14 -6
  26. package/lib/oauth/external-account-config.js +41 -1
  27. package/lib/oauth/external-account-signer.js +7 -2
  28. package/lib/oauth/verify-app.js +18 -3
  29. package/lib/queue-retention.js +56 -0
  30. package/lib/rate-limit.js +33 -11
  31. package/lib/respawn-backoff.js +95 -0
  32. package/lib/response-stream.js +138 -0
  33. package/lib/schemas.js +9 -2
  34. package/lib/sentry.js +8 -0
  35. package/lib/settings.js +4 -1
  36. package/lib/smtp-message-processor.js +131 -0
  37. package/lib/tools.js +48 -5
  38. package/lib/ui-routes/admin-config-routes.js +22 -18
  39. package/lib/ui-routes/internals-routes.js +32 -0
  40. package/lib/utils/network.js +122 -3
  41. package/lib/web-safe-html.js +401 -0
  42. package/lib/webhook-request.js +40 -2
  43. package/lib/webhooks.js +2 -3
  44. package/package.json +15 -13
  45. package/sbom.json +1 -1
  46. package/server.js +33 -8
  47. package/static/js/ee-client.js +55 -6
  48. package/static/js/ui.js +13 -0
  49. package/static/licenses.html +336 -286
  50. package/translations/messages.pot +12 -12
  51. package/views/config/webhooks.hbs +2 -2
  52. package/views/internals/index.hbs +8 -0
  53. package/views/partials/webhooks_editor_functions.hbs +1 -1
  54. package/workers/api.js +52 -233
  55. package/workers/documents.js +6 -0
  56. package/workers/export.js +37 -16
  57. package/workers/imap.js +64 -29
  58. package/workers/smtp.js +50 -91
  59. package/workers/submit.js +10 -0
  60. package/workers/webhooks.js +23 -2
@@ -1,10 +1,10 @@
1
1
  msgid ""
2
2
  msgstr ""
3
3
  "Content-Type: text/plain; charset=ascii\n"
4
- "POT-Creation-Date: 2026-07-23 15:18+0000\n"
4
+ "POT-Creation-Date: 2026-07-28 14:15+0000\n"
5
5
 
6
6
  #: views/error.hbs:6
7
- #: workers/api.js:3201
7
+ #: workers/api.js:3019
8
8
  msgid "Something went wrong"
9
9
  msgstr ""
10
10
 
@@ -254,19 +254,19 @@ msgid ""
254
254
  "connect your account."
255
255
  msgstr ""
256
256
 
257
- #: lib/tools.js:1040
257
+ #: lib/tools.js:1056
258
258
  #: lib/ui-routes/unsubscribe-routes.js:28
259
259
  #: lib/ui-routes/unsubscribe-routes.js:92
260
260
  msgid "Invalid input"
261
261
  msgstr ""
262
262
 
263
- #: lib/tools.js:1877
263
+ #: lib/tools.js:1893
264
264
  msgid "Signature validation failed"
265
265
  msgstr ""
266
266
 
267
- #: lib/tools.js:1900
268
- #: lib/tools.js:1906
269
- #: lib/tools.js:1911
267
+ #: lib/tools.js:1916
268
+ #: lib/tools.js:1922
269
+ #: lib/tools.js:1927
270
270
  #: lib/ui-routes/account-routes.js:976
271
271
  msgid "Invalid or expired account setup URL"
272
272
  msgstr ""
@@ -277,8 +277,8 @@ msgstr ""
277
277
  #: lib/ui-routes/account-routes.js:748
278
278
  #: lib/ui-routes/account-routes.js:1006
279
279
  #: lib/ui-routes/account-routes.js:1098
280
- #: workers/api.js:2376
281
- #: workers/api.js:2730
280
+ #: workers/api.js:2292
281
+ #: workers/api.js:2646
282
282
  msgid "Email Account Setup"
283
283
  msgstr ""
284
284
 
@@ -345,7 +345,7 @@ msgstr ""
345
345
  msgid "Temporary error, please try again"
346
346
  msgstr ""
347
347
 
348
- #: lib/ui-routes/admin-config-routes.js:171
348
+ #: lib/ui-routes/admin-config-routes.js:173
349
349
  msgid "Invalid API key for OpenAI"
350
350
  msgstr ""
351
351
 
@@ -399,7 +399,7 @@ msgstr ""
399
399
  msgid "Couldn't process request. Try again."
400
400
  msgstr ""
401
401
 
402
- #: workers/api.js:3200
403
- #: workers/api.js:3315
402
+ #: workers/api.js:3018
403
+ #: workers/api.js:3119
404
404
  msgid "Requested page not found"
405
405
  msgstr ""
@@ -171,7 +171,7 @@ class="mb-1"}}
171
171
  {{> ui/checkbox id="settingsNotifyWebSafeHtml" name="notifyWebSafeHtml"
172
172
  label="Sanitize HTML for web display" class="text-list" checked=values.notifyWebSafeHtml
173
173
  error=errors.notifyWebSafeHtml
174
- hint="Makes HTML safe for direct web page display. Converts plain text emails to HTML when needed."}}
174
+ hint="Makes HTML safe for direct web page display. Converts plain text emails to HTML when needed, and folds quoted thread history into a collapsed block."}}
175
175
  </div>
176
176
 
177
177
  <div>
@@ -285,7 +285,7 @@ class="mb-1"}}
285
285
  document.getElementById('test-payload-btn').addEventListener('click', e => {
286
286
  e.preventDefault()
287
287
  sendTestPayload().then(data => {
288
- showToast(data.error ? data.error : (data.success ? 'Test payload sent' : 'Failed to send payload'), data.success ? 'check-circle' : 'alert-triangle');
288
+ uiToastResult(data, 'Test payload sent', 'Failed to send payload');
289
289
  }).catch(err => {
290
290
  showToast('Request failed\n' + err.message, 'alert-triangle');
291
291
  })
@@ -76,6 +76,14 @@
76
76
  {{errorMessage}}
77
77
  {{/ui/tooltip-rich}}
78
78
  {{/if}}
79
+ {{#if recentlyRestarted}}
80
+ {{#> ui/tooltip-rich icon="icon-[tabler--refresh] text-warning"}}
81
+ <strong>Recently restarted</strong><br>
82
+ This worker came online noticeably later than the main process, so it started
83
+ after the initial boot rather than with the rest of the fleet. See the Uptime
84
+ column for when it last started.
85
+ {{/ui/tooltip-rich}}
86
+ {{/if}}
79
87
  </span>
80
88
  </td>
81
89
  <td><span class="text-base-content/60 font-mono text-sm">#{{formatInteger threadId userLocale}}</span></td>
@@ -20,7 +20,7 @@
20
20
  testSendBtn.addEventListener('click', e => {
21
21
  e.preventDefault();
22
22
  sendTestPayload().then(data => {
23
- showToast(data.error ? data.error : (data.success ? 'Test payload sent' : 'Failed to send payload'), data.success ? 'check-circle' : 'alert-triangle');
23
+ uiToastResult(data, 'Test payload sent', 'Failed to send payload');
24
24
  }).catch(err => {
25
25
  showToast('Request failed\n' + err.message, 'alert-triangle');
26
26
  })
package/workers/api.js CHANGED
@@ -30,6 +30,7 @@ const {
30
30
  runPrechecks,
31
31
  matcher,
32
32
  readEnvValue,
33
+ readEnvList,
33
34
  threadStats,
34
35
  hasEnvValue,
35
36
  getBoolean,
@@ -42,7 +43,7 @@ const {
42
43
  releaseFormNonce,
43
44
  setAdminSession
44
45
  } = require('../lib/tools');
45
- const { matchIp, detectAutomatedRequest } = require('../lib/utils/network');
46
+ const { matchIp, resolveClientIp, detectAutomatedRequest } = require('../lib/utils/network');
46
47
 
47
48
  const { initSentry } = require('../lib/sentry');
48
49
  initSentry('api');
@@ -61,7 +62,7 @@ const HapiSwagger = require('hapi-swagger');
61
62
  const pathlib = require('path');
62
63
 
63
64
  const crypto = require('crypto');
64
- const { Transform, finished } = require('stream');
65
+ const { registeredPublishers, openChangeStream } = require('../lib/response-stream');
65
66
  const { oauth2Apps, OAUTH_PROVIDERS } = require('../lib/oauth2-apps');
66
67
 
67
68
  const handlebars = require('handlebars');
@@ -101,27 +102,10 @@ const {
101
102
  NONCE_BYTES
102
103
  } = consts;
103
104
 
104
- const templateRoutes = require('../lib/api-routes/template-routes');
105
- const chatRoutes = require('../lib/api-routes/chat-routes');
105
+ const registerApiRoutes = require('../lib/api-routes');
106
106
  const bullBoardRoutes = require('../lib/api-routes/bull-board-routes');
107
- const accountRoutes = require('../lib/api-routes/account-routes');
108
- const messageRoutes = require('../lib/api-routes/message-routes');
109
- const exportRoutes = require('../lib/api-routes/export-routes');
110
- const pubsubRoutes = require('../lib/api-routes/pubsub-routes');
111
- const tokenRoutes = require('../lib/api-routes/token-routes');
112
- const mailboxRoutes = require('../lib/api-routes/mailbox-routes');
113
- const settingsRoutes = require('../lib/api-routes/settings-routes');
114
- const statsRoutes = require('../lib/api-routes/stats-routes');
115
- const licenseRoutes = require('../lib/api-routes/license-routes');
116
- const outboxRoutes = require('../lib/api-routes/outbox-routes');
117
- const webhookRouteRoutes = require('../lib/api-routes/webhook-route-routes');
118
- const oauth2AppRoutes = require('../lib/api-routes/oauth2-app-routes');
119
- const gatewayRoutes = require('../lib/api-routes/gateway-routes');
120
- const deliveryTestRoutes = require('../lib/api-routes/delivery-test-routes');
121
- const blocklistRoutes = require('../lib/api-routes/blocklist-routes');
122
- const submitRoutes = require('../lib/api-routes/submit-routes');
123
-
124
- const { imapSchema, smtpSchema, oauth2Schema, accountIdSchema, headerTimeoutSchema, errorResponses } = require('../lib/schemas');
107
+
108
+ const { imapSchema, smtpSchema, oauth2Schema, accountIdSchema, headerTimeoutSchema } = require('../lib/schemas');
125
109
 
126
110
  const OAuth2ProviderSchema = Joi.string()
127
111
  .valid(...Object.keys(OAUTH_PROVIDERS))
@@ -218,12 +202,11 @@ const USE_REUSE_PORT = !!(workerData && workerData.reusePort);
218
202
  // that must execute exactly once across all API workers.
219
203
  const IS_PRIMARY_API_WORKER = WORKER_INDEX === 0;
220
204
 
221
- const ADMIN_ACCESS_ADDRESSES = hasEnvValue('EENGINE_ADMIN_ACCESS_ADDRESSES')
222
- ? readEnvValue('EENGINE_ADMIN_ACCESS_ADDRESSES')
223
- .split(',')
224
- .map(v => v.trim())
225
- .filter(v => v)
226
- : null;
205
+ const ADMIN_ACCESS_ADDRESSES = readEnvList('EENGINE_ADMIN_ACCESS_ADDRESSES');
206
+
207
+ // Peers allowed to set X-Forwarded-For. Unset means the header is honored from any peer whenever
208
+ // the API proxy setting is on, which is the historical behavior; see resolveClientIp().
209
+ const API_PROXY_ADDRESSES = readEnvList('EENGINE_API_PROXY_ADDRESSES');
227
210
 
228
211
  const IMAP_WORKER_COUNT = getWorkerCount(readEnvValue('EENGINE_WORKERS') || (config.workers && config.workers.imap)) || 4;
229
212
 
@@ -279,73 +262,6 @@ logger.info({
279
262
 
280
263
  const TRACKER_IMAGE = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');
281
264
 
282
- let registeredPublishers = new Set();
283
-
284
- class ResponseStream extends Transform {
285
- constructor() {
286
- super();
287
- registeredPublishers.add(this);
288
- this.periodicKeepAliveTimer = false;
289
- this.updateTimer();
290
-
291
- this._finalized = false;
292
-
293
- // Ensure cleanup on all stream end scenarios
294
- this.on('error', () => this.finalize());
295
- this.once('close', () => this.finalize());
296
- this.once('end', () => this.finalize());
297
- }
298
-
299
- updateTimer() {
300
- clearTimeout(this.periodicKeepAliveTimer);
301
- this.periodicKeepAliveTimer = setTimeout(() => {
302
- if (this._finalized || this.destroyed) return;
303
- this.write(': still here\n\n');
304
- if (this._compressor) {
305
- this._compressor.flush();
306
- }
307
- this.updateTimer();
308
- }, 90 * 1000);
309
- this.periodicKeepAliveTimer.unref();
310
- }
311
-
312
- setCompressor(compressor) {
313
- this._compressor = compressor;
314
- }
315
-
316
- sendMessage(payload) {
317
- if (this._finalized || this.destroyed) return;
318
- let sendData = JSON.stringify(payload);
319
- this.write('event: message\ndata:' + sendData + '\n\n');
320
- if (this._compressor) {
321
- this._compressor.flush();
322
- }
323
- this.updateTimer();
324
- }
325
-
326
- finalize() {
327
- if (this._finalized) return; // Prevent double cleanup
328
- this._finalized = true;
329
-
330
- clearTimeout(this.periodicKeepAliveTimer);
331
- registeredPublishers.delete(this);
332
-
333
- if (!this.destroyed) {
334
- this.destroy();
335
- }
336
- }
337
-
338
- _transform(data, encoding, done) {
339
- this.push(data);
340
- done();
341
- }
342
-
343
- _flush(done) {
344
- this.finalize();
345
- done();
346
- }
347
- }
348
-
349
265
  let callQueue = new Map();
350
266
  let mids = 0;
351
267
 
@@ -862,19 +778,19 @@ const init = async () => {
862
778
  // set default, will be overriden once active language is resolved
863
779
  request.app.gt = gt;
864
780
 
781
+ // Both settings are needed on every request and neither depends on the other, so they are
782
+ // read in a single HMGET rather than two serialized round trips
783
+ let { enableApiProxy, disableTokens } = await settings.getMulti('enableApiProxy', 'disableTokens');
784
+
865
785
  // check if client IP is resolved from X-Forwarded-For or not
866
- let enableApiProxy = (await settings.get('enableApiProxy')) || false;
867
- if (enableApiProxy) {
868
- // check for the IP address from the Forwarded-For header
869
- const xFF = request.headers['x-forwarded-for'];
870
- request.app.ip = xFF ? xFF.split(',')[0] : request.info.remoteAddress;
871
- } else {
872
- // use socket address
873
- request.app.ip = request.info.remoteAddress;
874
- }
786
+ request.app.ip = resolveClientIp({
787
+ remoteAddress: request.info.remoteAddress,
788
+ forwardedFor: request.headers['x-forwarded-for'],
789
+ enableApiProxy: enableApiProxy || false,
790
+ trustedProxies: API_PROXY_ADDRESSES
791
+ });
875
792
 
876
793
  // check if access tokens for api requests are required
877
- let disableTokens = await settings.get('disableTokens');
878
794
  if (disableTokens && !request.url.searchParams.get('access_token') && !request.headers.authorization) {
879
795
  // make sure that we have a access_token value set in query args
880
796
  let url = new URL(request.url.href);
@@ -2779,124 +2695,26 @@ Include your token in requests using one of these methods:
2779
2695
  }
2780
2696
  });
2781
2697
 
2782
- // setup template routes
2783
- await templateRoutes({ server, call, CORS_CONFIG });
2784
-
2785
- // setup "chat with email" routes (deprecated Document Store feature; only when enabled)
2786
- if (documentStoreFeatureEnabled) {
2787
- await chatRoutes({ server, call, CORS_CONFIG });
2788
- }
2789
-
2790
- // setup account CRUD routes
2791
- await accountRoutes({
2698
+ // setup every /v1 route module (wiring lives in lib/api-routes/index.js so the route table
2699
+ // can be captured without booting this worker - see test/api-routes-table-test.js)
2700
+ await registerApiRoutes({
2792
2701
  server,
2793
2702
  call,
2703
+ notify,
2794
2704
  documentsQueue,
2795
- oauth2Schema,
2796
- imapSchema,
2797
- smtpSchema,
2798
- CORS_CONFIG,
2799
- AccountTypeSchema,
2800
- OAuth2ProviderSchema,
2801
- metrics
2802
- });
2803
-
2804
- // setup message routes
2805
- await messageRoutes({
2806
- server,
2807
- call,
2705
+ metrics,
2808
2706
  CORS_CONFIG,
2707
+ FLAG_SORT_ORDER,
2708
+ SMTP_TEST_HOST,
2809
2709
  MAX_ATTACHMENT_SIZE,
2810
2710
  MAX_BODY_SIZE,
2811
2711
  MAX_PAYLOAD_TIMEOUT,
2812
- documentStoreFeatureEnabled
2813
- });
2814
-
2815
- // setup export routes
2816
- await exportRoutes({
2817
- server,
2818
- CORS_CONFIG
2819
- });
2820
-
2821
- // setup Pub/Sub status route
2822
- await pubsubRoutes({ server, CORS_CONFIG });
2823
-
2824
- // setup access token routes
2825
- await tokenRoutes({ server, call, CORS_CONFIG });
2826
-
2827
- // setup mailbox routes
2828
- await mailboxRoutes({ server, call, CORS_CONFIG, FLAG_SORT_ORDER });
2829
-
2830
- // setup settings routes
2831
- await settingsRoutes({ server, notify, CORS_CONFIG });
2832
-
2833
- // setup stats route
2834
- await statsRoutes({ server, call, CORS_CONFIG });
2835
-
2836
- // setup license routes
2837
- await licenseRoutes({ server, call, CORS_CONFIG });
2838
-
2839
- // setup outbox routes
2840
- await outboxRoutes({ server, CORS_CONFIG });
2841
-
2842
- // setup webhook route management routes
2843
- await webhookRouteRoutes({ server, CORS_CONFIG });
2844
-
2845
- // setup OAuth2 application routes
2846
- await oauth2AppRoutes({ server, call, CORS_CONFIG, OAuth2ProviderSchema });
2847
-
2848
- // setup SMTP gateway routes
2849
- await gatewayRoutes({ server, call, CORS_CONFIG });
2850
-
2851
- // setup delivery test routes
2852
- await deliveryTestRoutes({ server, call, CORS_CONFIG, SMTP_TEST_HOST });
2853
-
2854
- // setup blocklist routes
2855
- await blocklistRoutes({ server, call, CORS_CONFIG });
2856
-
2857
- // setup message submit route
2858
- await submitRoutes({ server, call, CORS_CONFIG, MAX_ATTACHMENT_SIZE, MAX_BODY_SIZE, MAX_PAYLOAD_TIMEOUT });
2859
-
2860
- server.route({
2861
- method: 'GET',
2862
- path: '/v1/changes',
2863
-
2864
- async handler(request, h) {
2865
- request.app.stream = new ResponseStream();
2866
- finished(request.app.stream, err => request.app.stream.finalize(err));
2867
- setImmediate(() => {
2868
- try {
2869
- request.app.stream.write(`: EmailEngine v${packageData.version}\n\n`);
2870
- } catch (err) {
2871
- // ignore
2872
- }
2873
- });
2874
- return h
2875
- .response(request.app.stream)
2876
- .header('X-Accel-Buffering', 'no')
2877
- .header('Connection', 'keep-alive')
2878
- .header('Cache-Control', 'no-cache')
2879
- .type('text/event-stream');
2880
- },
2881
-
2882
- options: {
2883
- description: 'Stream state changes',
2884
- notes: 'Stream account state changes as an EventSource',
2885
- tags: ['api', 'Account'],
2886
-
2887
- plugins: {
2888
- 'hapi-swagger': {
2889
- produces: ['text/event-stream'],
2890
- responses: errorResponses(401, 403, 429, 500)
2891
- }
2892
- },
2893
-
2894
- auth: {
2895
- strategy: 'api-token',
2896
- mode: 'required'
2897
- },
2898
- cors: CORS_CONFIG
2899
- }
2712
+ documentStoreFeatureEnabled,
2713
+ oauth2Schema,
2714
+ imapSchema,
2715
+ smtpSchema,
2716
+ AccountTypeSchema,
2717
+ OAuth2ProviderSchema
2900
2718
  });
2901
2719
 
2902
2720
  // Web UI routes
@@ -3266,23 +3084,9 @@ Include your token in requests using one of these methods:
3266
3084
  method: 'GET',
3267
3085
  path: '/admin/changes',
3268
3086
 
3269
- async handler(request, h) {
3270
- request.app.stream = new ResponseStream();
3271
- finished(request.app.stream, err => request.app.stream.finalize(err));
3272
- setImmediate(() => {
3273
- try {
3274
- request.app.stream.write(`: EmailEngine v${packageData.version}\n\n`);
3275
- } catch (err) {
3276
- // ignore
3277
- }
3278
- });
3279
- return h
3280
- .response(request.app.stream)
3281
- .header('X-Accel-Buffering', 'no')
3282
- .header('Connection', 'keep-alive')
3283
- .header('Cache-Control', 'no-cache')
3284
- .type('text/event-stream');
3285
- }
3087
+ // Same feed as /v1/changes (lib/api-routes/changes-routes.js), opened through the shared
3088
+ // helper so the two can not drift apart on framing or on stream cleanup.
3089
+ handler: openChangeStream
3286
3090
  });
3287
3091
 
3288
3092
  // setup web UI
@@ -3347,6 +3151,21 @@ Include your token in requests using one of these methods:
3347
3151
  });
3348
3152
  }
3349
3153
 
3154
+ // An IP allowlist is only as trustworthy as the address it matches against. If the deployment
3155
+ // takes the client address from X-Forwarded-For but does not say which peers may set it, any
3156
+ // client that can reach this port can present whatever address the allowlist expects.
3157
+ // Length-checked, not just null-checked: readEnvList returns [] for a variable that is present
3158
+ // but empty (an unset shell interpolation, an empty secret), which is truthy. resolveClientIp
3159
+ // treats that as no proxies configured, so the warning has to agree or it goes quiet in
3160
+ // exactly the deployment it exists to warn.
3161
+ if (ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length && !API_PROXY_ADDRESSES?.length && (await settings.get('enableApiProxy'))) {
3162
+ logger.warn({
3163
+ msg: 'Admin IP allowlist is spoofable because X-Forwarded-For is trusted from any peer. Set EENGINE_API_PROXY_ADDRESSES to the addresses of your proxies, or disable the API proxy setting.',
3164
+ component: 'api',
3165
+ allowedAddresses: ADMIN_ACCESS_ADDRESSES
3166
+ });
3167
+ }
3168
+
3350
3169
  // trigger a request to cache swagger.json
3351
3170
  setImmediate(() => {
3352
3171
  server
@@ -92,6 +92,12 @@ async function onCommand(command) {
92
92
  switch (command.cmd) {
93
93
  case 'resource-usage':
94
94
  return threadStats.usage();
95
+
96
+ // Shutdown drain, forwarded by server.js because signals only reach the main thread
97
+ case 'close':
98
+ await documentsWorker.close();
99
+ return true;
100
+
95
101
  default:
96
102
  logger.debug({ msg: 'Unhandled command', command });
97
103
  return 999;
package/workers/export.js CHANGED
@@ -20,7 +20,18 @@ const {
20
20
  const { getDuration, readEnvValue, threadStats, maybeReloadHttpProxyAgent } = require('../lib/tools');
21
21
  const { webhooks: Webhooks } = require('../lib/webhooks');
22
22
  const settings = require('../lib/settings');
23
- const { Export, isTransientError, isSkippableError, isFolderMissingError, isRetryableError } = require('../lib/export');
23
+ const {
24
+ Export,
25
+ isTransientError,
26
+ isSkippableError,
27
+ isFolderMissingError,
28
+ isRetryableError,
29
+ resolveExportLimit,
30
+ isExportLimitReached,
31
+ parseActiveEntry,
32
+ getExportKey,
33
+ ACTIVE_EXPORTS_KEY
34
+ } = require('../lib/export');
24
35
 
25
36
  const { initSentry } = require('../lib/sentry');
26
37
  initSentry('export');
@@ -174,7 +185,7 @@ async function indexMessages(job, exportData) {
174
185
 
175
186
  await Export.update(account, exportId, { foldersTotal: foldersToProcess.length });
176
187
 
177
- const maxMessages = Number(await settings.get('exportMaxMessages')) || DEFAULT_EXPORT_MAX_MESSAGES;
188
+ const maxMessages = resolveExportLimit(await settings.get('exportMaxMessages'), DEFAULT_EXPORT_MAX_MESSAGES);
178
189
 
179
190
  logger.info({ msg: 'Starting export indexing', account, exportId, foldersToProcess: foldersToProcess.length, maxMessages: maxMessages || 'unlimited' });
180
191
 
@@ -249,7 +260,7 @@ async function indexMessages(job, exportData) {
249
260
  // The folder indexed successfully (failures throw above); count it toward progress.
250
261
  await Export.update(account, exportId, { foldersScanned: i + 1 });
251
262
 
252
- if (maxMessages && totalIndexed >= maxMessages) {
263
+ if (isExportLimitReached(totalIndexed, maxMessages)) {
253
264
  truncated = true;
254
265
  logger.warn({
255
266
  msg: 'Export indexing truncated: message limit reached',
@@ -354,8 +365,8 @@ async function exportMessages(job, exportData) {
354
365
  const rawMaxBytes = Number(exportData.maxBytes);
355
366
  // Preserve an explicit 0 ("unlimited" per the API contract); only fall back when unset/invalid.
356
367
  const maxBytes = Number.isFinite(rawMaxBytes) ? rawMaxBytes : 5 * 1024 * 1024;
357
- const maxMessageSize = (await settings.get('exportMaxMessageSize')) || DEFAULT_EXPORT_MAX_MESSAGE_SIZE;
358
- const maxExportSize = Number(await settings.get('exportMaxSize')) || DEFAULT_EXPORT_MAX_SIZE;
368
+ const maxMessageSize = resolveExportLimit(await settings.get('exportMaxMessageSize'), DEFAULT_EXPORT_MAX_MESSAGE_SIZE);
369
+ const maxExportSize = resolveExportLimit(await settings.get('exportMaxSize'), DEFAULT_EXPORT_MAX_SIZE);
359
370
  const isEncrypted = exportData.isEncrypted === '1';
360
371
 
361
372
  const accountObject = new Account({
@@ -576,7 +587,7 @@ async function exportMessages(job, exportData) {
576
587
  }
577
588
  } else if (result && result.data) {
578
589
  await processMessage(result.data, entry);
579
- if (maxExportSize && totalBytesWritten >= maxExportSize) {
590
+ if (isExportLimitReached(totalBytesWritten, maxExportSize)) {
580
591
  sizeLimitReached = true;
581
592
  break;
582
593
  }
@@ -661,7 +672,7 @@ async function exportMessages(job, exportData) {
661
672
 
662
673
  if (message) {
663
674
  await processMessage(message, entry);
664
- if (maxExportSize && totalBytesWritten >= maxExportSize) {
675
+ if (isExportLimitReached(totalBytesWritten, maxExportSize)) {
665
676
  sizeLimitReached = true;
666
677
  break;
667
678
  }
@@ -842,10 +853,17 @@ exportWorker.on('failed', async (job, err) => {
842
853
  });
843
854
  });
844
855
 
845
- function onCommand(command) {
856
+ async function onCommand(command) {
846
857
  if (command.cmd === 'resource-usage') {
847
858
  return threadStats.usage();
848
859
  }
860
+
861
+ // Shutdown drain, forwarded by server.js because signals only reach the main thread
862
+ if (command.cmd === 'close') {
863
+ await exportWorker.close();
864
+ return true;
865
+ }
866
+
849
867
  logger.debug({ msg: 'Unhandled command', command });
850
868
  return 999;
851
869
  }
@@ -883,16 +901,19 @@ function onCommand(command) {
883
901
  setInterval(
884
902
  async () => {
885
903
  try {
886
- const activeExports = await redis.smembers(`${REDIS_PREFIX}exp:active`);
904
+ // The set key, the entry encoding and the export key all come from lib/export.js.
905
+ // Hand-building them here meant this cleanup and the limiter that writes the
906
+ // entries could drift apart: entries added under one encoding and removed under
907
+ // another leave the active set growing forever, and once it reaches the global
908
+ // limit every export in the deployment is refused with 429.
909
+ const activeExports = await redis.smembers(ACTIVE_EXPORTS_KEY);
887
910
  for (const entry of activeExports) {
888
- const separatorIndex = entry.lastIndexOf(':exp_');
889
- if (separatorIndex === -1) continue;
890
- const entryAccount = entry.substring(0, separatorIndex);
891
- const entryExportId = entry.substring(separatorIndex + 1);
892
- const exists = await redis.exists(`${REDIS_PREFIX}exp:${entryAccount}:${entryExportId}`);
911
+ const parsed = parseActiveEntry(entry);
912
+ if (!parsed) continue;
913
+ const exists = await redis.exists(getExportKey(parsed.account, parsed.exportId));
893
914
  if (!exists) {
894
- await redis.srem(`${REDIS_PREFIX}exp:active`, entry);
895
- logger.info({ msg: 'Cleaned stale active set entry', account: entryAccount, exportId: entryExportId });
915
+ await redis.srem(ACTIVE_EXPORTS_KEY, entry);
916
+ logger.info({ msg: 'Cleaned stale active set entry', account: parsed.account, exportId: parsed.exportId });
896
917
  }
897
918
  }
898
919
  } catch (err) {