emailengine-app 2.81.2 → 2.82.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 (204) hide show
  1. package/.ncurc.js +12 -11
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/Dockerfile +2 -0
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/expected-identity.js +1 -1
  13. package/lib/account-assignment.js +138 -1
  14. package/lib/account.js +254 -859
  15. package/lib/api-reference/index.js +2 -3
  16. package/lib/api-reference/schema-tree.js +53 -3
  17. package/lib/api-routes/account-routes.js +18 -29
  18. package/lib/api-routes/blocklist-routes.js +2 -2
  19. package/lib/api-routes/bull-board-routes.js +1 -6
  20. package/lib/api-routes/export-routes.js +2 -22
  21. package/lib/api-routes/gateway-routes.js +5 -14
  22. package/lib/api-routes/index.js +1 -13
  23. package/lib/api-routes/mailbox-routes.js +2 -7
  24. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  25. package/lib/api-routes/mcp-routes.js +7 -7
  26. package/lib/api-routes/message-routes.js +40 -235
  27. package/lib/api-routes/mint-bounds.js +110 -0
  28. package/lib/api-routes/oauth2-app-routes.js +23 -32
  29. package/lib/api-routes/operation-impact.js +1 -1
  30. package/lib/api-routes/outbox-routes.js +2 -2
  31. package/lib/api-routes/permission-map.js +1 -7
  32. package/lib/api-routes/route-helpers.js +11 -5
  33. package/lib/api-routes/settings-routes.js +19 -19
  34. package/lib/api-routes/stats-routes.js +1 -1
  35. package/lib/api-routes/submit-routes.js +17 -18
  36. package/lib/api-routes/template-routes.js +4 -9
  37. package/lib/api-routes/token-routes.js +27 -5
  38. package/lib/api-token-scheme.js +71 -0
  39. package/lib/arf-detect.js +33 -6
  40. package/lib/auth-token.js +44 -24
  41. package/lib/autodetect-imap-settings.js +163 -123
  42. package/lib/bounce-detect.js +25 -16
  43. package/lib/calendar-event.js +78 -0
  44. package/lib/consts.js +42 -5
  45. package/lib/create-imap-client.js +24 -0
  46. package/lib/db.js +76 -11
  47. package/lib/delivery-error.js +2 -1
  48. package/lib/egress-fetch.js +54 -3
  49. package/lib/egress-filter.js +11 -0
  50. package/lib/email-client/api-retry.js +147 -0
  51. package/lib/email-client/base-client.js +377 -523
  52. package/lib/email-client/gmail/gmail-api.js +38 -125
  53. package/lib/email-client/gmail/send-request.js +1 -1
  54. package/lib/email-client/gmail-client.js +76 -50
  55. package/lib/email-client/imap/mailbox.js +158 -324
  56. package/lib/email-client/imap/stale-view.js +109 -0
  57. package/lib/email-client/imap/subconnection.js +46 -9
  58. package/lib/email-client/imap/sync-operations.js +5 -37
  59. package/lib/email-client/imap-client.js +188 -64
  60. package/lib/email-client/message-builder.js +9 -14
  61. package/lib/email-client/notification-handler.js +5 -219
  62. package/lib/email-client/outlook/graph-api.js +147 -126
  63. package/lib/email-client/outlook/send-request.js +10 -4
  64. package/lib/email-client/outlook-client.js +194 -397
  65. package/lib/email-client/smtp-pool-manager.js +3 -2
  66. package/lib/encrypt.js +184 -19
  67. package/lib/enum-descriptions.js +1 -2
  68. package/lib/export.js +133 -39
  69. package/lib/gateway.js +20 -6
  70. package/lib/get-raw-email.js +26 -44
  71. package/lib/handlebars-helpers.js +31 -10
  72. package/lib/imap-proxy-auth.js +13 -29
  73. package/lib/imapproxy/imap-core/README.md +1 -0
  74. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  75. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  76. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  77. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  78. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  79. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  80. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  81. package/lib/imapproxy/imap-server.js +17 -177
  82. package/lib/imapproxy/proxy-handoff.js +235 -0
  83. package/lib/imapproxy/response-error.js +33 -0
  84. package/lib/imapproxy/upstream-client.js +2 -2
  85. package/lib/license-beacon.js +3 -9
  86. package/lib/llm-pre-process.js +182 -43
  87. package/lib/logger.js +1 -1
  88. package/lib/lua/ee-export-queue-add.lua +39 -0
  89. package/lib/lua/ee-get-idempotency.lua +15 -3
  90. package/lib/lua/ee-release-attempts.lua +23 -0
  91. package/lib/lua/ee-reserve-attempts.lua +42 -0
  92. package/lib/lua/h-set-bigger.lua +12 -2
  93. package/lib/lua/s-list-accounts.lua +6 -3
  94. package/lib/mcp/index.js +1 -2
  95. package/lib/mcp/listen.js +221 -18
  96. package/lib/mcp/oauth.js +44 -5
  97. package/lib/mcp/resources.js +8 -2
  98. package/lib/mcp/tools.js +13 -0
  99. package/lib/message-port-stream.js +64 -6
  100. package/lib/oauth/external-account-signer.js +16 -13
  101. package/lib/oauth/gmail.js +22 -20
  102. package/lib/oauth/outlook.js +19 -16
  103. package/lib/oauth/pubsub/google.js +38 -2
  104. package/lib/oauth/scope-checker.js +4 -7
  105. package/lib/oauth/verify-app.js +2 -2
  106. package/lib/oauth2-apps.js +139 -44
  107. package/lib/openapi/build-document.js +1 -1
  108. package/lib/openapi/joi-schema.js +78 -9
  109. package/lib/parse-message.js +21 -0
  110. package/lib/payload-examples-webhooks.json +4 -7
  111. package/lib/pbkdf2-phc.js +101 -0
  112. package/lib/privileged-settings.js +0 -14
  113. package/lib/rate-limit.js +54 -15
  114. package/lib/redis-scan-delete.js +56 -29
  115. package/lib/redis-url.js +3 -1
  116. package/lib/respawn-backoff.js +5 -4
  117. package/lib/response-stream.js +25 -4
  118. package/lib/rewrite-text-nodes.js +27 -40
  119. package/lib/routes-ui.js +0 -5
  120. package/lib/schemas.js +122 -242
  121. package/lib/sentry.js +21 -5
  122. package/lib/settings.js +58 -59
  123. package/lib/smtp-auth.js +6 -2
  124. package/lib/smtp-message-processor.js +28 -7
  125. package/lib/sso.js +7 -3
  126. package/lib/stream-encrypt.js +14 -13
  127. package/lib/swagger-options.js +3 -1
  128. package/lib/tls/provision.js +69 -3
  129. package/lib/tls/store.js +14 -1
  130. package/lib/tools.js +113 -52
  131. package/lib/totp.js +16 -1
  132. package/lib/ui-routes/account-routes.js +27 -63
  133. package/lib/ui-routes/admin-config-routes.js +111 -134
  134. package/lib/ui-routes/admin-entities-routes.js +101 -191
  135. package/lib/ui-routes/ai-options.js +104 -0
  136. package/lib/ui-routes/auth-routes.js +98 -18
  137. package/lib/ui-routes/export-routes.js +3 -23
  138. package/lib/ui-routes/internals-routes.js +12 -9
  139. package/lib/ui-routes/network-config-routes.js +8 -18
  140. package/lib/ui-routes/oauth-config-routes.js +80 -214
  141. package/lib/ui-routes/route-helpers.js +40 -44
  142. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  143. package/lib/utils/decode-headers.js +32 -5
  144. package/lib/utils/header-map.js +62 -1
  145. package/lib/utils/network.js +2 -0
  146. package/lib/web-safe-html.js +77 -4
  147. package/lib/webhook-request.js +9 -1
  148. package/lib/webhook-routing.js +27 -1
  149. package/lib/webhooks.js +120 -43
  150. package/lib/worker-rpc-error.js +43 -2
  151. package/list-generate.js +13 -2
  152. package/package.json +33 -41
  153. package/sbom.json +1 -1
  154. package/scripts/refresh-test-tokens.js +42 -14
  155. package/server.js +317 -289
  156. package/static/css/flyonui.css +1 -1
  157. package/static/css/src/app.tailwind.css +7 -8
  158. package/static/js/ee-client.js +145 -70
  159. package/static/js/ui.js +350 -154
  160. package/static/licenses.html +434 -1835
  161. package/translations/messages.pot +97 -97
  162. package/views/accounts/browse.hbs +10 -4
  163. package/views/config/ai.hbs +49 -41
  164. package/views/config/oauth/app.hbs +2 -1
  165. package/views/dashboard.hbs +18 -16
  166. package/views/layout/app.hbs +0 -22
  167. package/views/layout/login.hbs +2 -1
  168. package/views/partials/filter_editor_js.hbs +4 -3
  169. package/views/partials/side_menu.hbs +0 -4
  170. package/views/partials/ui/account-picker.hbs +6 -32
  171. package/views/partials/ui/model-picker.hbs +31 -0
  172. package/views/partials/ui/pagination.hbs +6 -1
  173. package/views/partials/ui/picker.hbs +47 -0
  174. package/views/unsubscribe.hbs +1 -1
  175. package/workers/api.js +20 -20
  176. package/workers/export.js +55 -60
  177. package/workers/imap.js +126 -46
  178. package/workers/submit.js +3 -1
  179. package/workers/webhooks.js +46 -27
  180. package/.githooks/pre-commit +0 -80
  181. package/.github/CODE_OF_CONDUCT.md +0 -76
  182. package/.github/contributing.md +0 -17
  183. package/.github/dependabot.yml +0 -22
  184. package/.github/docker-smoke-test.sh +0 -61
  185. package/.github/workflows/deploy.yml +0 -215
  186. package/.github/workflows/e2e.yml +0 -55
  187. package/.github/workflows/release.yaml +0 -217
  188. package/.github/workflows/test.yml +0 -307
  189. package/lib/api-routes/chat-routes.js +0 -535
  190. package/lib/document-store.js +0 -75
  191. package/lib/es.js +0 -757
  192. package/lib/generate-text-preview.js +0 -61
  193. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  194. package/lib/pre-process.js +0 -196
  195. package/lib/threads.js +0 -155
  196. package/lib/ui-routes/document-store-routes.js +0 -806
  197. package/playwright.config.js +0 -47
  198. package/views/config/document-store/chat.hbs +0 -286
  199. package/views/config/document-store/index.hbs +0 -146
  200. package/views/config/document-store/mappings/index.hbs +0 -108
  201. package/views/config/document-store/mappings/new.hbs +0 -68
  202. package/views/config/document-store/pre-processing/index.hbs +0 -103
  203. package/views/partials/document_store_header.hbs +0 -30
  204. package/workers/documents.js +0 -1128
