emailengine-app 2.79.8 → 2.80.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 (182) hide show
  1. package/.github/dependabot.yml +22 -0
  2. package/.github/workflows/test.yml +39 -0
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +69 -0
  5. package/DOCKER_DEPLOYMENT.md +6 -7
  6. package/Dockerfile +35 -11
  7. package/config/default.toml +7 -2
  8. package/copy-static-files.sh +23 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +43 -0
  11. package/lib/account/account-state.js +62 -0
  12. package/lib/account.js +60 -3
  13. package/lib/api-routes/account-routes.js +20 -0
  14. package/lib/api-routes/bull-board-routes.js +3 -2
  15. package/lib/api-routes/index.js +1 -1
  16. package/lib/api-routes/route-helpers.js +8 -0
  17. package/lib/api-routes/settings-routes.js +17 -2
  18. package/lib/auth-token.js +73 -2
  19. package/lib/autodetect-imap-settings.js +379 -69
  20. package/lib/cert-handler.js +62 -0
  21. package/lib/consts.js +58 -7
  22. package/lib/db.js +12 -0
  23. package/lib/egress-fetch.js +145 -0
  24. package/lib/email-client/base-client.js +234 -66
  25. package/lib/email-client/credential-errors.js +118 -0
  26. package/lib/email-client/gmail/gmail-api.js +2 -1
  27. package/lib/email-client/gmail-client.js +70 -64
  28. package/lib/email-client/imap/connection-errors.js +52 -0
  29. package/lib/email-client/imap/listing-diff.js +47 -6
  30. package/lib/email-client/imap/mailbox.js +457 -379
  31. package/lib/email-client/imap/subconnection.js +15 -11
  32. package/lib/email-client/imap/sync-operations.js +46 -59
  33. package/lib/email-client/imap-client.js +136 -95
  34. package/lib/email-client/message-builder.js +11 -11
  35. package/lib/email-client/outlook/graph-api.js +2 -1
  36. package/lib/email-client/outlook-client.js +219 -106
  37. package/lib/export.js +35 -2
  38. package/lib/handlebars-helpers.js +129 -0
  39. package/lib/imap-proxy-auth.js +96 -21
  40. package/lib/imapproxy/imap-core/README.md +1 -0
  41. package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
  42. package/lib/imapproxy/imap-server.js +56 -66
  43. package/lib/lua/h-del-if-equals.lua +39 -0
  44. package/lib/lua/h-set-if-equals.lua +39 -0
  45. package/lib/openapi/index.js +3 -0
  46. package/lib/outbox.js +28 -3
  47. package/lib/rate-limit.js +23 -4
  48. package/lib/routes-ui.js +4 -34
  49. package/lib/schemas.js +42 -3
  50. package/lib/security-headers.js +411 -0
  51. package/lib/sentry.js +36 -4
  52. package/lib/smtp-auth.js +86 -7
  53. package/lib/tls/context.js +376 -0
  54. package/lib/tls/der.js +223 -0
  55. package/lib/tls/provision.js +555 -0
  56. package/lib/tls/self-signed.js +282 -0
  57. package/lib/tls/status.js +431 -0
  58. package/lib/tls/store.js +666 -0
  59. package/lib/tools.js +337 -147
  60. package/lib/ui-routes/account-routes.js +47 -33
  61. package/lib/ui-routes/admin-config-routes.js +22 -1
  62. package/lib/ui-routes/auth-routes.js +16 -1
  63. package/lib/ui-routes/export-routes.js +4 -0
  64. package/lib/ui-routes/internals-routes.js +3 -5
  65. package/lib/ui-routes/mcp-consent-routes.js +7 -0
  66. package/lib/ui-routes/network-config-routes.js +58 -48
  67. package/lib/ui-routes/route-helpers.js +24 -8
  68. package/lib/ui-routes/smtp-test-routes.js +7 -0
  69. package/lib/ui-routes/tls-config-routes.js +581 -0
  70. package/lib/utils/mailbox-path.js +51 -0
  71. package/lib/utils/severity.js +31 -0
  72. package/lib/webhook-egress.js +5 -0
  73. package/package.json +21 -24
  74. package/sbom.json +1 -1
  75. package/server.js +53 -36
  76. package/static/css/flyonui.css +1 -1
  77. package/static/css/src/app.tailwind.css +11 -0
  78. package/static/js/ace/css/ace.css +1462 -0
  79. package/static/js/ace/css/kuroir-1.png +0 -0
  80. package/static/js/ace/css/kuroir-2.png +0 -0
  81. package/static/js/ace/css/main-1.png +0 -0
  82. package/static/js/ace/css/main-10.svg +4 -0
  83. package/static/js/ace/css/main-11.svg +5 -0
  84. package/static/js/ace/css/main-12.svg +4 -0
  85. package/static/js/ace/css/main-13.png +0 -0
  86. package/static/js/ace/css/main-14.png +0 -0
  87. package/static/js/ace/css/main-15.png +0 -0
  88. package/static/js/ace/css/main-16.png +0 -0
  89. package/static/js/ace/css/main-17.png +0 -0
  90. package/static/js/ace/css/main-18.png +0 -0
  91. package/static/js/ace/css/main-19.png +0 -0
  92. package/static/js/ace/css/main-2.png +0 -0
  93. package/static/js/ace/css/main-20.png +0 -0
  94. package/static/js/ace/css/main-21.png +0 -0
  95. package/static/js/ace/css/main-22.png +0 -0
  96. package/static/js/ace/css/main-23.png +0 -0
  97. package/static/js/ace/css/main-24.png +0 -0
  98. package/static/js/ace/css/main-25.svg +1 -0
  99. package/static/js/ace/css/main-26.png +0 -0
  100. package/static/js/ace/css/main-3.png +0 -0
  101. package/static/js/ace/css/main-4.png +0 -0
  102. package/static/js/ace/css/main-5.svg +7 -0
  103. package/static/js/ace/css/main-6.svg +9 -0
  104. package/static/js/ace/css/main-7.svg +7 -0
  105. package/static/js/ace/css/main-8.svg +9 -0
  106. package/static/js/ace/css/main-9.svg +6 -0
  107. package/static/js/ace/css/theme/kuroir.css +78 -0
  108. package/static/js/ace/css/theme/tomorrow_night.css +128 -0
  109. package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
  110. package/static/js/ace/css/theme/xcode.css +106 -0
  111. package/static/js/ace/css/tomorrow_night-1.png +0 -0
  112. package/static/js/ace/css/tomorrow_night-2.png +0 -0
  113. package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
  114. package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
  115. package/static/js/ace/css/xcode-1.png +0 -0
  116. package/static/js/ace/css/xcode-2.png +0 -0
  117. package/static/js/app.js +34 -0
  118. package/static/js/ee-client.js +256 -102
  119. package/static/js/public.js +13 -2
  120. package/static/js/ui.js +40 -25
  121. package/static/licenses.html +393 -1282
  122. package/static/vendor/simplewebauthn/browser.min.js +2 -2
  123. package/translations/messages.pot +203 -157
  124. package/views/account/login-redirect.hbs +22 -0
  125. package/views/accounts/account.hbs +15 -37
  126. package/views/accounts/browse.hbs +3 -1
  127. package/views/accounts/edit.hbs +1 -1
  128. package/views/accounts/register/imap-server.hbs +1 -1
  129. package/views/config/ai.hbs +1 -1
  130. package/views/config/branding.hbs +2 -2
  131. package/views/config/document-store/chat.hbs +1 -1
  132. package/views/config/document-store/index.hbs +1 -1
  133. package/views/config/imap-proxy.hbs +1 -4
  134. package/views/config/license.hbs +1 -1
  135. package/views/config/mcp.hbs +1 -1
  136. package/views/config/network.hbs +14 -16
  137. package/views/config/oauth/app.hbs +2 -2
  138. package/views/config/service.hbs +1 -1
  139. package/views/config/smtp.hbs +1 -4
  140. package/views/config/tls-upload.hbs +81 -0
  141. package/views/config/tls.hbs +492 -0
  142. package/views/config/webhooks.hbs +2 -2
  143. package/views/error.hbs +4 -2
  144. package/views/internals/index.hbs +1 -1
  145. package/views/layout/app.hbs +3 -11
  146. package/views/mcp/authorize.hbs +1 -1
  147. package/views/partials/ace_assets.hbs +13 -0
  148. package/views/partials/add_account_modal.hbs +1 -1
  149. package/views/partials/address_list.hbs +4 -4
  150. package/views/partials/filter_editor_js.hbs +2 -2
  151. package/views/partials/gateway_js.hbs +1 -1
  152. package/views/partials/oauth_form.hbs +1 -1
  153. package/views/partials/public_theme_init.hbs +1 -1
  154. package/views/partials/side_menu.hbs +1 -0
  155. package/views/partials/template_form.hbs +2 -2
  156. package/views/partials/test_send.hbs +7 -4
  157. package/views/partials/theme_init.hbs +1 -1
  158. package/views/partials/tls_security_card.hbs +25 -53
  159. package/views/partials/ui/alert-banner.hbs +3 -2
  160. package/views/partials/ui/badge.hbs +6 -2
  161. package/views/partials/ui/btn.hbs +5 -2
  162. package/views/partials/ui/details.hbs +2 -2
  163. package/views/partials/webhooks_editor_functions.hbs +1 -1
  164. package/views/reference/redirect.hbs +1 -1
  165. package/views/templates/template.hbs +2 -2
  166. package/views/tokens/new.hbs +1 -1
  167. package/views/unsubscribe.hbs +1 -1
  168. package/views/webhooks/webhook.hbs +2 -2
  169. package/workers/api.js +131 -242
  170. package/workers/export.js +1 -5
  171. package/workers/imap-proxy.js +4 -1
  172. package/workers/imap.js +1 -3
  173. package/workers/smtp.js +59 -83
  174. package/workers/submit.js +6 -12
  175. package/workers/webhooks.js +6 -17
  176. package/static/front/EmailEngine_logo_horiz.png +0 -0
  177. package/static/front/EmailEngine_logo_vert.png +0 -0
  178. package/static/front/index.html +0 -57
  179. package/static/front/logo.png +0 -0
  180. package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
  181. package/views/partials/tls_security_js.hbs +0 -64
  182. package/views/partials/tls_security_modal.hbs +0 -22
