emailengine-app 2.88.0 → 2.90.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 (79) hide show
  1. package/.ncurc.js +36 -45
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +58 -0
  4. package/Dockerfile +5 -1
  5. package/bin/healthcheck.js +1 -1
  6. package/copy-static-files.sh +0 -8
  7. package/data/google-crawlers.json +1 -1
  8. package/encrypt.js +1 -4
  9. package/lib/account/field-codec.js +396 -0
  10. package/lib/account.js +158 -453
  11. package/lib/api-routes/account-routes.js +42 -6
  12. package/lib/api-routes/route-metadata.js +5 -2
  13. package/lib/api-routes/submit-routes.js +15 -2
  14. package/lib/api-token-auth.js +342 -274
  15. package/lib/arf-detect.js +174 -149
  16. package/lib/attachment-size.js +29 -0
  17. package/lib/autodetect-imap-settings.js +83 -234
  18. package/lib/consts.js +1 -5
  19. package/lib/db.js +1 -4
  20. package/lib/email-client/base-client.js +907 -780
  21. package/lib/email-client/gmail-client.js +557 -450
  22. package/lib/email-client/imap/cid-parts.js +61 -0
  23. package/lib/email-client/imap/mailbox.js +376 -422
  24. package/lib/email-client/imap/sync-operations.js +239 -178
  25. package/lib/email-client/new-message-steps.js +168 -2
  26. package/lib/email-client/outlook/graph-message.js +266 -0
  27. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  28. package/lib/email-client/outlook-client.js +652 -808
  29. package/lib/get-raw-email.js +338 -232
  30. package/lib/get-secret.js +1 -4
  31. package/lib/license-subscription.js +77 -11
  32. package/lib/load-env.js +48 -0
  33. package/lib/logger.js +1 -4
  34. package/lib/mcp/tools.js +244 -207
  35. package/lib/metric-values.js +76 -0
  36. package/lib/metrics.js +320 -0
  37. package/lib/node-version.js +99 -12
  38. package/lib/oauth/gmail.js +39 -120
  39. package/lib/oauth/http-request.js +195 -0
  40. package/lib/oauth/mail-ru.js +24 -58
  41. package/lib/oauth/outlook.js +37 -137
  42. package/lib/oauth/pubsub/google.js +176 -117
  43. package/lib/oauth2-apps.js +440 -463
  44. package/lib/openapi/build-document.js +10 -10
  45. package/lib/read-env-value.js +1 -1
  46. package/lib/route-descriptors.js +78 -0
  47. package/lib/schemas.js +10 -1
  48. package/lib/sentry-integrations.js +299 -0
  49. package/lib/sentry.js +75 -27
  50. package/lib/settings.js +4 -1
  51. package/lib/sso-routes.js +249 -0
  52. package/lib/sso.js +29 -6
  53. package/lib/tools.js +5 -4
  54. package/lib/ui-routes/account-edit-form.js +198 -0
  55. package/lib/ui-routes/account-page.js +241 -0
  56. package/lib/ui-routes/account-routes.js +12 -318
  57. package/lib/ui-routes/auth-routes.js +10 -10
  58. package/lib/ui-routes/dashboard-routes.js +4 -0
  59. package/lib/ui-view-context.js +328 -0
  60. package/lib/utils/public-suffix.js +22 -101
  61. package/lib/web-safe-html.js +70 -13
  62. package/lib/worker-metrics.js +82 -0
  63. package/list-generate.js +57 -23
  64. package/package.json +34 -33
  65. package/sbom.json +380 -1612
  66. package/scripts/refresh-test-tokens.js +1 -1
  67. package/server.js +351 -707
  68. package/static/css/flyonui.css +1 -1
  69. package/static/css/src/app.tailwind.css +18 -0
  70. package/static/js/ee-client.js +2619 -645
  71. package/static/js/ui.js +12 -2
  72. package/static/licenses.html +1055 -969
  73. package/translations/messages.pot +71 -60
  74. package/views/accounts/browse.hbs +19 -1
  75. package/views/dashboard.hbs +9 -0
  76. package/views/upgrade.hbs +25 -0
  77. package/workers/api.js +20 -451
  78. package/data/public_suffix_list.dat +0 -16597
  79. package/lib/net-tos-guard.js +0 -42
