emailengine-app 2.75.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 (113) hide show
  1. package/.github/workflows/release.yaml +24 -19
  2. package/.github/workflows/test.yml +0 -10
  3. package/.ncurc.js +14 -2
  4. package/.release-please-manifest.json +3 -0
  5. package/CHANGELOG.md +38 -0
  6. package/README.md +1 -1
  7. package/config/e2e.toml +1 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +71 -4
  10. package/lib/address-strategies.js +18 -0
  11. package/lib/api-reference/code-samples.js +194 -0
  12. package/lib/api-reference/format.js +179 -0
  13. package/lib/api-reference/index.js +205 -0
  14. package/lib/api-reference/model.js +336 -0
  15. package/lib/api-reference/schema-tree.js +366 -0
  16. package/lib/api-routes/account-routes.js +117 -37
  17. package/lib/api-routes/behavior-notes.js +54 -0
  18. package/lib/api-routes/blocklist-routes.js +9 -9
  19. package/lib/api-routes/changes-routes.js +6 -4
  20. package/lib/api-routes/chat-routes.js +3 -3
  21. package/lib/api-routes/delivery-test-routes.js +24 -6
  22. package/lib/api-routes/export-routes.js +14 -12
  23. package/lib/api-routes/gateway-routes.js +11 -11
  24. package/lib/api-routes/license-routes.js +7 -7
  25. package/lib/api-routes/mailbox-routes.js +18 -9
  26. package/lib/api-routes/message-routes.js +55 -35
  27. package/lib/api-routes/oauth2-app-routes.js +22 -16
  28. package/lib/api-routes/outbox-routes.js +7 -7
  29. package/lib/api-routes/pubsub-routes.js +3 -3
  30. package/lib/api-routes/route-helpers.js +3 -0
  31. package/lib/api-routes/settings-routes.js +10 -9
  32. package/lib/api-routes/stats-routes.js +3 -3
  33. package/lib/api-routes/submit-routes.js +213 -56
  34. package/lib/api-routes/template-routes.js +13 -13
  35. package/lib/api-routes/token-routes.js +15 -10
  36. package/lib/api-routes/webhook-route-routes.js +5 -5
  37. package/lib/consts.js +7 -0
  38. package/lib/email-client/base-client.js +230 -31
  39. package/lib/email-client/gmail/send-request.js +16 -1
  40. package/lib/email-client/gmail-client.js +89 -5
  41. package/lib/email-client/imap-client.js +103 -1
  42. package/lib/email-client/message-builder.js +24 -7
  43. package/lib/email-client/outlook/send-request.js +18 -1
  44. package/lib/email-client/outlook-client.js +79 -4
  45. package/lib/enum-descriptions.js +130 -0
  46. package/lib/imapproxy/imap-server.js +30 -26
  47. package/lib/imapproxy/upstream-client.js +38 -0
  48. package/lib/oauth2-apps.js +9 -3
  49. package/lib/openapi/build-document.js +318 -0
  50. package/lib/openapi/index.js +95 -0
  51. package/lib/openapi/joi-schema.js +523 -0
  52. package/lib/routes-ui.js +5 -1
  53. package/lib/schemas.js +76 -17
  54. package/lib/swagger-options.js +173 -0
  55. package/lib/tokens.js +69 -5
  56. package/lib/ui-routes/admin-entities-routes.js +3 -0
  57. package/lib/ui-routes/dashboard-routes.js +2 -26
  58. package/lib/ui-routes/reference-routes.js +195 -0
  59. package/lib/ui-routes/route-helpers.js +11 -0
  60. package/package.json +19 -26
  61. package/playwright.config.js +1 -1
  62. package/prepare-bundle-deps.sh +28 -0
  63. package/release-please-config.json +11 -0
  64. package/sbom.json +0 -1
  65. package/server.js +22 -2
  66. package/static/css/flyonui.css +1 -1
  67. package/static/css/src/app.tailwind.css +90 -0
  68. package/static/js/ee-client.js +238 -8
  69. package/static/js/reference.js +736 -0
  70. package/static/js/ui.js +61 -33
  71. package/static/licenses.html +16 -16
  72. package/translations/messages.pot +13 -13
  73. package/views/config/ai.hbs +1 -1
  74. package/views/config/document-store/chat.hbs +5 -5
  75. package/views/config/document-store/index.hbs +2 -2
  76. package/views/config/document-store/pre-processing/index.hbs +1 -1
  77. package/views/config/email-processing.hbs +1 -1
  78. package/views/config/imap-proxy.hbs +1 -1
  79. package/views/config/license.hbs +1 -1
  80. package/views/config/oauth/index.hbs +3 -3
  81. package/views/config/security.hbs +1 -1
  82. package/views/config/smtp.hbs +2 -2
  83. package/views/dashboard.hbs +1 -1
  84. package/views/layout/app.hbs +18 -7
  85. package/views/partials/oauth_form.hbs +4 -4
  86. package/views/partials/reference/anchor-link.hbs +20 -0
  87. package/views/partials/reference/disclosure.hbs +37 -0
  88. package/views/partials/reference/nav.hbs +93 -0
  89. package/views/partials/reference/operation.hbs +127 -0
  90. package/views/partials/reference/params.hbs +20 -0
  91. package/views/partials/reference/schema-node.hbs +99 -0
  92. package/views/partials/reference/schema.hbs +19 -0
  93. package/views/partials/reference/section-heading.hbs +16 -0
  94. package/views/partials/reference/token-alert.hbs +24 -0
  95. package/views/partials/reference/try-field.hbs +31 -0
  96. package/views/partials/reference/try-it.hbs +78 -0
  97. package/views/partials/side_menu.hbs +1 -1
  98. package/views/partials/ui/badge.hbs +4 -2
  99. package/views/partials/ui/page-header.hbs +1 -1
  100. package/views/partials/ui/search-input.hbs +31 -0
  101. package/views/partials/ui/setting-ref.hbs +1 -1
  102. package/views/partials/ui/stat-card.hbs +4 -2
  103. package/views/partials/ui/tab.hbs +6 -1
  104. package/views/partials/ui/tabs.hbs +2 -2
  105. package/views/reference/index.hbs +76 -0
  106. package/views/reference/redirect.hbs +49 -0
  107. package/views/reference/tag.hbs +28 -0
  108. package/views/reference/token.hbs +49 -0
  109. package/views/tokens/index.hbs +9 -1
  110. package/views/webhooks/index.hbs +3 -3
  111. package/workers/api.js +37 -215
  112. package/Gruntfile.js +0 -58
  113. package/views/swagger/index.hbs +0 -82
