emailengine-app 2.81.2 → 2.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/.ncurc.js +12 -11
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/Dockerfile +2 -0
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/expected-identity.js +1 -1
  13. package/lib/account-assignment.js +138 -1
  14. package/lib/account.js +254 -859
  15. package/lib/api-reference/index.js +2 -3
  16. package/lib/api-reference/schema-tree.js +53 -3
  17. package/lib/api-routes/account-routes.js +18 -29
  18. package/lib/api-routes/blocklist-routes.js +2 -2
  19. package/lib/api-routes/bull-board-routes.js +1 -6
  20. package/lib/api-routes/export-routes.js +2 -22
  21. package/lib/api-routes/gateway-routes.js +5 -14
  22. package/lib/api-routes/index.js +1 -13
  23. package/lib/api-routes/mailbox-routes.js +2 -7
  24. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  25. package/lib/api-routes/mcp-routes.js +7 -7
  26. package/lib/api-routes/message-routes.js +40 -235
  27. package/lib/api-routes/mint-bounds.js +110 -0
  28. package/lib/api-routes/oauth2-app-routes.js +23 -32
  29. package/lib/api-routes/operation-impact.js +1 -1
  30. package/lib/api-routes/outbox-routes.js +2 -2
  31. package/lib/api-routes/permission-map.js +1 -7
  32. package/lib/api-routes/route-helpers.js +11 -5
  33. package/lib/api-routes/settings-routes.js +19 -19
  34. package/lib/api-routes/stats-routes.js +1 -1
  35. package/lib/api-routes/submit-routes.js +17 -18
  36. package/lib/api-routes/template-routes.js +4 -9
  37. package/lib/api-routes/token-routes.js +27 -5
  38. package/lib/api-token-scheme.js +71 -0
  39. package/lib/arf-detect.js +33 -6
  40. package/lib/auth-token.js +44 -24
  41. package/lib/autodetect-imap-settings.js +163 -123
  42. package/lib/bounce-detect.js +25 -16
  43. package/lib/calendar-event.js +78 -0
  44. package/lib/consts.js +42 -5
  45. package/lib/create-imap-client.js +24 -0
  46. package/lib/db.js +76 -11
  47. package/lib/delivery-error.js +2 -1
  48. package/lib/egress-fetch.js +54 -3
  49. package/lib/egress-filter.js +11 -0
  50. package/lib/email-client/api-retry.js +147 -0
  51. package/lib/email-client/base-client.js +377 -523
  52. package/lib/email-client/gmail/gmail-api.js +38 -125
  53. package/lib/email-client/gmail/send-request.js +1 -1
  54. package/lib/email-client/gmail-client.js +76 -50
  55. package/lib/email-client/imap/mailbox.js +158 -324
  56. package/lib/email-client/imap/stale-view.js +109 -0
  57. package/lib/email-client/imap/subconnection.js +46 -9
  58. package/lib/email-client/imap/sync-operations.js +5 -37
  59. package/lib/email-client/imap-client.js +188 -64
  60. package/lib/email-client/message-builder.js +9 -14
  61. package/lib/email-client/notification-handler.js +5 -219
  62. package/lib/email-client/outlook/graph-api.js +147 -126
  63. package/lib/email-client/outlook/send-request.js +10 -4
  64. package/lib/email-client/outlook-client.js +194 -397
  65. package/lib/email-client/smtp-pool-manager.js +3 -2
  66. package/lib/encrypt.js +184 -19
  67. package/lib/enum-descriptions.js +1 -2
  68. package/lib/export.js +133 -39
  69. package/lib/gateway.js +20 -6
  70. package/lib/get-raw-email.js +26 -44
  71. package/lib/handlebars-helpers.js +31 -10
  72. package/lib/imap-proxy-auth.js +13 -29
  73. package/lib/imapproxy/imap-core/README.md +1 -0
  74. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  75. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  76. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  77. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  78. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  79. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  80. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  81. package/lib/imapproxy/imap-server.js +17 -177
  82. package/lib/imapproxy/proxy-handoff.js +235 -0
  83. package/lib/imapproxy/response-error.js +33 -0
  84. package/lib/imapproxy/upstream-client.js +2 -2
  85. package/lib/license-beacon.js +3 -9
  86. package/lib/llm-pre-process.js +182 -43
  87. package/lib/logger.js +1 -1
  88. package/lib/lua/ee-export-queue-add.lua +39 -0
  89. package/lib/lua/ee-get-idempotency.lua +15 -3
  90. package/lib/lua/ee-release-attempts.lua +23 -0
  91. package/lib/lua/ee-reserve-attempts.lua +42 -0
  92. package/lib/lua/h-set-bigger.lua +12 -2
  93. package/lib/lua/s-list-accounts.lua +6 -3
  94. package/lib/mcp/index.js +1 -2
  95. package/lib/mcp/listen.js +221 -18
  96. package/lib/mcp/oauth.js +44 -5
  97. package/lib/mcp/resources.js +8 -2
  98. package/lib/mcp/tools.js +13 -0
  99. package/lib/message-port-stream.js +64 -6
  100. package/lib/oauth/external-account-signer.js +16 -13
  101. package/lib/oauth/gmail.js +22 -20
  102. package/lib/oauth/outlook.js +19 -16
  103. package/lib/oauth/pubsub/google.js +38 -2
  104. package/lib/oauth/scope-checker.js +4 -7
  105. package/lib/oauth/verify-app.js +2 -2
  106. package/lib/oauth2-apps.js +139 -44
  107. package/lib/openapi/build-document.js +1 -1
  108. package/lib/openapi/joi-schema.js +78 -9
  109. package/lib/parse-message.js +21 -0
  110. package/lib/payload-examples-webhooks.json +4 -7
  111. package/lib/pbkdf2-phc.js +101 -0
  112. package/lib/privileged-settings.js +0 -14
  113. package/lib/rate-limit.js +54 -15
  114. package/lib/redis-scan-delete.js +56 -29
  115. package/lib/redis-url.js +3 -1
  116. package/lib/respawn-backoff.js +5 -4
  117. package/lib/response-stream.js +25 -4
  118. package/lib/rewrite-text-nodes.js +27 -40
  119. package/lib/routes-ui.js +0 -5
  120. package/lib/schemas.js +122 -242
  121. package/lib/sentry.js +21 -5
  122. package/lib/settings.js +58 -59
  123. package/lib/smtp-auth.js +6 -2
  124. package/lib/smtp-message-processor.js +28 -7
  125. package/lib/sso.js +7 -3
  126. package/lib/stream-encrypt.js +14 -13
  127. package/lib/swagger-options.js +3 -1
  128. package/lib/tls/provision.js +69 -3
  129. package/lib/tls/store.js +14 -1
  130. package/lib/tools.js +113 -52
  131. package/lib/totp.js +16 -1
  132. package/lib/ui-routes/account-routes.js +27 -63
  133. package/lib/ui-routes/admin-config-routes.js +111 -134
  134. package/lib/ui-routes/admin-entities-routes.js +101 -191
  135. package/lib/ui-routes/ai-options.js +104 -0
  136. package/lib/ui-routes/auth-routes.js +98 -18
  137. package/lib/ui-routes/export-routes.js +3 -23
  138. package/lib/ui-routes/internals-routes.js +12 -9
  139. package/lib/ui-routes/network-config-routes.js +8 -18
  140. package/lib/ui-routes/oauth-config-routes.js +80 -214
  141. package/lib/ui-routes/route-helpers.js +40 -44
  142. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  143. package/lib/utils/decode-headers.js +32 -5
  144. package/lib/utils/header-map.js +62 -1
  145. package/lib/utils/network.js +2 -0
  146. package/lib/web-safe-html.js +77 -4
  147. package/lib/webhook-request.js +9 -1
  148. package/lib/webhook-routing.js +27 -1
  149. package/lib/webhooks.js +120 -43
  150. package/lib/worker-rpc-error.js +43 -2
  151. package/list-generate.js +13 -2
  152. package/package.json +33 -41
  153. package/sbom.json +1 -1
  154. package/scripts/refresh-test-tokens.js +42 -14
  155. package/server.js +317 -289
  156. package/static/css/flyonui.css +1 -1
  157. package/static/css/src/app.tailwind.css +7 -8
  158. package/static/js/ee-client.js +145 -70
  159. package/static/js/ui.js +350 -154
  160. package/static/licenses.html +434 -1835
  161. package/translations/messages.pot +97 -97
  162. package/views/accounts/browse.hbs +10 -4
  163. package/views/config/ai.hbs +49 -41
  164. package/views/config/oauth/app.hbs +2 -1
  165. package/views/dashboard.hbs +18 -16
  166. package/views/layout/app.hbs +0 -22
  167. package/views/layout/login.hbs +2 -1
  168. package/views/partials/filter_editor_js.hbs +4 -3
  169. package/views/partials/side_menu.hbs +0 -4
  170. package/views/partials/ui/account-picker.hbs +6 -32
  171. package/views/partials/ui/model-picker.hbs +31 -0
  172. package/views/partials/ui/pagination.hbs +6 -1
  173. package/views/partials/ui/picker.hbs +47 -0
  174. package/views/unsubscribe.hbs +1 -1
  175. package/workers/api.js +20 -20
  176. package/workers/export.js +55 -60
  177. package/workers/imap.js +126 -46
  178. package/workers/submit.js +3 -1
  179. package/workers/webhooks.js +46 -27
  180. package/.githooks/pre-commit +0 -80
  181. package/.github/CODE_OF_CONDUCT.md +0 -76
  182. package/.github/contributing.md +0 -17
  183. package/.github/dependabot.yml +0 -22
  184. package/.github/docker-smoke-test.sh +0 -61
  185. package/.github/workflows/deploy.yml +0 -215
  186. package/.github/workflows/e2e.yml +0 -55
  187. package/.github/workflows/release.yaml +0 -217
  188. package/.github/workflows/test.yml +0 -307
  189. package/lib/api-routes/chat-routes.js +0 -535
  190. package/lib/document-store.js +0 -75
  191. package/lib/es.js +0 -757
  192. package/lib/generate-text-preview.js +0 -61
  193. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  194. package/lib/pre-process.js +0 -196
  195. package/lib/threads.js +0 -155
  196. package/lib/ui-routes/document-store-routes.js +0 -806
  197. package/playwright.config.js +0 -47
  198. package/views/config/document-store/chat.hbs +0 -286
  199. package/views/config/document-store/index.hbs +0 -146
  200. package/views/config/document-store/mappings/index.hbs +0 -108
  201. package/views/config/document-store/mappings/new.hbs +0 -68
  202. package/views/config/document-store/pre-processing/index.hbs +0 -103
  203. package/views/partials/document_store_header.hbs +0 -30
  204. package/workers/documents.js +0 -1128
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { metricsMeta, markRejectedAccessToken, renewRejectedAccessToken } = require('../base-client');
4
- const { isTransientNetworkError } = require('../credential-errors');
4
+ const apiRetry = require('../api-retry');
5
5
 
