emailengine-app 2.89.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 (72) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +44 -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 +60 -0
  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/oauth/gmail.js +39 -120
  38. package/lib/oauth/http-request.js +195 -0
  39. package/lib/oauth/mail-ru.js +24 -58
  40. package/lib/oauth/outlook.js +37 -137
  41. package/lib/oauth/pubsub/google.js +176 -117
  42. package/lib/oauth2-apps.js +440 -463
  43. package/lib/openapi/build-document.js +10 -10
  44. package/lib/read-env-value.js +1 -1
  45. package/lib/route-descriptors.js +78 -0
  46. package/lib/schemas.js +10 -1
  47. package/lib/sentry-integrations.js +299 -0
  48. package/lib/sentry.js +75 -27
  49. package/lib/sso-routes.js +249 -0
  50. package/lib/sso.js +29 -6
  51. package/lib/ui-routes/account-edit-form.js +198 -0
  52. package/lib/ui-routes/account-page.js +241 -0
  53. package/lib/ui-routes/account-routes.js +12 -318
  54. package/lib/ui-routes/auth-routes.js +10 -10
  55. package/lib/ui-view-context.js +328 -0
  56. package/lib/utils/public-suffix.js +22 -101
  57. package/lib/web-safe-html.js +20 -7
  58. package/lib/worker-metrics.js +82 -0
  59. package/list-generate.js +2 -5
  60. package/package.json +23 -19
  61. package/sbom.json +267 -908
  62. package/scripts/refresh-test-tokens.js +1 -1
  63. package/server.js +320 -676
  64. package/static/css/flyonui.css +1 -1
  65. package/static/css/src/app.tailwind.css +18 -0
  66. package/static/js/ee-client.js +2619 -645
  67. package/static/js/ui.js +12 -2
  68. package/static/licenses.html +219 -737
  69. package/translations/messages.pot +64 -53
  70. package/views/accounts/browse.hbs +19 -1
  71. package/workers/api.js +20 -451
  72. package/data/public_suffix_list.dat +0 -16698
@@ -23,7 +23,6 @@ const {
23
23
  MESSAGE_MISSING_NOTIFY,
24
24
  EMAIL_SENT_NOTIFY,
25
25
  REDIS_PREFIX,
26
- AUTH_ERROR_NOTIFY,
27
26
  DEFAULT_GMAIL_EXPORT_BATCH_SIZE,
28
27
  GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS
29
28
  } = require('../consts');
@@ -42,7 +41,6 @@ function isGmailNotFound(err) {
42
41
  }
43
42
  const { buildSendRequest, buildDraftSendRequest } = require('./gmail/send-request');
44
43
  const { pushHeaderValue } = require('../utils/header-map');
45
- const { getMessageOtp } = require('../otp');
46
44
 
47
45
  const MAX_GMAIL_BATCH_SIZE = 50;
48
46
 
@@ -91,6 +89,87 @@ function toGmailLabelId(label) {
91
89
  return SYSTEM_LABELS_REV.hasOwnProperty(label) ? SYSTEM_LABELS_REV[label] : label;
92
90
  }
93
91
 
92
+ // Special-use labels in the order they win when a message carries several: Junk over Inbox
93
+ const SPECIAL_USE_LABELS = ['\\Junk', '\\Sent', '\\Trash', '\\Inbox', '\\Drafts'];
94
+
95
+ // Sets the special use of the folder a formatted message is in, from its labels, when it has one
96
+ function setLabelSpecialUse(result) {
97
+ if (!result.labels) {
98
+ return;
99
+ }
100
+ for (const specialUseTag of SPECIAL_USE_LABELS) {
101
+ if (result.labels.includes(specialUseTag)) {
102
+ result.messageSpecialUse = specialUseTag;
103
+ return;
104
+ }
105
+ }
106
+ }
107
+
108
+ // internalDate is a string of epoch milliseconds; anything that is not a valid date reads as none
109
+ function gmailMessageDate(messageData) {
110
+ const date = messageData.internalDate && !isNaN(messageData.internalDate) ? new Date(Number(messageData.internalDate)) : undefined;
111
+ if (date?.toString() === 'Invalid Date') {
112
+ return undefined;
113
+ }
114
+ return date;
115
+ }
116
+
117
+ /**
118
+ * The message shape of a `format=minimal` listing, where the payload is not available: only the
119
+ * id, thread, labels, date and size
120
+ * @param {Object} messageData - Gmail message
121
+ * @param {Date} [date] - From gmailMessageDate()
122
+ * @param {Object} flagsAndLabels - From formatFlagsAndLabels()
123
+ */
124
+ function gmailMinimalMessage(messageData, date, { flags, labels, category }) {
125
+ const result = {
126
+ id: messageData.id,
127
+ emailId: messageData.id || undefined,
128
+ threadId: messageData.threadId || undefined,
129
+ date: date ? date.toISOString() : undefined,
130
+ flags,
131
+ labels,
132
+ category,
133
+ unseen: !flags.includes('\\Seen') ? true : undefined,
134
+ flagged: flags.includes('\\Flagged') ? true : undefined,
135
+ draft: flags.includes('\\Draft') ? true : undefined,
136
+ size: messageData.sizeEstimate
137
+ };
138
+
139
+ setLabelSpecialUse(result);
140
+
141
+ return result;
142
+ }
143
+
144
+ // All headers of a message by lowercase name. pushHeaderValue() guards against names that resolve
145
+ // to Object.prototype members, which would otherwise throw for every fetch of that message
146
+ function gmailHeaderMap(payloadHeaders) {
147
+ let headers = {};
148
+ for (let header of payloadHeaders) {
149
+ pushHeaderValue(headers, header.name.toLowerCase(), header.value);
150
+ }
151
+ return headers;
152
+ }
153
+
154
+ // The snippet carries HTML entities
155
+ function decodeSnippet(snippet) {
156
+ try {
157
+ return he.decode(snippet);
158
+ } catch (err) {
159
+ return snippet;
160
+ }
161
+ }
162
+
163
+ // The first entry of a list (an address list), or undefined
164
+ function firstEntry(list) {
165
+ return list && list[0] ? list[0] : undefined;
166
+ }
167
+
168
+ // A list (addresses, attachments), or undefined when it is missing or empty
169
+ function nonEmptyList(list) {
170
+ return list && list.length ? list : undefined;
171
+ }
172
+
94
173
  // Extract the Message-ID header value (including angle brackets) from a raw RFC822 message,
95
174
  // tolerating folded headers. Returns null if the message has no Message-ID header.
