emailengine-app 2.76.0 → 2.77.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 (102) hide show
  1. package/.github/workflows/release.yaml +24 -19
  2. package/.ncurc.js +14 -2
  3. package/.release-please-manifest.json +3 -0
  4. package/CHANGELOG.md +23 -0
  5. package/README.md +1 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/encrypt.js +71 -4
  8. package/lib/address-strategies.js +18 -0
  9. package/lib/api-reference/code-samples.js +194 -0
  10. package/lib/api-reference/format.js +179 -0
  11. package/lib/api-reference/index.js +205 -0
  12. package/lib/api-reference/model.js +336 -0
  13. package/lib/api-reference/schema-tree.js +366 -0
  14. package/lib/api-routes/account-routes.js +117 -37
  15. package/lib/api-routes/behavior-notes.js +54 -0
  16. package/lib/api-routes/blocklist-routes.js +9 -9
  17. package/lib/api-routes/changes-routes.js +6 -4
  18. package/lib/api-routes/chat-routes.js +3 -3
  19. package/lib/api-routes/delivery-test-routes.js +24 -6
  20. package/lib/api-routes/export-routes.js +14 -12
  21. package/lib/api-routes/gateway-routes.js +11 -11
  22. package/lib/api-routes/license-routes.js +7 -7
  23. package/lib/api-routes/mailbox-routes.js +18 -9
  24. package/lib/api-routes/message-routes.js +55 -35
  25. package/lib/api-routes/oauth2-app-routes.js +22 -16
  26. package/lib/api-routes/outbox-routes.js +7 -7
  27. package/lib/api-routes/pubsub-routes.js +3 -3
  28. package/lib/api-routes/settings-routes.js +10 -9
  29. package/lib/api-routes/stats-routes.js +3 -3
  30. package/lib/api-routes/submit-routes.js +58 -8
  31. package/lib/api-routes/template-routes.js +13 -13
  32. package/lib/api-routes/token-routes.js +15 -10
  33. package/lib/api-routes/webhook-route-routes.js +5 -5
  34. package/lib/consts.js +7 -0
  35. package/lib/email-client/base-client.js +66 -12
  36. package/lib/enum-descriptions.js +130 -0
  37. package/lib/imapproxy/imap-server.js +30 -26
  38. package/lib/imapproxy/upstream-client.js +38 -0
  39. package/lib/oauth2-apps.js +9 -3
  40. package/lib/openapi/build-document.js +318 -0
  41. package/lib/openapi/index.js +95 -0
  42. package/lib/openapi/joi-schema.js +523 -0
  43. package/lib/routes-ui.js +5 -1
  44. package/lib/schemas.js +76 -17
  45. package/lib/swagger-options.js +173 -0
  46. package/lib/tokens.js +69 -5
  47. package/lib/ui-routes/admin-entities-routes.js +3 -0
  48. package/lib/ui-routes/dashboard-routes.js +2 -26
  49. package/lib/ui-routes/reference-routes.js +195 -0
  50. package/lib/ui-routes/route-helpers.js +11 -0
  51. package/package.json +9 -11
  52. package/prepare-bundle-deps.sh +28 -0
  53. package/release-please-config.json +11 -0
  54. package/sbom.json +0 -1
  55. package/server.js +10 -2
  56. package/static/css/flyonui.css +1 -1
  57. package/static/css/src/app.tailwind.css +90 -0
  58. package/static/js/ee-client.js +238 -8
  59. package/static/js/reference.js +736 -0
  60. package/static/js/ui.js +61 -33
  61. package/static/licenses.html +4 -4
  62. package/translations/messages.pot +27 -27
  63. package/views/config/ai.hbs +1 -1
  64. package/views/config/document-store/chat.hbs +5 -5
  65. package/views/config/document-store/index.hbs +2 -2
  66. package/views/config/document-store/pre-processing/index.hbs +1 -1
  67. package/views/config/email-processing.hbs +1 -1
  68. package/views/config/imap-proxy.hbs +1 -1
  69. package/views/config/license.hbs +1 -1
  70. package/views/config/oauth/index.hbs +3 -3
  71. package/views/config/security.hbs +1 -1
  72. package/views/config/smtp.hbs +2 -2
  73. package/views/dashboard.hbs +1 -1
  74. package/views/layout/app.hbs +18 -7
  75. package/views/partials/oauth_form.hbs +4 -4
  76. package/views/partials/reference/anchor-link.hbs +20 -0
  77. package/views/partials/reference/disclosure.hbs +37 -0
  78. package/views/partials/reference/nav.hbs +93 -0
  79. package/views/partials/reference/operation.hbs +127 -0
  80. package/views/partials/reference/params.hbs +20 -0
  81. package/views/partials/reference/schema-node.hbs +99 -0
  82. package/views/partials/reference/schema.hbs +19 -0
  83. package/views/partials/reference/section-heading.hbs +16 -0
  84. package/views/partials/reference/token-alert.hbs +24 -0
  85. package/views/partials/reference/try-field.hbs +31 -0
  86. package/views/partials/reference/try-it.hbs +78 -0
  87. package/views/partials/side_menu.hbs +1 -1
  88. package/views/partials/ui/badge.hbs +4 -2
  89. package/views/partials/ui/page-header.hbs +1 -1
  90. package/views/partials/ui/search-input.hbs +31 -0
  91. package/views/partials/ui/setting-ref.hbs +1 -1
  92. package/views/partials/ui/stat-card.hbs +4 -2
  93. package/views/partials/ui/tab.hbs +6 -1
  94. package/views/partials/ui/tabs.hbs +2 -2
  95. package/views/reference/index.hbs +76 -0
  96. package/views/reference/redirect.hbs +49 -0
  97. package/views/reference/tag.hbs +28 -0
  98. package/views/reference/token.hbs +49 -0
  99. package/views/tokens/index.hbs +9 -1
  100. package/views/webhooks/index.hbs +3 -3
  101. package/workers/api.js +37 -215
  102. package/views/swagger/index.hbs +0 -82