@@ -8,7 +8,8 @@ const msgpack = require('../msgpack');
8
8
  const addressparser = require('nodemailer/lib/addressparser');
9
9
  const libmime = require('libmime');
10
10
  const he = require('he');
11
- const { BaseClient, metricsMeta, isTransientNetworkError } = require('./base-client');
11
+ const { BaseClient, metricsMeta } = require('./base-client');
12
+ const { isTransientCredentialError } = require('./credential-errors');
12
13
  const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
13
14
  const { emitChangeEvent, toCamelCase, collectCidReferences, cidReferenceRegex, truncateTextContents } = require('../tools');
14
15
  const { Gateway } = require('../gateway');
@@ -20,7 +21,6 @@ const {
20
21
  EMAIL_SENT_NOTIFY,
21
22
  REDIS_PREFIX,
22
23
  AUTH_ERROR_NOTIFY,
23
- AUTH_SUCCESS_NOTIFY,
24
24
  DEFAULT_GMAIL_EXPORT_BATCH_SIZE,
25
25
  GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS
26
26
  } = require('../consts');
@@ -384,10 +384,9 @@ class GmailClient extends BaseClient {
384
384
  profileRes = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/profile`);
385
385
  }
386
386
  } catch (err) {
387
- if (isTransientNetworkError(err)) {
388
- // The provider could not be reached - a connection problem, not a refused
389
- // credential. Left unflagged so the worker retries init() instead of reporting
390
- // an authentication error that only re-authorization could clear
387
+ if (isTransientCredentialError(err)) {
388
+ // Not a refused credential - left unflagged so the worker retries init() instead of
389
+ // reporting an authentication error only re-authorization could clear
391
390
  throw err;
392
391
  }
393
392
 
@@ -498,44 +497,12 @@ class GmailClient extends BaseClient {
498
497
  this.backgroundTimersArmed = true;
499
498
  }
500
499
 
501
- // Determine if this is a reconnection after error
502
- let prevConnectedCount = await this.redis.hget(this.getAccountKey(), `state:count:connected`);
503
- let isFirstSuccessfulConnection = prevConnectedCount === '0'; // string zero means the account has been initialized but not yet connected
500
+ // Before the state flip below - see notifyAuthenticationSuccess()
501
+ await this.notifyAuthenticationSuccess(accountData.oauth2?.auth?.user);
504
502
 
505
503
  this.state = 'connected';
506
504
  await this.setStateVal();
507
505
 
508
- let isInitial = !!isFirstSuccessfulConnection;
509
-
510
- if (!isFirstSuccessfulConnection) {
511
- // check if the connection was previously in an errored state
512
- let prevLastErrorState = await this.redis.hget(this.getAccountKey(), 'lastErrorState');
513
- if (prevLastErrorState) {
514
- try {
515
- prevLastErrorState = JSON.parse(prevLastErrorState);
516
- } catch (err) {
517
- // ignore
518
- }
519
- }
520
-
521
- if (prevLastErrorState && typeof prevLastErrorState === 'object' && Object.keys(prevLastErrorState).length) {
522
- // was previously errored
523
- isFirstSuccessfulConnection = true;
524
- }
525
- }
526
-
527
- // Send appropriate authentication success notification
528
- if (isFirstSuccessfulConnection) {
529
- this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isInitial, prevActive: false });
530
- await this.notify(false, AUTH_SUCCESS_NOTIFY, {
531
- user: accountData.oauth2?.auth?.user
532
- });
533
- } else {
534
- this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, isInitial, prevActive: true });
535
- }
536
-
537
- // Clear any previous error state
538
- await this.redis.hdel(this.getAccountKey(), 'lastErrorState', 'lastError:errorCount', 'lastError:first');
539
506
  await emitChangeEvent(this.logger, this.account, 'state', this.state);
540
507
  }
541
508
 
@@ -2030,9 +1997,15 @@ class GmailClient extends BaseClient {
2030
1997
  let tokenData;
2031
1998
  try {
2032
1999
  tokenData = await this.accountObject.getActiveAccessTokenData();
2033
- if (!['init', 'connecting', 'connected'].includes(this.state)) {
2034
- // We're in an error state (authenticationError, disconnected, etc.)
2035
- // But we just got a valid token, so we've recovered
2000
+ if (this.state === 'authenticationError') {
2001
+ // A valid token means the credential recovered, so announce it here as well as in
2002
+ // init() - this is also what clears the stored error state, which would otherwise
2003
+ // outlive the error it describes. Deliberately only the authentication error, the
2004
+ // same rule the Graph client follows: a token says nothing about `unset` (an
2005
+ // account the safety net parked) or `disconnected` (one that was closed), and
2006
+ // flipping either to `connected` for having fetched one was never right
2007
+ await this.notifyAuthenticationSuccess(tokenData.user);
2008
+
2036
2009
  this.state = 'connected';
2037
2010
  await this.setStateVal();
2038
2011
 
@@ -2052,23 +2025,7 @@ class GmailClient extends BaseClient {
2052
2025
  }
2053
2026
  } catch (E) {
2054
2027
  if (E.code === 'ETokenRefresh') {
2055
- // treat as authentication failure
2056
- this.state = 'authenticationError';
2057
- await this.setStateVal();
2058
-
2059
- E.authenticationFailed = true;
2060
-
2061
- // Track failed token refresh
2062
- const statusCode = String(E.statusCode || 0);
2063
- metricsMeta({ account: this.account }, this.logger, 'oauth2TokenRefresh', 'inc', { status: 'failure', provider: 'gmail', statusCode });
2064
-
2065
- if (!E.errorNotified) {
2066
- E.errorNotified = true;
2067
- await this.notify(false, AUTH_ERROR_NOTIFY, {
2068
- response: E.oauthRequest?.response?.error?.message || E.response,
2069
- serverResponseCode: 'TokenGenerationError'
2070
- });
2071
- }
2028
+ await this.reportTokenRefreshFailure(E, 'gmail');
2072
2029
  }
2073
2030
 
2074
2031
  throw E;
@@ -2122,8 +2079,10 @@ class GmailClient extends BaseClient {
2122
2079
  this.renewWatch()
2123
2080
  .catch(err => {
2124
2081
  this.logger.error({ msg: 'Failed to renew Gmail subscription watch', account: this.account, err });
2125
- // Check if this is a permanent auth failure
2126
- if (err.code === 'ETokenRefresh' || this.state === 'authenticationError') {
2082
+ // Check if this is a permanent auth failure. A token endpoint that answered 429
2083
+ // or a 5xx has not refused the credential, and stopping the timer on one would
2084
+ // leave the watch unrenewed until something else happens to fetch a token
2085
+ if ((err.code === 'ETokenRefresh' && !isTransientCredentialError(err)) || this.state === 'authenticationError') {
2127
2086
  authError = true;
2128
2087
  }
2129
2088
  })
@@ -2230,11 +2189,21 @@ class GmailClient extends BaseClient {
2230
2189
  watchExpiration: watchExpiration ? new Date(watchExpiration).toISOString() : null
2231
2190
  });
2232
2191
  } catch (err) {
2192
+ // NB! `lastWatch` is deliberately NOT moved here, so it now means "last
2193
+ // successful arm" rather than "last attempt". It gates the renewal at the top of
2194
+ // this method against MIN_WATCH_TTL, so writing it on a failure bought a broken
2195
+ // watch a full day of silence even though the renewal timer fires hourly - and a
2196
+ // Gmail watch lapses seven days after the last successful call, so a week of
2197
+ // daily failures ended push entirely. The attempt time goes on the failure
2198
+ // record instead, which is what reports how stale this is. A failing watch now
2199
+ // retries at the timer's own cadence, hourly, with no backoff and no cap: one
2200
+ // call per account per hour is orders of magnitude under the Gmail quota, and
2201
+ // the alternative is the seven-day lapse this replaces
2233
2202
  await this.accountObject.update({
2234
- lastWatch: new Date(now),
2235
2203
  watchFailure: {
2236
2204
  err: err.message,
2237
- req: err.oauthRequest
2205
+ req: err.oauthRequest,
2206
+ time: new Date(now).toISOString()
2238
2207
  }
2239
2208
  });
2240
2209
  this.logger.error({
@@ -2250,6 +2219,23 @@ class GmailClient extends BaseClient {
2250
2219
  // GCP, so ensurePubsub never persisted the markers). Surface it once per connection -
2251
2220
  // the renewal timer re-fires ~hourly and this branch never updates lastWatch, so an
2252
2221
  // unguarded warning would otherwise repeat every cycle.
2222
+ // Recorded, not just logged: this is the one failure mode that armed no watch and
2223
+ // wrote nothing, so an operator polling the account saw what a healthy one shows.
2224
+ // Written every cycle, unlike the warning below - the record's whole job is to say
2225
+ // when the state was last observed, and a latch would freeze that at the first
2226
+ // sighting while the check went on running hourly. Best effort, because init()
2227
+ // awaits this method and a Redis hiccup must not fail the account setup
2228
+ try {
2229
+ await this.accountObject.update({
2230
+ watchFailure: {
2231
+ err: 'Pub/Sub topic and IAM markers are not recorded on the linked application',
2232
+ time: new Date(now).toISOString()
2233
+ }
2234
+ });
2235
+ } catch (err) {
2236
+ this.logger.error({ msg: 'Failed to record the missing watch markers', account: this.account, err });
2237
+ }
2238
+
2253
2239
  if (!this._loggedMissingWatchMarkers) {
2254
2240
  this._loggedMissingWatchMarkers = true;
2255
2241
  this.logger.warn({
@@ -2261,6 +2247,26 @@ class GmailClient extends BaseClient {
2261
2247
  });
2262
2248
  }
2263
2249
  }
2250
+ } else if (!accountData._app?.pubSubApp && (accountData.watchFailure || accountData.watchResponse)) {
2251
+ // Nothing pushes to this account any more: the Pub/Sub app was unlinked, or the account
2252
+ // was re-authorized onto an app that has none. The watch record is only ever cleared by
2253
+ // a successful arm, so an account with no push configured went on reporting the last
2254
+ // failure - state 'error' with a frozen lastCheck - for good. Keyed on the pubSubApp
2255
+ // term alone, never on the whole condition above: a still-linked account inside
2256
+ // MIN_WATCH_TTL takes the same else and its failure has to stay.
2257
+ // Best effort, because init() awaits this method and a Redis hiccup must not fail the
2258
+ // account setup
2259
+ this.watchExpiration = null;
2260
+ try {
2261
+ await this.getAccount();
2262
+ await this.accountObject.update({
2263
+ lastWatch: null,
2264
+ watchResponse: null,
2265
+ watchFailure: null
2266
+ });
2267
+ } catch (err) {
2268
+ this.logger.error({ msg: 'Failed to clear the stored Gmail watch record', account: this.account, err });
2269
+ }
2264
2270
  }
2265
2271
  }
2266
2272
 
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+
3
+ // The failures the IMAP client raises on its own behalf, rather than passing on something a server
4
+ // said. Each was written out by hand at every site that needed it - ten copies of the first alone,
5
+ // across imap-client.js, mailbox.js and sync-operations.js - which is how one of them ended up
6
+ // carrying a different code from the rest.
7
+ //
8
+ // The first two are in CONNECTION_CLOSING_CODES, so every existing handler already treats them as
9
+ // "the connection is gone, retry after the reconnect" rather than as a command failure.
10
+ // `IMAPUnavailable` is deliberately NOT in that set: it says the account has no usable connection
11
+ // to serve a request with, which is a 503 for the caller and not something a sync retries past.
12
+ // All of them are 503, which is what an API path reports.
13
+
14
+ /**
15
+ * There is no connection to run this on: the client was torn down and not replaced yet.
16
+ * @returns {Error} A connection-closing error
17
+ */
18
+ function connectionNotAvailableError() {
19
+ const err = new Error('IMAP connection not available');
20
+ err.code = 'IMAPConnectionClosing';
21
+ err.statusCode = 503;
22
+ return err;
23
+ }
24
+
25
+ /**
26
+ * The connection went away in the middle of a sync. The original failure is kept as `cause`,
27
+ * because on this path it is the only record of why the server dropped the connection
28
+ * (NO [OVERQUOTA], * BYE Too many connections, [SERVERBUG]).
29
+ * @param {Error} [cause] - What the server or socket reported
30
+ * @returns {Error} A connection-closing error
31
+ */
32
+ function connectionClosedError(cause) {
33
+ const err = new Error('IMAP connection closed during sync', { cause });
34
+ err.code = 'IMAPConnectionClosing';
35
+ err.statusCode = 503;
36
+ return err;
37
+ }
38
+
39
+ /**
40
+ * The account has no usable connection to serve this request with. Unlike the two above, this is
41
+ * the answer to a caller rather than a signal to a sync loop, so its code stays outside
42
+ * CONNECTION_CLOSING_CODES and nothing retries past it.
43
+ * @returns {Error} A 503 for the caller
44
+ */
45
+ function connectionUnavailableError() {
46
+ const err = new Error('IMAP connection is currently not available for requested account');
47
+ err.code = 'IMAPUnavailable';
48
+ err.statusCode = 503;
49
+ return err;
50
+ }
51
+
52
+ module.exports = { connectionNotAvailableError, connectionClosedError, connectionUnavailableError };
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
- // Pure helpers behind IMAPClient.getCurrentListing().
3
+ // Pure helpers behind the mailbox listing: the diff IMAPClient.getCurrentListing() runs, and
4
+ // the comparisons that decide which listed folders an account watches.
4
5
  //
5
6
  // Every IMAP sync pass re-runs LIST and has to work out which folders are new, which changed
6
7
  // shape, and which disappeared, then persist the result. That comparison is the part worth
@@ -10,10 +11,13 @@
10
11
  // in imap-client.js.
11
12
  //
12
13
  // Folder paths are compared through normalizePath(), which case-folds INBOX so a server that
13
- // reports "Inbox" one pass and "INBOX" the next does not look like a delete plus an add.
14
+ // reports "Inbox" one pass and "INBOX" the next does not look like a delete plus an add. Every
15
+ // comparison of a path against another path goes through samePath() (lib/utils/mailbox-path.js)
16
+ // for that reason, which is why the ones that match stored account configuration against a
17
+ // listing live here too rather than as an open-coded `===` at each call site.
14
18
 
15
19
  const msgpack = require('../../msgpack');
16
- const { normalizePath } = require('../../tools');
20
+ const { normalizePath, samePath } = require('../../utils/mailbox-path');
17
21
  const { STORED_MAILBOX_FIELDS } = require('../../consts');
18
22
 
19
23
  // The fields diffMailboxListing() compares, i.e. everything buildStoredListingObject() persists
@@ -21,6 +25,35 @@ const { STORED_MAILBOX_FIELDS } = require('../../consts');
21
25
  // stored field list so that persisting a new field can not silently leave it uncompared.
22
26
  const COMPARED_MAILBOX_FIELDS = STORED_MAILBOX_FIELDS.filter(field => field !== 'path');
23
27
 
28
+ /**
29
+ * Does a configured selector pick out this listed folder? Account `path` entries and
30
+ * `subconnections` entries are stored exactly as the API received them and are either a folder
31
+ * path or a special-use token like "\Sent". Tokens are matched literally - they are a fixed
32
+ * vocabulary the server never spells differently - while paths go through samePath().
33
+ *
34
+ * @param {String} configuredPath - One entry of an account's `path` or `subconnections`
35
+ * @param {Object} entry - Mailbox entry from the server listing
36
+ * @returns {Boolean} True when the selector picks out this folder
37
+ */
38
+ function matchesListingEntry(configuredPath, entry) {
39
+ // The token compare is guarded on the token existing: most folders carry no special use, and
40
+ // an undefined configured entry must not match an undefined specialUse
41
+ return samePath(configuredPath, entry.path) || (!!entry.specialUse && configuredPath === entry.specialUse);
42
+ }
43
+
44
+ /**
45
+ * Index of the first configured selector that picks out this folder, or -1. The position is what
46
+ * orders the candidates for the folder the primary connection watches, so the lowest-numbered
47
+ * selector wins.
48
+ *
49
+ * @param {Array} configuredPaths - An account's `path` list
50
+ * @param {Object} entry - Mailbox entry from the server listing
51
+ * @returns {Number} Index into configuredPaths, or -1 when the folder is not selected
52
+ */
53
+ function configuredPathIndex(configuredPaths, entry) {
54
+ return configuredPaths.findIndex(configuredPath => matchesListingEntry(configuredPath, entry));
55
+ }
56
+
24
57
  /**
25
58
  * Decodes one msgpack-encoded entry of the stored mailbox listing hash, or returns false if the
26
59
  * value is unusable. Callers drop a false entry rather than failing: a single corrupt value must
@@ -83,11 +116,15 @@ function decodeStoredListing(storedListing) {
83
116
  *
84
117
  * @param {Array} listing - Mailbox entries from the server (already filtered of \Noselect)
85
118
  * @param {Array} storedListing - Decoded entries previously persisted for this account
86
- * @returns {Object} { hasChanges, deletedEntries } - deletedEntries are stored folders the
87
- * server no longer lists, whose message index the caller must clear
119
+ * @returns {Object} { hasChanges, hasChangesBesidesNew, deletedEntries } - deletedEntries are
120
+ * stored folders the server no longer lists, whose message index the caller must
121
+ * clear. The second flag is for the caller that defers the folders that appeared
122
+ * (see IMAPClient.getCurrentListing): without it, a pass whose only change was a
123
+ * deferred folder still rewrites the whole listing hash with what it just read
88
124
  */
89
125
  function diffMailboxListing(listing, storedListing) {
90
126
  let hasChanges = false;
127
+ let hasChangesBesidesNew = false;
91
128
 
92
129
  // Map for O(1) lookups - a linear scan per folder is quadratic on accounts with thousands
93
130
  // of folders, which is common on shared/public namespaces.
@@ -113,6 +150,7 @@ function diffMailboxListing(listing, storedListing) {
113
150
  for (let field of COMPARED_MAILBOX_FIELDS) {
114
151
  if (existingMailbox[field] !== mailbox[field]) {
115
152
  hasChanges = true;
153
+ hasChangesBesidesNew = true;
116
154
  break;
117
155
  }
118
156
  }
@@ -124,9 +162,10 @@ function diffMailboxListing(listing, storedListing) {
124
162
  const deletedEntries = storedListing.filter(entry => !listingPathSet.has(normalizePath(entry.path)));
125
163
  if (deletedEntries.length) {
126
164
  hasChanges = true;
165
+ hasChangesBesidesNew = true;
127
166
  }
128
167
 
129
- return { hasChanges, deletedEntries };
168
+ return { hasChanges, hasChangesBesidesNew, deletedEntries };
130
169
  }
131
170
 
132
171
  /**
@@ -158,6 +197,8 @@ function buildStoredListingObject(listing) {
158
197
  }
159
198
 
160
199
  module.exports = {
200
+ matchesListingEntry,
201
+ configuredPathIndex,
161
202
  decodeStoredMailboxEntry,
162
203
  decodeStoredListing,
163
204
  diffMailboxListing,