emailengine-app 2.79.7 → 2.79.9

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 (188) 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 +37 -0
  5. package/DOCKER_DEPLOYMENT.md +8 -7
  6. package/Dockerfile +35 -11
  7. package/bin/emailengine.js +29 -13
  8. package/config/default.toml +15 -4
  9. package/copy-static-files.sh +23 -5
  10. package/data/google-crawlers.json +7 -1
  11. package/docker-compose.yml +12 -3
  12. package/install.sh +2 -0
  13. package/lib/account.js +26 -1
  14. package/lib/api-routes/account-routes.js +14 -3
  15. package/lib/api-routes/bull-board-routes.js +3 -2
  16. package/lib/api-routes/mailbox-routes.js +4 -1
  17. package/lib/api-routes/message-routes.js +6 -5
  18. package/lib/api-routes/outbox-routes.js +7 -4
  19. package/lib/api-routes/route-helpers.js +8 -0
  20. package/lib/api-routes/settings-routes.js +34 -25
  21. package/lib/api-routes/stats-routes.js +8 -1
  22. package/lib/api-routes/submit-routes.js +2 -1
  23. package/lib/api-routes/template-routes.js +3 -2
  24. package/lib/auth-token.js +73 -2
  25. package/lib/autodetect-imap-settings.js +33 -25
  26. package/lib/bounce-detect.js +45 -0
  27. package/lib/consts.js +13 -2
  28. package/lib/egress-fetch.js +133 -0
  29. package/lib/egress-filter.js +39 -4
  30. package/lib/email-client/base-client.js +274 -24
  31. package/lib/email-client/gmail/gmail-api.js +15 -7
  32. package/lib/email-client/gmail-client.js +121 -64
  33. package/lib/email-client/imap/mailbox.js +18 -59
  34. package/lib/email-client/imap-client.js +53 -29
  35. package/lib/email-client/notification-handler.js +11 -2
  36. package/lib/email-client/outlook/graph-api.js +106 -90
  37. package/lib/email-client/outlook-client.js +222 -106
  38. package/lib/export.js +35 -2
  39. package/lib/generate-text-preview.js +10 -5
  40. package/lib/handlebars-helpers.js +129 -0
  41. package/lib/headers-rewriter.js +1 -1
  42. package/lib/imap-proxy-auth.js +41 -21
  43. package/lib/imapproxy/imap-core/README.md +1 -0
  44. package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
  45. package/lib/imapproxy/imap-server.js +9 -10
  46. package/lib/llm-pre-process.js +4 -1
  47. package/lib/mcp/json-schema.js +50 -2
  48. package/lib/openapi/index.js +3 -0
  49. package/lib/outbox.js +50 -8
  50. package/lib/pre-process.js +4 -1
  51. package/lib/rate-limit.js +23 -4
  52. package/lib/rewrite-text-nodes.js +12 -1
  53. package/lib/schemas.js +37 -8
  54. package/lib/security-headers.js +396 -0
  55. package/lib/sentry.js +36 -4
  56. package/lib/settings.js +19 -1
  57. package/lib/smtp-auth.js +86 -7
  58. package/lib/sso.js +13 -3
  59. package/lib/submit-progress.js +29 -0
  60. package/lib/templates.js +11 -0
  61. package/lib/tools.js +361 -173
  62. package/lib/ui-routes/account-routes.js +73 -13
  63. package/lib/ui-routes/admin-config-routes.js +7 -21
  64. package/lib/ui-routes/admin-entities-routes.js +42 -12
  65. package/lib/ui-routes/auth-routes.js +87 -28
  66. package/lib/ui-routes/dashboard-routes.js +1 -1
  67. package/lib/ui-routes/export-routes.js +4 -0
  68. package/lib/ui-routes/internals-routes.js +2 -0
  69. package/lib/ui-routes/mcp-consent-routes.js +12 -2
  70. package/lib/ui-routes/network-config-routes.js +6 -5
  71. package/lib/ui-routes/oauth-config-routes.js +12 -1
  72. package/lib/ui-routes/route-helpers.js +65 -14
  73. package/lib/ui-routes/settings-page.js +10 -0
  74. package/lib/ui-routes/smtp-test-routes.js +7 -0
  75. package/lib/ui-routes/suppression-list-routes.js +16 -5
  76. package/lib/ui-routes/unsubscribe-routes.js +22 -3
  77. package/lib/webhook-egress.js +5 -0
  78. package/lib/webhooks.js +14 -2
  79. package/package.json +23 -26
  80. package/sbom.json +1 -1
  81. package/server.js +100 -71
  82. package/static/css/flyonui.css +1 -1
  83. package/static/js/ace/css/ace.css +1462 -0
  84. package/static/js/ace/css/kuroir-1.png +0 -0
  85. package/static/js/ace/css/kuroir-2.png +0 -0
  86. package/static/js/ace/css/main-1.png +0 -0
  87. package/static/js/ace/css/main-10.svg +4 -0
  88. package/static/js/ace/css/main-11.svg +5 -0
  89. package/static/js/ace/css/main-12.svg +4 -0
  90. package/static/js/ace/css/main-13.png +0 -0
  91. package/static/js/ace/css/main-14.png +0 -0
  92. package/static/js/ace/css/main-15.png +0 -0
  93. package/static/js/ace/css/main-16.png +0 -0
  94. package/static/js/ace/css/main-17.png +0 -0
  95. package/static/js/ace/css/main-18.png +0 -0
  96. package/static/js/ace/css/main-19.png +0 -0
  97. package/static/js/ace/css/main-2.png +0 -0
  98. package/static/js/ace/css/main-20.png +0 -0
  99. package/static/js/ace/css/main-21.png +0 -0
  100. package/static/js/ace/css/main-22.png +0 -0
  101. package/static/js/ace/css/main-23.png +0 -0
  102. package/static/js/ace/css/main-24.png +0 -0
  103. package/static/js/ace/css/main-25.svg +1 -0
  104. package/static/js/ace/css/main-26.png +0 -0
  105. package/static/js/ace/css/main-3.png +0 -0
  106. package/static/js/ace/css/main-4.png +0 -0
  107. package/static/js/ace/css/main-5.svg +7 -0
  108. package/static/js/ace/css/main-6.svg +9 -0
  109. package/static/js/ace/css/main-7.svg +7 -0
  110. package/static/js/ace/css/main-8.svg +9 -0
  111. package/static/js/ace/css/main-9.svg +6 -0
  112. package/static/js/ace/css/theme/kuroir.css +78 -0
  113. package/static/js/ace/css/theme/tomorrow_night.css +128 -0
  114. package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
  115. package/static/js/ace/css/theme/xcode.css +106 -0
  116. package/static/js/ace/css/tomorrow_night-1.png +0 -0
  117. package/static/js/ace/css/tomorrow_night-2.png +0 -0
  118. package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
  119. package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
  120. package/static/js/ace/css/xcode-1.png +0 -0
  121. package/static/js/ace/css/xcode-2.png +0 -0
  122. package/static/js/ee-client.js +256 -102
  123. package/static/js/public.js +7 -0
  124. package/static/js/ui.js +32 -0
  125. package/static/licenses.html +338 -298
  126. package/static/vendor/simplewebauthn/browser.min.js +2 -2
  127. package/translations/messages.pot +158 -112
  128. package/views/account/passkeys.hbs +8 -0
  129. package/views/account/password.hbs +11 -0
  130. package/views/account/security.hbs +18 -7
  131. package/views/accounts/account.hbs +21 -38
  132. package/views/accounts/browse.hbs +3 -1
  133. package/views/accounts/edit.hbs +1 -1
  134. package/views/accounts/register/imap-server.hbs +11 -3
  135. package/views/config/ai.hbs +3 -1
  136. package/views/config/branding.hbs +4 -2
  137. package/views/config/document-store/chat.hbs +1 -1
  138. package/views/config/document-store/index.hbs +1 -1
  139. package/views/config/email-processing.hbs +2 -0
  140. package/views/config/imap-proxy.hbs +3 -1
  141. package/views/config/license.hbs +1 -1
  142. package/views/config/logging.hbs +3 -1
  143. package/views/config/mcp.hbs +3 -1
  144. package/views/config/network.hbs +16 -16
  145. package/views/config/oauth/app.hbs +4 -4
  146. package/views/config/security.hbs +2 -0
  147. package/views/config/service.hbs +3 -1
  148. package/views/config/smtp.hbs +3 -1
  149. package/views/config/webhooks.hbs +4 -2
  150. package/views/error.hbs +10 -2
  151. package/views/internals/index.hbs +1 -1
  152. package/views/layout/app.hbs +9 -14
  153. package/views/layout/login.hbs +1 -1
  154. package/views/layout/prompt.hbs +1 -1
  155. package/views/layout/public.hbs +1 -1
  156. package/views/legal.hbs +1 -1
  157. package/views/mcp/authorize.hbs +1 -1
  158. package/views/partials/ace_assets.hbs +13 -0
  159. package/views/partials/add_account_modal.hbs +1 -1
  160. package/views/partials/address_list.hbs +4 -4
  161. package/views/partials/filter_editor_js.hbs +3 -3
  162. package/views/partials/gateway_js.hbs +1 -1
  163. package/views/partials/oauth_form.hbs +6 -6
  164. package/views/partials/public_theme_init.hbs +1 -1
  165. package/views/partials/template_form.hbs +2 -2
  166. package/views/partials/test_send.hbs +7 -4
  167. package/views/partials/theme_init.hbs +1 -1
  168. package/views/partials/ui/details.hbs +2 -2
  169. package/views/partials/ui/env-managed-alert.hbs +19 -0
  170. package/views/partials/webhook_form.hbs +1 -1
  171. package/views/partials/webhooks_editor_functions.hbs +1 -1
  172. package/views/reference/redirect.hbs +1 -1
  173. package/views/templates/template.hbs +2 -2
  174. package/views/tokens/new.hbs +1 -1
  175. package/views/unsubscribe.hbs +7 -1
  176. package/views/webhooks/webhook.hbs +2 -2
  177. package/workers/api.js +179 -175
  178. package/workers/export.js +1 -5
  179. package/workers/imap.js +33 -6
  180. package/workers/smtp.js +19 -43
  181. package/workers/submit.js +31 -13
  182. package/workers/webhooks.js +9 -24
  183. package/lib/reconnection-manager.js +0 -106
  184. package/static/front/EmailEngine_logo_horiz.png +0 -0
  185. package/static/front/EmailEngine_logo_vert.png +0 -0
  186. package/static/front/index.html +0 -57
  187. package/static/front/logo.png +0 -0
  188. package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