@@ -8,7 +8,7 @@ const getSecret = require('../get-secret');
8
8
  const tokens = require('../tokens');
9
9
  const { failAction } = require('../tools');
10
10
  const { handleError } = require('./route-helpers');
11
- const { accountIdSchema, tokenRestrictionsSchema, ipSchema, tokenIdSchema, errorResponses } = require('../schemas');
11
+ const { accountIdSchema, tokenRestrictionsSchema, ipSchema, tokenIdSchema, apiResponses, ENUM_DESCRIPTIONS } = require('../schemas');
12
12
 
13
13
  const tokenAccessSchema = Joi.object({
14
14
  time: Joi.date().iso().allow(null).example('2021-02-17T13:43:18.860Z').description('Last time this token was used. Null if the token has never been used'),
@@ -49,6 +49,11 @@ const tokenListItemFields = {
49
49
  scopes: tokenScopesSchema,
50
50
  restrictions: tokenRestrictionsSchema,
51
51
  created: Joi.date().iso().example('2021-02-17T13:43:18.860Z').description('The time this token was created'),
52
+ expires: Joi.date()
53
+ .iso()
54
+ .example('2021-02-17T14:43:18.860Z')
55
+ .description('The time this token stops working. Absent for tokens that never expire')
56
+ .label('TokenExpires'),
52
57
  access: tokenAccessSchema,
53
58
  id: tokenIdSchema
54
59
  };
@@ -99,8 +104,8 @@ async function init(args) {
99
104
  tags: ['api', 'Access Tokens'],
100
105
 
101
106
  plugins: {
102
- 'hapi-swagger': {
103
- responses: errorResponses(400, 401, 403, 404, 429, 500)
107
+ openapi: {
108
+ responses: apiResponses('Returns the new token value. This is the only time it is shown - store it now.', 400, 401, 403, 404, 429, 500)
104
109
  }
105
110
  },
106
111
 
@@ -124,7 +129,7 @@ async function init(args) {
124
129
  description: Joi.string().empty('').trim().max(1024).required().example('Token description').description('Token description'),
125
130
 
126
131
  scopes: Joi.array()
127
- .items(Joi.string().valid('api', 'smtp', 'imap-proxy').label('TokenScope'))
132
+ .items(Joi.string().valid('api', 'smtp', 'imap-proxy').meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenScope }).label('TokenScope'))
128
133
  .single()
129
134
  .default(['api'])
130
135
  .required()
@@ -167,8 +172,8 @@ async function init(args) {
167
172
  tags: ['api', 'Access Tokens'],
168
173
 
169
174
  plugins: {
170
- 'hapi-swagger': {
171
- responses: errorResponses(400, 401, 403, 429, 500)
175
+ openapi: {
176
+ responses: apiResponses('Returns a deletion marker. The token stops working immediately.', 400, 401, 403, 429, 500)
172
177
  }
173
178
  },
174
179
 
@@ -219,8 +224,8 @@ async function init(args) {
219
224
  tags: ['api', 'Access Tokens'],
220
225
 
221
226
  plugins: {
222
- 'hapi-swagger': {
223
- responses: errorResponses(401, 403, 429, 500)
227
+ openapi: {
228
+ responses: apiResponses('Returns the root access tokens. Token values are never returned after creation.', 401, 403, 429, 500)
224
229
  }
225
230
  },
226
231
 
@@ -267,8 +272,8 @@ async function init(args) {
267
272
  tags: ['api', 'Access Tokens'],
268
273
 
269
274
  plugins: {
270
- 'hapi-swagger': {
271
- responses: errorResponses(400, 401, 403, 429, 500)
275
+ openapi: {
276
+ responses: apiResponses('Returns the access tokens scoped to the account.', 400, 401, 403, 429, 500)
272
277
  }
273
278
  },
274
279
 
@@ -4,7 +4,7 @@ const Joi = require('joi');
4
4
  const { webhooks: Webhooks } = require('../webhooks');
5
5
  const { failAction } = require('../tools');
6
6
  const { handleError, throwNotFound } = require('./route-helpers');
7
- const { settingsSchema, errorResponses } = require('../schemas');
7
+ const { settingsSchema, apiResponses } = require('../schemas');
8
8
 
9
9
  const webhookErrorFlagSchema = Joi.object({
10
10
  message: Joi.string().example('Request failed with status 500').description('Error message from the last failed delivery')
@@ -39,8 +39,8 @@ async function init(args) {
39
39
  tags: ['api', 'Webhooks'],
40
40
 
41
41
  plugins: {
42
- 'hapi-swagger': {
43
- responses: errorResponses(400, 401, 403, 429, 500)
42
+ openapi: {
43
+ responses: apiResponses('Returns a page of custom webhook routes.', 400, 401, 403, 429, 500)
44
44
  }
45
45
  },
46
46
 
@@ -126,8 +126,8 @@ async function init(args) {
126
126
  tags: ['api', 'Webhooks'],
127
127
 
128
128
  plugins: {
129
- 'hapi-swagger': {
130
- responses: errorResponses(400, 401, 403, 404, 429, 500)
129
+ openapi: {
130
+ responses: apiResponses('Returns the webhook route, including its filter and transform functions.', 400, 401, 403, 404, 429, 500)
131
131
  }
132
132
  },
133
133
 
package/lib/consts.js CHANGED
@@ -104,6 +104,13 @@ module.exports = {
104
104
  // is a write-only credential, it can only be used to submit events.
105
105
  COMMUNITY_SENTRY_DSN: 'https://bdd958f3e813a488904b0f254e0bb8a8@sentry.emailengine.dev/3',
106
106
 
107
+ // OAuth2 application fields that are encrypted at rest and redacted in API responses. Every
108
+ // consumer must agree on the list: the writer (lib/oauth2-apps.js), the `emailengine encrypt`
109
+ // rotation tool (a field it skips stays readable only with the old secret) and the API
110
+ // read routes (a field they skip is returned as-is, which is cleartext on an instance with
111
+ // no service secret).
112
+ ENCRYPTED_APP_KEYS: ['clientSecret', 'serviceKey', 'accessToken', 'externalAccount'],
113
+
107
114
  PDKDF2_ITERATIONS: 600000,
108
115
  PDKDF2_SALT_SIZE: 16,
109
116
  PDKDF2_DIGEST: 'sha256', // 'sha512', 'sha256' or 'sha1'
@@ -49,7 +49,8 @@ const {
49
49
  readEnvValue,
50
50
  emitChangeEvent,
51
51
  filterEmptyObjectValues,
52
- getDateBuckets
52
+ getDateBuckets,
53
+ resolveCredentials
53
54
  } = require('../tools');
54
55
 
55
56
  // Import application constants
@@ -79,6 +80,25 @@ const MAX_IMAP_AUTH_FAILURE_TIME = getDuration(readEnvValue('EENGINE_MAX_IMAP_AU
79
80
  // Map to track pending idempotency operations to prevent duplicate processing
80
81
  const pendingIdempotencyOperations = new Map();
81
82
 
83
+ // Failing to reach a remote endpoint is a connection problem, not a rejected credential. Both
84
+ // OAuth2 credential sources (EmailEngine's own token refresh and an external authentication server)
85
+ // use this to avoid reporting an unreachable host as an authentication error, which would webhook
86
+ // and park every account on the instance over a brief outage.
87
+ const TRANSIENT_CONNECT_CODES = new Set([
88
+ 'ENOTFOUND',
89
+ 'ETIMEDOUT',
90
+ 'ECONNREFUSED',
91
+ 'ECONNRESET',
92
+ 'EAI_AGAIN',
93
+ 'UND_ERR_CONNECT_TIMEOUT',
94
+ 'UND_ERR_SOCKET',
95
+ 'UND_ERR_HEADERS_TIMEOUT'
96
+ ]);
97
+
98
+ function isTransientNetworkError(err) {
99
+ return !!err && TRANSIENT_CONNECT_CODES.has(err.code);
100
+ }
101
+
82
102
  /**
83
103
  * Check if an error is a transient error that should be retried
84
104
  * @param {Error} err - The error to check
@@ -558,6 +578,50 @@ class BaseClient {
558
578
  throw error;
559
579
  }
560
580
 
581
+ // An external authentication server owns this account's tokens, so EmailEngine must ask for
582
+ // one instead of renewing from a stored refresh token (it has none). The app is still
583
+ // resolved above, because the caller needs it for the provider's host and port.
584
+ if (accountData.oauth2.useAuthServer) {
585
+ try {
586
+ let authData = await resolveCredentials(accountObject.account, target);
587
+ // The auth server owns the credentials, but a shared mailbox is still addressed by
588
+ // the configured delegatedUser - same precedence as the stored-token path above.
589
+ return {
590
+ oauth2User: accountData.oauth2.auth.delegatedUser || authData.user,
591
+ accessToken: authData.accessToken,
592
+ oauth2App
593
+ };
594
+ } catch (err) {
595
+ // A transient failure to reach the auth server is a connection problem, not a
596
+ // rejected credential. Reporting it as an authentication error would webhook every
597
+ // account on the instance and park them in an error state over a brief blip.
598
+ if (isTransientNetworkError(err)) {
599
+ ctx.logger.error({
600
+ msg: 'Network error while resolving credentials from the authentication server',
601
+ account: accountObject.account,
602
+ target,
603
+ code: err.code,
604
+ err
605
+ });
606
+ throw err;
607
+ }
608
+
609
+ err.authenticationFailed = true;
610
+ await ctx.notify(false, AUTH_ERROR_NOTIFY, {
611
+ response: err.message,
612
+ serverResponseCode: 'HTTPRequestError'
613
+ });
614
+ ctx.logger.error({
615
+ msg: 'Failed to resolve OAuth2 credentials from the authentication server',
616
+ account: accountObject.account,
617
+ target,
618
+ err
619
+ });
620
+ ctx.state = AUTH_ERROR_NOTIFY;
621
+ throw err;
622
+ }
623
+ }
624
+
561
625
  // Check if token needs refresh (with 30 second buffer)
562
626
  if (!accountData.oauth2.accessToken || !accountData.oauth2.expires || accountData.oauth2.expires < new Date(now + 30 * 1000)) {
563
627
  // renew access token
@@ -569,17 +633,7 @@ class BaseClient {
569
633
  accessToken = accountData.oauth2.accessToken;
570
634
  } catch (err) {
571
635
  // Transient network errors are not authentication failures
572
- let isNetworkError =
573
- err.code === 'ENOTFOUND' ||
574
- err.code === 'ETIMEDOUT' ||
575
- err.code === 'ECONNREFUSED' ||
576
- err.code === 'ECONNRESET' ||
577
- err.code === 'EAI_AGAIN' ||
578
- err.code === 'UND_ERR_CONNECT_TIMEOUT' ||
579
- err.code === 'UND_ERR_SOCKET' ||
580
- err.code === 'UND_ERR_HEADERS_TIMEOUT';
581
-
582
- if (isNetworkError) {
636
+ if (isTransientNetworkError(err)) {
583
637
  ctx.logger.error({
584
638
  msg: 'Network error during OAuth2 token refresh',
585
639
  account: accountObject.account,
@@ -0,0 +1,130 @@
1
+ 'use strict';
2
+
3
+ const { ADDRESS_STRATEGIES } = require('./address-strategies');
4
+
5
+ // Per-value documentation for the enums whose values are not self-explanatory. Attached to
6
+ // the joi schemas below with `.meta({ enumDescriptions })`, which the OpenAPI generator emits
7
+ // as `x-meta.enumDescriptions` alongside the `enum` array - so the meaning of each value
8
+ // reaches /swagger.json and every consumer of it, not just the admin API reference.
9
+ //
10
+ // Only enums whose values carry real semantics are listed. Ones that already spell their
11
+ // values out in their own description (imapIndexer, textType, action) are left alone.
12
+ const ENUM_DESCRIPTIONS = {
13
+ // derived, so adding a strategy cannot leave the API reference behind
14
+ addressStrategy: Object.fromEntries(ADDRESS_STRATEGIES.map(entry => [entry.key, entry.description])),
15
+
16
+ accountState: {
17
+ init: 'The account was just registered and has not connected yet',
18
+ connecting: 'Connecting to the mail server or authorizing with the provider',
19
+ syncing: 'Connected and performing the initial or a periodic mailbox sync',
20
+ connected: 'Connected and watching for changes. This is the healthy steady state',
21
+ disconnected: 'The connection dropped and EmailEngine is retrying with backoff',
22
+ paused: 'Syncing was paused through the API. No connection is maintained',
23
+ authenticationError: 'The credentials were rejected. Requires re-authentication before syncing resumes',
24
+ connectError: 'The server could not be reached or the TLS handshake failed. Retried with backoff',
25
+ unset: 'No IMAP or OAuth2 configuration is set, so the account is not synced'
26
+ },
27
+
28
+ outboxStatus: {
29
+ queued: 'Accepted and waiting for a delivery attempt',
30
+ processing: 'A submit worker has picked the message up',
31
+ 'smtp-starting': 'Opening the SMTP connection to the destination',
32
+ 'smtp-completed': 'The SMTP transaction finished and the message was handed over',
33
+ submitted: 'Delivered to the receiving server. Later bounces arrive as webhooks',
34
+ error: 'Delivery failed. See the error field for the reason and whether it will be retried'
35
+ },
36
+
37
+ outboxSource: {
38
+ smtp: 'Submitted through the built-in SMTP server',
39
+ api: 'Submitted through the REST API',
40
+ test: 'Generated by a deliverability test',
41
+ ui: 'Sent from the admin interface'
42
+ },
43
+
44
+ exportStatus: {
45
+ queued: 'Accepted and waiting for an export worker',
46
+ processing: 'Currently reading messages from the account',
47
+ completed: 'Finished. The download endpoint now serves the archive',
48
+ failed: 'Stopped on an error. See the error field',
49
+ cancelled: 'Deleted through the API before it finished'
50
+ },
51
+
52
+ exportPhase: {
53
+ indexing: 'Listing the folders and counting the messages to export',
54
+ exporting: 'Writing messages to the export file',
55
+ complete: 'All messages have been written'
56
+ },
57
+
58
+ messageCategory: {
59
+ primary: 'The Primary inbox tab',
60
+ social: 'The Social tab (notifications from social networks)',
61
+ promotions: 'The Promotions tab (marketing mail)',
62
+ updates: 'The Updates tab (receipts, confirmations, statements)',
63
+ forums: 'The Forums tab (mailing lists and discussion groups)'
64
+ },
65
+
66
+ oauth2Provider: {
67
+ gmail: 'Gmail and Google Workspace, using a user-consented OAuth2 flow',
68
+ gmailService: 'Google Workspace using a service account, with no per-user consent screen',
69
+ outlook: 'Outlook and Microsoft 365, using a user-consented OAuth2 flow',
70
+ outlookService: 'Microsoft 365 using application permissions, with no per-user consent screen',
71
+ mailRu: 'Mail.ru'
72
+ },
73
+
74
+ azureCloud: {
75
+ global: 'The worldwide Azure cloud, used by most tenants',
76
+ 'gcc-high': 'US Government Community Cloud High',
77
+ dod: 'US Department of Defense cloud',
78
+ china: 'Azure operated by 21Vianet in China'
79
+ },
80
+
81
+ appBaseScopes: {
82
+ imap: 'Access mailboxes over IMAP and SMTP using OAuth2 credentials',
83
+ api: 'Access mailboxes through the provider API (Gmail API or MS Graph)',
84
+ pubsub: 'Receive Gmail push notifications through Google Pub/Sub'
85
+ },
86
+
87
+ tokenScope: {
88
+ api: 'Call the REST API',
89
+ smtp: 'Authenticate against the built-in SMTP submission server',
90
+ 'imap-proxy': 'Authenticate against the built-in IMAP proxy'
91
+ },
92
+
93
+ queueId: {
94
+ notify: 'Webhook delivery queue',
95
+ submit: 'Outbound email delivery queue',
96
+ documents: 'Document Store indexing queue (deprecated feature)'
97
+ },
98
+
99
+ pubsubState: {
100
+ creating: 'The subscription is being created',
101
+ created: 'Active and delivering notifications',
102
+ renewing: 'Being renewed before it expires',
103
+ error: 'Creation or renewal failed. See the error field'
104
+ },
105
+
106
+ dsnNotify: {
107
+ never: 'Never send a delivery status notification',
108
+ success: 'Notify when the message is delivered',
109
+ failure: 'Notify when the message cannot be delivered',
110
+ delay: 'Notify when the message is delayed'
111
+ },
112
+
113
+ messageUploadDisposition: {
114
+ inline: 'Rendered inside the message body, referenced by a cid: URL',
115
+ attachment: 'Offered as a downloadable file'
116
+ },
117
+
118
+ mailboxSpecialUse: {
119
+ '\\All': 'Contains every message in the account (Gmail "All Mail")',
120
+ '\\Archive': 'Archived messages',
121
+ '\\Drafts': 'Unsent drafts',
122
+ '\\Flagged': 'Messages the user flagged or starred',
123
+ '\\Junk': 'Spam',
124
+ '\\Sent': 'Sent messages',
125
+ '\\Trash': 'Deleted messages awaiting purge',
126
+ '\\Inbox': 'The inbox'
127
+ }
128
+ };
129
+
130
+ module.exports = { ENUM_DESCRIPTIONS };
@@ -107,7 +107,7 @@ async function metrics(logger, key, method, ...args) {
107
107
  }
108
108
  }
109
109
 
110
- const { ImapFlow } = require('imapflow');
110
+ const { createUpstreamClient } = require('./upstream-client');
111
111
  const { IMAPServer, imapHandler } = require('./imap-core/index.js');
112
112
  const { PassThrough } = require('stream');
113
113
 
@@ -153,6 +153,14 @@ class PassThroughLogger extends PassThrough {
153
153
  // without booting this worker. call() is injected for the Account instance.
154
154
  const authenticateImapProxy = createImapProxyAuthHandler({ call });
155
155
 
156
+ // Tag a credential-loading failure as an IMAP authentication rejection for the proxy client.
157
+ function failImapAuth(err) {
158
+ err.authenticationFailed = true;
159
+ err.serverResponseCode = 'AUTHENTICATIONFAILED';
160
+ err.responseStatus = 'NO';
161
+ return err;
162
+ }
163
+
156
164
  async function onAuth(auth, session) {
157
165
  let account = auth.username;
158
166
 
@@ -166,21 +174,27 @@ async function onAuth(auth, session) {
166
174
  let imapConnectionConfig;
167
175
  if (accountData.oauth2 && accountData.oauth2.auth) {
168
176
  // load OAuth2 tokens
169
- let now = Date.now();
170
- let accessToken;
171
- if (!accountData.oauth2.accessToken || !accountData.oauth2.expires || accountData.oauth2.expires < new Date(now + 30 * 1000)) {
172
- // renew access token
177
+ let imapAuth;
178
+
179
+ if (accountData.oauth2.useAuthServer) {
180
+ // An external authentication server owns this account's tokens, so ask it for one
181
+ // rather than renewing from a stored refresh token (there is none). The response is
182
+ // already in the { user, accessToken } shape the connection config expects.
173
183
  try {
174
- accountData = await accountObject.renewAccessToken();
175
- accessToken = accountData.oauth2.accessToken;
184
+ imapAuth = await resolveCredentials(account, 'imap');
176
185
  } catch (err) {
177
- err.authenticationFailed = true;
178
- err.serverResponseCode = 'AUTHENTICATIONFAILED';
179
- err.responseStatus = 'NO';
180
- throw err;
186
+ throw failImapAuth(err);
181
187
  }
182
188
  } else {
183
- accessToken = accountData.oauth2.accessToken;
189
+ if (!accountData.oauth2.accessToken || !accountData.oauth2.expires || accountData.oauth2.expires < new Date(Date.now() + 30 * 1000)) {
190
+ // renew access token
191
+ try {
192
+ accountData = await accountObject.renewAccessToken();
193
+ } catch (err) {
194
+ throw failImapAuth(err);
195
+ }
196
+ }
197
+ imapAuth = { user: accountData.oauth2.auth.user, accessToken: accountData.oauth2.accessToken };
184
198
  }
185
199
 
186
200
  const oauth2App = await oauth2Apps.get(accountData.oauth2.provider);
@@ -189,15 +203,7 @@ async function onAuth(auth, session) {
189
203
  }
190
204
  const providerData = oauth2ProviderData(oauth2App.provider, oauth2App.cloud);
191
205
 
192
- imapConnectionConfig = Object.assign(
193
- {
194
- auth: {
195
- user: accountData.oauth2.auth.user,
196
- accessToken
197
- }
198
- },
199
- providerData.imap || {}
200
- );
206
+ imapConnectionConfig = Object.assign({ auth: imapAuth }, providerData.imap || {});
201
207
  } else {
202
208
  // deep copy of imap settings
203
209
  imapConnectionConfig = JSON.parse(JSON.stringify(accountData.imap));
@@ -208,10 +214,7 @@ async function onAuth(auth, session) {
208
214
  try {
209
215
  imapConnectionConfig.auth = await resolveCredentials(account, 'imap');
210
216
  } catch (err) {
211
- err.authenticationFailed = true;
212
- err.serverResponseCode = 'AUTHENTICATIONFAILED';
213
- err.responseStatus = 'NO';
214
- throw err;
217
+ throw failImapAuth(err);
215
218
  }
216
219
  }
217
220
 
@@ -269,7 +272,8 @@ const createProxy = async (options = {}) => {
269
272
  imapConfig.tls.rejectUnauthorized = false;
270
273
  }
271
274
 
272
- let imapClient = new ImapFlow(imapConfig);
275
+ // Carries its own permanent error sink - see lib/imapproxy/upstream-client.js
276
+ let imapClient = createUpstreamClient(imapConfig);
273
277
 
274
278
  await imapClient.connect();
275
279
 
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+
3
+ const { ImapFlow } = require('imapflow');
4
+
5
+ /**
6
+ * Creates the upstream ImapFlow client of a proxied session with a permanent 'error' sink.
7
+ *
8
+ * ImapFlow reports connection failures with a bare `emit('error')`, so an instance left
9
+ * without an 'error' listener turns the next socket failure into an uncaughtException that
10
+ * takes the whole IMAP proxy worker down with it. Two windows are only covered by a sink
11
+ * attached here:
12
+ *
13
+ * - `connect()` resolving and `unbind()` detaching ImapFlow's socket handlers are separated
14
+ * by an await, and a reset landing in between has nowhere else to go. (While `connect()`
15
+ * is still pending ImapFlow rejects the promise instead of emitting, so that part is safe
16
+ * on its own.)
17
+ * - after the handoff the caller wires teardown onto the sockets rather than the client, and
18
+ * `close()` on an already-dead connection can still surface an error on the instance.
19
+ *
20
+ * The sink therefore has to live for as long as the client does - it is attached before
21
+ * `connect()` and never removed.
22
+ *
23
+ * @param {Object} imapConfig - ImapFlow options for the upstream connection
24
+ * @returns {ImapFlow} Client with an error sink attached
25
+ */
26
+ function createUpstreamClient(imapConfig) {
27
+ let imapClient = new ImapFlow(imapConfig);
28
+
29
+ // reads the id off the client so the sink does not keep the config (credentials
30
+ // included) alive through the closure for as long as the connection lives
31
+ imapClient.on('error', err => {
32
+ imapClient.log.warn({ msg: 'Upstream IMAP connection error', cid: imapClient.id, err });
33
+ });
34
+
35
+ return imapClient;
36
+ }
37
+
38
+ module.exports = { createUpstreamClient };
@@ -3,7 +3,13 @@
3
3
  const { redis } = require('./db');
4
4
  const msgpack = require('msgpack5')();
5
5
  const logger = require('./logger');
6
- const { REDIS_PREFIX, TRANSIENT_NETWORK_CODES, GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL, GMAIL_PUBSUB_ACK_DEADLINE_SECONDS } = require('./consts');
6
+ const {
7
+ REDIS_PREFIX,
8
+ TRANSIENT_NETWORK_CODES,
9
+ GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL,
10
+ GMAIL_PUBSUB_ACK_DEADLINE_SECONDS,
11
+ ENCRYPTED_APP_KEYS
12
+ } = require('./consts');
7
13
  const { encrypt, decrypt } = require('./encrypt');
8
14
  const Boom = require('@hapi/boom');
9
15
  const settings = require('./settings');
@@ -704,7 +710,7 @@ class OAuth2AppsHandler {
704
710
  const id = await this.generateId();
705
711
 
706
712
  let encryptedValues = {};
707
- for (let key of ['clientSecret', 'serviceKey', 'accessToken', 'externalAccount']) {
713
+ for (let key of ENCRYPTED_APP_KEYS) {
708
714
  if (data[key]) {
709
715
  encryptedValues[key] = await this.encrypt(data[key]);
710
716
  }
@@ -785,7 +791,7 @@ class OAuth2AppsHandler {
785
791
  let oldPubSubApp = existingData.pubSubApp || null;
786
792
 
787
793
  let encryptedValues = {};
788
- for (let key of ['clientSecret', 'serviceKey', 'accessToken', 'externalAccount']) {
794
+ for (let key of ENCRYPTED_APP_KEYS) {
789
795
  if (data[key]) {
790
796
  encryptedValues[key] = await this.encrypt(data[key]);
791
797
  }