6
6
  // Gmail API configuration
7
7
  const GMAIL_API_BASE = 'https://gmail.googleapis.com';
@@ -9,44 +9,12 @@ const GMAIL_API_BASE = 'https://gmail.googleapis.com';
9
9
  // Maximum concurrent listing requests
10
10
  const LIST_BATCH_SIZE = 10;
11
11
 
12
- // Rate limiting configuration
13
- const MAX_RETRY_ATTEMPTS = 3;
14
- const RETRY_BASE_DELAY = 1000; // 1 second base delay
15
-
16
- // Gmail API error code mapping to internal error codes
17
- // https://developers.google.com/gmail/api/reference/rest#error-codes
18
- const GMAIL_ERROR_MAP = {
19
- INVALID_ARGUMENT: { code: 'InvalidArgument', status: 400 },
20
- FAILED_PRECONDITION: { code: 'FailedPrecondition', status: 400 },
21
- NOT_FOUND: { code: 'NotFound', status: 404 },
22
- PERMISSION_DENIED: { code: 'PermissionDenied', status: 403 },
23
- RESOURCE_EXHAUSTED: { code: 'RateLimitExceeded', status: 429 },
24
- UNAUTHENTICATED: { code: 'Unauthenticated', status: 401 },
25
- INTERNAL: { code: 'InternalError', status: 500 },
26
- UNAVAILABLE: { code: 'ServiceUnavailable', status: 503 }
27
- };
12
+ // Gmail answers a busy backend with these, and its documentation asks for a retry
13
+ const RETRYABLE_SERVER_STATUSES = new Set([500, 502, 503, 504]);
28
14
 