@@ -1,3 +1,5 @@
1
+ /* eslint no-bitwise: 0 */
2
+
1
3
  'use strict';
2
4
 
3
5
  const net = require('net');
@@ -50,11 +52,44 @@ function normalizePolicy(value) {
50
52
  return VALID_POLICIES.has(policy) ? policy : POLICY_LINK_LOCAL;
51
53
  }
52
54
 
55
+ const ipv4FromHextets = (hi, lo) => new ipaddr.IPv4([hi >> 8, hi & 0xff, lo >> 8, lo & 0xff]);
56
+
57
+ /**
58
+ * Extracts the IPv4 address an IPv6 transition address carries, if it is one.
59
+ *
60
+ * It is the embedded address the policy has to judge: `::ffff:169.254.169.254` (IPv4-mapped),
61
+ * `64:ff9b::169.254.169.254` (NAT64) and `2002:a9fe:a9fe::1` (6to4) all lead to the metadata
62
+ * service while classifying as plain unicast or as a transition range the policy does not list.
63
+ * Unwrapping rather than blocking the ranges outright keeps a NAT64-only host working: there,
64
+ * every IPv4-only receiver resolves into 64:ff9b::/96.
65
+ *
66
+ * @param {Object} parsed - An ipaddr.js IPv6 address
67
+ * @returns {Object|null} The embedded ipaddr.js IPv4 address, or null for a native IPv6 address
68
+ */
69
+ function embeddedIPv4(parsed) {
70
+ if (parsed.isIPv4MappedAddress()) {
71
+ return parsed.toIPv4Address();
72
+ }
73
+
74
+ const parts = parsed.parts;
75
+ switch (parsed.range()) {
76
+ case 'rfc6052': // 64:ff9b::/96 and 64:ff9b:1::/48, NAT64: the IPv4 is the low 32 bits
77
+ case 'rfc6145': // ::ffff:0:0:0/96, IPv4-translated: same layout
78
+ return ipv4FromHextets(parts[6], parts[7]);
79
+ case '6to4': // 2002:AABB:CCDD::/48, the IPv4 follows the 16-bit prefix
80
+ return ipv4FromHextets(parts[1], parts[2]);
81
+ case 'teredo': // 2001::/32, the client's IPv4 is the low 32 bits, bit-inverted
82
+ return ipv4FromHextets(parts[6] ^ 0xffff, parts[7] ^ 0xffff);
83
+ default:
84
+ return null;
85
+ }
86
+ }
87
+
53
88
  /**
54
89
  * Checks a single IP address against an egress policy.
55
90
  *
56
- * IPv4-mapped IPv6 addresses are unwrapped first, otherwise `::ffff:169.254.169.254` would be
57
- * classified as a plain IPv6 unicast address and sail through.
91
+ * IPv6 transition addresses are unwrapped to the IPv4 address they carry first, see
92
+ * embeddedIPv4().
58
93
  *
59
94
  * @param {string} ip - IP address to classify
60
95
  * @param {string} policy - One of the POLICY_* constants
@@ -73,8 +108,8 @@ function isBlockedAddress(ip, policy) {
73
108
  return true;
74
109
  }
75
110
 
76
- if (parsed.kind() === 'ipv6' && parsed.isIPv4MappedAddress()) {
77
- parsed = parsed.toIPv4Address();
111
+ if (parsed.kind() === 'ipv6') {
112
+ parsed = embeddedIPv4(parsed) || parsed;
78
113
  }
79
114
 
80
115
  if (ALWAYS_BLOCKED_ADDRESSES.has(parsed.toNormalizedString())) {
@@ -6,6 +6,7 @@ const logger = require('../logger');
6
6
  const settings = require('../settings');
7
7
  const { isDocumentStoreEnabled } = require('../document-store');
8
8
  const msgpack = require('../msgpack');
9
+ const appendList = require('../append-list');
9
10
  const { templates } = require('../templates');
10
11
  const { Gateway } = require('../gateway');
11
12
  const os = require('os');
@@ -72,10 +73,12 @@ const {
72
73
  AUTH_FAILURE_DISABLED_FIELD,
73
74
  AUTH_FAILURE_DISABLED_DESCRIPTION,
74
75
  EMAIL_DELIVERY_ERROR_NOTIFY,
75
- EMAIL_SENT_NOTIFY
76
+ EMAIL_SENT_NOTIFY,
77
+ TRANSIENT_NETWORK_CODES
76
78
  } = require('../consts');
77
79
  const { buildRetentionPolicy } = require('../queue-retention');
78
80
  const { readImapData } = require('../account/imap-data');
81
+ const { ReconnectBackoff } = require('./reconnect-backoff');
79
82
 
80
83
  // Configure download chunk size from environment or use default
81
84
  const DOWNLOAD_CHUNK_SIZE = getByteSize(readEnvValue('EENGINE_CHUNK_SIZE')) || DEFAULT_DOWNLOAD_CHUNK_SIZE;
@@ -86,21 +89,6 @@ const MAX_IMAP_AUTH_FAILURE_TIME = getDuration(readEnvValue('EENGINE_MAX_IMAP_AU
86
89
  // Map to track pending idempotency operations to prevent duplicate processing
87
90
  const pendingIdempotencyOperations = new Map();
88
91
 
89
- // Failing to reach a remote endpoint is a connection problem, not a rejected credential. Both
90
- // OAuth2 credential sources (EmailEngine's own token refresh and an external authentication server)
91
- // use this to avoid reporting an unreachable host as an authentication error, which would webhook
92
- // and park every account on the instance over a brief outage.
93
- const TRANSIENT_CONNECT_CODES = new Set([
94
- 'ENOTFOUND',
95
- 'ETIMEDOUT',
96
- 'ECONNREFUSED',
97
- 'ECONNRESET',
98
- 'EAI_AGAIN',
99
- 'UND_ERR_CONNECT_TIMEOUT',
100
- 'UND_ERR_SOCKET',
101
- 'UND_ERR_HEADERS_TIMEOUT'
102
- ]);
103
-
104
92
  /**
105
93
  * Keeps only the address entries a message can actually be delivered to.
106
94
  *
@@ -186,8 +174,55 @@ function findReferencedCidAttachments(html, attachments) {
186
174
  return cidAttachments;
187
175
  }
188
176
 
177
+ /**
178
+ * A 401 that survives renewing the access token is the provider refusing the account's
179
+ * credential. Left as it is it reaches the API caller as a 401, which reads as their own
180
+ * EmailEngine token being rejected, so it is reported as a coded 403 the way a failed token
181
+ * renewal (OauthRenewError) is. The raw exchange stays on err.oauthRequest for the logs
182
+ * @param {Error} err - Error raised by the OAuth2 request layer
183
+ * @returns {Error} The same error, marked when it was a 401
184
+ */
185
+ function markRejectedAccessToken(err) {
186
+ if (err && err.oauthRequest && err.oauthRequest.status === 401) {
187
+ err.code = 'OAuthTokenRejected';
188
+ err.statusCode = 403;
189
+ }
190
+ return err;
191
+ }
192
+
193
+ /**
194
+ * A cached token the provider now rejects (revoked or invalidated on their side) is renewed
195
+ * so the caller can repeat the request once. A token fresh from the token endpoint is not
196
+ * renewed again - the rejection is then about the grant, not about a stale copy. Shared by
197
+ * the retry loops of the Gmail API and Graph transports
198
+ * @param {Object} context - Client the request was made for (logger, account, invalidateAccessToken)
199
+ * @param {Error} err - Error raised by the OAuth2 request layer
200
+ * @param {Object} tokenData - Token the failed request used ({ accessToken, cached })
201
+ * @param {boolean} tokenRenewed - Whether the request already renewed its token once
202
+ * @returns {Promise<boolean>} True when the token was invalidated and the request should be repeated
203
+ */
204
+ async function renewRejectedAccessToken(context, err, tokenData, tokenRenewed) {
205
+ if (err.oauthRequest?.status !== 401 || !tokenData.cached || tokenRenewed) {
206
+ return false;
207
+ }
208
+ context.logger.warn({ msg: 'Cached access token was rejected, renewing it', account: context.account });
209
+ await context.invalidateAccessToken();
210
+ return true;
211
+ }
212
+
213
+ /**
214
+ * Failing to reach a remote endpoint is a connection problem, not a rejected credential. Both
215
+ * OAuth2 credential sources (EmailEngine's own token refresh and an external authentication
216
+ * server) use this to avoid reporting an unreachable host as an authentication error, which
217
+ * would webhook and park every account on the instance over a brief outage, and the API
218
+ * transports use it to decide which failed requests to repeat. undici reports a connection
219
+ * failure as a generic TypeError ("fetch failed") with the real DNS/socket error attached as
220
+ * err.cause, so the code is looked up there as well
221
+ * @param {Error} err - The error to check
222
+ * @returns {boolean} True if the error is a transient network failure
223
+ */
189
224
  function isTransientNetworkError(err) {
190
- return !!err && TRANSIENT_CONNECT_CODES.has(err.code);
225
+ return !!err && (TRANSIENT_NETWORK_CODES.has(err.code) || (!!err.cause && TRANSIENT_NETWORK_CODES.has(err.cause.code)));
191
226
  }