package/lib/account.js CHANGED
@@ -6,25 +6,20 @@ const msgpack = require('./msgpack');
6
6
  const {
7
7
  normalizePath,
8
8
  formatAccountListingResponse,
9
- unpackUIDRangeForSearch,
10
9
  mergeObjects,
11
- download,
12
10
  resolveCredentials,
13
11
  useAuthServerForOAuth2,
14
12
  isEmail,
15
13
  resolveDelegatedAccount,
16
14
  escapeRedisGlob,
17
- getMailboxStatusKey,
18
- cidReferenceRegex
15
+ getMailboxStatusKey
19
16
  } = require('./tools');
20
17
  const { MessageChannel } = require('worker_threads');
21
18
  const { MessagePortReadable } = require('./message-port-stream');
22
19
  const { isDeepStrictEqual } = require('util');
23
- const { encrypt, decrypt } = require('./encrypt');
20
+ const { encrypt, decrypt, decryptField, parseEncryptedData } = require('./encrypt');
24
21
  const { oauth2Apps, isApiBasedApp } = require('./oauth2-apps');
25
22
  const settings = require('./settings');
26
- const { buildRetentionPolicy } = require('./queue-retention');
27
- const { isDocumentStoreEnabled, documentStoreFeatureEnabled } = require('./document-store');
28
23
  const redisScanDelete = require('./redis-scan-delete');
29
24
  const { extractMultiValues, createTransaction } = require('./redis-operations');
30
25
  const outbox = require('./outbox');
@@ -33,8 +28,8 @@ const { customAlphabet } = require('nanoid');
33
28
  const Lock = require('ioredfour');
34
29
  const { redis } = require('./db');
35
30
  const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
36
- const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, AUTH_FAILURE_DISABLED_FIELD, AUTH_FAILURE_DISABLED_LEGACY_DESCRIPTION } = require('./consts');
37
- const { messageWebSafeHtml, webSafeTextResponse, applyWebSafeHtmlOptions } = require('./web-safe-html');
31
+ const { REDIS_PREFIX, AUTH_FAILURE_DISABLED_FIELD, AUTH_FAILURE_DISABLED_LEGACY_DESCRIPTION } = require('./consts');
32
+ const { webSafeTextResponse, applyWebSafeHtmlOptions } = require('./web-safe-html');
38
33
  const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
39
34
  const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
40
35
  const { decodeStoredMailboxEntry } = require('./email-client/imap/listing-diff');