29
15
  /**
30
- * Creates an error from a Gmail API error response
31
- * @param {Object} gmailError - The error object from Gmail API
32
- * @param {string} gmailErrorStatus - The error status from Gmail API
33
- * @returns {Error|null} A formatted error object or null if not mappable
34
- */
35
- function createGmailError(gmailError, gmailErrorStatus) {
36
- const mappedError = GMAIL_ERROR_MAP[gmailErrorStatus];
37
- if (!mappedError) {
38
- return null;
39
- }
40
-
41
- const error = new Error(gmailError?.message || gmailErrorStatus);
42
- error.code = mappedError.code;
43
- error.statusCode = mappedError.status;
44
- error.gmailErrorStatus = gmailErrorStatus;
45
- return error;
46
- }
47
-
48
- /**
49
- * Checks if an error indicates rate limiting
16
+ * Checks if an error indicates rate limiting. Gmail's usual throttling answer is a 403 with a
17
+ * rate-limit reason, not a 429
50
18
  * @param {Object} err - The error object
51
19
  * @returns {boolean} True if rate limited
52
20
  */
@@ -58,41 +26,21 @@ function isRateLimitError(err) {
58
26
  }
59
27
 
60
28
  /**
61
- * Calculates retry delay with exponential backoff and jitter
62
- * @param {Object} err - The error object (may contain Retry-After header)
63
- * @param {number} attempt - Current attempt number (0-indexed)
64
- * @returns {number} Delay in milliseconds
65
- */
66
- function calculateRetryDelay(err, attempt) {
67
- const retryAfter = err.oauthRequest?.headers?.['retry-after'];
68
-
69
- // Use Retry-After header if available, otherwise exponential backoff
70
- let delay = retryAfter ? parseInt(retryAfter, 10) * 1000 : RETRY_BASE_DELAY * Math.pow(2, attempt);
71
-
72
- // Add jitter (0-500ms) to prevent synchronized retries
73
- delay += Math.random() * 500;
74
-
75
- return delay;
76
- }
77
-
78
- /**
79
- * Makes authenticated requests to Gmail API with automatic retry on rate limiting
80
- * Implements exponential backoff with jitter
29
+ * Makes one authenticated request to the Gmail API, repeated only after a rejected cached token
81
30
  *
82
31
  * @param {Object} context - The client context (GmailClient instance)
83
32
  * @param {string} url - API endpoint URL
84
- * @param {string} [method='get'] - HTTP method
85
- * @param {*} [payload] - Request payload
86
- * @param {Object} [options={}] - Request options
33
+ * @param {string} method - HTTP method
34
+ * @param {*} payload - Request payload
35
+ * @param {Object} options - Request options
87
36
  * @returns {Promise<*>} API response
88
37
  */