96
175
  function extractMessageIdHeader(raw) {
@@ -337,115 +416,95 @@ class GmailClient extends BaseClient {
337
416
  this.state = 'connecting';
338
417
  this.cancelInitRetry();
339
418
  this.cancelDeferredRetryTimer();
340
- await this.setStateVal();
341
-
342
- await this.getAccount();
343
-
344
- // The auth-failure safety net switches an account off by setting `imap.disabled`, and
345
- // an API-backed account reaches it the same way an IMAP one does - its failures run
346
- // through the same setErrorState(). Checked before any credential work, because the
347
- // work that keeps failing for these accounts is the token refresh below.
348
- if (await this.isSyncDisabled()) {
349
- this.logger.info({ msg: 'Skipped connection setup', account: this.account, reason: 'disabled' });
350
- this.state = 'unset';
351
- await this.setStateVal();
419
+ if (!(await this.beginApiInit())) {
352
420
  return;
353
421
  }
354
422
 
355
423
  await this.getClient(true);
356
424
 
357
- // Ensure access token exists to get scopes
358
- let accountData;
359
- try {
360
- await this.getToken();
361
- // Reload account data after getting access token to ensure we have the latest OAuth2 scopes
362
- accountData = await this.accountObject.loadAccountData(this.account);
363
- } catch (err) {
364
- this.logger.warn({
365
- msg: 'Failed to get token or reload account data during init',
366
- account: this.account,
367
- err
368
- });
369
- throw err;
370
- }
371
-
372
- // Check if send-only mode
373
- const scopes = accountData.oauth2?.accessToken?.scope || accountData.oauth2?.scope || [];
374
- const { hasSendScope, hasReadScope } = checkAccountScopes('gmail', scopes);
375
- const isSendOnly = hasSendScope && !hasReadScope;
425
+ let accountData = await this.loadInitAccountData();
376
426
 
377
- this.logger.debug({
378
- msg: 'Account scopes loaded',
379
- account: this.account,
380
- scopes,
381
- hasSendScope,
382
- hasReadScope,
383
- isSendOnly
384
- });
427
+ const isSendOnly = this.computeSendOnly(accountData);
385
428
 
386
429
  if (!isSendOnly) {
387
430
  // Set up Gmail Pub/Sub watch for real-time notifications (not needed for send-only)
388
431
  await this.renewWatch(accountData, opts);
389
432
  }
390
433
 
391
- // Fetch user profile to verify authentication
392
- let profileRes;
393
- let userInfoRes;
394
- try {
395
- if (isSendOnly) {
396
- // For send-only accounts, use Google UserInfo endpoint which works with openid/email/profile scopes
397
- userInfoRes = await this.request(`https://www.googleapis.com/oauth2/v2/userinfo`, 'get');
398
- } else {
399
- // For full access accounts, use Gmail profile endpoint to also get historyId
400
- profileRes = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/profile`);
401
- }
402
- } catch (err) {
403
- if (isTransientCredentialError(err)) {
404
- // Not a refused credential - left unflagged so the worker retries init() instead of
405
- // reporting an authentication error only re-authorization could clear
406
- throw err;
407
- }
434
+ // Fetch user profile to verify authentication. Send-only accounts use the Google UserInfo
435
+ // endpoint, which works with openid/email/profile scopes; full access accounts use the
436
+ // Gmail profile endpoint to also get the historyId
437
+ const profileRes = await this.probeApiAuth(() =>
438
+ isSendOnly ? this.request(`https://www.googleapis.com/oauth2/v2/userinfo`, 'get') : this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/profile`)
439
+ );
408
440
 
409
- this.state = 'authenticationError';
410
- await this.setStateVal();
441
+ const updates = await this.collectProfileUpdates(accountData, profileRes, isSendOnly);
442
+ if (Object.keys(updates).length) {
443
+ await this.accountObject.update(updates);
444
+ accountData = await this.accountObject.loadAccountData(this.account, false);
445
+ }
446
+
447
+ this.logger.info({
448
+ msg: isSendOnly ? 'Initializing Gmail send-only account' : 'Initializing Gmail account',
449
+ provider: accountData.oauth2.provider,
450
+ user: accountData.oauth2.auth?.user,
451
+ sendOnly: isSendOnly
452
+ });
411
453
 
412
- err.authenticationFailed = true;
454
+ await this.ensurePubSubBinding(accountData);
413
455
 
414
- if (!err.errorNotified) {
415
- err.errorNotified = true;
416
- await this.notify(false, AUTH_ERROR_NOTIFY, {
417
- response: err.oauthRequest?.response?.error?.message || err.response,
418
- serverResponseCode: 'ApiRequestError'
419
- });
420
- }
456
+ if (!isSendOnly) {
457
+ await this.syncHistoryOnConnect(profileRes, accountData);
458
+ this.armBackgroundTimers();
459
+ }
460
+
461
+ await this.finishApiInit(accountData.oauth2?.auth?.user);
462
+ }
463
+
464
+ /**
465
+ * Which of the send and read scopes the account holds, see BaseClient.computeSendOnly()
466
+ * @param {Array<String>} scopes - Granted scopes
467
+ * @returns {{hasSendScope: Boolean, hasReadScope: Boolean}}
468
+ */
469
+ checkScopes(scopes) {
470
+ return checkAccountScopes('gmail', scopes);
471
+ }
421
472
 
473
+ /**
474
+ * Ensures an access token exists, then reloads the account data so the OAuth2 scopes it carries
475
+ * are the latest
476
+ * @returns {Promise<Object>} Account data
477
+ */
478
+ async loadInitAccountData() {
479
+ try {
480
+ await this.getToken();
481
+ return await this.accountObject.loadAccountData(this.account);
482
+ } catch (err) {
483
+ this.logger.warn({
484
+ msg: 'Failed to get token or reload account data during init',
485
+ account: this.account,
486
+ err
487
+ });
422
488
  throw err;
423
489
  }
490
+ }
424
491
 
492
+ /**
493
+ * Account updates the profile probe calls for: a changed address, and for a full access account
494
+ * a locale that was never stored
495
+ * @param {Object} accountData - Loaded account data
496
+ * @param {Object} profileRes - The UserInfo (send-only) or Gmail profile response
497
+ * @param {Boolean} isSendOnly - Whether the account is send-only
498
+ * @returns {Promise<Object>} Updates for Account.update(), empty when nothing changed
499
+ */
500
+ async collectProfileUpdates(accountData, profileRes, isSendOnly) {
425
501
  let updates = {};
426
502
 
427
- // Update account email if changed
428
- if (isSendOnly) {
429
- // Extract email from UserInfo response for send-only accounts
430
- if (userInfoRes?.email && accountData.oauth2.auth?.user !== userInfoRes.email) {
431
- updates._oldOAuth2User = accountData.oauth2.auth?.user;
432
- updates.oauth2 = {
433
- partial: true,
434
- auth: Object.assign(accountData.oauth2.auth || {}, {
435
- user: userInfoRes.email
436
- })
437
- };
438
- }
439
- } else if (profileRes.emailAddress && accountData.oauth2.auth?.user !== profileRes.emailAddress) {
440
- // Extract email from profile for full access accounts
503
+ // UserInfo names the address `email`, the Gmail profile `emailAddress`
504
+ const emailAddress = isSendOnly ? profileRes?.email : profileRes.emailAddress;
505
+ if (emailAddress && accountData.oauth2.auth?.user !== emailAddress) {
441
506
  updates._oldOAuth2User = accountData.oauth2.auth?.user; // needed for cleanups
442
- updates.oauth2 = {
443
- partial: true,
444
- auth: Object.assign(accountData.oauth2.auth || {}, {
445
- // update username
446
- user: profileRes.emailAddress
447
- })
448
- };
507
+ updates.oauth2 = this.oauthUserUpdate(accountData.oauth2.auth, emailAddress);
449
508
  }
450
509
 
451
510
  // Detect and store user locale (only for full access accounts)
@@ -464,74 +523,77 @@ class GmailClient extends BaseClient {
464
523
  }
465
524
  }
466
525
 
467
- if (Object.keys(updates).length) {
468
- await this.accountObject.update(updates);
469
- accountData = await this.accountObject.loadAccountData(this.account, false);
470
- }
471
-
472
- this.logger.info({
473
- msg: isSendOnly ? 'Initializing Gmail send-only account' : 'Initializing Gmail account',
474
- provider: accountData.oauth2.provider,
475
- user: accountData.oauth2.auth?.user,
476
- sendOnly: isSendOnly
477
- });
526
+ return updates;
527
+ }
478
528
 
479
- // Ensure Pub/Sub subscription mapping is correct
529
+ /**
530
+ * Makes sure the Pub/Sub routing hash sends this user's notifications to this account
531
+ * @param {Object} accountData - Loaded account data
532
+ */
533
+ async ensurePubSubBinding(accountData) {
480
534
  const bindingKey = `${REDIS_PREFIX}oapp:h:${accountData.oauth2.provider}`;
481
535
  const pubsubUser = accountData.oauth2.auth?.user;
482
- if (pubsubUser && (await this.redis.hget(bindingKey, pubsubUser.toLowerCase())) !== this.account) {
483
- try {
484
- // Another live account holding the same user keeps its routing: re-setting it here on
485
- // every connect let two such accounts take the notifications from each other
486
- await this.accountObject.assertOAuth2UserUnbound(accountData.oauth2.provider, pubsubUser);
487
- await this.redis.hset(bindingKey, pubsubUser.toLowerCase(), this.account);
488
- this.logger.info({ msg: 'Re-set missing Google Pub/Sub subscription', account: this.account, emailAddress: pubsubUser });
489
- } catch (err) {
490
- if (err.output?.payload?.code !== 'AccountAlreadyExists') {
491
- throw err;
492
- }
493
- this.logger.warn({
494
- msg: 'Another account holds the Google Pub/Sub routing for this user',
495
- account: this.account,
496
- existingAccount: err.output.payload.existingAccount,
497
- emailAddress: pubsubUser
498
- });
499
- }
536
+ if (!pubsubUser || (await this.redis.hget(bindingKey, pubsubUser.toLowerCase())) === this.account) {
537
+ return;
500
538
  }
501
539
 
502
- if (!isSendOnly) {
503
- // Check and process history changes since last sync (only for full access accounts)
504
- let historyId = Number(profileRes?.historyId) || null;
505
- if (!accountData.googleHistoryId) {
506
- // set as initial
507
- await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', historyId.toString());
508
- accountData.googleHistoryId = historyId;
509
- this.logger.info({ msg: 'Re-set missing Google History ID', account: this.account, historyId });
510
- }
511
-
512
- if (historyId && accountData.googleHistoryId && historyId > accountData.googleHistoryId) {
513
- // changes detected
514
- this.triggerSync(accountData.googleHistoryId, historyId);
540
+ try {
541
+ // Another live account holding the same user keeps its routing: re-setting it here on
542
+ // every connect let two such accounts take the notifications from each other
543
+ await this.accountObject.assertOAuth2UserUnbound(accountData.oauth2.provider, pubsubUser);
544
+ await this.redis.hset(bindingKey, pubsubUser.toLowerCase(), this.account);
545
+ this.logger.info({ msg: 'Re-set missing Google Pub/Sub subscription', account: this.account, emailAddress: pubsubUser });
546
+ } catch (err) {
547
+ if (err.output?.payload?.code !== 'AccountAlreadyExists') {
548
+ throw err;
515
549
  }
550
+ this.logger.warn({
551
+ msg: 'Another account holds the Google Pub/Sub routing for this user',
552
+ account: this.account,
553
+ existingAccount: err.output.payload.existingAccount,
554
+ emailAddress: pubsubUser
555
+ });
556
+ }
557
+ }
516
558
 
517
- // Schedule periodic watch renewal (only for full access accounts)
518
- this.setupRenewWatchTimer();
519
-
520
- // Schedule fallback polling in case Pub/Sub notifications are dropped
521
- this.lastNotificationTime = Date.now();
522
- this.setupFallbackPollingTimer();
523
-
524
- // Lets getToken() re-arm the timers after an authentication error clears
525
- this.backgroundTimersArmed = true;
559
+ /**
560
+ * Seeds a missing history checkpoint from the profile, or replays the history that arrived
561
+ * while the account was not connected
562
+ * @param {Object} profileRes - The Gmail profile response
563
+ * @param {Object} accountData - Loaded account data, its googleHistoryId updated when seeded
564
+ */
565
+ async syncHistoryOnConnect(profileRes, accountData) {
566
+ let historyId = Number(profileRes?.historyId) || null;
567
+ if (!accountData.googleHistoryId && !historyId) {
568
+ // Nothing to seed from. The checkpoint stays unset, which every reader of it already
569
+ // handles (a notification syncs from it as from a missing one), and the next connect
570
+ // seeds it from a profile that carries one
571
+ this.logger.warn({ msg: 'Profile has no history ID, left the history checkpoint unset', account: this.account });
572
+ } else if (!accountData.googleHistoryId) {
573
+ // set as initial
574
+ await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', historyId.toString());
575
+ accountData.googleHistoryId = historyId;
576
+ this.logger.info({ msg: 'Re-set missing Google History ID', account: this.account, historyId });
577
+ }
578
+
579
+ if (historyId && accountData.googleHistoryId && historyId > accountData.googleHistoryId) {
580
+ // changes detected
581
+ this.triggerSync(accountData.googleHistoryId, historyId);
526
582
  }
583
+ }
527
584
 
528
- // Before the state flip below - see notifyAuthenticationSuccess()
529
- await this.notifyAuthenticationSuccess(accountData.oauth2?.auth?.user);
585
+ /**
586
+ * Schedules the periodic watch renewal and the fallback polling (in case Pub/Sub notifications
587
+ * are dropped) of a full access account
588
+ */
589
+ armBackgroundTimers() {
590
+ this.setupRenewWatchTimer();
530
591
 
531
- this.state = 'connected';
532
- await this.setStateVal();
592
+ this.lastNotificationTime = Date.now();
593
+ this.setupFallbackPollingTimer();
533
594
 
534
- await emitChangeEvent(this.logger, this.account, 'state', this.state);
595
+ // Lets getToken() re-arm the timers after an authentication error clears
596
+ this.backgroundTimersArmed = true;
535
597
  }
536
598
 
537
599
  /**
@@ -799,139 +861,192 @@ class GmailClient extends BaseClient {
799
861
  }
800
862
 
801
863
  let pageSize = Math.abs(Number(query.pageSize) || 20);
802
- let requestQuery = {
803
- maxResults: pageSize
804
- };
805
864
 
806
865
  let pageCursor = PageCursor.create(query.cursor);
807
866
 
808
867
  let path;
868
+ let labelIds;
809
869
  if (query.path && query.path !== '\\All') {
810
870
  // Convert path to Gmail label ID
811
871
  let label = await this.getLabel(query.path);
812
872
  if (!label) {
813
873
  return false;
814
874
  }
815
- requestQuery.labelIds = [label.id];
875
+ labelIds = [label.id];
816
876
  path = query.path;
817
877
  }
818
878
 
819
- let messageList = [];
879
+ if (query.search?.emailId) {
880
+ return await this.listSingleMessage(query.search.emailId, path, pageSize);
881
+ }
820
882
 
821
- if (query.search) {
822
- if (query.search.emailId) {
823
- // Return only a single matching email
883
+ if (query.search?.threadId) {
884
+ return await this.listThreadMessages(query.search.threadId, path, pageSize, pageCursor);
885
+ }
824
886
 
825
- let messageEntry = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${encodeURIComponent(query.search.emailId)}`, 'get', {
826
- format: 'full'
827
- });
887
+ let currentPage = pageCursor.currentPage();
888
+ let requestQuery = this.buildGmailListQuery(query.search, pageSize, labelIds, currentPage);
828
889
 
829
- if (messageEntry) {
830
- messageList.push(this.formatMessage(messageEntry, { path }));
831
- }
890
+ // Fetch message list
891
+ let listingResult = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages`, 'get', requestQuery);
892
+ let messageCount = listingResult.resultSizeEstimate;
832
893
 
833
- let messageCount = messageList.length;
834
- let pages = Math.ceil(messageCount / pageSize);
894
+ let pages = Math.ceil(messageCount / pageSize);
835
895
 
836
- return {
837
- total: messageCount,
838
- page: 0,
839
- pages,
840
- nextPageCursor: null,
841
- prevPageCursor: null,
842
- messages: messageList
843
- };
844
- }
896
+ let nextPageCursor = pageCursor.nextPageCursor(listingResult.nextPageToken);
897
+ let prevPageCursor = pageCursor.prevPageCursor();
845
898
 
846
- if (query.search.threadId) {
847
- // Threading is a special case - fetch entire thread
848
- let threadListingResult = await this.request(
849
- `${GMAIL_API_BASE}/gmail/v1/users/me/threads/${encodeURIComponent(query.search.threadId)}`,
850
- 'get',
851
- {
852
- format: 'full'
853
- }
854
- );
899
+ let listingPage = messages => ({
900
+ total: messageCount,
901
+ page: currentPage.page,
902
+ pages,
903
+ nextPageCursor,
904
+ prevPageCursor,
905
+ messages
906
+ });
855
907
 
856
- let messageCount = threadListingResult?.messages?.length || 0;
857
- let currentPage = pageCursor.currentPage();
908
+ if (options.metadataOnly || query.metadataOnly) {
909
+ // Return just IDs without fetching full content
910
+ return listingPage(listingResult.messages);
911
+ }
858
912
 
859
- let nextPageToken = null;
860
- if (messageCount > pageSize) {
861
- // Handle pagination within thread
862
- let pageStart = 0;
913
+ return listingPage(await this.fetchMessagesBatched(listingResult.messages || [], path, options.minimalFields));
914
+ }
863
915
 
864
- if (currentPage?.cursor) {
865
- pageStart = Number(currentPage.cursor) || 0;
866
- }
916
+ /**
917
+ * Lists the one message a search names by its emailId
918
+ * @param {string} emailId - Gmail message ID
919
+ * @param {string} [path] - Folder the listing was asked for
920
+ * @param {number} pageSize - Requested page size
921
+ * @returns {Promise<Object>} Single-page message list
922
+ */
923
+ async listSingleMessage(emailId, path, pageSize) {
924
+ let messageList = [];
867
925
 
868
- if (pageStart + pageSize < messageCount) {
869
- nextPageToken = (pageStart + pageSize).toString(10);
870
- }
926
+ let messageEntry = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${encodeURIComponent(emailId)}`, 'get', {
927
+ format: 'full'
928
+ });
871
929
 
872
- // extract messages for the current page only
873
- threadListingResult.messages = threadListingResult.messages.slice(pageStart, pageStart + pageSize, messageCount);
874
- }
930
+ if (messageEntry) {
931
+ messageList.push(this.formatMessage(messageEntry, { path }));
932
+ }
875
933
 
876
- if (threadListingResult?.messages) {
877
- for (let entry of threadListingResult.messages) {
878
- messageList.push(this.formatMessage(entry, { path }));
879
- }
880
- }
934
+ let messageCount = messageList.length;
935
+ let pages = Math.ceil(messageCount / pageSize);
881
936
 
882
- let pages = Math.ceil(messageCount / pageSize);
883
- let nextPageCursor = pageCursor.nextPageCursor(nextPageToken);
884
- let prevPageCursor = pageCursor.prevPageCursor();
885
-
886
- return {
887
- total: messageCount,
888
- page: currentPage.page,
889
- pages,
890
- nextPageCursor,
891
- prevPageCursor,
892
- messages: messageList
893
- };
937
+ return {
938
+ total: messageCount,
939
+ page: 0,
940
+ pages,
941
+ nextPageCursor: null,
942
+ prevPageCursor: null,
943
+ messages: messageList
944
+ };
945
+ }
946
+
947
+ /**
948
+ * Lists the messages of one thread. Gmail returns the whole thread, so it is paged here, the
949
+ * cursor carrying the offset of the page
950
+ * @param {string} threadId - Gmail thread ID
951
+ * @param {string} [path] - Folder the listing was asked for
952
+ * @param {number} pageSize - Requested page size
953
+ * @param {PageCursor} pageCursor - Cursor of the requested page
954
+ * @returns {Promise<Object>} Paginated message list
955
+ */
956
+ async listThreadMessages(threadId, path, pageSize, pageCursor) {
957
+ let messageList = [];
958
+
959
+ let threadListingResult = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/threads/${encodeURIComponent(threadId)}`, 'get', {
960
+ format: 'full'
961
+ });
962
+
963
+ let messageCount = threadListingResult?.messages?.length || 0;
964
+ let currentPage = pageCursor.currentPage();
965
+
966
+ let nextPageToken = null;
967
+ if (messageCount > pageSize) {
968
+ // Handle pagination within thread
969
+ let pageStart = 0;
970
+
971
+ if (currentPage?.cursor) {
972
+ pageStart = Number(currentPage.cursor) || 0;
973
+ }
974
+
975
+ if (pageStart + pageSize < messageCount) {
976
+ nextPageToken = (pageStart + pageSize).toString(10);
977
+ }
978
+
979
+ // extract messages for the current page only
980
+ threadListingResult.messages = threadListingResult.messages.slice(pageStart, pageStart + pageSize);
981
+ }
982
+
983
+ if (threadListingResult?.messages) {
984
+ for (let entry of threadListingResult.messages) {
985
+ messageList.push(this.formatMessage(entry, { path }));
894
986
  }
987
+ }
895
988
 
989
+ let pages = Math.ceil(messageCount / pageSize);
990
+ let nextPageCursor = pageCursor.nextPageCursor(nextPageToken);
991
+ let prevPageCursor = pageCursor.prevPageCursor();
992
+
993
+ return {
994
+ total: messageCount,
995
+ page: currentPage.page,
996
+ pages,
997
+ nextPageCursor,
998
+ prevPageCursor,
999
+ messages: messageList
1000
+ };
1001
+ }
1002
+
1003
+ /**
1004
+ * Builds the query of a messages.list request
1005
+ * @param {Object} [search] - IMAP-style search, converted to a Gmail query
1006
+ * @param {number} pageSize - Requested page size
1007
+ * @param {Array<string>} [labelIds] - Label to list, none for the whole mailbox
1008
+ * @param {Object} currentPage - The cursor's current page
1009
+ * @returns {Object} Request query
1010
+ */
1011
+ buildGmailListQuery(search, pageSize, labelIds, currentPage) {
1012
+ let requestQuery = {
1013
+ maxResults: pageSize
1014
+ };
1015
+
1016
+ if (labelIds) {
1017
+ requestQuery.labelIds = labelIds;
1018
+ }
1019
+
1020
+ if (search) {
896
1021
  // Convert IMAP-style search to Gmail query
897
1022
  // NB! Might throw if using unsupported search terms
898
- const preparedQuery = this.prepareQuery(query.search);
1023
+ const preparedQuery = this.prepareQuery(search);
899
1024
  if (preparedQuery) {
900
1025
  requestQuery.q = preparedQuery;
901
1026
  }
902
1027
  }
903
1028
 
904
1029
  // Apply pagination cursor
905
- let currentPage = pageCursor.currentPage();
906
1030
  if (currentPage?.cursor) {
907
1031
  requestQuery.pageToken = currentPage.cursor;
908
1032
  }
909
1033
 
910
- // Fetch message list
911
- let listingResult = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages`, 'get', requestQuery);
912
- let messageCount = listingResult.resultSizeEstimate;
913
-
914
- let pages = Math.ceil(messageCount / pageSize);
915
-
916
- let nextPageCursor = pageCursor.nextPageCursor(listingResult.nextPageToken);
917
- let prevPageCursor = pageCursor.prevPageCursor();
918
-
919
- if (options.metadataOnly || query.metadataOnly) {
920
- // Return just IDs without fetching full content
921
- return {
922
- total: messageCount,
923
- page: currentPage.page,
924
- pages,
925
- nextPageCursor,
926
- prevPageCursor,
927
- messages: listingResult.messages
928
- };
929
- }
1034
+ return requestQuery;
1035
+ }
930
1036
 
931
- // Fetch message content for matching messages in batches
1037
+ /**
1038
+ * Fetches the listed messages, LIST_BATCH_SIZE requests at a time, and formats them in listing
1039
+ * order. A message deleted between the listing and its fetch is skipped
1040
+ * @param {Array<Object>} messages - Listed message entries
1041
+ * @param {string} [path] - Folder the listing was asked for
1042
+ * @param {boolean} [minimalFields] - Fetch with format=minimal
1043
+ * @returns {Promise<Array<Object>>} Formatted messages
1044
+ */
1045
+ async fetchMessagesBatched(messages, path, minimalFields) {
932
1046
  // Use format=minimal for minimalFields option (faster, returns only id, threadId, labelIds, internalDate, sizeEstimate)
933
- const messageFormat = options.minimalFields ? 'minimal' : undefined;
1047
+ const messageFormat = minimalFields ? 'minimal' : undefined;
934
1048
 
1049
+ let messageList = [];
935
1050
  let promises = [];
936
1051
 
937
1052
  let resolvePromises = async () => {
@@ -950,30 +1065,23 @@ class GmailClient extends BaseClient {
950
1065
  throw entry.reason;
951
1066
  }
952
1067
  if (entry.value) {
953
- messageList.push(this.formatMessage(entry.value, { path, minimalFields: options.minimalFields }));
1068
+ messageList.push(this.formatMessage(entry.value, { path, minimalFields }));
954
1069
  }
955
1070
  }
956
1071
  promises = [];
957
1072
  };
958
1073
 
959
- for (let { id: message } of listingResult.messages || []) {
1074
+ for (let { id: message } of messages) {
960
1075
  let requestUrl = `${GMAIL_API_BASE}/gmail/v1/users/me/messages/${message}`;
961
1076
  let requestParams = messageFormat ? { format: messageFormat } : undefined;
962
1077
  promises.push(this.request(requestUrl, 'get', requestParams));
963
- if (promises.length > LIST_BATCH_SIZE) {
1078
+ if (promises.length >= LIST_BATCH_SIZE) {
964
1079
  await resolvePromises();
965
1080
  }
966
1081
  }
967
1082
  await resolvePromises();
968
1083
 
969
- return {
970
- total: messageCount,
971
- page: currentPage.page,
972
- pages,
973
- nextPageCursor,
974
- prevPageCursor,
975
- messages: messageList
976
- };
1084
+ return messageList;
977
1085
  }
978
1086
 
979
1087
  /**
@@ -2504,6 +2612,8 @@ class GmailClient extends BaseClient {
2504
2612
  id: msgpack.encode(attachmentIdProps).toString('base64url'),
2505
2613
  contentType: node.mimeType,
2506
2614
  encodedSize: node.body.size,
2615
+ // the Gmail API reports the size of the decoded file
2616
+ size: node.body.size,
2507
2617
 
2508
2618
  embedded: isRelated,
2509
2619
  inline: disposition?.value === 'inline' || (!disposition && isRelated),
@@ -2637,49 +2747,17 @@ class GmailClient extends BaseClient {
2637
2747
  formatMessage(messageData, options) {
2638
2748
  let { extended, path, textType, minimalFields, maxBytes } = options || {};
2639
2749
 
2640
- let date = messageData.internalDate && !isNaN(messageData.internalDate) ? new Date(Number(messageData.internalDate)) : undefined;
2641
- if (date?.toString() === 'Invalid Date') {
2642
- date = undefined;
2643
- }
2644
-
2645
- let { flags, labels, category } = this.formatFlagsAndLabels(messageData);
2750
+ const date = gmailMessageDate(messageData);
2751
+ const flagsAndLabels = this.formatFlagsAndLabels(messageData);
2646
2752
 
2647
- // For minimalFields mode (format=minimal), payload is not available
2648
- // Return only basic fields: id, threadId, labelIds, internalDate, sizeEstimate
2649
2753
  if (minimalFields) {
2650
- const result = {
2651
- id: messageData.id,
2652
- emailId: messageData.id || undefined,
2653
- threadId: messageData.threadId || undefined,
2654
- date: date ? date.toISOString() : undefined,
2655
- flags,
2656
- labels,
2657
- category,
2658
- unseen: !flags.includes('\\Seen') ? true : undefined,
2659
- flagged: flags.includes('\\Flagged') ? true : undefined,
2660
- draft: flags.includes('\\Draft') ? true : undefined,
2661
- size: messageData.sizeEstimate
2662
- };
2663
-
2664
- // Set special-use based on labels
2665
- for (let specialUseTag of ['\\Junk', '\\Sent', '\\Trash', '\\Inbox', '\\Drafts']) {
2666
- if (result.labels && result.labels.includes(specialUseTag)) {
2667
- result.messageSpecialUse = specialUseTag;
2668
- break;
2669
- }
2670
- }
2671
-
2672
- return result;
2754
+ return gmailMinimalMessage(messageData, date, flagsAndLabels);
2673
2755
  }
2674
2756
 
2675
- let envelope = this.getEnvelope(messageData);
2757
+ const { flags, labels, category } = flagsAndLabels;
2676
2758
 
2677
- // Extract all headers. pushHeaderValue() guards against names that resolve to
2678
- // Object.prototype members, which would otherwise throw for every fetch of that message
2679
- let headers = {};
2680
- for (let header of messageData.payload.headers) {
2681
- pushHeaderValue(headers, header.name.toLowerCase(), header.value);
2682
- }
2759
+ let envelope = this.getEnvelope(messageData);
2760
+ let headers = gmailHeaderMap(messageData.payload.headers);
2683
2761
 
2684
2762
  const { attachments, textId, encodedTextSize, textContents } = this.getAttachmentList(messageData, { textType });
2685
2763
 
@@ -2689,14 +2767,6 @@ class GmailClient extends BaseClient {
2689
2767
  };
2690
2768
  const textHasMore = truncateTextContents(textValues, maxBytes);
2691
2769
 
2692
- // Decode snippet preview
2693
- let preview;
2694
- try {
2695
- preview = he.decode(messageData.snippet);
2696
- } catch (err) {
2697
- preview = messageData.snippet;
2698
- }
2699
-
2700
2770
  const result = {
2701
2771
  id: messageData.id,
2702
2772
  uid: messageData.uid,
@@ -2718,17 +2788,17 @@ class GmailClient extends BaseClient {
2718
2788
 
2719
2789
  size: messageData.sizeEstimate,
2720
2790
  subject: messageData.payload.headers.find(header => header.name.toLowerCase() === 'subject')?.value || undefined,
2721
- from: envelope.from && envelope.from[0] ? envelope.from[0] : undefined,
2791
+ from: firstEntry(envelope.from),
2722
2792
 
2723
- replyTo: envelope.replyTo && envelope.replyTo.length ? envelope.replyTo : undefined,
2724
- sender: extended && envelope.sender && envelope.sender[0] ? envelope.sender[0] : undefined,
2793
+ replyTo: nonEmptyList(envelope.replyTo),
2794
+ sender: extended ? firstEntry(envelope.sender) : undefined,
2725
2795
 
2726
- to: envelope.to && envelope.to.length ? envelope.to : undefined,
2727
- cc: envelope.cc && envelope.cc.length ? envelope.cc : undefined,
2796
+ to: nonEmptyList(envelope.to),
2797
+ cc: nonEmptyList(envelope.cc),
2728
2798
 
2729
- bcc: extended && envelope.bcc && envelope.bcc.length ? envelope.bcc : undefined,
2799
+ bcc: extended ? nonEmptyList(envelope.bcc) : undefined,
2730
2800
 
2731
- attachments: attachments && attachments.length ? attachments : undefined,
2801
+ attachments: nonEmptyList(attachments),
2732
2802
  messageId: (envelope.messageId && envelope.messageId.toString().trim()) || undefined,
2733
2803
  inReplyTo: envelope.inReplyTo || undefined,
2734
2804
 
@@ -2744,26 +2814,13 @@ class GmailClient extends BaseClient {
2744
2814
  }
2745
2815
  : undefined,
2746
2816
 
2747
- preview
2817
+ preview: decodeSnippet(messageData.snippet)
2748
2818
  };
2749
2819
 
2750
- // Detect auto-replies
2751
- if (this.isAutoreply(result)) {
2752
- result.isAutoReply = true;
2753
- }
2754
-
2755
- const otp = getMessageOtp(result.headers, this.summaryProvider());
2756
- if (otp) {
2757
- result.otp = otp;
2758
- }
2820
+ // Gmail checks every message for an auto-reply, the subject alone can mark one
2821
+ this.finalizeApiMessage(result, false);
2759
2822
 
2760
- // Set special-use based on labels
2761
- for (let specialUseTag of ['\\Junk', '\\Sent', '\\Trash', '\\Inbox', '\\Drafts']) {
2762
- if (result.labels && result.labels.includes(specialUseTag)) {
2763
- result.messageSpecialUse = specialUseTag;
2764
- break;
2765
- }
2766
- }
2823
+ setLabelSpecialUse(result);
2767
2824
 
2768
2825
  return result;
2769
2826
  }
@@ -3245,9 +3302,6 @@ class GmailClient extends BaseClient {
3245
3302
  * @param {number} updatedHistoryId - Target history ID
3246
3303
  */
3247
3304
  async processHistory(currentHistoryId, updatedHistoryId) {
3248
- let newestHistoryId = currentHistoryId;
3249
- let lastHistoryId = currentHistoryId;
3250
-
3251
3305
  // Resolved on first use, and once for the whole run, a failure included
3252
3306
  let contextPromise;
3253
3307
  const getContext = () => (contextPromise = contextPromise || this.getHistoryContext());
@@ -3260,75 +3314,21 @@ class GmailClient extends BaseClient {
3260
3314
  this.logger.error({ msg: 'Failed to process deferred mailbox changes', account: this.account, err });
3261
3315
  }
3262
3316
 
3263
- // The history cursor only advances after an entry is processed, so an
3264
- // entry that kills the worker (OOM, heartbeat restart) is refetched by
3265
- // the restarted worker and would loop forever. The in-flight marker
3266
- // records which entry processing last started on and how many times;
3267
- // once the limit is hit the entry is skipped with a syncWarning
3268
- let processingMarker = null;
3269
- try {
3270
- processingMarker = JSON.parse(await this.redis.hget(this.getAccountKey(), 'googleHistoryProcessing'));
3271
- } catch (err) {
3272
- // no marker or an unreadable one, nothing to resume
3273
- }
3274
-
3275
- // advance the durable cursor once an entry is handled (processed or skipped)
3276
- let advanceHistoryCursor = async historyEntryId => {
3277
- if (historyEntryId && historyEntryId > lastHistoryId) {
3278
- await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', historyEntryId.toString());
3279
- lastHistoryId = historyEntryId;
3280
- }
3317
+ // The state of one run, shared by its steps
3318
+ const run = {
3319
+ currentHistoryId,
3320
+ updatedHistoryId,
3321
+ newestHistoryId: currentHistoryId,
3322
+ lastHistoryId: currentHistoryId,
3323
+ processingMarker: await this.readHistoryProcessingMarker()
3281
3324
  };
3282
3325
 
3283
- /**
3284
- * Fetches and processes a page of history
3285
- * @param {string} pageToken - Pagination token
3286
- */
3287
- let getHistoryPage = async pageToken => {
3288
- let queryArgs = {
3289
- startHistoryId: currentHistoryId,
3290
- maxResults: 500
3291
- };
3292
-
3293
- if (pageToken) {
3294
- queryArgs.pageToken = pageToken;
3295
- }
3296
-
3297
- let historyRes;
3298
- try {
3299
- historyRes = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/history`, 'get', queryArgs);
3300
- } catch (err) {
3301
- switch (err?.oauthRequest?.response?.error?.code) {
3302
- case 404: {
3303
- // History ID too old - some changes may have been missed
3304
- this.logger.warn({
3305
- msg: 'History ID too old, some email changes may have been missed',
3306
- account: this.account,
3307
- currentHistoryId,
3308
- updatedHistoryId,
3309
- err
3310
- });
3311
- // Emit warning event so the account can be flagged for attention
3312
- await emitChangeEvent(this.logger, this.account, 'syncWarning', {
3313
- type: 'historyIdExpired',
3314
- message: 'Some email changes may have been missed due to expired history ID'
3315
- });
3316
- // Set to newest known value. A fallback poll or a retry is headed nowhere past
3317
- // the expired cursor, so ask for the current one, or every run would 404 again
3318
- newestHistoryId = updatedHistoryId;
3319
- if (!(updatedHistoryId > currentHistoryId)) {
3320
- try {
3321
- const profileRes = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/profile`);
3322
- newestHistoryId = Number(profileRes?.historyId) || newestHistoryId;
3323
- } catch (profileErr) {
3324
- this.logger.warn({ msg: 'Failed to fetch the current history ID', account: this.account, err: profileErr });
3325
- }
3326
- }
3327
- return;
3328
- }
3329
- default:
3330
- throw err;
3331
- }
3326
+ let pageToken = null;
3327
+ do {
3328
+ // null when the cursor expired, which ends the run
3329
+ const historyRes = await this.fetchHistoryPage(run, pageToken);
3330
+ if (!historyRes) {
3331
+ break;
3332
3332
  }
3333
3333
 
3334
3334
  // Before any entry is marked in flight: a failure here ends the run with the cursor
@@ -3337,82 +3337,189 @@ class GmailClient extends BaseClient {
3337
3337
 
3338
3338
  // Process each history entry
3339
3339
  for (let entry of historyRes?.history || []) {
3340
- let historyEntryId = Number(entry?.id) || null;
3341
-
3342
- let attempts = processingMarker && entry?.id && String(processingMarker.id) === String(entry.id) ? Number(processingMarker.count) || 0 : 0;
3343
- if (attempts >= GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS) {
3344
- // Every attempt to process this entry has taken the worker
3345
- // down with it. Skip it and advance the cursor so the
3346
- // account can make progress; the warning names the messages
3347
- // whose events were lost so they can be recovered manually
3348
- let messageIds = (entry?.messagesAdded || []).map(added => added?.message?.id).filter(id => id);
3349
- this.logger.error({
3350
- msg: 'Skipping history entry that repeatedly failed or killed the worker',
3351
- account: this.account,
3352
- entryId: entry?.id,
3353
- attempts,
3354
- messageIds
3355
- });
3356
- await emitChangeEvent(this.logger, this.account, 'syncWarning', {
3357
- type: 'historyEntrySkipped',
3358
- message: 'Processing a history entry repeatedly failed or killed the sync worker, its changes were skipped',
3359
- historyId: entry?.id,
3360
- messageIds
3361
- });
3362
- await advanceHistoryCursor(historyEntryId);
3363
- continue;
3364
- }
3365
-
3366
- if (entry?.id) {
3367
- // mark the entry as in flight before touching it, so a
3368
- // worker death mid-entry is attributable on restart
3369
- await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryProcessing', JSON.stringify({ id: entry.id, count: attempts + 1 }));
3370
- }
3371
-
3372
- try {
3373
- // A message in the entry that fails to fetch is deferred on its own inside
3374
- await this.processHistoryEntry(entry, context);
3375
- await advanceHistoryCursor(historyEntryId);
3376
- } catch (err) {
3377
- this.logger.error({
3378
- msg: 'Failed to process history entry',
3379
- account: this.account,
3380
- entryId: entry?.id,
3381
- messagesAdded: entry?.messagesAdded?.length,
3382
- messagesDeleted: entry?.messagesDeleted?.length,
3383
- labelsAdded: entry?.labelsAdded?.length,
3384
- labelsRemoved: entry?.labelsRemoved?.length,
3385
- err
3386
- });
3387
- // End the run here, with the cursor on the last entry that went through: the
3388
- // next run starts from this entry again. Moving past it lost its label changes
3389
- // and deletions without a trace. The in-flight marker stays, so an entry that
3390
- // keeps failing is skipped with a syncWarning after the attempt limit above
3391
- throw err;
3392
- }
3340
+ await this.processHistoryEntryGuarded(run, entry, context);
3393
3341
  }
3394
3342
 
3395
- if (Number(historyRes?.historyId) > newestHistoryId) {
3396
- newestHistoryId = Number(historyRes.historyId);
3343
+ if (Number(historyRes?.historyId) > run.newestHistoryId) {
3344
+ run.newestHistoryId = Number(historyRes.historyId);
3397
3345
  }
3398
3346
 
3399
3347
  // Continue with next page
3400
- if (historyRes?.nextPageToken) {
3401
- await getHistoryPage(historyRes?.nextPageToken);
3402
- }
3403
- };
3404
-
3405
- await getHistoryPage();
3348
+ pageToken = historyRes?.nextPageToken;
3349
+ } while (pageToken);
3406
3350
 
3407
3351
  // Update to newest history ID
3408
- if (newestHistoryId && newestHistoryId > currentHistoryId) {
3409
- await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', newestHistoryId.toString());
3352
+ if (run.newestHistoryId && run.newestHistoryId > currentHistoryId) {
3353
+ await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', run.newestHistoryId.toString());
3410
3354
  }
3411
3355
 
3412
3356
  // the run finished without dying, drop the in-flight marker
3413
3357
  await this.redis.hdel(this.getAccountKey(), 'googleHistoryProcessing');
3414
3358
  }
3415
3359
 
3360
+ /**
3361
+ * The history cursor only advances after an entry is processed, so an entry that kills the
3362
+ * worker (OOM, heartbeat restart) is refetched by the restarted worker and would loop forever.
3363
+ * The in-flight marker records which entry processing last started on and how many times;
3364
+ * once the limit is hit the entry is skipped with a syncWarning
3365
+ * @returns {Promise<Object|null>} the marker a previous run left, if any
3366
+ */
3367
+ async readHistoryProcessingMarker() {
3368
+ try {
3369
+ return JSON.parse(await this.redis.hget(this.getAccountKey(), 'googleHistoryProcessing'));
3370
+ } catch (err) {
3371
+ // no marker or an unreadable one, nothing to resume
3372
+ return null;
3373
+ }
3374
+ }
3375
+
3376
+ /**
3377
+ * Advances the durable cursor once an entry is handled (processed or skipped)
3378
+ * @param {Object} run - The history run
3379
+ * @param {number|null} historyEntryId - The entry that was handled
3380
+ */
3381
+ async advanceHistoryCursor(run, historyEntryId) {
3382
+ if (historyEntryId && historyEntryId > run.lastHistoryId) {
3383
+ await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', historyEntryId.toString());
3384
+ run.lastHistoryId = historyEntryId;
3385
+ }
3386
+ }
3387
+
3388
+ /**
3389
+ * Fetches a page of history
3390
+ * @param {Object} run - The history run
3391
+ * @param {string} [pageToken] - Pagination token
3392
+ * @returns {Promise<Object|null>} the page, null when the cursor has expired
3393
+ */
3394
+ async fetchHistoryPage(run, pageToken) {
3395
+ let queryArgs = {
3396
+ startHistoryId: run.currentHistoryId,
3397
+ maxResults: 500
3398
+ };
3399
+
3400
+ if (pageToken) {
3401
+ queryArgs.pageToken = pageToken;
3402
+ }
3403
+
3404
+ try {
3405
+ return await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/history`, 'get', queryArgs);
3406
+ } catch (err) {
3407
+ if (err?.oauthRequest?.response?.error?.code !== 404) {
3408
+ throw err;
3409
+ }
3410
+ await this.handleExpiredHistory(run, err);
3411
+ return null;
3412
+ }
3413
+ }
3414
+
3415
+ /**
3416
+ * History ID too old - some changes may have been missed. Moves the run to the newest known
3417
+ * history ID so the cursor does not stay on the expired one
3418
+ * @param {Object} run - The history run
3419
+ * @param {Error} err - The 404 from the history request
3420
+ */
3421
+ async handleExpiredHistory(run, err) {
3422
+ const { currentHistoryId, updatedHistoryId } = run;
3423
+
3424
+ this.logger.warn({
3425
+ msg: 'History ID too old, some email changes may have been missed',
3426
+ account: this.account,
3427
+ currentHistoryId,
3428
+ updatedHistoryId,
3429
+ err
3430
+ });
3431
+ // Emit warning event so the account can be flagged for attention
3432
+ await emitChangeEvent(this.logger, this.account, 'syncWarning', {
3433
+ type: 'historyIdExpired',
3434
+ message: 'Some email changes may have been missed due to expired history ID'
3435
+ });
3436
+ // Set to newest known value. A fallback poll or a retry is headed nowhere past
3437
+ // the expired cursor, so ask for the current one, or every run would 404 again
3438
+ run.newestHistoryId = updatedHistoryId;
3439
+ if (!(updatedHistoryId > currentHistoryId)) {
3440
+ try {
3441
+ const profileRes = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/profile`);
3442
+ run.newestHistoryId = Number(profileRes?.historyId) || run.newestHistoryId;
3443
+ } catch (profileErr) {
3444
+ this.logger.warn({ msg: 'Failed to fetch the current history ID', account: this.account, err: profileErr });
3445
+ }
3446
+ }
3447
+ }
3448
+
3449
+ /**
3450
+ * Processes one history entry under the in-flight marker: an entry that already took the
3451
+ * worker down GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS times is skipped, any other is marked in flight
3452
+ * before it is touched and the cursor advances only after it went through
3453
+ * @param {Object} run - The history run
3454
+ * @param {Object} entry - History entry
3455
+ * @param {Object} context - What every entry of the run needs, see getHistoryContext()
3456
+ */
3457
+ async processHistoryEntryGuarded(run, entry, context) {
3458
+ let historyEntryId = Number(entry?.id) || null;
3459
+
3460
+ let { processingMarker } = run;
3461
+ let attempts = processingMarker && entry?.id && String(processingMarker.id) === String(entry.id) ? Number(processingMarker.count) || 0 : 0;
3462
+ if (attempts >= GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS) {
3463
+ await this.skipPoisonHistoryEntry(run, entry, historyEntryId, attempts);
3464
+ return;
3465
+ }
3466
+
3467
+ if (entry?.id) {
3468
+ // mark the entry as in flight before touching it, so a
3469
+ // worker death mid-entry is attributable on restart
3470
+ await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryProcessing', JSON.stringify({ id: entry.id, count: attempts + 1 }));
3471
+ }
3472
+
3473
+ try {
3474
+ // A message in the entry that fails to fetch is deferred on its own inside
3475
+ await this.processHistoryEntry(entry, context);
3476
+ await this.advanceHistoryCursor(run, historyEntryId);
3477
+ } catch (err) {
3478
+ this.logger.error({
3479
+ msg: 'Failed to process history entry',
3480
+ account: this.account,
3481
+ entryId: entry?.id,
3482
+ messagesAdded: entry?.messagesAdded?.length,
3483
+ messagesDeleted: entry?.messagesDeleted?.length,
3484
+ labelsAdded: entry?.labelsAdded?.length,
3485
+ labelsRemoved: entry?.labelsRemoved?.length,
3486
+ err
3487
+ });
3488
+ // End the run here, with the cursor on the last entry that went through: the
3489
+ // next run starts from this entry again. Moving past it lost its label changes
3490
+ // and deletions without a trace. The in-flight marker stays, so an entry that
3491
+ // keeps failing is skipped with a syncWarning after the attempt limit above
3492
+ throw err;
3493
+ }
3494
+ }
3495
+
3496
+ /**
3497
+ * Every attempt to process this entry has taken the worker down with it. Skip it and advance
3498
+ * the cursor so the account can make progress; the warning names the messages whose events
3499
+ * were lost so they can be recovered manually
3500
+ * @param {Object} run - The history run
3501
+ * @param {Object} entry - History entry
3502
+ * @param {number|null} historyEntryId - The entry's ID as the cursor stores it
3503
+ * @param {number} attempts - How many times processing it already started
3504
+ */
3505
+ async skipPoisonHistoryEntry(run, entry, historyEntryId, attempts) {
3506
+ let messageIds = (entry?.messagesAdded || []).map(added => added?.message?.id).filter(id => id);
3507
+ this.logger.error({
3508
+ msg: 'Skipping history entry that repeatedly failed or killed the worker',
3509
+ account: this.account,
3510
+ entryId: entry?.id,
3511
+ attempts,
3512
+ messageIds
3513
+ });
3514
+ await emitChangeEvent(this.logger, this.account, 'syncWarning', {
3515
+ type: 'historyEntrySkipped',
3516
+ message: 'Processing a history entry repeatedly failed or killed the sync worker, its changes were skipped',
3517
+ historyId: entry?.id,
3518
+ messageIds
3519
+ });
3520
+ await this.advanceHistoryCursor(run, historyEntryId);
3521
+ }
3522
+
3416
3523
  /**
3417
3524
  * Prepares a new message for processing
3418
3525
  * @param {Object} eventEntry - Message event data