@@ -53,6 +48,14 @@ const defaultLock = new Lock({
53
48
  const ACCOUNT_UPDATE_LOCK_TTL = 10 * 1000;
54
49
  const ACCOUNT_UPDATE_LOCK_WAIT = 5 * 1000;
55
50
 
51
+ // Account fields that carry a credential without being one: the webhook URL and the proxy URL may
52
+ // embed `user:pass@`, and the custom webhook headers typically hold an Authorization value. The
53
+ // global settings of the same name are encrypted at rest (settings.js CREDENTIAL_BEARING_KEYS), so
54
+ // these are too. A value written before that is cleartext, which decrypt() passes through, so old
55
+ // records keep reading until their next save or `emailengine encrypt` run. `emailengine encrypt`
56
+ // re-encrypts exactly this list.
57
+ const ENCRYPTED_ACCOUNT_FIELDS = ['webhooks', 'webhooksCustomHeaders', 'proxy'];
58
+
56
59
  /**
57
60
  * What an incoming account payload asks of `imap.disabled`.
58
61
  *
@@ -135,14 +138,10 @@ class Account {
135
138
  this.redis = options.redis;
136
139
  this.account = options.account || false;
137
140
 
138
- this.documentsQueue = options.documentsQueue || false;
139
-
140
141
  this.secret = options.secret;
141
142
 
142
143
  this.timeout = options.timeout ? Number(options.timeout) : 0;
143
144
 
144
- this.esClient = options.esClient;
145
-
146
145
  this.call = options.call; // async method to request data from parent
147
146
 
148
147
  this.logger = options.logger || logger;
@@ -291,7 +290,9 @@ class Account {
291
290
 
292
291
  let result = await this.redis.sListAccounts(`${REDIS_PREFIX}ia:accounts`, filterState, skip, limit, `${REDIS_PREFIX}`, search);
293
292
 
294
- let accounts = result[2].map(formatAccountListingResponse).map(this.unserializeAccountData.bind(this));
293
+ // No decryption here: the listing outputs none of the credentials, and the two
294
+ // credential-bearing URLs it does output are decrypted below, only for rows that set them
295
+ let accounts = result[2].map(formatAccountListingResponse).map(row => this.unserializeAccountData(row, { skipDecrypt: true }));
295
296
  let oauthApps = new Map();
296
297
 
297
298
  for (let accountData of accounts) {
@@ -324,7 +325,7 @@ class Account {
324
325
  if (delegatedAccount) {
325
326
  accountData.delegatedAccount = delegatedAccount;
326
327
  let delegatedAccountRow = await this.redis.hgetall(`${REDIS_PREFIX}iad:${delegatedAccount}`);
327
- let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow);
328
+ let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow, { skipDecrypt: true });
328
329
  if (delegatedAccountData.oauth2 && delegatedAccountData.oauth2.provider) {
329
330
  let app;
330
331
  if (oauthApps.has(delegatedAccountData.oauth2.provider)) {
@@ -376,8 +377,8 @@ class Account {
376
377
  : undefined,
377
378
  state: getDisplayState(accountData, runIndex),
378
379
 
379
- webhooks: accountData.webhooks || undefined,
380
- proxy: accountData.proxy || undefined,
380
+ webhooks: this.decryptAccountField('webhooks', accountData.webhooks, accountData.account) || undefined,
381
+ proxy: this.decryptAccountField('proxy', accountData.proxy, accountData.account) || undefined,
381
382
  smtpEhloName: accountData.smtpEhloName || undefined,
382
383
 
383
384
  counters: accountData.counters,
@@ -437,7 +438,22 @@ class Account {
437
438
  });
438
439
  }
439
440
 
440
- unserializeAccountData(accountData) {
441
+ /**
442
+ * Turns a stored account hash into the account object.
443
+ *
444
+ * @param {Object} accountData - The hash as read from Redis
445
+ * @param {Object} [opts]
446
+ * @param {boolean} [opts.skipDecrypt] - Leave every encrypted value as stored. Each stored value
447
+ * has its own salt, so a cold decrypt is a synchronous key derivation; a listing that decrypted the
448
+ * IMAP/SMTP passwords and OAuth2 tokens of every row blocked the API worker for tens of
449
+ * seconds on a 1000-account page, for fields it never outputs. For callers that read only
450
+ * the non-secret structure (listings, delegated-row lookups): the credentials and the
451
+ * ENCRYPTED_ACCOUNT_FIELDS stay ciphertext, and an encrypted custom header list is left out
452
+ * rather than failing to parse. decryptAccountField() opens the few such values a caller needs.
453
+ * @returns {Object} The unserialized account
454
+ */
455
+ unserializeAccountData(accountData, opts) {
456
+ const skipDecrypt = !!(opts && opts.skipDecrypt);
441
457
  const result = {};
442
458
 
443
459
  // The loop below drops every `_`-prefixed field, which is what keeps the auth-failure marker
@@ -473,7 +489,6 @@ class Account {
473
489
 
474
490
  switch (key) {
475
491
  case 'notifyFrom':
476
- case 'syncFrom':
477
492
  case 'lastWatch':
478
493
  // Date object
479
494
  if (accountData[key]) {
@@ -524,8 +539,41 @@ class Account {
524
539
  }
525
540
  break;
526
541
 
542
+ case 'webhooks':
543
+ case 'proxy': {
544
+ let value = skipDecrypt ? accountData[key] : this.decryptAccountField(key, accountData[key], accountData.account);
545
+ if (typeof value !== 'undefined') {
546
+ result[key] = value;
547
+ }
548
+ break;
549
+ }
550
+
551
+ case 'webhooksCustomHeaders': {
552
+ let stored = accountData[key];
553
+ if (skipDecrypt) {
554
+ if (this.secret && parseEncryptedData(stored).format !== 'cleartext') {
555
+ // not read by any caller that skips decryption
556
+ break;
557
+ }
558
+ } else {
559
+ stored = this.decryptAccountField(key, stored, accountData.account);
560
+ if (typeof stored === 'undefined') {
561
+ break;
562
+ }
563
+ }
564
+ try {
565
+ let value = JSON.parse(stored);
566
+ if (value === null) {
567
+ break;
568
+ }
569
+ result[key] = value;
570
+ } catch (err) {
571
+ this.logUnserializeFailure('Failed to parse input from Redis', key, stored, accountData.account, err);
572
+ }
573
+ break;
574
+ }
575
+
527
576
  // generic JSON values
528
- case 'webhooksCustomHeaders':
529
577
  case 'subconnections':
530
578
  case 'watchResponse':
531
579
  case 'watchFailure':
@@ -609,7 +657,7 @@ class Account {
609
657
  });
610
658
 
611
659
  // decrypt secrets
612
- if (this.secret) {
660
+ if (this.secret && !skipDecrypt) {
613
661
  for (let type of ['imap', 'smtp', 'oauth2']) {
614
662
  if (result[type] && result[type].auth) {
615
663
  for (let key of ['pass', 'accessToken', 'refreshToken']) {
@@ -652,6 +700,31 @@ class Account {
652
700
  return result;
653
701
  }
654
702
 
703
+ /**
704
+ * Decrypts one of ENCRYPTED_ACCOUNT_FIELDS. Cleartext (a value stored before the field was
705
+ * encrypted, or written without a secret) passes through unchanged.
706
+ *
707
+ * @returns {String|undefined} The cleartext, or undefined when the value does not decrypt with
708
+ * the current secret; the field then reads as unset rather than failing the whole account
709
+ */
710
+ decryptAccountField(key, value, ownerAccount) {
711
+ return decryptField(value, this.secret, err => this.logUnserializeFailure('Failed to decrypt value', key, value, ownerAccount, err));
712
+ }
713
+
714
+ // Encrypts one of ENCRYPTED_ACCOUNT_FIELDS for storage. The empty string is a marker (a cleared
715
+ // value) and is stored as is.
716
+ encryptAccountField(key, value) {
717
+ if (!this.secret || !value) {
718
+ return value;
719
+ }
720
+ try {
721
+ return encrypt(value, this.secret);
722
+ } catch (err) {
723
+ this.logger.error({ msg: 'Failed to encrypt value', key, account: this.account, err });
724
+ return value;
725
+ }
726
+ }
727
+
655
728
  serializeAccountData(accountData) {
656
729
  let result = {};
657
730
 
@@ -662,7 +735,6 @@ class Account {
662
735
  }
663
736
  switch (key) {
664
737
  case 'notifyFrom':
665
- case 'syncFrom':
666
738
  case 'lastWatch':
667
739
  // Date object
668
740
  if (accountData[key] === 'now') {
@@ -700,9 +772,22 @@ class Account {
700
772
  }
701
773
  break;
702
774
 
775
+ case 'webhooksCustomHeaders':
776
+ try {
777
+ result[key] = this.encryptAccountField(key, JSON.stringify(accountData[key]));
778
+ } catch (err) {
779
+ this.logger.error({ msg: 'Failed to stringify input for Redis', key, account: this.account, err });
780
+ }
781
+ break;
782
+
783
+ case 'proxy':
784
+ if (typeof accountData[key] !== 'undefined' && accountData[key] !== null && typeof accountData[key].toString === 'function') {
785
+ result[key] = this.encryptAccountField(key, accountData[key].toString());
786
+ }
787
+ break;
788
+
703
789
  // generic JSON values
704
790
  case 'subconnections':
705
- case 'webhooksCustomHeaders':
706
791
  case 'watchResponse':
707
792
  case 'watchFailure':
708
793
  try {
@@ -787,11 +872,12 @@ class Account {
787
872
 
788
873
  case 'webhooks':
789
874
  if (typeof accountData[key] !== 'undefined' && accountData[key] !== null && typeof accountData[key].toString === 'function') {
790
- result[key] = accountData[key].toString();
791
- if (!result[key]) {
875
+ let value = accountData[key].toString();
876
+ if (!value) {
792
877
  // clear potential error flag
793
878
  result.webhookErrorFlag = '{}';
794
879
  }
880
+ result[key] = this.encryptAccountField(key, value);
795
881
  }
796
882
  break;
797
883
 
@@ -865,7 +951,7 @@ class Account {
865
951
  if (delegatedAccount) {
866
952
  accountData.delegatedAccount = delegatedAccount;
867
953
  let delegatedAccountRow = await this.redis.hgetall(`${REDIS_PREFIX}iad:${delegatedAccount}`);
868
- let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow);
954
+ let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow, { skipDecrypt: true });
869
955
  if (delegatedAccountData.oauth2 && delegatedAccountData.oauth2.provider) {
870
956
  let app = await oauth2Apps.get(delegatedAccountData.oauth2.provider);
871
957
  if (app) {
@@ -917,14 +1003,61 @@ class Account {
917
1003
  * external caller, i.e. possible operator re-authorization. Only the public account-update
918
1004
  * API route sets it; every unattended writer (token renewal, client initialize(),
919
1005
  * invalidateAccessToken) leaves it false and can therefore never trigger the reconnect gate.
920
- * @returns {Promise<Object>} `{ account }`
1006
+ * @param {String} [opts.expectedRefreshToken] - Write only while the stored OAuth2 refresh token
1007
+ * is still this one. Token renewal reads the account, then waits on the provider without the
1008
+ * update lock; a re-authorization landing in that window must not be overwritten with the
1009
+ * renewal's older grant. Checked under the lock, against the stored value.
1010
+ * @returns {Promise<Object>} `{ account }`, plus `skipped: true` when expectedRefreshToken no
1011
+ * longer matched and nothing was written
921
1012
  */
922
- async update(accountData, { reauthorized = false } = {}) {
1013
+ async update(accountData, { reauthorized = false, expectedRefreshToken } = {}) {
923
1014
  // Captured before persistUpdate() merges a `partial` payload into the stored object
924
1015
  const disabledIntent = imapDisabledIntent(accountData);
925
1016
 
1017
+ let current = null;
1018
+ let oldAccountData = await this.withUpdateLock(accountData.account, async () => {
1019
+ let stored;
1020
+ if (typeof expectedRefreshToken === 'string') {
1021
+ stored = await this.loadAccountData(accountData.account);
1022
+ // A grant without a refresh token (a service account) is spelled ''
1023
+ if (((stored.oauth2 && stored.oauth2.refreshToken) || '') !== expectedRefreshToken) {
1024
+ current = stored;
1025
+ return null;
1026
+ }
1027
+ }
1028
+ // The record just read is handed on, so the write does not load and decrypt it again
1029
+ return await this.persistUpdate(accountData, stored);
1030
+ });
1031
+
1032
+ if (!oldAccountData) {
1033
+ this.logger.info({ msg: 'Skipped a token write, the stored OAuth2 grant changed meanwhile', account: this.account });
1034
+ // `current` is the account as stored now, so the caller need not read it a third time
1035
+ return {
1036
+ account: this.account,
1037
+ skipped: true,
1038
+ current
1039
+ };
1040
+ }
1041
+
1042
+ await this.dispatchPostUpdateCommands(accountData, oldAccountData, reauthorized, disabledIntent);
1043
+
1044
+ return {
1045
+ account: this.account
1046
+ };
1047
+ }
1048
+
1049
+ /**
1050
+ * Runs `fn` holding the per-account update lock that serializes account writes.
1051
+ *
1052
+ * Lock acquisition failing is not treated as an error, see update() for why.
1053
+ *
1054
+ * @param {String} account - Account ID
1055
+ * @param {Function} fn - Async critical section
1056
+ * @returns {Promise<*>} Whatever `fn` resolves to
1057
+ */
1058
+ async withUpdateLock(account, fn) {
926
1059
  const lock = this.getLock();
927
- const lockKey = `account:update:${accountData.account}`;
1060
+ const lockKey = `account:update:${account}`;
928
1061
  let updateLock;
929
1062
 
930
1063
  let lockErr;
@@ -935,28 +1068,49 @@ class Account {
935
1068
  }
936
1069
 
937
1070
  if (!updateLock?.success) {
938
- this.logger.warn({ msg: 'Failed to get account update lock, proceeding unserialized', account: accountData.account, lockKey, err: lockErr });
1071
+ this.logger.warn({ msg: 'Failed to get account update lock, proceeding unserialized', account, lockKey, err: lockErr });
939
1072
  }
940
1073
 
941
- let oldAccountData;
942
1074
  try {
943
- oldAccountData = await this.persistUpdate(accountData);
1075
+ return await fn();
944
1076
  } finally {
945
1077
  if (updateLock?.success) {
946
1078
  try {
947
1079
  await lock.releaseLock(updateLock);
948
1080
  } catch (err) {
949
1081
  // The lock expires on its own, so a failed release must not mask the result
950
- this.logger.warn({ msg: 'Failed to release account update lock', account: accountData.account, lockKey, err });
1082
+ this.logger.warn({ msg: 'Failed to release account update lock', account, lockKey, err });
951
1083
  }
952
1084
  }
953
1085
  }
1086
+ }
954
1087
 
955
- await this.dispatchPostUpdateCommands(accountData, oldAccountData, reauthorized, disabledIntent);
956
-
957
- return {
958
- account: this.account
959
- };
1088
+ /**
1089
+ * Sends a command to the worker that owns the account after a change was already written.
1090
+ * The write stands either way, so a dispatch that fails (an RPC timeout, no worker yet) is
1091
+ * logged rather than thrown: an error response for a saved change made a retried create report
1092
+ * the account as existing and a retried delete answer 404. The worker catches up on its next
1093
+ * reconnect or assignment pass.
1094
+ *
1095
+ * @returns {Promise<Boolean>} Whether the worker acknowledged the command
1096
+ */
1097
+ async notifyWorker(cmd) {
1098
+ if (typeof this.call !== 'function') {
1099
+ // This Account instance has no parent RPC channel (constructed without `call`)
1100
+ this.logger.warn({ msg: 'Skipping worker command dispatch, no parent RPC channel', account: this.account, cmd });
1101
+ return false;
1102
+ }
1103
+ try {
1104
+ await this.call({
1105
+ cmd,
1106
+ account: this.account,
1107
+ timeout: this.timeout
1108
+ });
1109
+ return true;
1110
+ } catch (err) {
1111
+ this.logger.error({ msg: 'Failed to notify the worker after a saved account change', account: this.account, cmd, err });
1112
+ return false;
1113
+ }
960
1114
  }
961
1115
 
962
1116
  /**
@@ -966,8 +1120,9 @@ class Account {
966
1120
  * @param {Object} accountData - Account fields to write
967
1121
  * @returns {Promise<Object>} The account as it was before the write
968
1122
  */
969
- async persistUpdate(accountData) {
970
- let oldAccountData = await this.loadAccountData(accountData.account);
1123
+ async persistUpdate(accountData, oldAccountData) {
1124
+ // update() hands over the record it already loaded under the lock, when it loaded one
1125
+ oldAccountData = oldAccountData || (await this.loadAccountData(accountData.account));
971
1126
 
972
1127
  if (accountData.oauth2?.provider) {
973
1128
  // check if this OAuth2 provider exists
@@ -1163,17 +1318,7 @@ class Account {
1163
1318
  // Changes detected. The full reconnect above supersedes this: it assigns a fresh
1164
1319
  // client, which reads the changed settings on its way in.
1165
1320
  this.logger.info({ msg: 'IMAP configuration changed for account', account: this.account });
1166
- if (typeof this.call === 'function') {
1167
- await this.call({
1168
- cmd: 'update',
1169
- account: this.account,
1170
- timeout: this.timeout
1171
- });
1172
- } else {
1173
- // This Account instance has no parent RPC channel (constructed without `call`).
1174
- // Skip the dispatch instead of throwing - the persisted change stands.
1175
- this.logger.warn({ msg: 'Skipping update command dispatch, no parent RPC channel', account: this.account });
1176
- }
1321
+ await this.notifyWorker('update');
1177
1322
  }
1178
1323
  }
1179
1324
 
@@ -1316,6 +1461,22 @@ class Account {
1316
1461
  cmd: 'runIndex'
1317
1462
  });
1318
1463
 
1464
+ // Under the same lock as update(): the OAuth2 user uniqueness check below is a
1465
+ // check-then-set, and a re-registration racing an update or a token renewal of the same
1466
+ // account would otherwise interleave its write with theirs
1467
+ let result = await this.withUpdateLock(this.account, async () => await this.writeCreatedAccount(accountData, runIndex));
1468
+
1469
+ if (!result || !result[1] || result[1][0] || result[1][1] !== 'OK') {
1470
+ let message = 'Something went wrong';
1471
+ let error = Boom.boomify(new Error(message), { statusCode: 500 });
1472
+ throw error;
1473
+ }
1474
+
1475
+ return await this.finishCreate(accountData, result);
1476
+ }
1477
+
1478
+ // The write half of create(), run under the account update lock
1479
+ async writeCreatedAccount(accountData, runIndex) {
1319
1480
  let pipeline = this.redis
1320
1481
  .multi()
1321
1482
  .hgetall(this.getAccountKey())
@@ -1354,14 +1515,11 @@ class Account {
1354
1515
  }
1355
1516
  }
1356
1517
 
1357
- let result = await pipeline.exec();
1358
-
1359
- if (!result || !result[1] || result[1][0] || result[1][1] !== 'OK') {
1360
- let message = 'Something went wrong';
1361
- let error = Boom.boomify(new Error(message), { statusCode: 500 });
1362
- throw error;
1363
- }
1518
+ return await pipeline.exec();
1519
+ }
1364
1520
 
1521
+ // The post-write half of create(): provider rebinding, auth-failure recovery and the worker dispatch
1522
+ async finishCreate(accountData, result) {
1365
1523
  let state;
1366
1524
  if (result[0][1] && result[0][1].account) {
1367
1525
  // existing user
@@ -1448,19 +1606,11 @@ class Account {
1448
1606
  this.logger.error({ msg: 'Failed to request reconnect after re-auth', account: this.account, state: oldState, err });
1449
1607
  }
1450
1608
  } else {
1451
- await this.call({
1452
- cmd: 'update',
1453
- account: this.account,
1454
- timeout: this.timeout
1455
- });
1609
+ await this.notifyWorker('update');
1456
1610
  }
1457
1611
  } else {
1458
1612
  state = 'new';
1459
- await this.call({
1460
- cmd: 'new',
1461
- account: this.account,
1462
- timeout: this.timeout
1463
- });
1613
+ await this.notifyWorker('new');
1464
1614
  }
1465
1615
 
1466
1616
  return { account: this.account, state };
@@ -1563,7 +1713,12 @@ class Account {
1563
1713
 
1564
1714
  // scan and delete keys
1565
1715
  // should we wait though? might take a lot of time
1566
- await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${escapeRedisGlob(this.account)}:*`);
1716
+ // Best effort like the cleanups above: the account record is already gone
1717
+ try {
1718
+ await redisScanDelete(this.redis, this.logger, `${escapeRedisGlob(REDIS_PREFIX)}iam:${escapeRedisGlob(this.account)}:*`);
1719
+ } catch (err) {
1720
+ this.logger.error({ msg: 'Failed to delete the log keys of a deleted account', account: this.account, err });
1721
+ }
1567
1722
 
1568
1723
  if (!result || !result[1] || !result[1][1]) {
1569
1724
  return {
@@ -1572,39 +1727,7 @@ class Account {
1572
1727
  };
1573
1728
  }
1574
1729
 
1575
- // Only notify the documents queue when the deprecated Document Store feature is enabled.
1576
- // When it is off the documents worker is not running, so an enqueued job would never be
1577
- // consumed and would pile up in Redis.
1578
- if (documentStoreFeatureEnabled) {
1579
- try {
1580
- let queueKeep = (await settings.get('queueKeep')) ?? true;
1581
- let serviceUrl = (await settings.get('serviceUrl')) || null;
1582
-
1583
- let payload = {
1584
- serviceUrl,
1585
- account: this.account,
1586
- date: new Date().toISOString(),
1587
- event: ACCOUNT_DELETED_NOTIFY
1588
- };
1589
-
1590
- await this.documentsQueue.add(ACCOUNT_DELETED_NOTIFY, payload, {
1591
- ...buildRetentionPolicy(queueKeep),
1592
- attempts: 10,
1593
- backoff: {
1594
- type: 'exponential',
1595
- delay: 5000
1596
- }
1597
- });
1598
- } catch (err) {
1599
- this.logger.error({ msg: 'Failed to add entry to documents queue', account: this.account, err });
1600
- }
1601
- }
1602
-
1603
- await this.call({
1604
- cmd: 'delete',
1605
- account: this.account,
1606
- timeout: this.timeout
1607
- });
1730
+ await this.notifyWorker('delete');
1608
1731
 
1609
1732
  return {
1610
1733
  account: this.account,
@@ -2008,43 +2131,6 @@ class Account {
2008
2131
  options = Object.assign({}, options, { textType: '*' });
2009
2132
  }
2010
2133
 
2011
- if (options.documentStore && (await isDocumentStoreEnabled())) {
2012
- await this.loadAccountData(this.account, false);
2013
-
2014
- const { index, client } = this.esClient;
2015
-
2016
- let buf = Buffer.from(text, 'base64url');
2017
- let message = buf.subarray(0, 8).toString('base64url');
2018
-
2019
- let getResult = await client.get({
2020
- index,
2021
- id: `${this.account}:${message}`
2022
- });
2023
-
2024
- this.logger.trace({
2025
- msg: 'Executed ES query',
2026
- query: { type: 'get', index, id: `${this.account}:${message}` },
2027
- results: getResult && getResult._source ? 1 : 0
2028
- });
2029
-
2030
- let messageData = this.assertMessageFound(getResult && getResult._source);
2031
- let response = {};
2032
-
2033
- response.hasMore = false;
2034
- for (let textType of Object.keys(messageData.text || {})) {
2035
- if (['plain', 'html'].includes(textType) && (options.textType === '*' || options.textType === textType)) {
2036
- if (options.maxBytes && messageData.text[textType].length > options.maxBytes) {
2037
- response[textType] = messageData.text[textType].substring(0, options.maxBytes);
2038
- response.hasMore = true;
2039
- } else {
2040
- response[textType] = messageData.text[textType];
2041
- }
2042
- }
2043
- }
2044
-
2045
- return this.textResponse(response, options);
2046
- }
2047
-
2048
2134
  await this.loadAccountData(this.account, true);
2049
2135
 
2050
2136
  let textData = await this.call({
@@ -2056,185 +2142,13 @@ class Account {
2056
2142
  });
2057
2143
 
2058
2144
  // IMAP backend returns false for unknown messages and folders
2059
- return this.textResponse(this.assertMessageFound(textData), options);
2060
- }
2061
-
2062
- // The one exit of getText(), so the document-store branch and the live one cannot answer a
2063
- // webSafeHtml request differently
2064
- async textResponse(textData, options) {
2145
+ textData = this.assertMessageFound(textData);
2065
2146
  return options.webSafeHtml ? webSafeTextResponse(textData) : textData;
2066
2147
  }
2067
2148
 
2068
2149
  async getMessage(message, options) {
2069
2150
  applyWebSafeHtmlOptions(options);
2070
2151
 
2071
- if (options.documentStore && (await isDocumentStoreEnabled())) {
2072
- await this.loadAccountData(this.account, false);
2073
-
2074
- const { index, client } = this.esClient;
2075
-
2076
- const reqOpts = {
2077
- index,
2078
- id: `${this.account}:${message}`,
2079
- _source_excludes: 'preview,seemsLikeNew,account,created,updateTime,bounces'
2080
- };
2081
-
2082
- switch (options.textType) {
2083
- case '*':
2084
- break;
2085
- case 'html':
2086
- reqOpts._source_excludes += ',text.plain';
2087
- break;
2088
- case 'plain':
2089
- reqOpts._source_excludes += ',text.html,text._generatedHtml';
2090
- break;
2091
- default:
2092
- reqOpts._source_excludes += ',text.plain,text.html,text._generatedHtml';
2093
- }
2094
-
2095
- let getResult = await client.get(reqOpts);
2096
-
2097
- this.logger.trace({
2098
- msg: 'Executed ES query',
2099
- query: { type: 'get', index, id: `${this.account}:${message}` },
2100
- results: getResult && getResult._source ? 1 : 0
2101
- });
2102
-
2103
- let messageData = this.assertMessageFound(getResult && getResult._source);
2104
-
2105
- // restore headers and text object as per the API response
2106
- let headersObj = {};
2107
- for (let { key, value } of messageData.headers) {
2108
- headersObj[key] = value;
2109
- }
2110
- messageData.headers = headersObj;
2111
-
2112
- if (messageData.text && (messageData.text.html || messageData.text.plain)) {
2113
- messageData.text.hasMore = false;
2114
-
2115
- for (let textType of Object.keys(messageData.text || {})) {
2116
- if (['plain', 'html'].includes(textType) && options.maxBytes && messageData.text[textType].length > options.maxBytes) {
2117
- messageData.text[textType] = messageData.text[textType].substring(0, options.maxBytes);
2118
- messageData.text.hasMore = true;
2119
- }
2120
- }
2121
- }
2122
-
2123
- for (let key of ['unseen', 'flagged', 'answered', 'draft']) {
2124
- if (messageData[key] === false) {
2125
- delete messageData[key];
2126
- }
2127
- }
2128
-
2129
- if (options.preProcessHtml && messageData.text && (messageData.text.html || messageData.text.plain)) {
2130
- // If available, use the cached version
2131
- messageData.text.html = messageData.text._generatedHtml || (await messageWebSafeHtml(messageData));
2132
- messageData.text.webSafe = true;
2133
- messageData.text._cachedWebSafe = !!messageData.text._generatedHtml;
2134
- }
2135
-
2136
- if (options.embedAttachedImages && messageData.text && messageData.text.html && messageData.attachments && messageData.attachments.length) {
2137
- // map both content id forms (bare and <bracketed>) to the first attachment carrying them,
2138
- // so the passes below cost one lookup per reference instead of a scan of all attachments
2139
- let attachmentsByContentId = new Map();
2140
- for (let attachment of messageData.attachments) {
2141
- if (!attachment.contentId) {
2142
- continue;
2143
- }
2144
- for (let key of [attachment.contentId, attachment.contentId.replace(/^<(.*)>$/, '$1')]) {
2145
- if (!attachmentsByContentId.has(key)) {
2146
- attachmentsByContentId.set(key, attachment);
2147
- }
2148
- }
2149
- }
2150
-
2151
- // first pass, find attachments to inline
2152
- let attachmentsToDownload = new Set();
2153
- for (let match of messageData.text.html.matchAll(cidReferenceRegex())) {
2154
- let attachment = attachmentsByContentId.get(match[1]);
2155
- if (attachment && !attachment.content) {
2156
- attachmentsToDownload.add(attachment);
2157
- }
2158
- }
2159
-
2160
- // download large inline attachments not stored in ES
2161
- for (let attachment of attachmentsToDownload) {
2162
- let downloadStream;
2163
- try {
2164
- downloadStream = await this.getAttachment(attachment.id);
2165
- if (downloadStream) {
2166
- let content = await download(downloadStream);
2167
- this.logger.trace({ msg: 'Fetched attachment content', account: this.account, attachment, size: content.length });
2168
- attachment.content = content.toString('base64');
2169
- }
2170
- } catch (err) {
2171
- // Release the reader if download() failed mid-stream so its
2172
- // MessagePort is not left open (destroy() is idempotent).
2173
- if (downloadStream) {
2174
- downloadStream.destroy();
2175
- }
2176
- this.logger.error({ msg: 'Failed to fetch attachment content', account: this.account, attachment, err });
2177
- }
2178
- }
2179
-
2180
- // second pass, replace placeholders with inline attachments
2181
- messageData.text.html = messageData.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
2182
- let attachment = attachmentsByContentId.get(cidMatch);
2183
- if (attachment && attachment.content) {
2184
- return `data:${attachment.contentType || 'application/octet-stream'};base64,${attachment.content}`;
2185
- }
2186
- return fullMatch;
2187
- });
2188
- }
2189
-
2190
- if (messageData.text && messageData.text._generatedHtml) {
2191
- // remove cached pre-processed HTML from output
2192
- delete messageData.text._generatedHtml;
2193
- }
2194
-
2195
- // Add event file content if the attachment exists
2196
- if (messageData.calendarEvents) {
2197
- for (let calendarEvent of messageData.calendarEvents) {
2198
- if (!calendarEvent.content && calendarEvent.attachment) {
2199
- let attachment = messageData.attachments && messageData.attachments.find(attachment => attachment.id === calendarEvent.attachment);
2200
- if (attachment && attachment.content) {
2201
- calendarEvent.encoding = 'base64';
2202
- calendarEvent.content = attachment.content;
2203
- }
2204
- }
2205
- }
2206
- }
2207
-
2208
- if (messageData.attachments) {
2209
- for (let attachment of messageData.attachments) {
2210
- delete attachment.content;
2211
- }
2212
- }
2213
-
2214
- if (options.markAsSeen && (!messageData.flags || !messageData.flags.includes('\\Seen'))) {
2215
- // mark message as seen
2216
- if (!messageData.flags) {
2217
- messageData.flags = [];
2218
- }
2219
- messageData.flags.push('\\Seen');
2220
- // do not wait until the update is completed, return immediately
2221
- this.updateMessage(message, { flags: { add: ['\\Seen'] } }).catch(err => {
2222
- this.logger.error({ msg: 'Failed to mark message as Seen', account: this.account, message, err });
2223
- });
2224
- }
2225
-
2226
- if (messageData.specialUse && !messageData.messageSpecialUse) {
2227
- for (let specialUseTag of ['\\Junk', '\\Sent', '\\Trash', '\\Inbox', '\\Drafts']) {
2228
- if (messageData.specialUse === specialUseTag || (messageData.labels && messageData.labels.includes(specialUseTag))) {
2229
- messageData.messageSpecialUse = specialUseTag;
2230
- break;
2231
- }
2232
- }
2233
- }
2234
-
2235
- return messageData;
2236
- }
2237
-
2238
2152
  await this.loadAccountData(this.account, true);
2239
2153
 
2240
2154
  let messageData = await this.call({
@@ -2260,107 +2174,6 @@ class Account {
2260
2174
  }
2261
2175
 
2262
2176
  async listMessages(query) {
2263
- if (query.documentStore && (await isDocumentStoreEnabled())) {
2264
- await this.loadAccountData(this.account, false);
2265
-
2266
- const { index, client } = this.esClient;
2267
-
2268
- let inboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), 'INBOX'));
2269
- let delimiter = inboxData ? inboxData.delimiter : '/'; // hope for the best
2270
-
2271
- inboxData = inboxData || {
2272
- path: 'INBOX',
2273
- delimiter
2274
- };
2275
-
2276
- inboxData.specialUse = inboxData.specialUse || '\\Inbox';
2277
-
2278
- let path = normalizePath(query.path, delimiter);
2279
- let mailboxData = path === 'INBOX' ? inboxData : false;
2280
- if (!mailboxData) {
2281
- mailboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), path));
2282
- }
2283
-
2284
- let searchQuery = {
2285
- bool: {
2286
- must: [
2287
- {
2288
- term: {
2289
- account: this.account
2290
- }
2291
- }
2292
- ]
2293
- }
2294
- };
2295
-
2296
- searchQuery.bool.must.push({
2297
- bool: {
2298
- should: [
2299
- {
2300
- term: {
2301
- path
2302
- }
2303
- },
2304
- {
2305
- term: {
2306
- labels: (mailboxData && mailboxData.specialUse) || path
2307
- }
2308
- }
2309
- ],
2310
- minimum_should_match: 1
2311
- }
2312
- });
2313
-
2314
- let page = Number(query.page) || 0;
2315
- let pageSize = Math.abs(Number(query.pageSize) || 20);
2316
-
2317
- if (page < 0) {
2318
- page = 0;
2319
- }
2320
-
2321
- let searchResult = await client.search({
2322
- index,
2323
- size: pageSize,
2324
- from: pageSize * page,
2325
- query: searchQuery,
2326
- sort: { uid: 'desc' },
2327
- _source_excludes: 'headers,text.plain,text.html,text._generatedHtml,seemsLikeNew,attachments.content,summary,riskAssessment,updateTime,bounces'
2328
- });
2329
-
2330
- this.logger.trace({
2331
- msg: 'Executed ES query',
2332
- query: { type: 'search', index, size: pageSize, from: pageSize * page, query: searchQuery, sort: { uid: 'desc' } },
2333
- results: searchResult.hits.total.value
2334
- });
2335
-
2336
- let response = {
2337
- total: searchResult.hits.total.value,
2338
- page,
2339
- pages: Math.max(Math.ceil(searchResult.hits.total.value / pageSize), 1),
2340
- messages: searchResult.hits.hits.map(entry => {
2341
- let messageData = entry._source;
2342
-
2343
- // normalize as per the API response
2344
-
2345
- for (let key of ['unseen', 'flagged', 'answered', 'draft']) {
2346
- if (messageData[key] === false) {
2347
- messageData[key] = undefined;
2348
- }
2349
- }
2350
-
2351
- for (let key of ['account', 'created', 'specialUse']) {
2352
- if (messageData[key]) {
2353
- messageData[key] = undefined;
2354
- }
2355
- }
2356
-
2357
- return messageData;
2358
- })
2359
- };
2360
-
2361
- return response;
2362
- }
2363
-
2364
2177
  await this.loadAccountData(this.account, true);
2365
2178
 
2366
2179
  let listing = await this.call(
@@ -2378,394 +2191,9 @@ class Account {
2378
2191
  return this.assertFolderFound(listing);
2379
2192
  }
2380
2193
 
2381
- async searchMessages(query, searchOpts) {
2382
- searchOpts = searchOpts || {};
2383
- if (query.documentStore && (await isDocumentStoreEnabled())) {
2384
- if (!searchOpts.unified) {
2385
- await this.loadAccountData(this.account, false);
2386
- }
2387
-
2388
- const { index, client } = this.esClient;
2389
-
2390
- let searchQuery = {
2391
- bool: {
2392
- must: []
2393
- }
2394
- };
2395
-
2396
- if (this.account) {
2397
- searchQuery.bool.must.push({
2398
- term: {
2399
- account: this.account
2400
- }
2401
- });
2402
- }
2403
-
2404
- if (searchOpts.unified && query.accounts && query.accounts.length) {
2405
- searchQuery.bool.must.push({
2406
- bool: {
2407
- should: query.accounts.map(account => ({
2408
- term: {
2409
- account
2410
- }
2411
- })),
2412
- minimum_should_match: 1
2413
- }
2414
- });
2415
- }
2416
-
2417
- if (query.path) {
2418
- let inboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), 'INBOX'));
2419
- let delimiter = inboxData ? inboxData.delimiter : '/'; // hope for the best
2420
-
2421
- inboxData = inboxData || {
2422
- path: 'INBOX',
2423
- delimiter
2424
- };
2425
-
2426
- inboxData.specialUse = inboxData.specialUse || '\\Inbox';
2427
-
2428
- let path = normalizePath(query.path, delimiter);
2429
- let mailboxData = path === 'INBOX' ? inboxData : false;
2430
- if (!mailboxData) {
2431
- mailboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), path));
2432
- }
2433
-
2434
- searchQuery.bool.must.push({
2435
- bool: {
2436
- should: [
2437
- {
2438
- term: {
2439
- path
2440
- }
2441
- },
2442
- {
2443
- term: {
2444
- labels: (mailboxData && mailboxData.specialUse) || path
2445
- }
2446
- }
2447
- ],
2448
- minimum_should_match: 1
2449
- }
2450
- });
2451
- }
2452
-
2453
- if (searchOpts.unified && query.paths && query.paths.length) {
2454
- searchQuery.bool.must.push({
2455
- bool: {
2456
- should: query.paths.flatMap(path => {
2457
- let res = [
2458
- {
2459
- term: {
2460
- path
2461
- }
2462
- },
2463
- {
2464
- term: {
2465
- labels: path
2466
- }
2467
- },
2468
- {
2469
- term: {
2470
- messageSpecialUse: path
2471
- }
2472
- }
2473
- ];
2474
-
2475
- if (/^inbox$/i.test(path)) {
2476
- res.push({
2477
- term: {
2478
- messageSpecialUse: '\\Inbox'
2479
- }
2480
- });
2481
- }
2482
-
2483
- return res;
2484
- }),
2485
- minimum_should_match: 1
2486
- }
2487
- });
2488
- }
2489
-
2490
- for (let key of ['answered', 'deleted', 'draft', 'unseen', 'flagged']) {
2491
- if (typeof query.search[key] === 'boolean') {
2492
- searchQuery.bool.must.push({
2493
- term: {
2494
- [key]: query.search[key]
2495
- }
2496
- });
2497
- }
2498
- }
2499
-
2500
- if (typeof query.search.seen === 'boolean') {
2501
- searchQuery.bool.must.push({
2502
- term: {
2503
- unseen: !query.search.seen
2504
- }
2505
- });
2506
- }
2507
-
2508
- for (let key of ['from', 'to', 'cc', 'bcc']) {
2509
- if (query.search[key]) {
2510
- searchQuery.bool.must.push({
2511
- bool: {
2512
- should: [
2513
- {
2514
- match: {
2515
- [`${key}.name`]: {
2516
- query: query.search[key],
2517
- operator: 'and'
2518
- }
2519
- }
2520
- },
2521
- {
2522
- term: {
2523
- [`${key}.address`]: query.search[key]
2524
- }
2525
- }
2526
- ],
2527
- minimum_should_match: 1
2528
- }
2529
- });
2530
- }
2531
- }
2532
-
2533
- if (query.search.uid) {
2534
- let uidEntries = unpackUIDRangeForSearch(query.search.uid);
2535
- if (uidEntries && uidEntries.length) {
2536
- let mustList = [];
2537
- for (let entry of uidEntries) {
2538
- if (typeof entry === 'number') {
2539
- mustList.push({
2540
- match: {
2541
- uid: {
2542
- query: entry,
2543
- operator: 'and'
2544
- }
2545
- }
2546
- });
2547
- } else if (typeof entry === 'object') {
2548
- mustList.push({
2549
- range: {
2550
- uid: entry
2551
- }
2552
- });
2553
- }
2554
- }
2555
-
2556
- if (mustList.length) {
2557
- searchQuery.bool.must.push({
2558
- bool: {
2559
- should: mustList,
2560
- minimum_should_match: 1
2561
- }
2562
- });
2563
- }
2564
- }
2565
- }
2566
-
2567
- for (let key of ['emailId', 'threadId']) {
2568
- if (query.search[key]) {
2569
- searchQuery.bool.must.push({
2570
- term: {
2571
- [key]: query.search[key]
2572
- }
2573
- });
2574
- }
2575
- }
2576
-
2577
- if (query.search.subject) {
2578
- searchQuery.bool.must.push({
2579
- match: {
2580
- subject: {
2581
- query: query.search.subject,
2582
- operator: 'and'
2583
- }
2584
- }
2585
- });
2586
- }
2587
-
2588
- if (query.search.body) {
2589
- searchQuery.bool.must.push({
2590
- bool: {
2591
- should: [
2592
- {
2593
- match: {
2594
- 'text.plain': {
2595
- query: query.search.body,
2596
- operator: 'and'
2597
- }
2598
- }
2599
- },
2600
- {
2601
- match: {
2602
- 'text.html': {
2603
- query: query.search.body,
2604
- operator: 'and'
2605
- }
2606
- }
2607
- }
2608
- ],
2609
- minimum_should_match: 1
2610
- }
2611
- });
2612
- }
2613
-
2614
- let dateMatch = {};
2615
-
2616
- for (let key of ['before', 'sentBefore']) {
2617
- if (query.search[key]) {
2618
- dateMatch.lte = query.search[key];
2619
- }
2620
- }
2621
-
2622
- for (let key of ['since', 'sentSince']) {
2623
- if (query.search[key]) {
2624
- dateMatch.gte = query.search[key];
2625
- }
2626
- }
2627
-
2628
- if (Object.keys(dateMatch).length) {
2629
- searchQuery.bool.must.push({
2630
- range: { date: dateMatch }
2631
- });
2632
- }
2633
-
2634
- let sizeMatch = {};
2635
-
2636
- if (query.search.larger) {
2637
- sizeMatch.gte = query.search.larger;
2638
- }
2639
-
2640
- if (query.search.smaller) {
2641
- sizeMatch.lte = query.search.smaller;
2642
- }
2643
-
2644
- if (Object.keys(sizeMatch).length) {
2645
- searchQuery.bool.must.push({
2646
- range: { size: sizeMatch }
2647
- });
2648
- }
2649
-
2650
- // headers, nested query
2651
- if (Object.keys(query.search.header || {}).length) {
2652
- Object.keys(query.search.header).forEach(header => {
2653
- searchQuery.bool.must.push({
2654
- nested: {
2655
- path: 'headers',
2656
- query: {
2657
- bool: {
2658
- must: [
2659
- {
2660
- term: {
2661
- 'headers.key': header.toLowerCase()
2662
- }
2663
- },
2664
- {
2665
- match: {
2666
- 'headers.value': {
2667
- query: (query.search.header[header] || '').toString(),
2668
- operator: 'and'
2669
- }
2670
- }
2671
- }
2672
- ]
2673
- }
2674
- }
2675
- }
2676
- });
2677
- });
2678
- }
2679
-
2680
- if (query.documentQuery) {
2681
- searchQuery.bool.must.push(query.documentQuery);
2682
- }
2683
-
2684
- let page = Number(query.page) || 0;
2685
- let pageSize = Math.abs(Number(query.pageSize) || 20);
2686
-
2687
- if (page < 0) {
2688
- page = 0;
2689
- }
2690
-
2691
- let searchResult = await client.search({
2692
- index,
2693
- size: pageSize,
2694
- from: pageSize * page,
2695
- query: searchQuery,
2696
- sort: { [!searchOpts.unified ? 'uid' : 'date']: 'desc' },
2697
- _source_excludes: 'headers,text.plain,text.html,text._generatedHtml,seemsLikeNew,attachments.content,summary,riskAssessment,updateTime,bounces'
2698
- });
2699
-
2700
- this.logger.trace({
2701
- msg: 'Executed ES query',
2702
- query: {
2703
- type: 'search',
2704
- index,
2705
- size: pageSize,
2706
- from: pageSize * page,
2707
- query: searchQuery,
2708
- sort: { [!searchOpts.unified ? 'uid' : 'date']: 'desc' }
2709
- },
2710
- results: searchResult.hits.total.value
2711
- });
2712
-
2713
- let response = {
2714
- total: searchResult.hits.total.value,
2715
- page,
2716
- pages: Math.max(Math.ceil(searchResult.hits.total.value / pageSize), 1)
2717
- };
2718
-
2719
- if (query.exposeQuery) {
2720
- response.documentStoreQuery = query;
2721
- }
2722
-
2723
- if (query.accounts) {
2724
- response.accounts = query.accounts;
2725
- }
2726
-
2727
- if (query.paths) {
2728
- response.paths = query.paths;
2729
- }
2730
-
2731
- response.messages = searchResult.hits.hits.map(entry => {
2732
- let messageData = entry._source;
2733
-
2734
- // normalize as per the API response
2735
-
2736
- for (let key of ['unseen', 'flagged', 'answered', 'draft']) {
2737
- if (messageData[key] === false) {
2738
- messageData[key] = undefined;
2739
- }
2740
- }
2741
-
2742
- for (let key of ['created', 'specialUse'].concat(!searchOpts.unified ? 'account' : [])) {
2743
- if (messageData[key]) {
2744
- messageData[key] = undefined;
2745
- }
2746
- }
2747
-
2748
- return messageData;
2749
- });
2750
-
2751
- return response;
2752
- }
2753
-
2754
- await this.loadAccountData(this.account, true);
2755
-
2756
- let listing = await this.call(
2757
- Object.assign(
2758
- {
2759
- cmd: 'listMessages',
2760
- account: this.account
2761
- },
2762
- query,
2763
- { timeout: this.timeout }
2764
- )
2765
- );
2766
-
2767
- // IMAP and Gmail backends return false for unknown folders
2768
- return this.assertFolderFound(listing);
2194
+ // A search is a listing with a `search` query; the same worker command answers both
2195
+ async searchMessages(query) {
2196
+ return await this.listMessages(query);
2769
2197
  }
2770
2198
 
2771
2199
  async uploadMessage(data) {
@@ -2948,64 +2376,10 @@ class Account {
2948
2376
  pipeline = pipeline.hset(this.getAccountKey(), 'imapIndexer', imapIndexer);
2949
2377
  }
2950
2378
 
2951
- if (data.syncFrom || data.syncFrom === null) {
2952
- pipeline = pipeline.hset(this.getAccountKey(), 'syncFrom', data.syncFrom ? data.syncFrom.toISOString() : 'null');
2953
- }
2954
-
2955
2379
  await pipeline.exec();
2956
2380
 
2957
2381
  // scan and delete keys
2958
- await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${escapeRedisGlob(this.account)}:*`);
2959
-
2960
- if (await isDocumentStoreEnabled()) {
2961
- // Flush ElasticSearch index for this account
2962
- const { index, client } = this.esClient;
2963
- if (!client) {
2964
- // Account data in Redis was already flushed, only the index cleanup was skipped
2965
- this.logger.error({ msg: 'Document store is enabled but the ElasticSearch client is not available', action: 'flush' });
2966
- return true;
2967
- }
2968
-
2969
- let deleteResult = {};
2970
- let deletedCount = 0;
2971
-
2972
- let filterQuery = {
2973
- match: {
2974
- account: this.account
2975
- }
2976
- };
2977
-
2978
- for (let indexName of [index, `${index}.threads`, `${index}.embeddings`]) {
2979
- try {
2980
- deleteResult[indexName] = await client.deleteByQuery({
2981
- index: indexName,
2982
- query: filterQuery
2983
- });
2984
- deletedCount += deleteResult[indexName].deleted || 0;
2985
- } catch (err) {
2986
- this.logger.error({
2987
- msg: 'Failed to delete account emails from index',
2988
- action: 'flush',
2989
- code: 'document_delete_account_error',
2990
- index: indexName,
2991
- request: filterQuery,
2992
- err
2993
- });
2994
- if (indexName === index) {
2995
- throw err;
2996
- }
2997
- }
2998
- }
2999
-
3000
- this.logger.trace({
3001
- msg: 'Deleted account emails from index',
3002
- action: 'flush',
3003
- code: 'document_delete_account',
3004
- account: this.account,
3005
- deletedCount,
3006
- deleteResult
3007
- });
3008
- }
2382
+ await redisScanDelete(this.redis, this.logger, `${escapeRedisGlob(REDIS_PREFIX)}iam:${escapeRedisGlob(this.account)}:*`);
3009
2383
 
3010
2384
  return true;
3011
2385
  } finally {
@@ -3114,6 +2488,28 @@ class Account {
3114
2488
  updates.scope = r.scope.split(/\s+/);
3115
2489
  }
3116
2490
 
2491
+ // Only the token fields are written, merged into whatever is stored at write time, and
2492
+ // only while the stored grant is still the one this renewal used. The account was read
2493
+ // before the provider round trip and without the update lock, so writing that whole
2494
+ // snapshot back put an older refresh token and scope list over a re-authorization that
2495
+ // landed meanwhile. userFlag is cleared by a null, which unserialize drops.
2496
+ let usedRefreshToken = accountData.oauth2.refreshToken;
2497
+ let writeResult = await this.update(
2498
+ { account: accountData.account, oauth2: Object.assign({ partial: true, userFlag: null }, updates) },
2499
+ { expectedRefreshToken: usedRefreshToken || '' }
2500
+ );
2501
+
2502
+ if (writeResult && writeResult.skipped) {
2503
+ this.logger.info({
2504
+ msg: 'Discarded a renewed OAuth2 access token, the account was re-authorized during the renewal',
2505
+ action: 'ensureAccessToken',
2506
+ account: this.account,
2507
+ oauth2App: accountData.oauth2.provider
2508
+ });
2509
+ // The skipped write read the account as stored now, so that read is reused
2510
+ return writeResult.current || (await this.loadAccountData(this.account, false));
2511
+ }
2512
+
3117
2513
  accountData.oauth2 = Object.assign(accountData.oauth2 || {}, updates);
3118
2514
  delete accountData.oauth2.userFlag;
3119
2515
 
@@ -3127,8 +2523,6 @@ class Account {
3127
2523
  oauth2App: accountData.oauth2.provider
3128
2524
  });
3129
2525
 
3130
- await this.update({ account: accountData.account, oauth2: accountData.oauth2 });
3131
-
3132
2526
  return accountData;
3133
2527
  } catch (err) {
3134
2528
  this.logger.warn({
@@ -3257,7 +2651,7 @@ class Account {
3257
2651
  if (delegatedAccount) {
3258
2652
  accountData.delegatedAccount = delegatedAccount;
3259
2653
  let delegatedAccountRow = await this.redis.hgetall(`${REDIS_PREFIX}iad:${delegatedAccount}`);
3260
- let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow);
2654
+ let delegatedAccountData = this.unserializeAccountData(delegatedAccountRow, { skipDecrypt: true });
3261
2655
  if (delegatedAccountData?.oauth2?.provider) {
3262
2656
  let app = await oauth2Apps.get(delegatedAccountData.oauth2.provider);
3263
2657
  return isApiBasedApp(app);
@@ -3519,6 +2913,7 @@ function isAccessTokenInvalidated(oauth2) {
3519
2913
  }
3520
2914
 
3521
2915
  module.exports = {
2916
+ ENCRYPTED_ACCOUNT_FIELDS,
3522
2917
  Account,
3523
2918
  accountExists,
3524
2919
  accountsExist,