89
- async function request(context, url, method, payload, options = {}) {
90
- const maxRetries = options.maxRetries ?? MAX_RETRY_ATTEMPTS;
91
- let lastError;
38
+ async function requestOnce(context, url, method, payload, options) {
92
39
  let tokenRenewed = false;
93
40
 
94
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
95
- let result, tokenData;
41
+ // Loops only for the single repeat after a rejected cached token
42
+ for (;;) {
43
+ let tokenData;
96
44
 
97
45
  try {
98
46
  tokenData = await context.getTokenData();
@@ -106,7 +54,7 @@ async function request(context, url, method, payload, options = {}) {
106
54
  await context.getClient();
107
55
  }
108
56
 
109
- result = await context.oAuth2Client.request(tokenData.accessToken, url, method, payload, options);
57
+ const result = await context.oAuth2Client.request(tokenData.accessToken, url, method, payload, options);
110
58
 
111
59
  // Track successful API request
112
60
  metricsMeta({ account: context.account }, context.logger, 'oauth2ApiRequest', 'inc', {
@@ -117,59 +65,10 @@ async function request(context, url, method, payload, options = {}) {
117
65
 
118
66
  return result;
119
67
  } catch (err) {
120
- lastError = err;
121
-
122
68
  // A rejected cached token is renewed and the request repeated once, see
123
69
  // renewRejectedAccessToken()
124
70
  if (await renewRejectedAccessToken(context, err, tokenData, tokenRenewed)) {
125
71
  tokenRenewed = true;
126
- attempt -= 1;
127
- continue;
128
- }
129
-
130
- // Check if this is a transient network error
131
- if (isTransientNetworkError(err) && attempt < maxRetries) {
132
- const delay = RETRY_BASE_DELAY * Math.pow(2, attempt) + Math.random() * 500;
133
-
134
- context.logger.warn({
135
- msg: 'Transient network error during Gmail API request, retrying',
136
- account: context.account,
137
- attempt: attempt + 1,
138
- maxRetries,
139
- delay,
140
- code: err.code
141
- });
142
-
143
- metricsMeta({ account: context.account }, context.logger, 'oauth2ApiRequest', 'inc', {
144
- status: 'network_error',
145
- provider: 'gmail',
146
- statusCode: '0'
147
- });
148
-
149
- await new Promise(resolve => setTimeout(resolve, delay));
150
- continue;
151
- }
152
-
153
- // Check if this is a rate limit error
154
- if (isRateLimitError(err) && attempt < maxRetries) {
155
- const delay = calculateRetryDelay(err, attempt);
156
-
157
- context.logger.warn({
158
- msg: 'Rate limited by Gmail API, retrying',
159
- account: context.account,
160
- attempt: attempt + 1,
161
- maxRetries,
162
- delay,
163
- errorReason: err.oauthRequest?.response?.error?.errors?.[0]?.reason
164
- });
165
-
166
- metricsMeta({ account: context.account }, context.logger, 'oauth2ApiRequest', 'inc', {
167
- status: 'rate_limited',
168
- provider: 'gmail',
169
- statusCode: '429'
170
- });
171
-
172
- await new Promise(resolve => setTimeout(resolve, delay));
173
72
  continue;
174
73
  }
175
74
 
@@ -185,19 +84,37 @@ async function request(context, url, method, payload, options = {}) {
185
84
  }
186
85
 
187
86
  // Track failed API request
188
- const statusCode = String(err.oauthRequest?.status || 0);
189
87
  metricsMeta({ account: context.account }, context.logger, 'oauth2ApiRequest', 'inc', {
190
88
  status: 'failure',
191
89
  provider: 'gmail',
192
- statusCode
90
+ statusCode: String(status || 0)
193
91
  });
194
92
 
195
93
  throw markRejectedAccessToken(err);
196
94
  }
197
95
  }
96
+ }
198
97
 
199
- // If we exhausted all retries, throw the last error
200
- throw lastError;
98
+ /**
99
+ * Makes authenticated requests to Gmail API, retried under the policy of lib/email-client/api-retry.js
100
+ *
101
+ * @param {Object} context - The client context (GmailClient instance)
102
+ * @param {string} url - API endpoint URL
103
+ * @param {string} [method='get'] - HTTP method
104
+ * @param {*} [payload] - Request payload
105
+ * @param {Object} [options={}] - Request options. `noRetry` sends the request exactly once
106
+ * @returns {Promise<*>} API response
107
+ */
108
+ async function request(context, url, method, payload, options = {}) {
109
+ return await apiRetry.requestWithRetry(() => requestOnce(context, url, method, payload, options), {
110
+ context,
111
+ provider: 'gmail',
112
+ url,
113
+ method,
114
+ options,
115
+ isRateLimited: isRateLimitError,
116
+ serverErrorStatuses: RETRYABLE_SERVER_STATUSES
117
+ });
201
118
  }
202
119
 
203
120
  /**
@@ -260,9 +177,7 @@ module.exports = {
260
177
  // Constants
261
178
  GMAIL_API_BASE,
262
179
  LIST_BATCH_SIZE,
263
- MAX_RETRY_ATTEMPTS,
264
- RETRY_BASE_DELAY,
265
- GMAIL_ERROR_MAP,
180
+ RETRYABLE_SERVER_STATUSES,
266
181
 
267
182
  // Request functions
268
183
  request,
@@ -270,7 +185,5 @@ module.exports = {
270
185
  executeBatchRequests,
271
186
 
272
187
  // Error handling
273
- createGmailError,
274
- isRateLimitError,
275
- calculateRetryDelay
188
+ isRateLimitError
276
189
  };
@@ -23,7 +23,7 @@ const JSON_SEND_LIMIT = 3.5 * 1024 * 1024;
23
23
  */
24
24
  function buildSendRequest(raw, threadId) {
25
25
  if (raw.length <= JSON_SEND_LIMIT) {
26
- // JSON endpoint with base64url encoding (retry-safe, no ArrayBuffer issues)
26
+ // JSON endpoint with base64url encoding
27
27
  const payload = { raw: raw.toString('base64url') };
28
28
  if (threadId) {
29
29
  payload.threadId = threadId;
@@ -11,7 +11,7 @@ const he = require('he');
11
11
  const { BaseClient, metricsMeta } = require('./base-client');
12
12
  const { isTransientCredentialError } = require('./credential-errors');
13
13
  const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
14
- const { emitChangeEvent, toCamelCase, collectCidReferences, cidReferenceRegex, truncateTextContents } = require('../tools');
14
+ const { emitChangeEvent, toCamelCase, collectCidReferences, embedCidImages, truncateTextContents } = require('../tools');
15
15
  const { Gateway } = require('../gateway');
16
16
 
17
17
  const {
@@ -1367,14 +1367,9 @@ class GmailClient extends BaseClient {
1367
1367
  }
1368
1368
 
1369
1369
  // Replace CID references with data URIs
1370
- formattedMessage.text.html = formattedMessage.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1371
- if (attachmentMap.has(cidMatch)) {
1372
- let { content } = attachmentMap.get(cidMatch);
1373
- if (content.content) {
1374
- return `data:${content.contentType || 'application/octet-stream'};base64,${content.content.toString('base64')}`;
1375
- }
1376
- }
1377
- return fullMatch;
1370
+ formattedMessage.text.html = embedCidImages(formattedMessage.text.html, contentId => {
1371
+ let { content } = attachmentMap.get(contentId) || {};
1372
+ return content?.content && { contentType: content.contentType, content: content.content.toString('base64') };
1378
1373
  });
1379
1374
  }
1380
1375
 
@@ -1523,7 +1518,7 @@ class GmailClient extends BaseClient {
1523
1518
  }
1524
1519
 
1525
1520
  // Generate raw message
1526
- let { raw, messageId, referencedMessage, documentStoreUsed } = await this.prepareRawMessage(data);
1521
+ let { raw, messageId, referencedMessage } = await this.prepareRawMessage(data);
1527
1522
  if (raw?.buffer) {
1528
1523
  // convert from a Uint8Array to a Buffer
1529
1524
  raw = Buffer.from(raw);
@@ -1568,7 +1563,6 @@ class GmailClient extends BaseClient {
1568
1563
  response.reference = {};
1569
1564
  if (data.reference.message) {
1570
1565
  response.reference.message = data.reference.message;
1571
- response.reference.documentStore = documentStoreUsed;
1572
1566
  response.reference.success = referencedMessage ? true : false;
1573
1567
  if (!referencedMessage) {
1574
1568
  response.reference.error = 'Referenced message was not found';
@@ -1669,11 +1663,10 @@ class GmailClient extends BaseClient {
1669
1663
  let gatewayObject;
1670
1664
  if (data.gateway) {
1671
1665
  gatewayObject = new Gateway({ gateway: data.gateway, redis: this.redis, secret: this.secret });
1672
- try {
1673
- gatewayData = await gatewayObject.loadGatewayData();
1674
- } catch (err) {
1675
- this.logger.warn({ msg: 'Failed to load gateway data', messageId: data.messageId, gateway: data.gateway, err });
1676
- }
1666
+ // The message was queued for this gateway, so it must not go out through the
1667
+ // provider API instead: a missing gateway throws GatewayNotFound and the job is
1668
+ // discarded, a Redis failure is thrown as is and the job retries
1669
+ gatewayData = await gatewayObject.loadGatewayData();
1677
1670
  }
1678
1671
 
1679
1672
  if (gatewayData) {
@@ -1702,7 +1695,9 @@ class GmailClient extends BaseClient {
1702
1695
 
1703
1696
  let submitInfo;
1704
1697
  try {
1705
- submitInfo = await this.request(`${GMAIL_API_BASE}${targetEndpoint}`, 'post', payload, { contentType });
1698
+ // noRetry: a send is never repeated, not even after a 429 - a socket that drops after
1699
+ // Gmail accepted the message would otherwise deliver it twice
1700
+ submitInfo = await this.request(`${GMAIL_API_BASE}${targetEndpoint}`, 'post', payload, { contentType, noRetry: true });
1706
1701
  } catch (err) {
1707
1702
  // Report the failure the way the SMTP path does (messageDeliveryError webhook,
1708
1703
  // feedback key) before the job decides whether to retry
@@ -1710,6 +1705,21 @@ class GmailClient extends BaseClient {
1710
1705
  throw err;
1711
1706
  }
1712
1707
 
1708
+ // Record the accept before anything else can throw: once Gmail has the message, a failure
1709
+ // in the bookkeeping below must not make the job retry and send it a second time
1710
+ // (isAlreadySent() in the submit worker keys on this progress state). Written once: the
1711
+ // Message-ID Gmail may rewrite is read back below and reaches the caller through the
1712
+ // messageSent notification and the job result, not through a second progress write
1713
+ try {
1714
+ await submitJobEntry.updateProgress({
1715
+ status: 'smtp-completed',
1716
+ messageId,
1717
+ originalMessageId: messageId
1718
+ });
1719
+ } catch (err) {
1720
+ this.logger.warn({ msg: 'Failed to update submit job progress', queueId, messageId, err });
1721
+ }
1722
+
1713
1723
  if (data.draft && !data.draft.draftId) {
1714
1724
  // The draft resource could not be resolved at queue time, so the draft was sent as
1715
1725
  // a raw copy - remove the original draft message (the Gmail API can only move it
@@ -1724,38 +1734,32 @@ class GmailClient extends BaseClient {
1724
1734
  }
1725
1735
  */
1726
1736
 
1727
- let gmailMessageId;
1737
+ // Gmail may rewrite the Message-ID, so the sent copy is read back for the real value.
1738
+ // Best effort: the message is already sent, a failed read only costs the rewritten id
1739
+ let gmailMessageId = messageId;
1728
1740
  if (submitInfo?.id) {
1729
1741
  // Detect send-only mode using centralized scope checker
1730
1742
  const scopes = accountData.oauth2?.accessToken?.scope || accountData.oauth2?.scope || [];
1731
1743
  const { hasSendScope, hasReadScope } = checkAccountScopes('gmail', scopes);
1732
1744
  const isSendOnly = hasSendScope && !hasReadScope;
1733
1745
 
1746
+ // Send-only accounts cannot read messages back, they keep the original messageId
1734
1747
  if (!isSendOnly) {
1735
- // fetch message data to get actual Message-ID value (requires read scope)
1736
- let messageEntry = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${submitInfo?.id}`, 'get', {
1737
- format: 'metadata',
1738
- metadataHeaders: 'message-id'
1739
- });
1740
- let messageIdHeader = messageEntry?.payload?.headers?.find(h => /^Message-ID$/i.test(h.name));
1741
- gmailMessageId = messageIdHeader?.value;
1742
- } else {
1743
- // For send-only accounts, use the original messageId since we can't read messages back
1744
- gmailMessageId = messageId;
1748
+ try {
1749
+ let messageEntry = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${submitInfo.id}`, 'get', {
1750
+ format: 'metadata',
1751
+ metadataHeaders: 'message-id'
1752
+ });
1753
+ let messageIdHeader = messageEntry?.payload?.headers?.find(h => /^Message-ID$/i.test(h.name));
1754
+ if (messageIdHeader?.value) {
1755
+ gmailMessageId = messageIdHeader.value;
1756
+ }
1757
+ } catch (err) {
1758
+ this.logger.warn({ msg: 'Failed to read the Message-ID of a sent message', queueId, messageId, gmailId: submitInfo.id, err });
1759
+ }
1745
1760
  }
1746
1761
  }
1747
1762
 
1748
- try {
1749
- // try to update job progress
1750
- await submitJobEntry.updateProgress({
1751
- status: 'smtp-completed',
1752
- messageId: gmailMessageId,
1753
- originalMessageId: messageId
1754
- });
1755
- } catch (err) {
1756
- // ignore
1757
- }
1758
-
1759
1763
  // Send success notification
1760
1764
  await this.notify(false, EMAIL_SENT_NOTIFY, {
1761
1765
  messageId: gmailMessageId,
@@ -2465,23 +2469,25 @@ class GmailClient extends BaseClient {
2465
2469
  }
2466
2470
  encodedTextSize[type] += node.body.size;
2467
2471
 
2468
- // Track part IDs and optionally extract content
2472
+ // Track part IDs and optionally extract content. A zero-size part carries
2473
+ // no body.data at all, so only parts with content are decoded (as getText does)
2474
+ const hasData = typeof node.body.data === 'string';
2469
2475
  switch (type) {
2470
2476
  case 'plain':
2471
2477
  textParts[0].push(node.partId);
2472
- if ([type, '*'].includes(options.textType)) {
2478
+ if (hasData && [type, '*'].includes(options.textType)) {
2473
2479
  textContents[0].push(Buffer.from(node.body.data, 'base64'));
2474
2480
  }
2475
2481
  break;
2476
2482
  case 'html':
2477
2483
  textParts[1].push(node.partId);
2478
- if ([type, '*'].includes(options.textType)) {
2484
+ if (hasData && [type, '*'].includes(options.textType)) {
2479
2485
  textContents[1].push(Buffer.from(node.body.data, 'base64'));
2480
2486
  }
2481
2487
  break;
2482
2488
  default:
2483
2489
  textParts[2].push(node.partId);
2484
- if (['*'].includes(options.textType)) {
2490
+ if (hasData && ['*'].includes(options.textType)) {
2485
2491
  textContents[0].push(Buffer.from(node.body.data, 'base64'));
2486
2492
  }
2487
2493
  break;
@@ -2956,7 +2962,25 @@ class GmailClient extends BaseClient {
2956
2962
  * @param {Object} historyEntry - Gmail history entry
2957
2963
  */
2958
2964
  async processHistoryEntry(historyEntry, context) {
2959
- const { labels, newMessageOptions } = context || (await this.getHistoryContext());
2965
+ const historyContext = context || (await this.getHistoryContext());
2966
+ const { newMessageOptions } = historyContext;
2967
+
2968
+ // The label list is cached for an hour, so a label created since is unknown to it and its
2969
+ // changes were silently dropped. An unknown id refreshes the list once per run; an id that
2970
+ // is still unknown after that is reported as is rather than dropped
2971
+ const resolveLabelName = async labelId => {
2972
+ let label = historyContext.labels?.find(entry => entry.id === labelId);
2973
+ if (!label && !historyContext.labelsRefreshed) {
2974
+ historyContext.labelsRefreshed = true;
2975
+ try {
2976
+ historyContext.labels = await this.getLabels(true);
2977
+ } catch (err) {
2978
+ this.logger.warn({ msg: 'Failed to refresh the label list', account: this.account, err });
2979
+ }
2980
+ label = historyContext.labels?.find(entry => entry.id === labelId);
2981
+ }
2982
+ return label ? label.name : labelId;
2983
+ };
2960
2984
 
2961
2985
  /**
2962
2986
  * Processes label changes and sends update notifications
@@ -3006,10 +3030,7 @@ class GmailClient extends BaseClient {
3006
3030
  // ignore category labels
3007
3031
  } else {
3008
3032
  // resolve Path for the label
3009
- let label = labels.find(label => label.id === labelId);
3010
- if (label) {
3011
- changes.labels[addedProp].push(label.name);
3012
- }
3033
+ changes.labels[addedProp].push(await resolveLabelName(labelId));
3013
3034
  }
3014
3035
  break;
3015
3036
  }
@@ -3249,7 +3270,7 @@ class GmailClient extends BaseClient {
3249
3270
  // whose events were lost so they can be recovered manually
3250
3271
  let messageIds = (entry?.messagesAdded || []).map(added => added?.message?.id).filter(id => id);
3251
3272
  this.logger.error({
3252
- msg: 'Skipping history entry that repeatedly killed the worker',
3273
+ msg: 'Skipping history entry that repeatedly failed or killed the worker',
3253
3274
  account: this.account,
3254
3275
  entryId: entry?.id,
3255
3276
  attempts,
@@ -3257,7 +3278,7 @@ class GmailClient extends BaseClient {
3257
3278
  });
3258
3279
  await emitChangeEvent(this.logger, this.account, 'syncWarning', {
3259
3280
  type: 'historyEntrySkipped',
3260
- message: 'Processing a history entry repeatedly killed the sync worker, its changes were skipped',
3281
+ message: 'Processing a history entry repeatedly failed or killed the sync worker, its changes were skipped',
3261
3282
  historyId: entry?.id,
3262
3283
  messageIds
3263
3284
  });
@@ -3286,6 +3307,11 @@ class GmailClient extends BaseClient {
3286
3307
  labelsRemoved: entry?.labelsRemoved?.length,
3287
3308
  err
3288
3309
  });
3310
+ // End the run here, with the cursor on the last entry that went through: the
3311
+ // next run starts from this entry again. Moving past it lost its label changes
3312
+ // and deletions without a trace. The in-flight marker stays, so an entry that
3313
+ // keeps failing is skipped with a syncWarning after the attempt limit above
3314
+ throw err;
3289
3315
  }
3290
3316
  }
3291
3317