emailengine-app 2.85.0 → 2.86.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 (128) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +74 -0
  4. package/Dockerfile +14 -1
  5. package/ENVIRONMENT.md +139 -0
  6. package/README.md +1 -1
  7. package/config/default.toml +2 -0
  8. package/copy-static-files.sh +4 -2
  9. package/data/google-crawlers.json +1 -1
  10. package/data/public_suffix_list.dat +4 -3
  11. package/lib/account-assignment.js +19 -0
  12. package/lib/account.js +194 -165
  13. package/lib/api-error-codes.js +49 -0
  14. package/lib/api-reference/model.js +6 -1
  15. package/lib/api-routes/account-routes.js +78 -26
  16. package/lib/api-routes/blocklist-routes.js +68 -2
  17. package/lib/api-routes/delivery-test-routes.js +1 -1
  18. package/lib/api-routes/gateway-routes.js +82 -10
  19. package/lib/api-routes/index.js +4 -0
  20. package/lib/api-routes/license-routes.js +2 -2
  21. package/lib/api-routes/mailbox-routes.js +3 -3
  22. package/lib/api-routes/message-routes.js +15 -7
  23. package/lib/api-routes/oauth2-app-routes.js +15 -8
  24. package/lib/api-routes/outbox-routes.js +77 -66
  25. package/lib/api-routes/permission-map.js +55 -6
  26. package/lib/api-routes/scoped-routes.js +74 -0
  27. package/lib/api-routes/settings-routes.js +11 -4
  28. package/lib/api-routes/stats-routes.js +5 -1
  29. package/lib/api-routes/submit-routes.js +4 -3
  30. package/lib/api-routes/template-routes.js +7 -6
  31. package/lib/api-routes/token-routes.js +11 -5
  32. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  33. package/lib/api-routes/webhook-route-routes.js +119 -4
  34. package/lib/calendar-event.js +81 -1
  35. package/lib/consts.js +38 -46
  36. package/lib/db.js +14 -6
  37. package/lib/delivery-error.js +6 -0
  38. package/lib/deprecations.js +270 -0
  39. package/lib/email-client/base-client.js +130 -156
  40. package/lib/email-client/fallback-poll.js +62 -0
  41. package/lib/email-client/gmail-client.js +51 -11
  42. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  43. package/lib/email-client/imap/adaptive-idle.js +278 -0
  44. package/lib/email-client/imap/connection-errors.js +14 -1
  45. package/lib/email-client/imap/idle-settings.js +31 -5
  46. package/lib/email-client/imap/listing-diff.js +37 -0
  47. package/lib/email-client/imap/mailbox.js +372 -226
  48. package/lib/email-client/imap/subconnection.js +7 -29
  49. package/lib/email-client/imap/sync-operations.js +220 -127
  50. package/lib/email-client/imap-client.js +227 -163
  51. package/lib/email-client/message-builder.js +14 -79
  52. package/lib/email-client/outlook-client.js +372 -338
  53. package/lib/email-client/smtp-pool-manager.js +16 -13
  54. package/lib/email-client/sync-state-fields.js +19 -0
  55. package/lib/encrypt.js +157 -41
  56. package/lib/enum-descriptions.js +3 -1
  57. package/lib/env-setting-overrides.js +288 -0
  58. package/lib/export-worker.js +751 -0
  59. package/lib/export.js +64 -15
  60. package/lib/gateway.js +17 -1
  61. package/lib/get-raw-email.js +25 -107
  62. package/lib/health.js +75 -0
  63. package/lib/lock-run.js +119 -0
  64. package/lib/logger-consts.js +48 -0
  65. package/lib/logger.js +1 -1
  66. package/lib/lua/z-head-scores.lua +28 -0
  67. package/lib/network-errors.js +1 -1
  68. package/lib/node-version.js +24 -0
  69. package/lib/notify-attachments.js +20 -1
  70. package/lib/oauth2-apps.js +630 -655
  71. package/lib/outbox.js +184 -54
  72. package/lib/parse-message.js +3 -3
  73. package/lib/privileged-settings.js +2 -2
  74. package/lib/queue-browser/definitions.js +11 -0
  75. package/lib/queue-browser/index.js +68 -19
  76. package/lib/queue-job-actions.js +18 -1
  77. package/lib/queue-retention.js +48 -12
  78. package/lib/queue-stats.js +11 -2
  79. package/lib/read-env-value.js +3 -0
  80. package/lib/redis-memory-warnings.js +99 -0
  81. package/lib/redis-reconnect.js +29 -0
  82. package/lib/request-timing.js +23 -0
  83. package/lib/respawn-backoff.js +35 -0
  84. package/lib/rewrite-text-nodes.js +19 -59
  85. package/lib/schemas.js +163 -39
  86. package/lib/settings.js +6 -2
  87. package/lib/smtp-auth.js +19 -1
  88. package/lib/thread-diagnostics.js +18 -1
  89. package/lib/tls/provision.js +6 -3
  90. package/lib/token-audit-log.js +19 -20
  91. package/lib/token-permission-view.js +4 -3
  92. package/lib/tools.js +8 -41
  93. package/lib/ui-routes/admin-config-routes.js +64 -90
  94. package/lib/ui-routes/admin-entities-routes.js +2 -14
  95. package/lib/ui-routes/imap-idle-field.js +1 -1
  96. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  97. package/lib/ui-routes/overridable-fields.js +84 -0
  98. package/lib/ui-routes/queue-routes.js +8 -5
  99. package/lib/ui-routes/settings-page.js +6 -0
  100. package/lib/utils/decode-headers.js +3 -12
  101. package/lib/utils/filter-empty.js +20 -0
  102. package/lib/utils/int-setting.js +48 -0
  103. package/lib/utils/tracking-settings.js +35 -0
  104. package/lib/web-safe-html.js +18 -105
  105. package/lib/webhook-delivery.js +461 -0
  106. package/lib/webhook-failures.js +132 -0
  107. package/lib/webhook-request.js +29 -1
  108. package/lib/webhook-routing.js +30 -1
  109. package/lib/webhook-test.js +88 -0
  110. package/lib/webhooks.js +54 -41
  111. package/lib/worker-rpc-error.js +2 -1
  112. package/package.json +21 -20
  113. package/sbom.json +304 -382
  114. package/server.js +149 -76
  115. package/static/js/ace/ace.js +1 -1
  116. package/static/licenses.html +21 -31
  117. package/translations/messages.pot +26 -26
  118. package/views/config/security.hbs +22 -0
  119. package/views/config/service.hbs +44 -0
  120. package/views/config/webhooks.hbs +36 -0
  121. package/views/partials/queue_retention_note.hbs +12 -8
  122. package/views/partials/ui/env-managed-alert.hbs +16 -7
  123. package/workers/api.js +102 -28
  124. package/workers/export.js +16 -631
  125. package/workers/imap.js +13 -0
  126. package/workers/smtp.js +9 -11
  127. package/workers/webhooks.js +18 -432
  128. package/lib/email-client/outlook-fallback-poll.js +0 -30
