emailengine-app 2.79.1 → 2.79.2

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 (81) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +40 -0
  3. package/bin/emailengine.js +8 -1
  4. package/config/default.toml +6 -0
  5. package/data/google-crawlers.json +1 -1
  6. package/lib/account.js +95 -18
  7. package/lib/api-routes/account-routes.js +13 -1
  8. package/lib/api-routes/index.js +12 -0
  9. package/lib/api-routes/mailbox-routes.js +6 -0
  10. package/lib/api-routes/mcp-oauth-routes.js +259 -0
  11. package/lib/api-routes/mcp-routes.js +172 -0
  12. package/lib/api-routes/message-routes.js +125 -4
  13. package/lib/api-routes/outbox-routes.js +7 -0
  14. package/lib/api-routes/permission-map.js +97 -1
  15. package/lib/api-routes/route-helpers.js +16 -4
  16. package/lib/api-routes/route-metadata.js +24 -4
  17. package/lib/api-routes/submit-routes.js +41 -0
  18. package/lib/api-routes/template-routes.js +7 -0
  19. package/lib/api-routes/token-routes.js +4 -2
  20. package/lib/consts.js +30 -1
  21. package/lib/email-client/base-client.js +102 -117
  22. package/lib/email-client/gmail-client.js +87 -22
  23. package/lib/email-client/imap/mailbox.js +140 -66
  24. package/lib/email-client/outlook-client.js +17 -14
  25. package/lib/enum-descriptions.js +2 -1
  26. package/lib/field-usage.js +17 -1
  27. package/lib/lua/s-list-accounts.lua +5 -2
  28. package/lib/mcp/index.js +29 -0
  29. package/lib/mcp/inject.js +70 -0
  30. package/lib/mcp/json-schema.js +120 -0
  31. package/lib/mcp/listen.js +171 -0
  32. package/lib/mcp/oauth.js +324 -0
  33. package/lib/mcp/protocol.js +489 -0
  34. package/lib/mcp/resources.js +139 -0
  35. package/lib/mcp/tools.js +655 -0
  36. package/lib/openapi/index.js +3 -1
  37. package/lib/response-stream.js +52 -21
  38. package/lib/routes-ui.js +4 -0
  39. package/lib/schemas.js +24 -3
  40. package/lib/token-permission-view.js +104 -8
  41. package/lib/tokens.js +34 -5
  42. package/lib/tools.js +96 -0
  43. package/lib/ui-routes/account-routes.js +43 -1
  44. package/lib/ui-routes/admin-config-routes.js +114 -1
  45. package/lib/ui-routes/admin-entities-routes.js +54 -5
  46. package/lib/ui-routes/auth-routes.js +13 -0
  47. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  48. package/lib/ui-routes/route-helpers.js +116 -1
  49. package/lib/utils/network.js +9 -1
  50. package/lib/web-safe-html.js +61 -0
  51. package/lib/webhooks.js +3 -8
  52. package/package.json +9 -8
  53. package/sbom.json +1 -1
  54. package/scripts/README.md +25 -0
  55. package/scripts/build-icon.js +77 -0
  56. package/static/css/flyonui.css +1 -1
  57. package/static/css/src/app.tailwind.css +98 -0
  58. package/static/emailengine.ico +0 -0
  59. package/static/js/ui.js +465 -1
  60. package/static/licenses.html +42 -22
  61. package/translations/messages.pot +57 -57
  62. package/views/config/mcp.hbs +361 -0
  63. package/views/config/oauth/index.hbs +7 -0
  64. package/views/layout/prompt.hbs +62 -0
  65. package/views/mcp/authorize.hbs +136 -0
  66. package/views/partials/head_assets.hbs +3 -3
  67. package/views/partials/mcp_access_levels.hbs +13 -0
  68. package/views/partials/mcp_account_limit.hbs +14 -0
  69. package/views/partials/mcp_tool_count.hbs +19 -0
  70. package/views/partials/side_menu.hbs +1 -0
  71. package/views/partials/ui/account-picker.hbs +59 -0
  72. package/views/partials/ui/code-block.hbs +26 -0
  73. package/views/partials/ui/menu-item.hbs +5 -0
  74. package/views/partials/ui/radio.hbs +41 -0
  75. package/views/partials/ui/tab.hbs +15 -10
  76. package/views/partials/ui/tabs.hbs +8 -5
  77. package/views/templates/template.hbs +4 -3
  78. package/views/tokens/index.hbs +8 -2
  79. package/views/tokens/new.hbs +514 -243
  80. package/winconf.js +148 -48
  81. package/workers/api.js +198 -48