192
227
 
193
228
  /**
@@ -297,6 +332,10 @@ class BaseClient {
297
332
  // Track sub-connections (e.g., for IMAP IDLE)
298
333
  this.subconnections = [];
299
334
 
335
+ // Set by the API clients: a failed init() is scheduled again by the worker through
336
+ // scheduleInitRetry(). IMAPClient reconnects with its own backoff instead
337
+ this.retriesInit = false;
338
+
300
339
  // Initialize notification handler for webhook and event delivery
301
340
  this.notificationHandler = new NotificationHandler({
302
341
  account: this.account,
@@ -340,6 +379,56 @@ class BaseClient {
340
379
  return false;
341
380
  }
342
381
 
382
+ /**
383
+ * Schedules another init() attempt after one failed on something other than a refused
384
+ * credential. IMAPClient.init() reconnects with its own backoff, but a Gmail API or Graph
385
+ * client whose token endpoint or profile request failed on the network used to stay
386
+ * 'connecting' until someone reconnected it by hand. The delay grows through a backoff
387
+ * that resetInitRetry() clears once an attempt succeeds, init()/close()/delete() cancel a
388
+ * pending attempt, and a client closed in the meantime is left alone when the timer fires.
389
+ * The timer never keeps the worker alive on its own
390
+ * @param {Function} retry - Runs the next attempt
391
+ */
392
+ scheduleInitRetry(retry) {
393
+ if (this.closed) {
394
+ return;
395
+ }
396
+
397
+ this.initRetryBackoff = this.initRetryBackoff || new ReconnectBackoff({ baseDelay: 2000, maxDelay: 30000, jitter: 1000 });
398
+ const delay = this.initRetryBackoff.nextDelay();
399
+ this.logger.info({
400
+ msg: 'Scheduling account initialization retry',
401
+ account: this.account,
402
+ delay: Math.round(delay),
403
+ attempt: this.initRetryBackoff.attempts
404
+ });
405
+
406
+ clearTimeout(this.initRetryTimer);
407
+ this.initRetryTimer = setTimeout(() => {
408
+ if (this.closed) {
409
+ return;
410
+ }
411
+ retry();
412
+ }, delay);
413
+ this.initRetryTimer.unref();
414
+ }
415
+
416
+ /**
417
+ * Drops a pending init() retry, if any
418
+ */
419
+ cancelInitRetry() {
420
+ clearTimeout(this.initRetryTimer);
421
+ }
422
+
423
+ /**
424
+ * Starts the retry delays over after init() succeeded
425
+ */
426
+ resetInitRetry() {
427
+ if (this.initRetryBackoff) {
428
+ this.initRetryBackoff.reset();
429
+ }
430
+ }
431
+
343
432
  /**
344
433
  * Generates a random 20-character ID for connection tracking
345
434
  * @returns {string} Random ID string
@@ -399,6 +488,136 @@ class BaseClient {
399
488
  return `${REDIS_PREFIX}iar:s:${this.account}`;
400
489
  }
401
490
 
491
+ /**
492
+ * Redis hash holding the bounces detected for this account, keyed by the Message-ID of
493
+ * the message that bounced. Filled by the new-message processors of every client type
494
+ * and read back into the `bounces` field of the message details response
495
+ */
496
+ getBounceKey() {
497
+ return `${REDIS_PREFIX}iar:b:${this.account}`;
498
+ }
499
+
500
+ /**
501
+ * Records a detected bounce against the Message-ID of the message that bounced
502
+ * @param {string} bounceMessageId - EmailEngine id of the bounce message itself
503
+ * @param {Object} bounce - Parsed bounce (recipient, action, messageId, response)
504
+ * @returns {Promise<number|boolean>} appendList.append() result
505
+ */
506
+ async storeBounce(bounceMessageId, bounce) {
507
+ let storedBounce = {
508
+ i: bounceMessageId,
509
+ r: bounce.recipient,
510
+ t: Date.now(),
511
+ a: bounce.action
512
+ };
513
+
514
+ if (bounce.response && bounce.response.message) {
515
+ storedBounce.m = bounce.response.message;
516
+ }
517
+
518
+ if (bounce.response && bounce.response.status) {
519
+ storedBounce.s = bounce.response.status;
520
+ }
521
+
522
+ return await appendList.append(this.redis, this.getBounceKey(), bounce.messageId, storedBounce);
523
+ }
524
+
525
+ /**
526
+ * Lists the bounces recorded for a Message-ID in the shape of the `bounces` response field
527
+ * @param {string} messageId - Message-ID header value of the sent message
528
+ * @returns {Promise<Object[]>} Bounce entries, empty when none were recorded
529
+ */
530
+ async listBounces(messageId) {
531
+ let rows = await appendList.list(this.redis, this.getBounceKey(), messageId);
532
+ return rows.map(row => {
533
+ let bounce = {
534
+ message: row.i,
535
+ recipient: row.r,
536
+ action: row.a
537
+ };
538
+ if (row.m || row.s) {
539
+ bounce.response = {};
540
+ }
541
+ if (row.m) {
542
+ bounce.response.message = row.m;
543
+ }
544
+ if (row.s) {
545
+ bounce.response.status = row.s;
546
+ }
547
+ bounce.date = new Date(row.t).toISOString();
548
+ return bounce;
549
+ });
550
+ }
551
+
552
+ /**
553
+ * Adds the recorded bounces to a formatted message, when there are any. A lookup failure
554
+ * is logged and leaves the message without the field rather than failing the fetch
555
+ * @param {Object} messageData - Formatted message (needs `messageId`), updated in place
556
+ */
557
+ async attachBounces(messageData) {
558
+ if (!messageData || !messageData.messageId) {
559
+ return;
560
+ }
561
+ try {
562
+ let bounces = await this.listBounces(messageData.messageId);
563
+ if (bounces.length) {
564
+ messageData.bounces = bounces;
565
+ }
566
+ } catch (err) {
567
+ this.logger.error({
568
+ msg: 'Failed to fetch bounces',
569
+ id: messageData.id,
570
+ uid: messageData.uid,
571
+ messageId: messageData.messageId,
572
+ err
573
+ });
574
+ }
575
+ }
576
+
577
+ /**
578
+ * Decodes a base64url msgpack identifier the API clients hand out for text and
579
+ * attachment references. A truncated or foreign value used to surface as a RangeError,
580
+ * or as a TypeError from destructuring a non-array, which the API reported as a 500
581
+ * @param {string} encoded - Identifier from the request
582
+ * @param {Function} isValid - Receives the decoded array, returns whether it has the expected shape
583
+ * @returns {Array} Decoded parts
584
+ */
585
+ unpackApiId(encoded, isValid) {
586
+ let parts;
587
+ try {
588
+ parts = msgpack.decode(Buffer.from((encoded || '').toString(), 'base64url'));
589
+ } catch (err) {
590
+ parts = null;
591
+ }
592
+
593
+ if (!Array.isArray(parts) || !isValid(parts)) {
594
+ let error = new Error('Invalid identifier');
595
+ error.info = {
596
+ response: 'The provided identifier can not be decoded'
597
+ };
598
+ error.code = 'InvalidId';
599
+ error.statusCode = 400;
600
+ throw error;
601
+ }
602
+
603
+ return parts;
604
+ }
605
+
606
+ /**
607
+ * Builds the canonical 404 error for a mailbox path that does not exist on the account
608
+ * @param {string} path - Requested mailbox path
609
+ * @returns {Error} Error object with code and statusCode set
610
+ */
611
+ unknownPathError(path) {
612
+ let error = new Error('Unknown path');
613
+ error.info = {
614
+ response: `Mailbox doesn't exist: ${path}`
615
+ };
616
+ error.code = 'NotFound';
617
+ error.statusCode = 404;
618
+ return error;
619
+ }
620
+
402
621
  getLogKey() {
403
622
  // this format ensures that the key is deleted when user is removed
404
623
  return `${REDIS_PREFIX}iam:${this.account}:g`;
@@ -882,6 +1101,23 @@ class BaseClient {
882
1101
  return { oauth2User, accessToken, oauth2App };
883
1102
  }
884
1103
 
1104
+ /**
1105
+ * Resolves the current access token through the subclass getTokenData()
1106
+ * @returns {Promise<string>} Access token
1107
+ */
1108
+ async getToken() {
1109
+ return (await this.getTokenData()).accessToken;
1110
+ }
1111
+
1112
+ /**
1113
+ * Expires the stored access token so the next getToken() renews it. Used when the
1114
+ * provider rejects a token that is still within its recorded lifetime. A delegated
1115
+ * (shared mailbox) account holds the credential, so the token is expired there
1116
+ */
1117
+ async invalidateAccessToken() {
1118
+ await (this.delegatedAccountObject || this.accountObject).invalidateAccessToken();
1119
+ }
1120
+
885
1121
  /**
886
1122
  * Resolves delegated account chain for OAuth2 authentication
887
1123
  * Follows delegation chain up to 20 hops, detecting loops
@@ -1413,7 +1649,7 @@ class BaseClient {
1413
1649
  // Permanent 404 error - respect ignoreMissing
1414
1650
  if (!data.reference.ignoreMissing) {
1415
1651
  let error = new Error('Referenced message was not found');
1416
- error.code = 'MessageNotFound';
1652
+ error.code = 'ReferenceNotFound';
1417
1653
  error.statusCode = 404;
1418
1654
  throw error;
1419
1655
  }
@@ -1427,7 +1663,7 @@ class BaseClient {
1427
1663
 
1428
1664
  if (!referencedMessage && !data.reference.ignoreMissing) {
1429
1665
  let err = new Error('Referenced message was not found');
1430
- err.code = 'MessageNotFound';
1666
+ err.code = 'ReferenceNotFound';
1431
1667
  err.statusCode = 404;
1432
1668
  throw err;
1433
1669
  }
@@ -2629,7 +2865,11 @@ class BaseClient {
2629
2865
  }
2630
2866
  }
2631
2867
 
2868
+ let stored = 0;
2632
2869
  if (bounce.action && bounce.recipient && bounce.messageId) {
2870
+ // Record it for the `bounces` field of the bounced message, as the IMAP path does
2871
+ stored = await this.storeBounce(messageData.id, bounce);
2872
+
2633
2873
  bounceNotifyInfo = Object.assign({ bounceMessage: messageData.id }, bounce);
2634
2874
 
2635
2875
  messageData.isBounce = true;
@@ -2641,7 +2881,8 @@ class BaseClient {
2641
2881
  id: messageData.id,
2642
2882
  uid: messageData.uid,
2643
2883
  messageId: messageData.messageId,
2644
- bounce
2884
+ bounce,
2885
+ stored
2645
2886
  });
2646
2887
  }
2647
2888
  } catch (err) {
@@ -3481,10 +3722,12 @@ class BaseClient {
3481
3722
  })
3482
3723
  );
3483
3724
 
3484
- // Enhance error with additional context
3725
+ // Enhance error with additional context. The API clients report their send failures
3726
+ // through here as well, and those arrive with a statusCode and info of their own that
3727
+ // must survive - only an SMTP reply code overrides the status
3485
3728
  err.code = err.code || 'SubmitFail';
3486
- err.statusCode = Number(err.responseCode) || null;
3487
- err.info = { networkRouting };
3729
+ err.statusCode = Number(err.responseCode) || err.statusCode || null;
3730
+ err.info = Object.assign({}, err.info, { networkRouting });
3488
3731
  }
3489
3732
 
3490
3733
  // stub - to be implemented by subclasses
@@ -3496,4 +3739,11 @@ class BaseClient {
3496
3739
  // Re-export postMetrics from notification-handler for backward compatibility
3497
3740
  // applyReferenceRecipients is exported for tests: the methods that call it need a live
3498
3741
  // account, a connection and a referenced message fetched from the server
3499
- module.exports = { BaseClient, metricsMeta: postMetrics, applyReferenceRecipients };
3742
+ module.exports = {
3743
+ BaseClient,
3744
+ metricsMeta: postMetrics,
3745
+ applyReferenceRecipients,
3746
+ isTransientNetworkError,
3747
+ markRejectedAccessToken,
3748
+ renewRejectedAccessToken
3749
+ };
@@ -1,7 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const { metricsMeta } = require('../base-client');
4
- const { TRANSIENT_NETWORK_CODES } = require('../../consts');
3
+ const { metricsMeta, markRejectedAccessToken, renewRejectedAccessToken, isTransientNetworkError } = require('../base-client');
5
4
 
6
5
  // Gmail API configuration
7
6
  const GMAIL_API_BASE = 'https://gmail.googleapis.com';
@@ -89,12 +88,13 @@ function calculateRetryDelay(err, attempt) {
89
88
  async function request(context, url, method, payload, options = {}) {
90
89
  const maxRetries = options.maxRetries ?? MAX_RETRY_ATTEMPTS;
91
90
  let lastError;
91
+ let tokenRenewed = false;
92
92
 
93
93
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
94
- let result, accessToken;
94
+ let result, tokenData;
95
95
 
96
96
  try {
97
- accessToken = await context.getToken();
97
+ tokenData = await context.getTokenData();
98
98
  } catch (err) {
99
99
  context.logger.error({ msg: 'Failed to load access token', account: context.account, err });
100
100
  throw err;
@@ -105,7 +105,7 @@ async function request(context, url, method, payload, options = {}) {
105
105
  await context.getClient();
106
106
  }
107
107
 
108
- result = await context.oAuth2Client.request(accessToken, url, method, payload, options);
108
+ result = await context.oAuth2Client.request(tokenData.accessToken, url, method, payload, options);
109
109
 
110
110
  // Track successful API request
111
111
  metricsMeta({ account: context.account }, context.logger, 'oauth2ApiRequest', 'inc', {
@@ -118,8 +118,16 @@ async function request(context, url, method, payload, options = {}) {
118
118
  } catch (err) {
119
119
  lastError = err;
120
120
 
121
+ // A rejected cached token is renewed and the request repeated once, see
122
+ // renewRejectedAccessToken()
123
+ if (await renewRejectedAccessToken(context, err, tokenData, tokenRenewed)) {
124
+ tokenRenewed = true;
125
+ attempt -= 1;
126
+ continue;
127
+ }
128
+
121
129
  // Check if this is a transient network error
122
- if (TRANSIENT_NETWORK_CODES.has(err.code) && attempt < maxRetries) {
130
+ if (isTransientNetworkError(err) && attempt < maxRetries) {
123
131
  const delay = RETRY_BASE_DELAY * Math.pow(2, attempt) + Math.random() * 500;
124
132
 
125
133
  context.logger.warn({
@@ -183,7 +191,7 @@ async function request(context, url, method, payload, options = {}) {
183
191
  statusCode
184
192
  });
185
193
 
186
- throw err;
194
+ throw markRejectedAccessToken(err);
187
195
  }
188
196
  }
189
197