package/lib/account.js CHANGED
@@ -17,7 +17,7 @@ const {
17
17
  const { MessageChannel } = require('worker_threads');
18
18
  const { MessagePortReadable } = require('./message-port-stream');
19
19
  const { isDeepStrictEqual } = require('util');
20
- const { encrypt, decrypt, decryptField, parseEncryptedData } = require('./encrypt');
20
+ const { encrypt, decrypt, decryptAsync, decryptField, parseEncryptedData } = require('./encrypt');
21
21
  const { oauth2Apps, isApiBasedApp } = require('./oauth2-apps');
22
22
  const settings = require('./settings');
23
23
  const redisScanDelete = require('./redis-scan-delete');
@@ -26,23 +26,20 @@ const { extractMultiValues, createTransaction } = require('./redis-operations');
26
26
  const outbox = require('./outbox');
27
27
  const tokens = require('./tokens');
28
28
  const { randomId } = require('./utils/random-id');
29
- const Lock = require('ioredfour');
30
- const { redis } = require('./db');
31
29
  const { REDIS_PREFIX, AUTH_FAILURE_DISABLED_FIELD, AUTH_FAILURE_DISABLED_LEGACY_DESCRIPTION } = require('./consts');
32
30
  const { webSafeTextResponse, applyWebSafeHtmlOptions } = require('./web-safe-html');
33
31
  const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
34
32
  const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
35
33
  const { decodeStoredMailboxEntry } = require('./email-client/imap/listing-diff');
34
+ const { SYNC_STATE_FIELDS } = require('./email-client/sync-state-fields');
35
+ const { runLocked, refuseUnavailableLock, getSharedLock } = require('./lock-run');
36
36
  const { readImapData } = require('./account/imap-data');
37
37
  const { isTransientCredentialError, credentialErrorStatus } = require('./email-client/credential-errors');
38
38
  const { getAccountHttpRoute } = require('./utils/network');
39
39
 
40
- // Shared Lock instance to prevent Redis connection leak (one subscriber per Lock instance)
41
- // Previously, each Account created its own Lock, causing ~30k connections with 30k accounts
42
- const defaultLock = new Lock({
43
- redis,
44
- namespace: 'ee'
45
- });
40
+ // Every Account takes its locks from the one shared instance (lib/lock-run.js getSharedLock()): each
41
+ // ioredfour Lock opens a subscriber connection, and a Lock per Account once meant ~30k connections
42
+ // with 30k accounts
46
43
 
47
44
  // Serialization window for Account.update(). The critical section is a few Redis round trips, so
48
45
  // the TTL only has to cover a stalled writer, and the wait only has to outlast a normal one.
@@ -57,6 +54,33 @@ const ACCOUNT_UPDATE_LOCK_WAIT = 5 * 1000;
57
54
  // re-encrypts exactly this list.
58
55
  const ENCRYPTED_ACCOUNT_FIELDS = ['webhooks', 'webhooksCustomHeaders', 'proxy'];
59
56
 
57
+ /**
58
+ * The encrypted credential fields of an unserialized account, as [holder, key] pairs: a credential
59
+ * is under `auth` when the configuration has one, otherwise on the configuration itself
60
+ * @param {Object} accountData
61
+ * @returns {Array<[Object, string]>}
62
+ */
63
+ function credentialFields(accountData) {
64
+ const fields = [];
65
+ for (const type of ['imap', 'smtp', 'oauth2']) {
66
+ const config = accountData[type];
67
+ if (!config || !config.auth) {
68
+ continue;
69
+ }
70
+ for (const key of ['pass', 'accessToken', 'refreshToken']) {
71
+ if (key in config.auth) {
72
+ fields.push([config.auth, key]);
73
+ } else if (key in config) {
74
+ fields.push([config, key]);
75
+ }
76
+ }
77
+ }
78
+ return fields;
79
+ }
80
+
81
+ // Sync positions the Gmail API and Graph clients keep in the account hash, cleared by a flush
82
+ const FLUSHED_SYNC_FIELDS = Object.values(SYNC_STATE_FIELDS).flat();
83
+
60
84
  /**
61
85
  * What an incoming account payload asks of `imap.disabled`.
62
86
  *
@@ -149,7 +173,7 @@ class Account {
149
173
  }
150
174
 
151
175
  getLock() {
152
- return this.lock || defaultLock;
176
+ return this.lock || getSharedLock();
153
177
  }
154
178
 
155
179
  /**
@@ -452,10 +476,13 @@ class Account {
452
476
  * the non-secret structure (listings, delegated-row lookups): the credentials and the
453
477
  * ENCRYPTED_ACCOUNT_FIELDS stay ciphertext, and an encrypted custom header list is left out
454
478
  * rather than failing to parse. decryptAccountField() opens the few such values a caller needs.
479
+ * @param {boolean} [opts.deferCredentials] - Leave only the credentials (passwords, tokens) as
480
+ * stored, for a caller that decrypts them with decryptCredentials()
455
481
  * @returns {Object} The unserialized account
456
482
  */
457
483
  unserializeAccountData(accountData, opts) {
458
484
  const skipDecrypt = !!(opts && opts.skipDecrypt);
485
+ const deferCredentials = !!(opts && opts.deferCredentials);
459
486
  const result = {};
460
487
 
461
488
  // The loop below drops every `_`-prefixed field, which is what keeps the auth-failure marker
@@ -659,26 +686,13 @@ class Account {
659
686
  });
660
687
 
661
688
  // decrypt secrets
662
- if (this.secret && !skipDecrypt) {
663
- for (let type of ['imap', 'smtp', 'oauth2']) {
664
- if (result[type] && result[type].auth) {
665
- for (let key of ['pass', 'accessToken', 'refreshToken']) {
666
- if (key in result[type].auth) {
667
- try {
668
- result[type].auth[key] = decrypt(result[type].auth[key], this.secret);
669
- } catch (err) {
670
- // ignore??
671
- this.logUnserializeFailure('Failed to decrypt value', key, result[type].auth[key], result.account, err);
672
- }
673
- } else if (key in result[type]) {
674
- try {
675
- result[type][key] = decrypt(result[type][key], this.secret);
676
- } catch (err) {
677
- // ignore??
678
- this.logUnserializeFailure('Failed to decrypt value', key, result[type][key], result.account, err);
679
- }
680
- }
681
- }
689
+ if (this.secret && !skipDecrypt && !deferCredentials) {
690
+ for (const [holder, key] of credentialFields(result)) {
691
+ try {
692
+ holder[key] = decrypt(holder[key], this.secret);
693
+ } catch (err) {
694
+ // ignore??
695
+ this.logUnserializeFailure('Failed to decrypt value', key, holder[key], result.account, err);
682
696
  }
683
697
  }
684
698
  }
@@ -702,6 +716,27 @@ class Account {
702
716
  return result;
703
717
  }
704
718
 
719
+ /**
720
+ * Decrypts the stored credentials of an unserialized account in place, the asynchronous
721
+ * counterpart of the decrypt step in unserializeAccountData(). A value that does not decrypt is
722
+ * logged and left as it is, as the synchronous path does
723
+ * @param {Object} accountData - From unserializeAccountData() with deferCredentials
724
+ */
725
+ async decryptCredentials(accountData) {
726
+ if (!this.secret) {
727
+ return;
728
+ }
729
+ await Promise.all(
730
+ credentialFields(accountData).map(async ([holder, key]) => {
731
+ try {
732
+ holder[key] = await decryptAsync(holder[key], this.secret);
733
+ } catch (err) {
734
+ this.logUnserializeFailure('Failed to decrypt value', key, holder[key], accountData.account, err);
735
+ }
736
+ })
737
+ );
738
+ }
739
+
705
740
  /**
706
741
  * Decrypts one of ENCRYPTED_ACCOUNT_FIELDS. Cleartext (a value stored before the field was
707
742
  * encrypted, or written without a secret) passes through unchanged.
@@ -915,6 +950,20 @@ class Account {
915
950
  return result;
916
951
  }
917
952
 
953
+ /**
954
+ * Reads one stored field of the account, decoded the way loadAccountData() decodes it, without
955
+ * loading the rest of the record. Not for credential fields, which stay encrypted here
956
+ * @param {string} field
957
+ * @returns {Promise<*>} The value, undefined when the field is not stored or holds nothing
958
+ */
959
+ async getStoredField(field) {
960
+ const stored = await this.redis.hget(this.getAccountKey(), field);
961
+ if (stored === null) {
962
+ return undefined;
963
+ }
964
+ return this.unserializeAccountData({ [field]: stored }, { skipDecrypt: true })[field];
965
+ }
966
+
918
967
  async loadAccountData(account, requireValid, runIndex) {
919
968
  if (!this.account || (account && account !== this.account)) {
920
969
  let message = 'Invalid account ID';
@@ -930,7 +979,11 @@ class Account {
930
979
  throw error;
931
980
  }
932
981
 
933
- let accountData = this.unserializeAccountData(result);
982
+ // Decrypted asynchronously, see decryptAsync(): a key that is not cached yet is a 600000
983
+ // iteration PBKDF2, and the synchronous decrypt blocked the worker's event loop for it once
984
+ // per account loaded at startup
985
+ let accountData = this.unserializeAccountData(result, { deferCredentials: true });
986
+ await this.decryptCredentials(accountData);
934
987
 
935
988
  if (accountData.oauth2 && accountData.oauth2.provider) {
936
989
  let app = await oauth2Apps.get(accountData.oauth2.provider);
@@ -1058,32 +1111,27 @@ class Account {
1058
1111
  * @returns {Promise<*>} Whatever `fn` resolves to
1059
1112
  */
1060
1113
  async withUpdateLock(account, fn) {
1061
- const lock = this.getLock();
1062
1114
  const lockKey = `account:update:${account}`;
1063
- let updateLock;
1064
-
1065
- let lockErr;
1066
- try {
1067
- updateLock = await lock.waitAcquireLock(lockKey, ACCOUNT_UPDATE_LOCK_TTL, ACCOUNT_UPDATE_LOCK_WAIT);
1068
- } catch (err) {
1069
- lockErr = err;
1070
- }
1115
+ return await runLocked(this.getLock(), lockKey, { ttl: ACCOUNT_UPDATE_LOCK_TTL, wait: ACCOUNT_UPDATE_LOCK_WAIT }, fn, async err => {
1116
+ this.logger.warn({ msg: 'Failed to get account update lock, proceeding unserialized', account, lockKey, err });
1117
+ return await fn();
1118
+ });
1119
+ }
1071
1120
 
1072
- if (!updateLock?.success) {
1073
- this.logger.warn({ msg: 'Failed to get account update lock, proceeding unserialized', account, lockKey, err: lockErr });
1121
+ /**
1122
+ * Asks the worker holding the account to remove what the provider keeps for it, and waits.
1123
+ * Best effort: a deletion must not fail because a provider or the worker did not answer
1124
+ * @returns {Promise<boolean>} True when something was removed
1125
+ */
1126
+ async releaseRemoteResources() {
1127
+ if (typeof this.call !== 'function') {
1128
+ return false;
1074
1129
  }
1075
-
1076
1130
  try {
1077
- return await fn();
1078
- } finally {
1079
- if (updateLock?.success) {
1080
- try {
1081
- await lock.releaseLock(updateLock);
1082
- } catch (err) {
1083
- // The lock expires on its own, so a failed release must not mask the result
1084
- this.logger.warn({ msg: 'Failed to release account update lock', account, lockKey, err });
1085
- }
1086
- }
1131
+ return !!(await this.call({ cmd: 'teardown', account: this.account, timeout: this.timeout }));
1132
+ } catch (err) {
1133
+ this.logger.warn({ msg: 'Failed to release provider resources before account delete', account: this.account, err });
1134
+ return false;
1087
1135
  }
1088
1136
  }
1089
1137
 
@@ -1655,6 +1703,11 @@ class Account {
1655
1703
 
1656
1704
  let accountData = await this.loadAccountData(this.account);
1657
1705
 
1706
+ // First, while the record and its token still exist: the worker's own teardown after the
1707
+ // unlink below has no token left, so the Graph subscription and the Gmail watch used to
1708
+ // outlive the account. Ahead of the revoke for the same reason
1709
+ await this.releaseRemoteResources();
1710
+
1658
1711
  if (opts.revoke && accountData.oauth2?.provider) {
1659
1712
  // Prefer refresh token over access token: revoking either invalidates the grant per Google's docs,
1660
1713
  // but the stored access token may be expired (a 400 from the provider would leave the grant intact),
@@ -1679,12 +1732,6 @@ class Account {
1679
1732
  }
1680
1733
  }
1681
1734
 
1682
- const dateKeyTdy = new Date().toISOString().substring(0, 10).replace(/-/g, '');
1683
- const dateKeyYdy = new Date(Date.now() - 24 * 3600 * 1000).toISOString().substring(0, 10).replace(/-/g, '');
1684
-
1685
- const tombstoneTdy = `${REDIS_PREFIX}tomb:${this.account}:${dateKeyTdy}`;
1686
- const tombstoneYdy = `${REDIS_PREFIX}tomb:${this.account}:${dateKeyYdy}`;
1687
-
1688
1735
  // UNLINK rather than DEL throughout: none of these need the memory reclaimed synchronously,
1689
1736
  // and the outbox and the message ID index can hold enough entries that freeing them inline
1690
1737
  // would block Redis for every other worker.
@@ -1707,9 +1754,6 @@ class Account {
1707
1754
  .unlink(`${REDIS_PREFIX}iap:${this.account}`) // external event notification queue
1708
1755
  .unlink(this.getDeferredQueueKey()) // mailbox changes waiting for a retry
1709
1756
 
1710
- .unlink(tombstoneTdy)
1711
- .unlink(tombstoneYdy)
1712
-
1713
1757
  .unlink(`${REDIS_PREFIX}tpl:${this.account}:i`) // stored templates index
1714
1758
  .unlink(`${REDIS_PREFIX}tpl:${this.account}:c`); // stored templates index
1715
1759
 
@@ -2364,92 +2408,87 @@ class Account {
2364
2408
  // use a global lock to decrease Redis scanning operations
2365
2409
  let lockKey = ['flush' /*, this.account*/].join(':');
2366
2410
 
2367
- let lock = this.getLock();
2368
- let flushLock;
2411
+ // One flush at a time across the instance, and no waiting for it
2412
+ return await runLocked(
2413
+ this.getLock(),
2414
+ lockKey,
2415
+ // extended while the flush runs, so a stalled process frees it in minutes rather than half an hour
2416
+ { ttl: 2 * 60 * 1000, wait: false, extend: true },
2417
+ () => this.flushLocked(data),
2418
+ refuseUnavailableLock(
2419
+ this.logger,
2420
+ 'Failed to get flush lock',
2421
+ { account: this.account, lockKey },
2422
+ {
2423
+ statusCode: 429,
2424
+ code: 'LockFail',
2425
+ message: 'One flush operation at a time allowed, try again later',
2426
+ logMessage: 'Failed to get flush lock, another flush is already running',
2427
+ failureMessage: 'Failed to get flush lock, try again later'
2428
+ }
2429
+ )
2430
+ );
2431
+ }
2369
2432
 
2370
- try {
2371
- flushLock = await lock.acquireLock(lockKey, 30 * 60 * 1000);
2372
- if (!flushLock.success) {
2373
- // contention: another flush already holds the lock
2374
- this.logger.warn({ msg: 'Failed to get flush lock, another flush is already running', account: this.account, lockKey });
2433
+ /**
2434
+ * The part of flush() that runs under the flush lock: pauses the account, clears its sync
2435
+ * state and resumes it a few seconds later
2436
+ * @param {Object} data - The flush request
2437
+ */
2438
+ async flushLocked(data) {
2439
+ await this.call({
2440
+ cmd: 'pause',
2441
+ account: this.account,
2442
+ timeout: this.timeout
2443
+ });
2375
2444
 
2376
- let error = Boom.boomify(new Error('One flush operation at a time allowed, try again later'), { statusCode: 429 });
2377
- error.output.payload.code = 'LockFail';
2378
- throw error;
2379
- }
2380
- } catch (err) {
2381
- if (Boom.isBoom(err)) {
2382
- // contention was already logged above
2383
- throw err;
2384
- }
2385
- this.logger.error({ msg: 'Failed to get flush lock', account: this.account, lockKey, err });
2386
- let error = Boom.boomify(new Error('Failed to get flush lock, try again later'), { statusCode: 500 });
2387
- if (err.code) {
2388
- error.output.payload.code = err.code || 'LockFail';
2389
- }
2390
- throw error;
2391
- }
2445
+ let notifyFrom = data.notifyFrom && data.notifyFrom !== 'now' ? data.notifyFrom : new Date();
2446
+ let imapIndexer = data.imapIndexer;
2392
2447
 
2393
2448
  try {
2394
- await this.call({
2395
- cmd: 'pause',
2396
- account: this.account,
2397
- timeout: this.timeout
2398
- });
2399
-
2400
- let notifyFrom = data.notifyFrom && data.notifyFrom !== 'now' ? data.notifyFrom : new Date();
2401
- let imapIndexer = data.imapIndexer;
2402
-
2403
- const dateKeyTdy = new Date().toISOString().substring(0, 10).replace(/-/g, '');
2404
- const dateKeyYdy = new Date(Date.now() - 24 * 3600 * 1000).toISOString().substring(0, 10).replace(/-/g, '');
2405
-
2406
- const tombstoneTdy = `${REDIS_PREFIX}tomb:${this.account}:${dateKeyTdy}`;
2407
- const tombstoneYdy = `${REDIS_PREFIX}tomb:${this.account}:${dateKeyYdy}`;
2408
-
2409
- try {
2410
- let pipeline = this.redis
2411
- .multi()
2412
- // start syncing new messages from current time
2413
- .hset(this.getAccountKey(), 'notifyFrom', notifyFrom.toISOString())
2414
- // mark connection count to 0 to trigger `accountInitialized` event
2415
- .hset(this.getAccountKey(), `state:count:${ACCOUNT_STATES.CONNECTED}`, '0')
2416
- .del(this.getMailboxListKey()) // mailbox list
2417
- // Note: mailbox ID hash (iah:) and listRegistry are intentionally NOT deleted
2418
- // to preserve message ID stability across reconnections. Message IDs depend on
2419
- // the specific mailbox ID entries, so deleting them would invalidate existing IDs.
2420
- .del(`${REDIS_PREFIX}iar:b:${this.account}`) // retired bounce store, an older version sharing this Redis may still write it
2421
- .del(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
2422
- .del(tombstoneTdy)
2423
- .del(tombstoneYdy);
2424
-
2425
- if (imapIndexer) {
2426
- pipeline = pipeline.hset(this.getAccountKey(), 'imapIndexer', imapIndexer);
2427
- }
2449
+ let pipeline = this.redis
2450
+ .multi()
2451
+ // start syncing new messages from current time
2452
+ .hset(this.getAccountKey(), 'notifyFrom', notifyFrom.toISOString())
2453
+ // mark connection count to 0 to trigger `accountInitialized` event
2454
+ .hset(this.getAccountKey(), `state:count:${ACCOUNT_STATES.CONNECTED}`, '0')
2455
+ // The Gmail API and Graph clients keep their sync position in the account hash
2456
+ // rather than in the keys removed below. Without these a flushed Gmail account
2457
+ // went on from its old history ID, and a flushed Graph account kept the point
2458
+ // its announced set started from while the set itself was removed, so the next
2459
+ // recovery pass took every message since then for unannounced and announced it
2460
+ // again. Each client sets a fresh value when it starts.
2461
+ .hdel(this.getAccountKey(), ...FLUSHED_SYNC_FIELDS)
2462
+ .del(this.getMailboxListKey()) // mailbox list
2463
+ // Note: mailbox ID hash (iah:) and listRegistry are intentionally NOT deleted
2464
+ // to preserve message ID stability across reconnections. Message IDs depend on
2465
+ // the specific mailbox ID entries, so deleting them would invalidate existing IDs.
2466
+ .del(`${REDIS_PREFIX}iar:b:${this.account}`) // retired bounce store, an older version sharing this Redis may still write it
2467
+ .del(`${REDIS_PREFIX}iar:s:${this.account}`); // seen messages list
2468
+
2469
+ if (imapIndexer) {
2470
+ pipeline = pipeline.hset(this.getAccountKey(), 'imapIndexer', imapIndexer);
2471
+ }
2428
2472
 
2429
- await pipeline.exec();
2473
+ await pipeline.exec();
2430
2474
 
2431
- // scan and delete keys
2432
- await this.deleteOwnAccountKeys();
2475
+ // scan and delete keys
2476
+ await this.deleteOwnAccountKeys();
2433
2477
 
2434
- return true;
2435
- } finally {
2436
- let finalize = async () => {
2437
- // Wait a bit before resuming. Just to be sure all pending processes have been completed.
2438
- await new Promise(r => setTimeout(r, 5 * 1000));
2439
- await this.call({
2440
- cmd: 'resume',
2441
- account: this.account,
2442
- timeout: this.timeout
2443
- });
2444
- };
2445
- finalize().catch(err => {
2446
- this.logger.error({ msg: 'Failed to finish flushing', account: this.account, err });
2447
- });
2448
- }
2478
+ return true;
2449
2479
  } finally {
2450
- if (flushLock?.success) {
2451
- await lock.releaseLock(flushLock);
2452
- }
2480
+ let finalize = async () => {
2481
+ // Wait a bit before resuming. Just to be sure all pending processes have been completed.
2482
+ await new Promise(r => setTimeout(r, 5 * 1000));
2483
+ await this.call({
2484
+ cmd: 'resume',
2485
+ account: this.account,
2486
+ timeout: this.timeout
2487
+ });
2488
+ };
2489
+ finalize().catch(err => {
2490
+ this.logger.error({ msg: 'Failed to finish flushing', account: this.account, err });
2491
+ });
2453
2492
  }
2454
2493
  }
2455
2494
 
@@ -2461,28 +2500,21 @@ class Account {
2461
2500
  return accountData;
2462
2501
  }
2463
2502
 
2464
- let lock = this.getLock();
2465
- let renewLock;
2466
-
2467
- try {
2468
- renewLock = await lock.waitAcquireLock(lockKey, 5 * 60 * 1000, 1 * 60 * 1000);
2469
- if (!renewLock.success) {
2470
- // contention: timed out waiting for the current lock holder
2471
- this.logger.warn({ msg: 'Failed to get renewal lock, timed out waiting for the current holder', account: this.account, lockKey });
2472
- throw new Error('Failed to get renewal lock');
2473
- }
2474
- } catch (err) {
2475
- if (!renewLock) {
2476
- // unexpected lock-layer error; contention was already logged above
2477
- this.logger.error({ msg: 'Failed to get renewal lock', account: this.account, lockKey, err });
2478
- }
2479
- let error = Boom.boomify(new Error('Failed to get renewal lock'), { statusCode: 500 });
2480
- if (err.code) {
2481
- error.output.payload.code = err.code || 'LockFail';
2482
- }
2483
- throw error;
2484
- }
2503
+ return await runLocked(
2504
+ this.getLock(),
2505
+ lockKey,
2506
+ { ttl: 5 * 60 * 1000, wait: 1 * 60 * 1000 },
2507
+ () => this.renewAccessTokenLocked(oauth2Opts),
2508
+ refuseUnavailableLock(this.logger, 'Failed to get renewal lock', { account: this.account, lockKey })
2509
+ );
2510
+ }
2485
2511
 
2512
+ /**
2513
+ * The part of renewAccessToken() that runs under the renewal lock: renews unless another
2514
+ * holder renewed meanwhile
2515
+ * @param {Object} oauth2Opts
2516
+ */
2517
+ async renewAccessTokenLocked(oauth2Opts) {
2486
2518
  try {
2487
2519
  let accountData = await this.loadAccountData(this.account, false);
2488
2520
 
@@ -2590,10 +2622,6 @@ class Account {
2590
2622
  }
2591
2623
 
2592
2624
  throw err;
2593
- } finally {
2594
- if (renewLock?.success) {
2595
- await lock.releaseLock(renewLock);
2596
- }
2597
2625
  }
2598
2626
  }
2599
2627
 
@@ -2995,6 +3023,7 @@ function isAccessTokenInvalidated(oauth2) {
2995
3023
 
2996
3024
  module.exports = {
2997
3025
  ENCRYPTED_ACCOUNT_FIELDS,
3026
+ FLUSHED_SYNC_FIELDS,
2998
3027
  Account,
2999
3028
  accountExists,
3000
3029
  accountsExist,
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ // Machine-readable `code` values for API error responses whose throw site did not set one.
4
+ // Dependency-free, so workers/api.js and the tests can share it.
5
+ //
6
+ // A 404 used to carry `code: 'NotFound'` only when it came from throwNotFound() or one of the
7
+ // lib-level update() methods. The others - an unknown export, queued message, blocklist entry,
8
+ // account log or account (lib/account.js throws a bare Boom 404) - came back without a code,
9
+ // because handleError() passes Boom errors through untouched, so a client could not branch on
10
+ // `code` for the most common error there is. Filled in once, where the JSON error body is built,
11
+ // so a 404 thrown by any route, now or later, carries it.
12
+
13
+ const DEFAULT_ERROR_CODES = {
14
+ 404: 'NotFound'
15
+ };
16
+
17
+ /**
18
+ * Sets the default `code` on an API error payload that has none
19
+ * @param {Object} payload - Boom output payload ({ statusCode, error, message, ... }), modified in place
20
+ * @returns {Object} The same payload
21
+ */
22
+ function addDefaultErrorCode(payload) {
23
+ if (!payload || typeof payload !== 'object' || payload.code) {
24
+ return payload;
25
+ }
26
+ const code = DEFAULT_ERROR_CODES[payload.statusCode];
27
+ if (code) {
28
+ payload.code = code;
29
+ }
30
+ return payload;
31
+ }
32
+
33
+ /**
34
+ * Hapi onPreResponse step that fills in the default code of an error response. Registered by
35
+ * workers/api.js ahead of the handler that renders error pages and JSON errors, and by the route
36
+ * tests' bare servers, so a route test sees the same error body a client does
37
+ * @param {Object} request - Hapi request
38
+ * @param {Object} h - Hapi response toolkit
39
+ * @returns {Symbol} h.continue
40
+ */
41
+ function errorCodeExt(request, h) {
42
+ const response = request.response;
43
+ if (response && response.isBoom) {
44
+ addDefaultErrorCode(response.output.payload);
45
+ }
46
+ return h.continue;
47
+ }
48
+
49
+ module.exports = { addDefaultErrorCode, errorCodeExt, DEFAULT_ERROR_CODES };
@@ -107,6 +107,7 @@ function buildParameter(spec, parameter, operationId) {
107
107
  in: parameter.in,
108
108
  required: !!parameter.required,
109
109
  typeLabel: typeLabel(spec, schema),
110
+ description: parameter.description || schema.description,
110
111
  descriptionHtml: formatDescription(parameter.description || schema.description),
111
112
  usageHtml: formatDescription(schema['x-meta'] && schema['x-meta'].usage),
112
113
  constraints: constraintList(schema),
@@ -156,6 +157,10 @@ function buildParameter(spec, parameter, operationId) {
156
157
  // looser than that sentence would eventually match a group of undocumented strings and
157
158
  // describe it wrongly, having also dropped each member's type, default and anchor. Predicate
158
159
  // and prose have to mean the same thing.
160
+ // A description that says no more than the chip sentence does ("Include the `x` setting in the
161
+ // response"), which the settings flags carry for code generators and readers of the raw document
162
+ const INCLUDE_FLAG_DESCRIPTION = /^Include the .+ in the response$/;
163
+
159
164
  function flagNames(parameters) {
160
165
  if (parameters.length < FLAG_GROUP_MIN) {
161
166
  return null;
@@ -165,7 +170,7 @@ function flagNames(parameters) {
165
170
  parameter =>
166
171
  parameter.typeLabel === 'boolean' &&
167
172
  parameter.defaultValue === 'false' &&
168
- !parameter.descriptionHtml &&
173
+ (!parameter.descriptionHtml || INCLUDE_FLAG_DESCRIPTION.test(parameter.description)) &&
169
174
  !parameter.required &&
170
175
  !parameter.deprecated &&
171
176
  !parameter.enumValues