emailengine-app 2.82.0 → 2.82.1

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 (65) hide show
  1. package/.ncurc.js +23 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +44 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/bin/emailengine.js +77 -7
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +35 -10
  8. package/lib/api-routes/account-binding.js +58 -0
  9. package/lib/api-routes/account-routes.js +48 -9
  10. package/lib/api-routes/behavior-notes.js +4 -0
  11. package/lib/api-routes/gateway-routes.js +10 -2
  12. package/lib/api-routes/message-routes.js +10 -3
  13. package/lib/api-routes/outbox-routes.js +1 -1
  14. package/lib/api-routes/settings-routes.js +1 -2
  15. package/lib/api-routes/token-routes.js +1 -1
  16. package/lib/autodetect-imap-settings.js +146 -4
  17. package/lib/consts.js +12 -0
  18. package/lib/db.js +1 -19
  19. package/lib/delivery-error.js +68 -1
  20. package/lib/email-client/base-client.js +6 -13
  21. package/lib/email-client/credential-errors.js +21 -5
  22. package/lib/email-client/gmail-client.js +2 -2
  23. package/lib/email-client/imap-client.js +2 -1
  24. package/lib/email-client/message-builder.js +41 -11
  25. package/lib/email-client/outlook-client.js +196 -67
  26. package/lib/enum-descriptions.js +5 -1
  27. package/lib/export.js +8 -2
  28. package/lib/gateway.js +5 -0
  29. package/lib/get-secret.js +1 -21
  30. package/lib/mcp/tools.js +95 -36
  31. package/lib/oauth/gmail.js +42 -12
  32. package/lib/oauth/mail-ru.js +24 -17
  33. package/lib/oauth/outlook.js +34 -24
  34. package/lib/oauth/scope-checker.js +35 -1
  35. package/lib/oauth/scope-list.js +55 -0
  36. package/lib/oauth/token-fetch.js +47 -0
  37. package/lib/oauth2-apps.js +16 -47
  38. package/lib/outbox.js +2 -7
  39. package/lib/queue-retention.js +4 -2
  40. package/lib/read-env-value.js +33 -2
  41. package/lib/schemas.js +62 -15
  42. package/lib/token-audit-log.js +3 -2
  43. package/lib/tools.js +1 -1
  44. package/lib/ui-routes/account-routes.js +40 -7
  45. package/lib/ui-routes/oauth-config-routes.js +3 -14
  46. package/lib/ui-routes/route-helpers.js +23 -23
  47. package/lib/ui-routes/special-use-paths.js +33 -0
  48. package/lib/utils/network.js +9 -17
  49. package/package.json +18 -18
  50. package/sbom.json +1 -1
  51. package/server.js +21 -3
  52. package/setup-production.sh +16 -7
  53. package/static/licenses.html +30 -20
  54. package/translations/messages.pot +74 -56
  55. package/views/account-workspace-error.hbs +30 -0
  56. package/views/accounts/account.hbs +9 -4
  57. package/views/accounts/edit.hbs +11 -2
  58. package/views/internals/index.hbs +1 -1
  59. package/views/partials/gmail_api_scopes.hbs +16 -0
  60. package/views/partials/oauth_form.hbs +67 -94
  61. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  62. package/views/partials/scope_info.hbs +14 -23
  63. package/workers/api.js +62 -27
  64. package/workers/imap.js +6 -3
  65. package/workers/submit.js +2 -5
@@ -9,7 +9,7 @@ const { oauth2Apps } = require('../oauth2-apps');
9
9
  const getSecret = require('../get-secret');
10
10
  const msgpack = require('../msgpack');
11
11
  const he = require('he');
12
- const { emitChangeEvent, prepareUrl, collectCidReferences, embedCidImages, truncateTextContents } = require('../tools');
12
+ const { emitChangeEvent, prepareUrl, collectCidReferences, embedCidImages, truncateTextContents, readEnvValue, getDuration } = require('../tools');
13
13
  const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
14
14
  const crypto = require('crypto');
15
15
  const { Gateway } = require('../gateway');
@@ -46,6 +46,35 @@ const MAX_BATCH_SIZE = graphApi.MAX_BATCH_SIZE;
46
46
  // Subscription is renewed automatically. But just in case, check once in an hour
47
47
  const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h
48
48
 