@@ -124,6 +124,47 @@ async function init(args) {
124
124
  tags: ['api', 'Submit'],
125
125
 
126
126
  plugins: {
127
+ mcp: {
128
+ name: 'send_message',
129
+ title: 'Send message',
130
+ description:
131
+ 'Send an email from the account to real recipients - confirm with the user before calling this. Takes structured fields (to, subject, text, html). ' +
132
+ 'To answer or pass on a message the user is looking at, set `reference.message` to its id and `reference.action` to reply, reply-all or forward, ' +
133
+ 'and write only the new text: the subject, the recipients (for a reply) and the threading headers come from the referenced message. ' +
134
+ 'Add `reference.inline` to quote the original under it, and `reference.forwardAttachments` to carry its attachments along when forwarding. ' +
135
+ 'Delivery is queued; the response carries the queue id for get_outbox.',
136
+ // An allowlist, not a deny list. The submit payload is the widest one in the
137
+ // API and it grows; with `omit` a field added here later would join the
138
+ // agent-facing schema by default, which fails open on the one tool that
139
+ // reaches people outside the mailbox.
140
+ //
141
+ // What is kept is the message an agent composes: who it goes to, what it
142
+ // says, what it answers, what it carries and when it leaves. What is not is a
143
+ // decision the operator made when they connected the account - routing,
144
+ // tracking, bounce handling, whether the sent copy is filed - plus every way
145
+ // around the structured fields (`raw` replaces the whole message, `envelope`
146
+ // overrides the SMTP conversation, `headers`/`messageId` set headers
147
+ // EmailEngine derives) and `mailMerge`, which would turn one call into a bulk
148
+ // send to a recipient list - not what "confirm before sending" protects
149
+ // against. An agent that should mail several people calls the tool several
150
+ // times, where each send is visible as a send.
151
+ keep: [
152
+ 'account',
153
+ 'reference',
154
+ 'from',
155
+ 'replyTo',
156
+ 'to',
157
+ 'cc',
158
+ 'bcc',
159
+ 'subject',
160
+ 'text',
161
+ 'html',
162
+ 'template',
163
+ 'render',
164
+ 'attachments',
165
+ 'sendAt'
166
+ ]
167
+ },
127
168
  openapi: {
128
169
  'x-ee-impact': IMPACT.SENDS,
129
170
  'x-ee-behavior': [BEHAVIOR.QUEUED_DELIVERY, BEHAVIOR.SENT_FOLDER_UPLOAD],
@@ -10,6 +10,7 @@ const { handleError, throwNotFound } = require('./route-helpers');
10
10
 
11
11
  const { templateSchemas, accountIdSchema, apiResponses } = require('../schemas');
12
12
  const { IMPACT } = require('./operation-impact');
13
+ const { MCP_MAX_PAGE_SIZE } = require('../consts');
13
14
 
14
15
  // Template owner field shared by all template response schemas
15
16
  const templateAccountIdSchema = accountIdSchema.required().allow(null).description('Account ID. Null for public templates');
@@ -226,6 +227,12 @@ async function init(args) {
226
227
  tags: ['api', 'Templates'],
227
228
 
228
229
  plugins: {
230
+ mcp: {
231
+ name: 'list_templates',
232
+ title: 'List templates',
233
+ description: 'List stored email templates, paged. Pass an account id for account-specific templates or omit it for shared ones.',
234
+ bounds: { pageSize: MCP_MAX_PAGE_SIZE }
235
+ },
229
236
  openapi: {
230
237
  responses: apiResponses('Returns a page of stored templates for the account.', 400, 401, 403, 404, 429, 500)
231
238
  }
@@ -123,11 +123,13 @@ async function init(args) {
123
123
  description: Joi.string().empty('').trim().max(1024).required().example('Token description').description('Token description'),
124
124
 
125
125
  scopes: Joi.array()
126
- .items(Joi.string().valid('api', 'smtp', 'imap-proxy').meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenScope }).label('TokenScope'))
126
+ .items(Joi.string().valid('api', 'smtp', 'imap-proxy', 'mcp').meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenScope }).label('TokenScope'))
127
127
  .single()
128
128
  .default(['api'])
129
129
  .required()
130
- .description('Token permission scopes: "api" for REST API access, "smtp" for SMTP submission, "imap-proxy" for IMAP proxy authentication')
130
+ .description(
131
+ 'Token permission scopes: "api" for REST API access, "smtp" for SMTP submission, "imap-proxy" for IMAP proxy authentication, "mcp" for the MCP endpoint only'
132
+ )
131
133
  .label('Scopes'),
132
134
 
133
135
  metadata: tokenMetadataSchema,
package/lib/consts.js CHANGED
@@ -171,6 +171,14 @@ module.exports = {
171
171
 
172
172
  MAX_INLINE_ATTACHMENT_SIZE: 2 * 1024 * 1024,
173
173
 
174
+ // How many times processing of the same Gmail history entry may start
175
+ // without finishing before the entry is skipped as poisonous. Only abrupt
176
+ // worker deaths reach this: a thrown error is caught and the cursor
177
+ // advances, a graceful close clears the marker, but an entry that kills the
178
+ // worker (OOM, heartbeat restart) is refetched on restart because the
179
+ // history cursor only moves after processing completes
180
+ GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS: 3,
181
+
174
182
  TOTP_WINDOW_SIZE: 6,
175
183
 
176
184
  WEBAUTHN_CHALLENGE_TTL: 300, // 5 minutes
@@ -219,6 +227,15 @@ module.exports = {
219
227
  COLLAPSE_CLASS: 'ee-collapsed-thread',
220
228
  COLLAPSE_TOGGLE_CLASS: 'ee-collapsed-thread-toggle',
221
229
 
230
+ // The largest page an MCP listing tool advertises and accepts, applied through the `bounds`
231
+ // option of a route's plugins.mcp block (lib/mcp/tools.js). The routes themselves keep taking
232
+ // 1000, which is right for a REST client writing the rows somewhere; a model asked to pick a
233
+ // page size picks the maximum it is shown, and 1000 message entries is a tool result large
234
+ // enough to crowd out the conversation it was fetched for. MAX_TOOL_RESULT_BYTES is still the
235
+ // backstop - this is what keeps a normal call from reaching it. Defined once so the five
236
+ // listing tools cannot drift apart on it.
237
+ MCP_MAX_PAGE_SIZE: 100,
238
+
222
239
  // We are using a legacy hash function in caching operations
223
240
  // This is not insecure but it pops out in security scanners, so we need to mask the name of the hash
224
241
  MAILBOX_HASH: Buffer.from('c2hhMQ', 'base64url').toString(),
@@ -287,7 +304,19 @@ module.exports = {
287
304
  // each detail context, and `rawPacket` is a TLS-error field that can carry an unparsed
288
305
  // credential frame - without these a failed validation writes plaintext passwords, OAuth2
289
306
  // client secrets and access tokens into the log, the per-account log store and Sentry.
290
- REDACTED_LOG_KEYS: ['req.headers.authorization', 'req.headers.cookie', 'err.rawPacket', 'err._original', 'err.details[*].context.value'],
307
+ // `req.query.access_token` is here because the api-token scheme accepts the credential as a
308
+ // query argument, and hapi-pino logs the parsed query object with every request - so a client
309
+ // using that form wrote a live token into this instance's own request log. The serialized
310
+ // `req.url` is the pathname only (pino-std-serializers reports `req.path`), so the credential
311
+ // reaches the log through the query object and nowhere else.
312
+ REDACTED_LOG_KEYS: [
313
+ 'req.headers.authorization',
314
+ 'req.headers.cookie',
315
+ 'req.query.access_token',
316
+ 'err.rawPacket',
317
+ 'err._original',
318
+ 'err.details[*].context.value'
319
+ ],
291
320
 
292
321
  generateWebhookTable() {
293
322
  let entries = [];
@@ -51,7 +51,9 @@ const {
51
51
  filterEmptyObjectValues,
52
52
  getDateBuckets,
53
53
  resolveCredentials,
54
- useAuthServerForOAuth2
54
+ useAuthServerForOAuth2,
55
+ collectCidReferences,
56
+ cidReferenceRegex
55
57
  } = require('../tools');
56
58
 
57
59
  // Import application constants
@@ -96,6 +98,91 @@ const TRANSIENT_CONNECT_CODES = new Set([
96
98
  'UND_ERR_HEADERS_TIMEOUT'
97
99
  ]);
98
100
 
101
+ /**
102
+ * Keeps only the address entries a message can actually be delivered to.
103
+ *
104
+ * An address entry may carry a display name and no address at all: RFC 9051 7.5.2 group
105
+ * markers look like that, and so does a server that answered FETCH ENVELOPE after failing
106
+ * to parse a malformed address header. A group name is not a mailbox, so such an entry has
107
+ * to be dropped here rather than travel on as a recipient with an empty address.
108
+ *
109
+ * @param {Object[]|Object} list - Address entries, or the single entry the `from` field holds
110
+ * @returns {Object[]} Entries carrying an address
111
+ */
112
+ function addressableEntries(list) {
113
+ return [].concat(list || []).filter(entry => entry && entry.address);
114
+ }
115
+
116
+ /**
117
+ * Fills in the recipients of a reply or reply-all from the message being answered.
118
+ *
119
+ * Shared by prepareRawMessage() and queueMessageEntry(), which used to carry byte-identical
120
+ * copies of this. `data` is updated in place, and `data.to` is always a list. Falling back
121
+ * to the sender used to assign the bare `from` entry instead, and getRawEmail() maps over
122
+ * the address fields when building the envelope for a structured submission, so a reply to
123
+ * a message carrying no Reply-To threw "data[key]?.map is not a function" on that path.
124
+ *
125
+ * @param {Object} data - Submission payload, updated in place
126
+ * @param {Object} referencedMessage - The message being replied to
127
+ */
128
+ function applyReferenceRecipients(data, referencedMessage) {
129
+ // Answer the address the message nominates, falling back to whoever sent it
130
+ let replyTo = addressableEntries(referencedMessage.replyTo);
131
+ let answerTo = replyTo.length ? replyTo : addressableEntries(referencedMessage.from);
132
+
133
+ if (!data.to && data.reference.action === 'reply') {
134
+ data.to = answerTo.length ? answerTo : false;
135
+ }
136
+
137
+ if (data.reference.action !== 'reply-all') {
138
+ return;
139
+ }
140
+
141
+ // answerTo is already a fresh list, so the pushes below cannot reach referencedMessage
142
+ let envelope = {
143
+ to: answerTo,
144
+ cc: [],
145
+ bcc: []
146
+ };
147
+
148
+ // Deduplicate recipients
149
+ let addressesSeen = new Set([].concat(data.from?.address || []).concat(envelope.to.map(addr => addr.address)));
150
+ for (let rcpt of ['to', 'cc', 'bcc']) {
151
+ // A reply-all addresses the people visible on the conversation, so the referenced
152
+ // message contributes its To and Cc but never its Bcc. A Bcc header is normally
153
+ // stripped before transmission, so one that survived is either an artefact of how
154
+ // a copy was filed or, on a message someone else sent us, a header they chose to
155
+ // leave in. Either way nobody on the thread saw it. Copying it put a recipient of
156
+ // the sender's choosing into the reply envelope, and removeBcc() strips the header
157
+ // on the way out, so the sent copy recorded nothing about where the reply went.
158
+ let referenced = rcpt === 'bcc' ? [] : addressableEntries(referencedMessage[rcpt]);
159
+
160
+ for (let addr of referenced.concat(addressableEntries(data[rcpt]))) {
161
+ if (addressesSeen.has(addr.address)) {
162
+ continue;
163
+ }
164
+ addressesSeen.add(addr.address);
165
+ envelope[rcpt].push(addr);
166
+ }
167
+
168
+ if (envelope[rcpt].length) {
169
+ data[rcpt] = envelope[rcpt];
170
+ }
171
+ }
172
+ }
173
+
174
+ // Finds the attachments of a referenced message whose content id the given HTML links to
175
+ function findReferencedCidAttachments(html, attachments) {
176
+ let cidAttachments = [];
177
+ let cidReferences = collectCidReferences(html);
178
+ for (let attachment of attachments || []) {
179
+ if (attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
180
+ cidAttachments.push(attachment);
181
+ }
182
+ }
183
+ return cidAttachments;
184
+ }
185
+
99
186
  function isTransientNetworkError(err) {
100
187
  return !!err && TRANSIENT_CONNECT_CODES.has(err.code);
101
188
  }
@@ -1304,14 +1391,7 @@ class BaseClient {
1304
1391
 
1305
1392
  if (inlineMessageData.html) {
1306
1393
  // Find inline attachments referenced in HTML
1307
- if (referencedMessage.attachments) {
1308
- // find all attachments that are referenced in the HTML
1309
- for (let attachment of referencedMessage.attachments) {
1310
- if (attachment.contentId && inlineMessageData.html.indexOf(`cid:${attachment.contentId.replace(/^<|>$/g, '')}`) >= 0) {
1311
- cidAttachments.push(attachment);
1312
- }
1313
- }
1314
- }
1394
+ cidAttachments = findReferencedCidAttachments(inlineMessageData.html, referencedMessage.attachments);
1315
1395
 
1316
1396
  try {
1317
1397
  let html = data.html;
@@ -1334,54 +1414,8 @@ class BaseClient {
1334
1414
  }
1335
1415
  }
1336
1416
 
1337
- // Set recipient for reply
1338
- if (!data.to && data.reference.action === 'reply') {
1339
- data.to =
1340
- referencedMessage.replyTo && referencedMessage.replyTo.length
1341
- ? referencedMessage.replyTo
1342
- : referencedMessage.from
1343
- ? referencedMessage.from
1344
- : false;
1345
- }
1346
-
1347
- // Handle reply-all recipients
1348
- if (data.reference.action === 'reply-all') {
1349
- let envelope = {
1350
- to: [].concat(
1351
- referencedMessage.replyTo && referencedMessage.replyTo.length
1352
- ? referencedMessage.replyTo
1353
- : referencedMessage.from
1354
- ? referencedMessage.from
1355
- : []
1356
- ),
1357
- cc: [],
1358
- bcc: []
1359
- };
1360
-
1361
- // Deduplicate recipients
1362
- let addressesSeen = new Set([].concat(data.from?.address || []).concat(envelope.to.map(addr => addr.address)));
1363
- for (let rcpt of ['to', 'cc', 'bcc']) {
1364
- for (let addr of referencedMessage[rcpt] || []) {
1365
- if (addressesSeen.has(addr.address)) {
1366
- continue;
1367
- }
1368
- addressesSeen.add(addr.address);
1369
- envelope[rcpt].push(addr);
1370
- }
1371
-
1372
- for (let addr of data[rcpt] || []) {
1373
- if (addressesSeen.has(addr.address)) {
1374
- continue;
1375
- }
1376
- addressesSeen.add(addr.address);
1377
- envelope[rcpt].push(addr);
1378
- }
1379
-
1380
- if (envelope[rcpt].length) {
1381
- data[rcpt] = envelope[rcpt];
1382
- }
1383
- }
1384
- }
1417
+ // Set the recipients of a reply or reply-all
1418
+ applyReferenceRecipients(data, referencedMessage);
1385
1419
 
1386
1420
  // Determine which attachments to include
1387
1421
  let attachmentsToDownload;
@@ -1807,14 +1841,7 @@ class BaseClient {
1807
1841
 
1808
1842
  if (inlineMessageData.html) {
1809
1843
  // Find inline attachments referenced in HTML
1810
- if (referencedMessage.attachments) {
1811
- // find all attachments that are referenced in the HTML
1812
- for (let attachment of referencedMessage.attachments) {
1813
- if (attachment.contentId && inlineMessageData.html.indexOf(`cid:${attachment.contentId.replace(/^<|>$/g, '')}`) >= 0) {
1814
- cidAttachments.push(attachment);
1815
- }
1816
- }
1817
- }
1844
+ cidAttachments = findReferencedCidAttachments(inlineMessageData.html, referencedMessage.attachments);
1818
1845
 
1819
1846
  try {
1820
1847
  let html = data.html;
@@ -1837,54 +1864,8 @@ class BaseClient {
1837
1864
  }
1838
1865
  }
1839
1866
 
1840
- // Set recipient for reply
1841
- if (!data.to && data.reference.action === 'reply') {
1842
- data.to =
1843
- referencedMessage.replyTo && referencedMessage.replyTo.length
1844
- ? referencedMessage.replyTo
1845
- : referencedMessage.from
1846
- ? referencedMessage.from
1847
- : false;
1848
- }
1849
-
1850
- // Handle reply-all recipients
1851
- if (data.reference.action === 'reply-all') {
1852
- let envelope = {
1853
- to: [].concat(
1854
- referencedMessage.replyTo && referencedMessage.replyTo.length
1855
- ? referencedMessage.replyTo
1856
- : referencedMessage.from
1857
- ? referencedMessage.from
1858
- : []
1859
- ),
1860
- cc: [],
1861
- bcc: []
1862
- };
1863
-
1864
- // Deduplicate recipients
1865
- let addressesSeen = new Set([].concat(data.from?.address || []).concat(envelope.to.map(addr => addr.address)));
1866
- for (let rcpt of ['to', 'cc', 'bcc']) {
1867
- for (let addr of referencedMessage[rcpt] || []) {
1868
- if (addressesSeen.has(addr.address)) {
1869
- continue;
1870
- }
1871
- addressesSeen.add(addr.address);
1872
- envelope[rcpt].push(addr);
1873
- }
1874
-
1875
- for (let addr of data[rcpt] || []) {
1876
- if (addressesSeen.has(addr.address)) {
1877
- continue;
1878
- }
1879
- addressesSeen.add(addr.address);
1880
- envelope[rcpt].push(addr);
1881
- }
1882
-
1883
- if (envelope[rcpt].length) {
1884
- data[rcpt] = envelope[rcpt];
1885
- }
1886
- }
1887
- }
1867
+ // Set the recipients of a reply or reply-all
1868
+ applyReferenceRecipients(data, referencedMessage);
1888
1869
 
1889
1870
  // Determine which attachments to include
1890
1871
  let attachmentsToDownload;
@@ -2579,13 +2560,14 @@ class BaseClient {
2579
2560
  // Fetch inline attachments referenced in HTML
2580
2561
  if (messageData.attachments && messageData.attachments.length && messageData.text && messageData.text.html) {
2581
2562
  // fetch inline attachments
2563
+ let cidReferences = collectCidReferences(messageData.text.html);
2582
2564
  for (let attachment of messageData.attachments) {
2583
2565
  if (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE) {
2584
2566
  // skip large attachments
2585
2567
  continue;
2586
2568
  }
2587
2569
 
2588
- if (!attachment.content && attachment.contentId && messageData.text.html.indexOf(`cid:${attachment.contentId.replace(/^<|>$/g, '')}`) >= 0) {
2570
+ if (!attachment.content && attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
2589
2571
  try {
2590
2572
  attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
2591
2573
  } catch (err) {
@@ -2826,11 +2808,12 @@ class BaseClient {
2826
2808
  // embed inline images as data URIs
2827
2809
  if (messageData.text.html && messageData.attachments) {
2828
2810
  let attachmentList = new Map();
2811
+ let cidReferences = collectCidReferences(messageData.text.html);
2829
2812
 
2830
2813
  // Find CID references in HTML
2831
2814
  for (let attachment of messageData.attachments) {
2832
2815
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
2833
- if (contentId && messageData.text.html.indexOf(contentId) >= 0) {
2816
+ if (contentId && cidReferences.has(contentId)) {
2834
2817
  if (attachment.content) {
2835
2818
  // already downloaded in a previous step
2836
2819
  continue;
@@ -2847,7 +2830,7 @@ class BaseClient {
2847
2830
 
2848
2831
  // Replace CID references with data URIs
2849
2832
  if (attachmentList.size) {
2850
- messageData.text.html = messageData.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
2833
+ messageData.text.html = messageData.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
2851
2834
  if (attachmentList.has(cidMatch)) {
2852
2835
  let { attachment, content } = attachmentList.get(cidMatch);
2853
2836
  if (content) {
@@ -3394,4 +3377,6 @@ class BaseClient {
3394
3377
  }
3395
3378
 
3396
3379
  // Re-export postMetrics from notification-handler for backward compatibility
3397
- module.exports = { BaseClient, metricsMeta: postMetrics };
3380
+ // applyReferenceRecipients is exported for tests: the methods that call it need a live
3381
+ // account, a connection and a referenced message fetched from the server
3382
+ module.exports = { BaseClient, metricsMeta: postMetrics, applyReferenceRecipients };
@@ -9,8 +9,8 @@ const addressparser = require('nodemailer/lib/addressparser');
9
9
  const libmime = require('libmime');
10
10
  const he = require('he');
11
11
  const { BaseClient, metricsMeta } = require('./base-client');
12
- const { messageWebSafeHtml } = require('../web-safe-html');
13
- const { emitChangeEvent, toCamelCase } = require('../tools');
12
+ const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
13
+ const { emitChangeEvent, toCamelCase, collectCidReferences, cidReferenceRegex, truncateTextContents } = require('../tools');
14
14
  const { Gateway } = require('../gateway');
15
15
 
16
16
  const {
@@ -21,7 +21,8 @@ const {
21
21
  REDIS_PREFIX,
22
22
  AUTH_ERROR_NOTIFY,
23
23
  AUTH_SUCCESS_NOTIFY,
24
- DEFAULT_GMAIL_EXPORT_BATCH_SIZE
24
+ DEFAULT_GMAIL_EXPORT_BATCH_SIZE,
25
+ GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS
25
26
  } = require('../consts');
26
27
 
27
28
  const settings = require('../settings');
@@ -513,6 +514,16 @@ class GmailClient extends BaseClient {
513
514
  clearTimeout(this.fallbackPollingTimer);
514
515
  this.closed = true;
515
516
 
517
+ // A graceful close means the in-flight history entry did not kill this
518
+ // worker, so it must not keep the strike a deploy or a pause would
519
+ // otherwise leave behind. Guarded because the caller does not await
520
+ // close() - a rejection here would surface as an unhandled rejection
521
+ try {
522
+ await this.redis.hdel(this.getAccountKey(), 'googleHistoryProcessing');
523
+ } catch (err) {
524
+ this.logger.debug({ msg: 'Failed to clear history processing marker', account: this.account, err });
525
+ }
526
+
516
527
  // Clean up cached data
517
528
  this.cachedLabels = null;
518
529
  this.cachedLabelsTime = null;
@@ -1286,18 +1297,14 @@ class GmailClient extends BaseClient {
1286
1297
  await this.prepare();
1287
1298
 
1288
1299
  // Enable all enhancements for web-safe HTML
1289
- if (options.webSafeHtml) {
1290
- options.textType = '*';
1291
- options.embedAttachedImages = true;
1292
- options.preProcessHtml = true;
1293
- }
1300
+ applyWebSafeHtmlOptions(options);
1294
1301
 
1295
1302
  const requestQuery = {
1296
1303
  format: 'full'
1297
1304
  };
1298
1305
  const messageData = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${emailId}`, 'get', requestQuery);
1299
1306
 
1300
- let formattedMessage = this.formatMessage(messageData, { extended: true, textType: options.textType });
1307
+ let formattedMessage = this.formatMessage(messageData, { extended: true, textType: options.textType, maxBytes: options.maxBytes });
1301
1308
 
1302
1309
  // Resolve label IDs to human-readable names
1303
1310
  await this.resolveLabels(formattedMessage);
@@ -1324,11 +1331,12 @@ class GmailClient extends BaseClient {
1324
1331
  // Embed inline images as data URIs
1325
1332
  if (options.embedAttachedImages && formattedMessage.text?.html && formattedMessage.attachments) {
1326
1333
  let attachmentMap = new Map();
1334
+ let cidReferences = collectCidReferences(formattedMessage.text.html);
1327
1335
 
1328
1336
  // Find CID references in HTML
1329
1337
  for (let attachment of formattedMessage.attachments) {
1330
1338
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
1331
- if (contentId && formattedMessage.text.html.indexOf(contentId) >= 0) {
1339
+ if (contentId && cidReferences.has(contentId)) {
1332
1340
  attachmentMap.set(contentId, { attachment, content: null });
1333
1341
  }
1334
1342
  }
@@ -1341,7 +1349,7 @@ class GmailClient extends BaseClient {
1341
1349
  }
1342
1350
 
1343
1351
  // Replace CID references with data URIs
1344
- formattedMessage.text.html = formattedMessage.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1352
+ formattedMessage.text.html = formattedMessage.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1345
1353
  if (attachmentMap.has(cidMatch)) {
1346
1354
  let { content } = attachmentMap.get(cidMatch);
1347
1355
  if (content.content) {
@@ -1388,7 +1396,7 @@ class GmailClient extends BaseClient {
1388
1396
  try {
1389
1397
  const requestQuery = { format: 'full' };
1390
1398
  const messageData = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${emailId}`, 'get', requestQuery);
1391
- const formattedMessage = this.formatMessage(messageData, { extended: true, textType: options.textType });
1399
+ const formattedMessage = this.formatMessage(messageData, { extended: true, textType: options.textType, maxBytes: options.maxBytes });
1392
1400
 
1393
1401
  await this.resolveLabels(formattedMessage, labelMap);
1394
1402
 
@@ -1473,7 +1481,7 @@ class GmailClient extends BaseClient {
1473
1481
  response[key] = textContent[key].map(buf => buf.toString()).join('\n');
1474
1482
  }
1475
1483
 
1476
- response.hasMore = false;
1484
+ response.hasMore = truncateTextContents(response, options.maxBytes);
1477
1485
 
1478
1486
  return response;
1479
1487
  }
@@ -2491,7 +2499,7 @@ class GmailClient extends BaseClient {
2491
2499
  * @returns {Object} Formatted message
2492
2500
  */
2493
2501
  formatMessage(messageData, options) {
2494
- let { extended, path, textType, minimalFields } = options || {};
2502
+ let { extended, path, textType, minimalFields, maxBytes } = options || {};
2495
2503
 
2496
2504
  let date = messageData.internalDate && !isNaN(messageData.internalDate) ? new Date(Number(messageData.internalDate)) : undefined;
2497
2505
  if (date?.toString() === 'Invalid Date') {
@@ -2539,6 +2547,12 @@ class GmailClient extends BaseClient {
2539
2547
 
2540
2548
  const { attachments, textId, encodedTextSize, textContents } = this.getAttachmentList(messageData, { textType });
2541
2549
 
2550
+ const textValues = {
2551
+ plain: textContents?.[0]?.toString(),
2552
+ html: textContents?.[1]?.toString()
2553
+ };
2554
+ const textHasMore = truncateTextContents(textValues, maxBytes);
2555
+
2542
2556
  // Decode snippet preview
2543
2557
  let preview;
2544
2558
  try {
@@ -2588,9 +2602,9 @@ class GmailClient extends BaseClient {
2588
2602
  ? {
2589
2603
  id: textId,
2590
2604
  encodedSize: encodedTextSize,
2591
- plain: textContents?.[0]?.toString(),
2592
- html: textContents?.[1]?.toString(),
2593
- hasMore: textContents?.[0] || textContents?.[1] ? false : undefined
2605
+ plain: textValues.plain,
2606
+ html: textValues.html,
2607
+ hasMore: textContents?.[0] || textContents?.[1] ? textHasMore : undefined
2594
2608
  }
2595
2609
  : undefined,
2596
2610
 
@@ -3030,6 +3044,26 @@ class GmailClient extends BaseClient {
3030
3044
  let newestHistoryId = currentHistoryId;
3031
3045
  let lastHistoryId = currentHistoryId;
3032
3046
 
3047
+ // The history cursor only advances after an entry is processed, so an
3048
+ // entry that kills the worker (OOM, heartbeat restart) is refetched by
3049
+ // the restarted worker and would loop forever. The in-flight marker
3050
+ // records which entry processing last started on and how many times;
3051
+ // once the limit is hit the entry is skipped with a syncWarning
3052
+ let processingMarker = null;
3053
+ try {
3054
+ processingMarker = JSON.parse(await this.redis.hget(this.getAccountKey(), 'googleHistoryProcessing'));
3055
+ } catch (err) {
3056
+ // no marker or an unreadable one, nothing to resume
3057
+ }
3058
+
3059
+ // advance the durable cursor once an entry is handled (processed or skipped)
3060
+ let advanceHistoryCursor = async historyEntryId => {
3061
+ if (historyEntryId && historyEntryId > lastHistoryId) {
3062
+ await this.redis.hset(this.getAccountKey(), 'googleHistoryId', historyEntryId.toString());
3063
+ lastHistoryId = historyEntryId;
3064
+ }
3065
+ };
3066
+
3033
3067
  /**
3034
3068
  * Fetches and processes a page of history
3035
3069
  * @param {string} pageToken - Pagination token
@@ -3074,13 +3108,41 @@ class GmailClient extends BaseClient {
3074
3108
 
3075
3109
  // Process each history entry
3076
3110
  for (let entry of historyRes?.history || []) {
3111
+ let historyEntryId = Number(entry?.id) || null;
3112
+
3113
+ let attempts = processingMarker && entry?.id && String(processingMarker.id) === String(entry.id) ? Number(processingMarker.count) || 0 : 0;
3114
+ if (attempts >= GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS) {
3115
+ // Every attempt to process this entry has taken the worker
3116
+ // down with it. Skip it and advance the cursor so the
3117
+ // account can make progress; the warning names the messages
3118
+ // whose events were lost so they can be recovered manually
3119
+ let messageIds = (entry?.messagesAdded || []).map(added => added?.message?.id).filter(id => id);
3120
+ this.logger.error({
3121
+ msg: 'Skipping history entry that repeatedly killed the worker',
3122
+ account: this.account,
3123
+ entryId: entry?.id,
3124
+ attempts,
3125
+ messageIds
3126
+ });
3127
+ await emitChangeEvent(this.logger, this.account, 'syncWarning', {
3128
+ type: 'historyEntrySkipped',
3129
+ message: 'Processing a history entry repeatedly killed the sync worker, its changes were skipped',
3130
+ historyId: entry?.id,
3131
+ messageIds
3132
+ });
3133
+ await advanceHistoryCursor(historyEntryId);
3134
+ continue;
3135
+ }
3136
+
3137
+ if (entry?.id) {
3138
+ // mark the entry as in flight before touching it, so a
3139
+ // worker death mid-entry is attributable on restart
3140
+ await this.redis.hset(this.getAccountKey(), 'googleHistoryProcessing', JSON.stringify({ id: entry.id, count: attempts + 1 }));
3141
+ }
3142
+
3077
3143
  try {
3078
3144
  await this.processHistoryEntry(entry);
3079
- let historyEntryId = Number(entry?.id) || null;
3080
- if (historyEntryId && historyEntryId > lastHistoryId) {
3081
- await this.redis.hset(this.getAccountKey(), 'googleHistoryId', historyEntryId.toString());
3082
- lastHistoryId = historyEntryId;
3083
- }
3145
+ await advanceHistoryCursor(historyEntryId);
3084
3146
  } catch (err) {
3085
3147
  this.logger.error({
3086
3148
  msg: 'Failed to process history entry',
@@ -3111,6 +3173,9 @@ class GmailClient extends BaseClient {
3111
3173
  if (newestHistoryId && newestHistoryId > currentHistoryId) {
3112
3174
  await this.redis.hset(this.getAccountKey(), 'googleHistoryId', newestHistoryId.toString());
3113
3175
  }
3176
+
3177
+ // the run finished without dying, drop the in-flight marker
3178
+ await this.redis.hdel(this.getAccountKey(), 'googleHistoryProcessing');
3114
3179
  }
3115
3180
 
3116
3181
  /**