@@ -180,15 +180,8 @@ class PubSubInstance {
180
180
  return;
181
181
  }
182
182
 
183
- // Check if subscription needs initial setup (use cached data first)
184
- await this.getApp();
185
- if (!this.appData.pubSubSubscription) {
186
- // Force refresh to confirm subscription is really missing
187
- await this.getApp(true);
188
- if (!this.appData.pubSubSubscription) {
189
- await this.attemptRecovery('Subscription not configured');
190
- return; // re-enter pull loop via startLoop
191
- }
183
+ if (!(await this.ensureSubscriptionConfigured())) {
184
+ return; // re-enter pull loop via startLoop
192
185
  }
193
186
 
194
187
  let accessToken = await this.getAccessToken();
@@ -203,21 +196,7 @@ class PubSubInstance {
203
196
  try {
204
197
  let pullStartTime = Date.now();
205
198
 
206
- this._abortController = new AbortController();
207
- let pullTimeoutId = setTimeout(() => this._abortController.abort(), 5 * 60 * 1000);
208
- let pullRes;
209
- try {
210
- pullRes = await this.client.request(
211
- accessToken,
212
- pullUrl,
213
- 'POST',
214
- { returnImmediately: false, maxMessages: 100 },
215
- { signal: this._abortController.signal }
216
- );
217
- } finally {
218
- clearTimeout(pullTimeoutId);
219
- this._abortController = null;
220
- }
199
+ let pullRes = await this.pullMessages(accessToken, pullUrl);
221
200
  if (this.stopped) {
222
201
  return;
223
202
  }
@@ -231,56 +210,15 @@ class PubSubInstance {
231
210
  reqTime
232
211
  });
233
212
 
234
- // Collect ackIds for batch acknowledgement
235
- let ackIds = [];
236
-
237
- for (let receivedMessage of pullRes?.receivedMessages || []) {
238
- // Check stopped flag at start of each message for faster shutdown
239
- if (this.stopped) {
240
- logger.info({ msg: 'Stopping message processing due to shutdown', app: this.app });
241
- return;
242
- }
243
-
244
- let messageId = receivedMessage?.message?.messageId;
245
-
246
- try {
247
- await this.processPulledMessage(messageId, Buffer.from(receivedMessage?.message?.data || '', 'base64').toString());
248
- } catch (err) {
249
- // Processing failed - skip ACK so message will be redelivered
250
- logger.error({ msg: 'Failed to process subscription message', app: this.app, messageId, err });
251
- continue;
252
- }
253
-
254
- if (receivedMessage?.ackId) {
255
- ackIds.push(receivedMessage.ackId);
256
- }
213
+ let ackIds = await this.processPulledBatch(pullRes);
214
+ if (!ackIds) {
215
+ // stopped while processing
216
+ return;
257
217
  }
258
218
 
259
219
  // Batch ACK all successfully processed messages
260
220
  if (ackIds.length > 0) {
261
- // Refresh access token if the pull took a long time (token may be near expiration)
262
- let elapsed = Date.now() - pullStartTime;
263
- if (elapsed > 4 * 60 * 1000) {
264
- try {
265
- accessToken = await this.getAccessToken();
266
- } catch (err) {
267
- logger.warn({ msg: 'Failed to refresh access token before ACK, using original', app: this.app, err });
268
- }
269
- }
270
-
271
- try {
272
- await this.client.request(accessToken, acknowledgeUrl, 'POST', { ackIds }, { returnText: true });
273
- logger.debug({ msg: 'Batch acked subscription messages', app: this.app, count: ackIds.length });
274
- } catch (err) {
275
- logger.warn({ msg: 'Batch ACK failed, retrying once', app: this.app, count: ackIds.length, err });
276
- try {
277
- await new Promise(resolve => setTimeout(resolve, 1000));
278
- await this.client.request(accessToken, acknowledgeUrl, 'POST', { ackIds }, { returnText: true });
279
- logger.info({ msg: 'Batch ACK retry succeeded', app: this.app, count: ackIds.length });
280
- } catch (retryErr) {
281
- logger.error({ msg: 'Batch ACK retry also failed, messages will be redelivered', app: this.app, count: ackIds.length, err: retryErr });
282
- }
283
- }
221
+ await this.ackMessages(ackIds, accessToken, acknowledgeUrl, pullStartTime);
284
222
  }
285
223
 
286
224
  if (this._hadPubSubFlag) {
@@ -294,63 +232,184 @@ class PubSubInstance {
294
232
 
295
233
  return ackIds.length;
296
234
  } catch (err) {
297
- // Manual timeout abort or shutdown - not an error, just restart the loop
298
- if (err.name === 'AbortError') {
299
- throw err;
235
+ return await this.handlePullError(err);
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Checks the app has a subscription to pull from, using the cached app data first and a fresh
241
+ * read to confirm a missing one, and runs a recovery attempt when it is really missing
242
+ * @returns {Promise<boolean>} False when there was nothing to pull from
243
+ */
244
+ async ensureSubscriptionConfigured() {
245
+ await this.getApp();
246
+ if (this.appData.pubSubSubscription) {
247
+ return true;
248
+ }
249
+
250
+ // Force refresh to confirm subscription is really missing
251
+ await this.getApp(true);
252
+ if (this.appData.pubSubSubscription) {
253
+ return true;
254
+ }
255
+
256
+ await this.attemptRecovery('Subscription not configured');
257
+ return false;
258
+ }
259
+
260
+ /**
261
+ * One long-poll pull, aborted after five minutes or by stop()
262
+ * @param {string} accessToken - Service access token
263
+ * @param {string} pullUrl - The subscription's pull URL
264
+ * @returns {Promise<Object>} Pull response
265
+ */
266
+ async pullMessages(accessToken, pullUrl) {
267
+ this._abortController = new AbortController();
268
+ let pullTimeoutId = setTimeout(() => this._abortController.abort(), 5 * 60 * 1000);
269
+ try {
270
+ return await this.client.request(
271
+ accessToken,
272
+ pullUrl,
273
+ 'POST',
274
+ { returnImmediately: false, maxMessages: 100 },
275
+ { signal: this._abortController.signal }
276
+ );
277
+ } finally {
278
+ clearTimeout(pullTimeoutId);
279
+ this._abortController = null;
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Routes each pulled message to its accounts. A message that failed to process is left out of
285
+ * the ACK so Pub/Sub delivers it again
286
+ * @param {Object} pullRes - Pull response
287
+ * @returns {Promise<Array<string>|null>} The ackIds to acknowledge, null when stopped meanwhile
288
+ */
289
+ async processPulledBatch(pullRes) {
290
+ let ackIds = [];
291
+
292
+ for (let receivedMessage of pullRes?.receivedMessages || []) {
293
+ // Check stopped flag at start of each message for faster shutdown
294
+ if (this.stopped) {
295
+ logger.info({ msg: 'Stopping message processing due to shutdown', app: this.app });
296
+ return null;
300
297
  }
301
- // Transient network errors are expected for long-polling connections
302
- if (isTransientNetworkError(err)) {
303
- logger.warn({ msg: 'Transient error pulling subscription messages', app: this.app, code: err.code });
304
- err.retryDelay = 5000;
305
- err.eeLogged = true;
306
- throw err;
298
+
299
+ let messageId = receivedMessage?.message?.messageId;
300
+
301
+ try {
302
+ await this.processPulledMessage(messageId, Buffer.from(receivedMessage?.message?.data || '', 'base64').toString());
303
+ } catch (err) {
304
+ // Processing failed - skip ACK so message will be redelivered
305
+ logger.error({ msg: 'Failed to process subscription message', app: this.app, messageId, err });
306
+ continue;
307
307
  }
308
- // Rate limited by Google API - respect Retry-After header
309
- if (err.statusCode === 429) {
310
- let retryDelay = (err.retryAfter ? err.retryAfter * 1000 : null) || 30000;
311
- logger.warn({ msg: 'Rate limited by Google Pub/Sub API', app: this.app, retryAfterSec: err.retryAfter });
312
- err.retryDelay = retryDelay;
313
- err.eeLogged = true;
314
- throw err;
308
+
309
+ if (receivedMessage?.ackId) {
310
+ ackIds.push(receivedMessage.ackId);
315
311
  }
316
- // Detect deleted subscription (expired after 31 days of inactivity) and try to recreate
317
- if (err.statusCode === 404 || err?.oauthRequest?.response?.error?.code === 404) {
318
- await this.attemptRecovery('Subscription not found (404)');
319
- return; // re-enter the pull loop
312
+ }
313
+
314
+ return ackIds;
315
+ }
316
+
317
+ /**
318
+ * Acknowledges the processed messages in one request, retried once. A failure is logged, not
319
+ * thrown: the messages are delivered again
320
+ * @param {Array<string>} ackIds - Ids to acknowledge
321
+ * @param {string} accessToken - The token the pull used
322
+ * @param {string} acknowledgeUrl - The subscription's acknowledge URL
323
+ * @param {number} pullStartTime - When the pull started
324
+ */
325
+ async ackMessages(ackIds, accessToken, acknowledgeUrl, pullStartTime) {
326
+ // Refresh access token if the pull took a long time (token may be near expiration)
327
+ let elapsed = Date.now() - pullStartTime;
328
+ if (elapsed > 4 * 60 * 1000) {
329
+ try {
330
+ accessToken = await this.getAccessToken();
331
+ } catch (err) {
332
+ logger.warn({ msg: 'Failed to refresh access token before ACK, using original', app: this.app, err });
320
333
  }
334
+ }
321
335
 
322
- // Authentication or authorization failure -- set operator-visible flag and let startLoop retry with backoff.
323
- // 401: token refresh happens automatically via getServiceAccessToken() on next run().
324
- // 403: permanent until operator fixes IAM permissions; retrying ensurePubsub wastes API calls.
325
- if (err.statusCode === 401 || err.statusCode === 403) {
326
- if (err.statusCode === 401) {
327
- // The cached service token was refused. Left in place, every run would keep
328
- // presenting it until its recorded expiry instead of fetching a new one
329
- await this.invalidateAccessToken();
330
- }
331
- logger.error({
332
- msg: 'Authentication/authorization error pulling subscription messages',
333
- app: this.app,
334
- statusCode: err.statusCode,
335
- err
336
- });
337
- err.eeLogged = true;
338
- if (!this._pubSubFlagSetThisSession) {
339
- await this._setPubSubFlag({
340
- message:
341
- err.statusCode === 401
342
- ? 'Service account access token expired or revoked'
343
- : 'Insufficient permissions to pull from the subscription',
344
- description: [err.message, err.reason, err.code].filter(val => val).join('; ')
345
- });
346
- }
347
- throw err;
336
+ try {
337
+ await this.client.request(accessToken, acknowledgeUrl, 'POST', { ackIds }, { returnText: true });
338
+ logger.debug({ msg: 'Batch acked subscription messages', app: this.app, count: ackIds.length });
339
+ } catch (err) {
340
+ logger.warn({ msg: 'Batch ACK failed, retrying once', app: this.app, count: ackIds.length, err });
341
+ try {
342
+ await new Promise(resolve => setTimeout(resolve, 1000));
343
+ await this.client.request(accessToken, acknowledgeUrl, 'POST', { ackIds }, { returnText: true });
344
+ logger.info({ msg: 'Batch ACK retry succeeded', app: this.app, count: ackIds.length });
345
+ } catch (retryErr) {
346
+ logger.error({ msg: 'Batch ACK retry also failed, messages will be redelivered', app: this.app, count: ackIds.length, err: retryErr });
348
347
  }
348
+ }
349
+ }
349
350
 
350
- logger.error({ msg: 'Failed to pull subscription messages', app: this.app, err });
351
+ /**
352
+ * Decides what a failed pull means for the loop. Rethrows with a retryDelay for the errors the
353
+ * loop backs off from, and answers (re-entering the loop) after a recovery attempt for a
354
+ * subscription that is gone
355
+ * @param {Error} err - The failure
356
+ * @returns {Promise<undefined>} Only for a deleted subscription; everything else throws
357
+ */
358
+ async handlePullError(err) {
359
+ // Manual timeout abort or shutdown - not an error, just restart the loop
360
+ if (err.name === 'AbortError') {
361
+ throw err;
362
+ }
363
+ // Transient network errors are expected for long-polling connections
364
+ if (isTransientNetworkError(err)) {
365
+ logger.warn({ msg: 'Transient error pulling subscription messages', app: this.app, code: err.code });
366
+ err.retryDelay = 5000;
367
+ err.eeLogged = true;
368
+ throw err;
369
+ }
370
+ // Rate limited by Google API - respect Retry-After header
371
+ if (err.statusCode === 429) {
372
+ let retryDelay = (err.retryAfter ? err.retryAfter * 1000 : null) || 30000;
373
+ logger.warn({ msg: 'Rate limited by Google Pub/Sub API', app: this.app, retryAfterSec: err.retryAfter });
374
+ err.retryDelay = retryDelay;
351
375
  err.eeLogged = true;
352
376
  throw err;
353
377
  }
378
+ // Detect deleted subscription (expired after 31 days of inactivity) and try to recreate
379
+ if (err.statusCode === 404 || err?.oauthRequest?.response?.error?.code === 404) {
380
+ await this.attemptRecovery('Subscription not found (404)');
381
+ return; // re-enter the pull loop
382
+ }
383
+
384
+ // Authentication or authorization failure -- set operator-visible flag and let startLoop retry with backoff.
385
+ // 401: token refresh happens automatically via getServiceAccessToken() on next run().
386
+ // 403: permanent until operator fixes IAM permissions; retrying ensurePubsub wastes API calls.
387
+ if (err.statusCode === 401 || err.statusCode === 403) {
388
+ if (err.statusCode === 401) {
389
+ // The cached service token was refused. Left in place, every run would keep
390
+ // presenting it until its recorded expiry instead of fetching a new one
391
+ await this.invalidateAccessToken();
392
+ }
393
+ logger.error({
394
+ msg: 'Authentication/authorization error pulling subscription messages',
395
+ app: this.app,
396
+ statusCode: err.statusCode,
397
+ err
398
+ });
399
+ err.eeLogged = true;
400
+ if (!this._pubSubFlagSetThisSession) {
401
+ await this._setPubSubFlag({
402
+ message:
403
+ err.statusCode === 401 ? 'Service account access token expired or revoked' : 'Insufficient permissions to pull from the subscription',
404
+ description: [err.message, err.reason, err.code].filter(val => val).join('; ')
405
+ });
406
+ }
407
+ throw err;
408
+ }
409
+
410
+ logger.error({ msg: 'Failed to pull subscription messages', app: this.app, err });
411
+ err.eeLogged = true;
412
+ throw err;
354
413
  }
355
414
 
356
415
  async attemptRecovery(reason) {