49
+ const DEFAULT_FALLBACK_POLL_INTERVAL = 10 * 60 * 1000;
50
+ const MIN_FALLBACK_POLL_INTERVAL = 10 * 1000;
51
+
52
+ /**
53
+ * Reads EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL: a duration, 0 switching the periodic pass off.
54
+ * Anything unreadable gets the default, and a positive value is never shorter than ten seconds, so
55
+ * a typo cannot point every account at Graph in a loop
56
+ * @param {*} value - The raw environment value
57
+ * @returns {number} Milliseconds, 0 when the pass is off
58
+ */
59
+ function parseFallbackPollInterval(value) {
60
+ // blank is "unset", which getDuration() would read as 0, the value that switches the pass off
61
+ const raw = String(value ?? '').trim();
62
+ const duration = raw ? getDuration(raw) : DEFAULT_FALLBACK_POLL_INTERVAL;
63
+ if (!Number.isFinite(duration) || duration < 0) {
64
+ return DEFAULT_FALLBACK_POLL_INTERVAL;
65
+ }
66
+ return duration && Math.max(duration, MIN_FALLBACK_POLL_INTERVAL);
67
+ }
68
+
69
+ // When the announced set (see OutlookClient.getAnnouncedKey()) started being kept, the point a
70
+ // recovery pass never looks back past. Renamed along with the set when it became keyed by folder,
71
+ // so the first pass after an upgrade does not take the messages recorded in the old format for
72
+ // unannounced ones and announce hours of mail again
73
+ const ANNOUNCED_SINCE_FIELD = 'outlookAnnouncedInSince';
74
+
75
+ // See setupFallbackPollTimer()
76
+ const FALLBACK_POLL_INTERVAL = parseFallbackPollInterval(readEnvValue('EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL'));
77
+
49
78
  // The `serverResponseCode` a failed change subscription is reported with, and the marker that
50
79
  // tells the report apart from anything else the account may have stored. Only this client reads
51
80
  // it: reportSubscriptionFailure() writes it, clearSubscriptionFailure() lifts it, and
@@ -103,7 +132,7 @@ Supported operations status:
103
132
  ✅ deleteMailbox
104
133
  ✅ getAttachment
105
134
  ✅ submitMessage
106
- ✅ uploadMessage - only drafts. Cannot change draft status
135
+ ✅ uploadMessage - Graph creates a draft; the \Draft flag then sets PR_MESSAGE_FLAGS mfUnsent
107
136
  🟡 subconnections - not supported
108
137
  */
109
138
 