@@ -511,6 +511,27 @@ class SmtpErrorBuilder {
511
511
  * Determines whether to copy sent message to Sent folder
512
512
  */
513
513
  class SentMailCopyDecider {
514
+ /**
515
+ * Whether the provider files SMTP-submitted messages into the Sent Mail folder on its
516
+ * own. True for Gmail and for non-delegated Outlook when no gateway is used - both store
517
+ * the sent message themselves, so an upload would duplicate it. Emails for delegated
518
+ * Outlook accounts are still uploaded as the sender is different (SMTP is disabled for
519
+ * shared mailboxes, so the message is sent using the main account).
520
+ * @param {Object} options - Decision options
521
+ * @param {Object} options.accountData - Account data
522
+ * @param {boolean} options.isGmail - Whether account is Gmail
523
+ * @param {boolean} options.isOutlook - Whether account is Outlook
524
+ * @param {Object} options.gatewayData - Gateway data if using gateway
525
+ * @returns {boolean} Whether the provider stores the sent copy itself
526
+ */
527
+ static providerSavesSentCopy(options) {
528
+ const { accountData, isGmail, isOutlook, gatewayData } = options;
529
+
530
+ const skipIfOutlook = isOutlook && (!accountData.oauth2 || !accountData.oauth2.auth || !accountData.oauth2.auth.delegatedUser);
531
+
532
+ return Boolean((isGmail || skipIfOutlook) && !gatewayData);
533
+ }
534
+
514
535
  /**
515
536
  * Determines if sent mail should be copied to Sent folder
516
537
  * @param {Object} options - Decision options
@@ -522,7 +543,7 @@ class SentMailCopyDecider {
522
543
  * @returns {boolean} Whether to copy to Sent folder
523
544
  */
524
545
  static shouldCopy(options) {
525
- const { accountData, data, isGmail, isOutlook, gatewayData } = options;
546
+ const { accountData, data } = options;
526
547
 
527
548
  // The default is to copy message to Sent Mail folder
528
549
  let shouldCopy = !Object.prototype.hasOwnProperty.call(accountData, 'copy');
@@ -532,14 +553,10 @@ class SentMailCopyDecider {
532
553
  shouldCopy = accountData.copy;
533
554
  }
534
555
 
535
- // Suppress uploads for Gmail and Outlook
556
+ // Suppress uploads when the provider stores the sent copy itself.
536
557
  // Unfortunately, previous default schema for all added accounts was copy=true,
537
558
  // so can't prefer account specific setting here
538
- // Emails for delegated accounts will be uploaded as the sender is different.
539
- // SMTP is disabled for shared mailboxes, so we need to send using the main account.
540
- const skipIfOutlook = isOutlook && (!accountData.oauth2 || !accountData.oauth2.auth || !accountData.oauth2.auth.delegatedUser);
541
-
542
- if ((isGmail || skipIfOutlook) && !gatewayData) {
559
+ if (this.providerSavesSentCopy(options)) {
543
560
  shouldCopy = false;
544
561
  }
545
562
 
@@ -45,4 +45,21 @@ function buildStructuredSendMailRequest(messagePayload, oauth2UserPath) {
45
45
  };
46
46
  }
47
47
 
48
- module.exports = { buildRawSendMailRequest, buildStructuredSendMailRequest };
48
+ /**
49
+ * Builds the request that sends an existing draft message. Graph requires an empty body
50
+ * (Content-Length: 0), answers 202 Accepted, and files the message into Sent Items itself.
51
+ *
52
+ * @param {String} emailId - Graph message id of the draft
53
+ * @param {String} oauth2UserPath - Graph user path ("me" or "users/<id>")
54
+ * @returns {Object} { path, body, options } for OutlookOauth.request()
55
+ */
56
+ function buildDraftSendRequest(emailId, oauth2UserPath) {
57
+ return {
58
+ path: `/${oauth2UserPath}/messages/${emailId}/send`,
59
+ // An empty Buffer keeps the request body at Content-Length: 0
60
+ body: Buffer.alloc(0),
61
+ options: { returnText: true }
62
+ };
63
+ }
64
+
65
+ module.exports = { buildRawSendMailRequest, buildStructuredSendMailRequest, buildDraftSendRequest };
@@ -16,7 +16,7 @@ const { detectMimeType, detectExtension } = require('nodemailer/lib/mime-funcs/m
16
16
 
17
17
  // Import Graph API module for MS Graph API handling
18
18
  const graphApi = require('./outlook/graph-api');
19
- const { buildRawSendMailRequest, buildStructuredSendMailRequest } = require('./outlook/send-request');
19
+ const { buildRawSendMailRequest, buildStructuredSendMailRequest, buildDraftSendRequest } = require('./outlook/send-request');
20
20
 
21
21
  const {
22
22
  REDIS_PREFIX,
@@ -2379,6 +2379,50 @@ class OutlookClient extends BaseClient {
2379
2379
  * Send an email message
2380
2380
  * Can use either Graph API sendMail endpoint or fall back to SMTP
2381
2381
  */
2382
+ /**
2383
+ * Resolves a stored draft message for sending
2384
+ * Verifies that the message is a Graph draft and downloads its raw content
2385
+ * @param {string} emailId - Graph message id of the draft
2386
+ * @returns {Object} { raw: Buffer, draft: { message } }
2387
+ */
2388
+ async resolveDraftForSubmit(emailId) {
2389
+ await this.prepare();
2390
+
2391
+ // The draft check and the raw download have no data dependency, so run them in parallel
2392
+ let messageData;
2393
+ let raw;
2394
+ try {
2395
+ [messageData, raw] = await Promise.all([
2396
+ this.request(`/${this.oauth2UserPath}/messages/${emailId}`, 'get', { $select: 'id,isDraft' }),
2397
+ this.getRawMessage(emailId)
2398
+ ]);
2399
+ } catch (err) {
2400
+ if (err.oauthRequest?.status === 404 || err.code === 'NotFound') {
2401
+ let error = new Error('Requested message was not found');
2402
+ error.code = 'MessageNotFound';
2403
+ error.statusCode = 404;
2404
+ throw error;
2405
+ }
2406
+ throw err;
2407
+ }
2408
+
2409
+ if (!messageData?.isDraft) {
2410
+ let err = new Error('Requested message is not a draft');
2411
+ err.code = 'MessageNotDraft';
2412
+ err.statusCode = 400;
2413
+ throw err;
2414
+ }
2415
+
2416
+ if (!raw) {
2417
+ let err = new Error('Requested message was not found');
2418
+ err.code = 'MessageNotFound';
2419
+ err.statusCode = 404;
2420
+ throw err;
2421
+ }
2422
+
2423
+ return { raw, draft: { message: emailId } };
2424
+ }
2425
+
2382
2426
  async submitMessage(data) {
2383
2427
  await this.prepare();
2384
2428
 
@@ -2426,9 +2470,40 @@ class OutlookClient extends BaseClient {
2426
2470
  return false;
2427
2471
  }
2428
2472
 
2429
- // Check if structured format should be used (opt-in)
2430
- // Default is raw MIME to preserve backward compatibility and calendar invites
2431
- if (data.useStructuredFormat) {
2473
+ // Three delivery shapes: an existing draft is sent via /messages/{id}/send, otherwise
2474
+ // the message goes through /sendMail as raw MIME (default - preserves calendar invites
2475
+ // and special MIME types) or as a structured JSON message (opt-in - respects the from
2476
+ // field for shared mailboxes)
2477
+ if (data.draft) {
2478
+ // Send the existing draft message - Graph files it into Sent Items itself
2479
+ try {
2480
+ let sendRequest = buildDraftSendRequest(data.draft.message, this.oauth2UserPath);
2481
+ await this.request(sendRequest.path, 'post', sendRequest.body, sendRequest.options);
2482
+ } catch (err) {
2483
+ switch (err.oauthRequest?.status) {
2484
+ case 400:
2485
+ case 404: {
2486
+ // the draft is gone or not sendable - retrying would not help
2487
+ let error = new Error(err.oauthRequest.status === 404 ? 'Draft message was not found' : 'Draft message can not be sent');
2488
+ error.info = {
2489
+ response: err.oauthRequest?.response?.error?.message || error.message
2490
+ };
2491
+ error.code = err.oauthRequest?.response?.error?.code || 'MessageNotFound';
2492
+ error.statusCode = 500; // do not retry sending
2493
+ throw error;
2494
+ }
2495
+
2496
+ default:
2497
+ this.logger.error({
2498
+ msg: 'Failed to submit draft message',
2499
+ messageId,
2500
+ draft: data.draft.message,
2501
+ err
2502
+ });
2503
+ throw err;
2504
+ }
2505
+ }
2506
+ } else if (data.useStructuredFormat) {
2432
2507
  // Parse raw message into structured format to properly handle 'from' address
2433
2508
  // Microsoft Graph API ignores the From header in raw MIME messages and uses
2434
2509
  // the authenticated user's address instead. By parsing and sending as structured
@@ -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
  }