@@ -152,6 +181,11 @@ class OutlookClient extends BaseClient {
152
181
  this.renewRetryTimer = null;
153
182
  this.renewalInProgress = false; // In-memory flag to prevent concurrent subscription renewals
154
183
 
184
+ // Periodic missed-notification recovery, see setupFallbackPollTimer()
185
+ this.fallbackPollTimer = null;
186
+ this.fallbackPollInterval = FALLBACK_POLL_INTERVAL;
187
+ this.periodicRecoveryDue = false;
188
+
155
189
  // MS Graph webhook subscription state (for metrics)
156
190
  // Possible values: 'unset', 'valid', 'expired', 'failed', 'pending'
157
191
  this.subscriptionState = 'unset';
@@ -275,10 +309,7 @@ class OutlookClient extends BaseClient {
275
309
  */
276
310
  async init() {
277
311
  this.state = 'connecting';
278
- clearTimeout(this.renewWatchTimer);
279
- clearTimeout(this.renewRetryTimer);
280
- this.cancelDeferredRetryTimer();
281
- this.cancelInitRetry();
312
+ this.clearTimers();
282
313
  await this.setStateVal();
283
314
 
284
315
  await this.getAccount();
@@ -406,11 +437,12 @@ class OutlookClient extends BaseClient {
406
437
 
407
438
  // A recovery pass must not look back past the point announced messages were first
408
439
  // recorded, or its first run after an upgrade would announce hours of mail again
409
- await this.redis.hsetnx(this.getAccountKey(), 'outlookAnnouncedSince', Date.now().toString());
440
+ await this.redis.hsetnx(this.getAccountKey(), ANNOUNCED_SINCE_FIELD, Date.now().toString());
410
441
 
411
442
  // Set up webhook subscription for real-time updates
412
443
  await this.ensureSubscription();
413
444
  this.setupRenewWatchTimer();
445
+ this.setupFallbackPollTimer({ first: true });
414
446
 
415
447
  // Cache mailbox folder structure
416
448
  try {
@@ -425,14 +457,20 @@ class OutlookClient extends BaseClient {
425
457
  }
426
458
  }
427
459
 
428
- /**
429
- * Close the client connection and clean up resources
430
- */
431
- async close() {
460
+ // Every background timer of the client, stopped on connect, close and delete
461
+ clearTimers() {
432
462
  clearTimeout(this.renewWatchTimer);
433
463
  clearTimeout(this.renewRetryTimer);
464
+ clearTimeout(this.fallbackPollTimer);
434
465
  this.cancelDeferredRetryTimer();
435
466
  this.cancelInitRetry();
467
+ }
468
+
469
+ /**
470
+ * Close the client connection and clean up resources
471
+ */
472
+ async close() {
473
+ this.clearTimers();
436
474
  this.closed = true;
437
475
 
438
476
  if (['init', 'connecting', 'syncing', 'connected'].includes(this.state)) {
@@ -449,8 +487,11 @@ class OutlookClient extends BaseClient {
449
487
  * (PUT /v1/account/{account}/sync). Outlook syncs via webhook subscriptions and delta
450
488
  * queries rather than a folder walk, so a manual sync refreshes the folder cache and queues
451
489
  * the missed-notification recovery, which then runs and is retried like any other change.
490
+ * @param {Object} [opts]
491
+ * @param {number} [opts.since] - Epoch ms to look back to instead of the usual window. Reaches
492
+ * past what announced messages are remembered for, so it may announce messages again
452
493
  */
453
- async syncMailboxes() {
494
+ async syncMailboxes({ since } = {}) {
454
495
  if (this.closed) {
455
496
  return null;
456
497
  }
@@ -461,7 +502,7 @@ class OutlookClient extends BaseClient {
461
502
  this.logger.warn({ msg: 'Failed to refresh folder cache for manual sync', account: this.account, err });
462
503
  }
463
504
 
464
- await this.accountObject.queueMissedRecovery();
505
+ await this.accountObject.queueMissedRecovery({ reason: 'manual', since });
465
506
  this.recoverMissedNotifications();
466
507
 
467
508
  return true;
@@ -477,6 +518,70 @@ class OutlookClient extends BaseClient {
477
518
  return true;
478
519
  }
479
520
 
521
+ /**
522
+ * Arms the periodic missed-notification recovery (EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL).
523
+ * Graph loses change notifications without reporting it - a `missed` lifecycle event only
524
+ * covers the deliveries our endpoint failed - and a lost one interleaves with deliveries that
525
+ * do arrive, so the pass runs on every interval rather than after a quiet spell. Each pass
526
+ * starts where the previous one finished, so one that missed nothing is one listing request.
527
+ * The request lives in memory, not in the deferred store: a restart re-arms the timer, and a
528
+ * failed pass is left to the next one, which covers its window too.
529
+ * @param {Object} [opts]
530
+ * @param {boolean} [opts.first] - The first pass after a connect, which runs at a random point
531
+ * of the interval so a restart does not send every account's pass to Graph at once
532
+ */
533
+ setupFallbackPollTimer({ first = false } = {}) {
534
+ clearTimeout(this.fallbackPollTimer);
535
+ if (this.closed || !this.fallbackPollInterval) {
536
+ return;
537
+ }
538
+
539
+ const delay = first ? Math.floor(Math.random() * this.fallbackPollInterval) : this.fallbackPollInterval;
540
+ this.fallbackPollTimer = setTimeout(() => {
541
+ this.requestPeriodicRecovery();
542
+ this.setupFallbackPollTimer();
543
+ }, delay);
544
+ this.fallbackPollTimer.unref();
545
+ }
546
+
547
+ /**
548
+ * One tick of the periodic recovery. Only a connected account is checked: in any other state
549
+ * Graph either refuses the request (an authentication error, a tenant that disabled the
550
+ * service) or nothing should be syncing (a parked or closed account), and the timer keeps
551
+ * running so the pass resumes once the account recovers
552
+ */
553
+ requestPeriodicRecovery() {
554
+ if (this.closed || this.state !== 'connected') {
555
+ this.logger.debug({ msg: 'Skipped periodic missed notification recovery', account: this.account, state: this.state });
556
+ return;
557
+ }
558
+ this.periodicRecoveryDue = true;
559
+ this.triggerSync();
560
+ }
561
+
562
+ /**
563
+ * Runs the periodic recovery pass the timer asked for, if any, unless a recovery earlier in the
564
+ * same drain already covered its window
565
+ * @param {Object} context - The drain's shared context
566
+ */
567
+ async runPeriodicRecovery(context) {
568
+ if (!this.periodicRecoveryDue) {
569
+ return;
570
+ }
571
+ this.periodicRecoveryDue = false;
572
+
573
+ try {
574
+ const since = await this.missedRecoveryStart(Date.now());
575
+ if (context.recoveredSince && context.recoveredSince <= since) {
576
+ return;
577
+ }
578
+ await this.syncMissedMessages({ since, options: () => this.getDrainFetchOptions(context), reason: 'periodic' });
579
+ context.recoveredSince = since;
580
+ } catch (err) {
581
+ this.logger.warn({ msg: 'Periodic missed notification recovery failed', account: this.account, err });
582
+ }
583
+ }
584
+
480
585
  /**
481
586
  * Get the current connection state from Redis
482
587
  */
@@ -488,10 +593,7 @@ class OutlookClient extends BaseClient {
488
593
  * Delete the account and clean up resources
489
594
  */
490
595
  async delete() {
491
- clearTimeout(this.renewWatchTimer);
492
- clearTimeout(this.renewRetryTimer);
493
- this.cancelDeferredRetryTimer();
494
- this.cancelInitRetry();
596
+ this.clearTimers();
495
597
  this.closed = true;
496
598
 
497
599
  // Best-effort: delete MS Graph subscription
@@ -3068,9 +3170,9 @@ class OutlookClient extends BaseClient {
3068
3170
  * revoked - exhausts them within minutes and leaves the account with no subscription at all.
3069
3171
  * This pass used to read that count, find it at the cap and give up, waiting for a reconnect
3070
3172
  * that only a worker restart, an account update or a re-authorization brings; a tenant that
3071
- * fixed the cause an hour later was never noticed. Unlike the Gmail client there is no poller
3072
- * behind this to fall back on, so an account left unsubscribed syncs nothing at all while it
3073
- * waits. The counters are cleared before anything else is attempted, so an hour that could have
3173
+ * fixed the cause an hour later was never noticed. A failed subscription reports
3174
+ * `connectError`, which pauses the periodic recovery pass too, so an account left unsubscribed
3175
+ * syncs nothing at all while it waits. The counters are cleared before anything else is attempted, so an hour that could have
3074
3176
  * recovered gets the fast ladder back instead of one attempt every hour forever - a renewal
3075
3177
  * ladder as much as a creation one, since a subscription inside the renew window whose retries
3076
3178
  * are spent is not recreated by this pass at all and would otherwise never get another.
@@ -4083,13 +4185,15 @@ class OutlookClient extends BaseClient {
4083
4185
  }
4084
4186
  };
4085
4187
 
4086
- // Changes deferred for a retry go first, then the queue
4188
+ // Changes deferred for a retry go first, then the periodic recovery, then the queue
4087
4189
  try {
4088
4190
  await this.processDueDeferredEvents(handle);
4089
4191
  } catch (err) {
4090
4192
  this.logger.error({ msg: 'Failed to process deferred mailbox changes', account: this.account, err });
4091
4193
  }
4092
4194
 
4195
+ await this.runPeriodicRecovery(context);
4196
+
4093
4197
  while ((event = await this.accountObject.pullQueueEvent()) !== null) {
4094
4198
  processedAny = true;
4095
4199
  await handle(event);
@@ -4118,17 +4222,11 @@ class OutlookClient extends BaseClient {
4118
4222
  case 'created': {
4119
4223
  let messageData = await this.prepareNewMessage(event.message, await this.getDrainFetchOptions(context));
4120
4224
  if (messageData) {
4121
- // When an email is sent, multiple "created" events are triggered: one for the draft and one for the sent mail folder.
4122
- // However, since we process the event with a delay, we only observe the message stored in the Sent Mail folder.
4123
- // This happens because the message was already moved there by the time we began processing the initial event from the drafts folder.
4124
-
4125
- // Check rolling bucket lock to see if we recently processed the same new email event for the same folder
4126
- // A retry runs up to an hour later, past the short-lived dedupe buckets, while a
4127
- // recovery pass may have announced the message in the meantime
4128
- if (
4129
- (await this.isRecentlySeen(`${messageData.id}:created`, messageData.path)) ||
4130
- (event.attempt && (await this.getAnnounced([messageData.id])).has(messageData.id))
4131
- ) {
4225
+ // The announced set catches a duplicate notification, a retry, and a delivery
4226
+ // Graph kept retrying for hours after a recovery pass announced the message.
4227
+ // It is checked after the fetch because it is keyed by folder too, see
4228
+ // getAnnouncedKey()
4229
+ if ((await this.getAnnounced([messageData])).has(messageData.id)) {
4132
4230
  this.logger.debug({ msg: 'Ignore recently seen new email event', type: 'history-event', emailId: event.message });
4133
4231
  break;
4134
4232
  }
@@ -4142,12 +4240,14 @@ class OutlookClient extends BaseClient {
4142
4240
  }
4143
4241
 
4144
4242
  case 'missedRecovery': {
4145
- const since = await this.missedRecoveryStart(event.receivedAt);
4243
+ // An explicit start (Run sync `since`) is the operator's call and skips every floor
4244
+ const since = event.since || (await this.missedRecoveryStart(event.receivedAt));
4146
4245
  if (context.recoveredSince && context.recoveredSince <= since) {
4147
4246
  // an earlier request in the same drain already covered this window
4148
4247
  break;
4149
4248
  }
4150
- await this.syncMissedMessages({ since, options: await this.getDrainFetchOptions(context) });
4249
+ // a request stored before the reason was recorded came from the lifecycle webhook
4250
+ await this.syncMissedMessages({ since, options: () => this.getDrainFetchOptions(context), reason: event.reason || 'missed' });
4151
4251
  context.recoveredSince = since;
4152
4252
  break;
4153
4253
  }
@@ -4189,7 +4289,7 @@ class OutlookClient extends BaseClient {
4189
4289
  */
4190
4290
  async missedRecoveryStart(receivedAt) {
4191
4291
  const [lastNotification, announcedSince, recoveredUntil] = (
4192
- await this.redis.hmget(this.getAccountKey(), 'outlookLastNotification', 'outlookAnnouncedSince', 'outlookRecoveredUntil')
4292
+ await this.redis.hmget(this.getAccountKey(), 'outlookLastNotification', ANNOUNCED_SINCE_FIELD, 'outlookRecoveredUntil')
4193
4293
  ).map(Number);
4194
4294
 
4195
4295
  // 2-minute safety margin before the last known good notification and the last pass
@@ -4212,20 +4312,27 @@ class OutlookClient extends BaseClient {
4212
4312
 
4213
4313
  /**
4214
4314
  * Recover messages missed due to failed webhook delivery. Queued by the Graph 'missed'
4215
- * lifecycle event and by "Run sync" (see Account.queueMissedRecovery()), and run from the
4216
- * change drain, so a failure is retried like any other change. Lists the messages received
4217
- * since `since` oldest first, a page at a time, and announces the ones not announced yet
4315
+ * lifecycle event, by "Run sync" and by the periodic pass (see Account.queueMissedRecovery()),
4316
+ * and run from the change drain, so a failure is retried like any other change. Lists the
4317
+ * messages received since `since` oldest first, a page at a time, and announces the ones not
4318
+ * announced yet
4218
4319
  * @param {Object} opts
4219
4320
  * @param {number} opts.since - Epoch ms to look back to
4220
- * @param {Object} opts.options - Message fetch options
4321
+ * @param {Object|Function} opts.options - Message fetch options, or an async function returning
4322
+ * them, called only once a message needs fetching (a pass usually finds none)
4323
+ * @param {string} [opts.reason] - What asked for the pass: 'missed', 'manual' or 'periodic'
4221
4324
  */
4222
- async syncMissedMessages({ since, options }) {
4325
+ async syncMissedMessages({ since, options, reason = 'missed' }) {
4223
4326
  const startedAt = Date.now();
4224
4327
  const sinceTime = new Date(since);
4328
+ // a periodic pass that found nothing logs at debug, or every account would log each interval
4329
+ const periodic = reason === 'periodic';
4330
+ let fetchOptions = typeof options === 'function' ? null : options || {};
4225
4331
 
4226
- this.logger.info({
4332
+ this.logger[periodic ? 'debug' : 'info']({
4227
4333
  msg: 'Recovering missed notifications',
4228
4334
  account: this.account,
4335
+ reason,
4229
4336
  since: sinceTime.toISOString()
4230
4337
  });
4231
4338
 
@@ -4247,25 +4354,32 @@ class OutlookClient extends BaseClient {
4247
4354
  let messages = pageResult?.value || [];
4248
4355
  checked += messages.length;
4249
4356
 
4250
- let announced = await this.getAnnounced(messages.map(msg => msg.id));
4357
+ // The folder of each listed message, from the cached listing, so the ones already
4358
+ // announced are skipped without a fetch. One whose folder is not in the listing yet is
4359
+ // fetched and checked by the folder the fetch resolved
4360
+ const listing = messages.length ? (await this.getCachedMailboxListing()) || (await this.getMailboxListing()) : [];
4361
+ const folderPaths = new Map(listing.map(entry => [entry.id, entry.pathName]));
4362
+ const candidates = messages.map(msg => ({ id: msg.id, path: folderPaths.get(msg.parentFolderId) }));
4363
+ const announced = await this.getAnnounced(candidates.filter(candidate => candidate.path));
4251
4364
 
4252
- for (const msg of messages) {
4253
- if (announced.has(msg.id)) {
4365
+ for (const candidate of candidates) {
4366
+ if (announced.has(candidate.id)) {
4254
4367
  continue;
4255
4368
  }
4256
4369
  try {
4257
- let messageData = await this.prepareNewMessage(msg.id, options);
4258
- if (!messageData) {
4370
+ fetchOptions = fetchOptions || (await options());
4371
+ let messageData = await this.prepareNewMessage(candidate.id, fetchOptions);
4372
+ if (!messageData || (!candidate.path && (await this.getAnnounced([messageData])).has(messageData.id))) {
4259
4373
  continue;
4260
4374
  }
4261
4375
 
4262
4376
  // processNew() clears messageData.path
4263
4377
  const path = messageData.path;
4264
- await this.processNew(messageData, options);
4378
+ await this.processNew(messageData, fetchOptions);
4265
4379
  await this.markAnnounced(messageData.id, path);
4266
4380
  recoveredCount++;
4267
4381
  } catch (err) {
4268
- await this.deferFailedChangeEvent({ type: 'created', message: msg.id }, err);
4382
+ await this.deferFailedChangeEvent({ type: 'created', message: candidate.id }, err);
4269
4383
  }
4270
4384
  }
4271
4385
 
@@ -4273,13 +4387,20 @@ class OutlookClient extends BaseClient {
4273
4387
  reqPayload = null; // nextLink includes all query params
4274
4388
  }
4275
4389
 
4276
- this.logger.info({
4390
+ this.logger[periodic && !recoveredCount ? 'debug' : 'info']({
4277
4391
  msg: 'Missed notification recovery completed',
4278
4392
  account: this.account,
4393
+ reason,
4394
+ since: sinceTime.toISOString(),
4279
4395
  checked,
4280
4396
  recovered: recoveredCount
4281
4397
  });
4282
4398
 
4399
+ metricsMeta({ account: this.account }, this.logger, 'outlookMissedRecovery', 'inc', { reason, outcome: recoveredCount ? 'recovered' : 'none' });
4400
+ if (recoveredCount) {
4401
+ metricsMeta({ account: this.account }, this.logger, 'outlookMissedRecoveredMessages', 'inc', { reason }, recoveredCount);
4402
+ }
4403
+
4283
4404
  // Everything received before the pass started has been looked at. hSetExists, so a pass
4284
4405
  // that outlives a deleted account does not recreate its record
4285
4406
  await this.redis.hSetExists(this.getAccountKey(), 'outlookRecoveredUntil', startedAt.toString());
@@ -4698,47 +4819,55 @@ class OutlookClient extends BaseClient {
4698
4819
  .exec();
4699
4820
  }
4700
4821
 
4701
- // Messages announced as new over the last OUTLOOK_ANNOUNCED_RETENTION, by message ID. The
4702
- // short-lived dedupe buckets cover a burst of duplicate notifications; this covers a recovery
4703
- // pass that looks back hours
4822
+ // Messages announced as new over the last OUTLOOK_ANNOUNCED_RETENTION - the one record a
4823
+ // `created` notification and a recovery pass are both checked against. Keyed by message ID and
4824
+ // folder: an immutable ID survives the move from Drafts to Sent Items when a draft is sent, and
4825
+ // the sent copy is announced as new in its own folder, as it always was. The folder in the
4826
+ // member is why this is not the `announced` set earlier versions kept by ID alone, see
4827
+ // ANNOUNCED_SINCE_FIELD
4704
4828
  getAnnouncedKey() {
4705
- return `${REDIS_PREFIX}iam:${this.account}:announced`;
4829
+ return `${REDIS_PREFIX}iam:${this.account}:announced-in`;
4830
+ }
4831
+
4832
+ announcedMember(messageId, path) {
4833
+ // a Graph ID never contains a tab, a folder path may contain anything
4834
+ return `${messageId}\t${path || ''}`;
4706
4835
  }
4707
4836
 
4708
4837
  /**
4709
- * Marks a new message as announced, for both the dedupe buckets and the recovery pass
4838
+ * Marks a new message as announced in a folder, see getAnnounced()
4839
+ * @param {string} messageId
4840
+ * @param {string} path - The folder it was announced in
4710
4841
  */
4711
4842
  async markAnnounced(messageId, path) {
4712
4843
  const now = Date.now();
4713
4844
  const announcedKey = this.getAnnouncedKey();
4714
- const bucketKey = this.dedupeBucketKeys()[1];
4715
4845
  await this.redis
4716
4846
  .multi()
4717
- .hset(bucketKey, `${messageId}:created`, path)
4718
- .expire(bucketKey, 12 * 60)
4719
- .zadd(announcedKey, now, messageId)
4847
+ .zadd(announcedKey, now, this.announcedMember(messageId, path))
4720
4848
  .zremrangebyscore(announcedKey, '-inf', now - OUTLOOK_ANNOUNCED_RETENTION)
4721
4849
  .pexpire(announcedKey, OUTLOOK_ANNOUNCED_RETENTION)
4722
4850
  .exec();
4723
4851
  }
4724
4852
 
4725
4853
  /**
4726
- * @param {string[]} messageIds
4727
- * @returns {Promise<Set<string>>} The ones announced within OUTLOOK_ANNOUNCED_RETENTION
4854
+ * @param {{id: string, path: string}[]} messages - Messages and the folder each is in now
4855
+ * @returns {Promise<Set<string>>} The IDs of the ones announced in that folder within
4856
+ * OUTLOOK_ANNOUNCED_RETENTION
4728
4857
  */
4729
- async getAnnounced(messageIds) {
4730
- if (!messageIds.length) {
4858
+ async getAnnounced(messages) {
4859
+ if (!messages.length) {
4731
4860
  return new Set();
4732
4861
  }
4733
4862
  const announcedKey = this.getAnnouncedKey();
4734
4863
  const cutoff = Date.now() - OUTLOOK_ANNOUNCED_RETENTION;
4735
- // ZSCORE per ID rather than ZMSCORE, which needs Redis 6.2
4864
+ // ZSCORE per message rather than ZMSCORE, which needs Redis 6.2
4736
4865
  let pipeline = this.redis.pipeline();
4737
- for (const messageId of messageIds) {
4738
- pipeline = pipeline.zscore(announcedKey, messageId);
4866
+ for (const { id, path } of messages) {
4867
+ pipeline = pipeline.zscore(announcedKey, this.announcedMember(id, path));
4739
4868
  }
4740
4869
  const results = await pipeline.exec();
4741
- return new Set(messageIds.filter((id, i) => results[i][1] !== null && Number(results[i][1]) > cutoff));
4870
+ return new Set(messages.filter((message, i) => results[i][1] !== null && Number(results[i][1]) > cutoff).map(message => message.id));
4742
4871
  }
4743
4872
 
4744
4873
  /**
@@ -4820,4 +4949,4 @@ class OutlookClient extends BaseClient {
4820
4949
  }
4821
4950
  }
4822
4951
 
4823
- module.exports = { OutlookClient, encodeFolderSegment, decodeFolderSegment };
4952
+ module.exports = { OutlookClient, encodeFolderSegment, decodeFolderSegment, parseFallbackPollInterval };
@@ -27,7 +27,11 @@ const ENUM_DESCRIPTIONS = {
27
27
  disconnected: 'The connection dropped and EmailEngine is retrying with backoff',
28
28
  paused: 'Syncing was paused through the API. No connection is maintained',
29
29
  authenticationError: 'The credentials were rejected. Requires re-authentication before syncing resumes',
30
- connectError: 'The server could not be reached or the TLS handshake failed. Retried with backoff',
30
+ // No note here about account operations answering 503: every state outside connected,
31
+ // connecting and syncing does that, so saying it under one of them reads as if the others
32
+ // did not
33
+ connectError:
34
+ 'The server could not be reached, the TLS handshake failed, or - for an MS Graph account - its change subscription could not be created or renewed, which leaves the account with no way to learn about new mail. Retried with backoff',
31
35
  unset: 'The account is not syncing: either no IMAP or OAuth2 configuration is set, or syncing was switched off - by the operator, or automatically after repeated authentication failures'
32
36
  },
33
37
 
package/lib/export.js CHANGED
@@ -12,6 +12,7 @@ const settings = require('./settings');
12
12
  const logger = require('./logger');
13
13
  const getSecret = require('./get-secret');
14
14
  const { escapeRedisGlob } = require('./tools');
15
+ const { readEnvValue } = require('./read-env-value');
15
16
  const { ImapFlowErrorCode } = require('imapflow');
16
17
 
17
18
  const {
@@ -340,13 +341,18 @@ function getExportQueueKey(account, exportId) {
340
341
  return `${REDIS_PREFIX}exq:${account}:${exportId}`;
341
342
  }
342
343
 
344
+ // The directory exports are written to and served from. Deliberately NOT a setting: the value is a
345
+ // filesystem path this process writes files into, so a settings editor that could move it would be an
346
+ // arbitrary file write, and an operator picks a deployment path through the environment anyway. This
347
+ // used to consult an `exportPath` setting first, which no schema declares and so nothing could ever
348
+ // have written.
343
349
  async function getExportPath() {
344
- return (await settings.get('exportPath')) || process.env.EENGINE_EXPORT_PATH || os.tmpdir();
350
+ return readEnvValue('EENGINE_EXPORT_PATH') || os.tmpdir();
345
351
  }
346
352
 
347
353
  async function getExportMaxAge() {
348
354
  const settingsMaxAge = await settings.get('exportMaxAge');
349
- const envMaxAge = process.env.EENGINE_EXPORT_MAX_AGE;
355
+ const envMaxAge = readEnvValue('EENGINE_EXPORT_MAX_AGE');
350
356
 
351
357
  if (settingsMaxAge && !isNaN(settingsMaxAge)) return Number(settingsMaxAge);
352
358
  if (envMaxAge && !isNaN(envMaxAge)) return Number(envMaxAge);
package/lib/gateway.js CHANGED
@@ -169,6 +169,11 @@ class Gateway {
169
169
  // account's own SMTP server, which nothing asked for
170
170
  let error = Boom.boomify(new Error(`Gateway "${this.gateway}" was not found`), { statusCode: 404 });
171
171
  error.code = 'GatewayNotFound';
172
+ // Boom serializes output.payload and not the error's own properties, so the code has to be
173
+ // written there as well or an in-process caller (GET /v1/gateway/{gateway}, the delivery
174
+ // test) answers a 404 without the `code` field every other not-found answer carries.
175
+ // handleError() passes a Boom error through untouched (lib/api-routes/route-helpers.js)
176
+ error.output.payload.code = error.code;
172
177
  // Boom keeps the status in output.statusCode, which the worker RPC hop does not carry
173
178
  // (lib/worker-rpc-error.js), so the submit worker and the API caller get it here too
174
179
  error.statusCode = 404;
package/lib/get-secret.js CHANGED
@@ -6,30 +6,10 @@ if (!process.env.EE_ENV_LOADED) {
6
6
  }
7
7
 
8
8
  const config = require('@zone-eu/wild-config');
9
- const fs = require('fs');
10
- const logger = require('./logger');
9
+ const { readEnvValue } = require('./read-env-value');
11
10
 
12
11
  config.service = config.service || {};
13
12
 
14
- // duplicate function declaration to avoid requiring tools.js
15
- const readEnvValue = key => {
16
- if (key in process.env) {
17
- return process.env[key];
18
- }
19
-
20
- if (typeof process.env[`${key}_FILE`] === 'string' && process.env[`${key}_FILE`]) {
21
- try {
22
- // try to load from file
23
- process.env[key] = fs.readFileSync(process.env[`${key}_FILE`], 'utf-8').replace(/\r?\n$/, '');
24
- logger.trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
25
- } catch (err) {
26
- logger.error({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
27
- process.env[key] = '';
28
- }
29
- return process.env[key];
30
- }
31
- };
32
-
33
13
  const ENCRYPT_SECRET = readEnvValue('EENGINE_SECRET') || config.service.secret;
34
14
 
35
15
  async function getSecret() {