emailengine-app 2.79.6 → 2.79.8

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 (109) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +32 -0
  3. package/DOCKER_DEPLOYMENT.md +2 -0
  4. package/bin/emailengine.js +29 -13
  5. package/config/default.toml +13 -3
  6. package/data/google-crawlers.json +7 -1
  7. package/docker-compose.yml +12 -3
  8. package/install.sh +2 -0
  9. package/lib/api-routes/account-routes.js +14 -3
  10. package/lib/api-routes/mailbox-routes.js +4 -1
  11. package/lib/api-routes/message-routes.js +6 -5
  12. package/lib/api-routes/outbox-routes.js +7 -4
  13. package/lib/api-routes/settings-routes.js +34 -25
  14. package/lib/api-routes/stats-routes.js +8 -1
  15. package/lib/api-routes/submit-routes.js +2 -1
  16. package/lib/api-routes/template-routes.js +3 -2
  17. package/lib/bounce-detect.js +45 -0
  18. package/lib/consts.js +9 -3
  19. package/lib/egress-filter.js +39 -4
  20. package/lib/email-client/base-client.js +274 -24
  21. package/lib/email-client/gmail/gmail-api.js +15 -7
  22. package/lib/email-client/gmail-client.js +121 -64
  23. package/lib/email-client/imap/mailbox.js +18 -59
  24. package/lib/email-client/imap-client.js +53 -29
  25. package/lib/email-client/notification-handler.js +11 -2
  26. package/lib/email-client/outlook/graph-api.js +106 -90
  27. package/lib/email-client/outlook-client.js +222 -106
  28. package/lib/generate-text-preview.js +10 -5
  29. package/lib/headers-rewriter.js +1 -1
  30. package/lib/llm-pre-process.js +4 -1
  31. package/lib/mcp/json-schema.js +50 -2
  32. package/lib/outbox.js +22 -5
  33. package/lib/passkeys.js +39 -7
  34. package/lib/pre-process.js +4 -1
  35. package/lib/rewrite-text-nodes.js +12 -1
  36. package/lib/schemas.js +27 -5
  37. package/lib/settings.js +19 -1
  38. package/lib/sso.js +60 -7
  39. package/lib/submit-progress.js +29 -0
  40. package/lib/templates.js +11 -0
  41. package/lib/tools.js +115 -53
  42. package/lib/ui-routes/account-routes.js +79 -12
  43. package/lib/ui-routes/admin-config-routes.js +7 -21
  44. package/lib/ui-routes/admin-entities-routes.js +42 -12
  45. package/lib/ui-routes/auth-routes.js +242 -87
  46. package/lib/ui-routes/dashboard-routes.js +1 -1
  47. package/lib/ui-routes/internals-routes.js +2 -0
  48. package/lib/ui-routes/mcp-consent-routes.js +5 -2
  49. package/lib/ui-routes/network-config-routes.js +12 -3
  50. package/lib/ui-routes/oauth-config-routes.js +12 -1
  51. package/lib/ui-routes/route-helpers.js +41 -6
  52. package/lib/ui-routes/settings-page.js +10 -0
  53. package/lib/ui-routes/suppression-list-routes.js +16 -5
  54. package/lib/ui-routes/unsubscribe-routes.js +22 -3
  55. package/lib/webhooks.js +14 -2
  56. package/package.json +17 -17
  57. package/sbom.json +1 -1
  58. package/server.js +63 -35
  59. package/static/css/flyonui.css +1 -1
  60. package/static/css/src/app.tailwind.css +55 -0
  61. package/static/js/app.js +4 -35
  62. package/static/js/passkey-register.js +50 -1
  63. package/static/js/public.js +128 -0
  64. package/static/js/ui.js +183 -6
  65. package/static/licenses.html +371 -770
  66. package/translations/messages.pot +66 -66
  67. package/views/account/passkeys.hbs +141 -0
  68. package/views/account/password.hbs +11 -0
  69. package/views/account/security.hbs +318 -326
  70. package/views/accounts/account.hbs +90 -115
  71. package/views/accounts/register/imap-server.hbs +18 -12
  72. package/views/config/ai.hbs +2 -0
  73. package/views/config/branding.hbs +2 -0
  74. package/views/config/document-store/index.hbs +6 -6
  75. package/views/config/email-processing.hbs +2 -0
  76. package/views/config/imap-proxy.hbs +2 -0
  77. package/views/config/license.hbs +4 -1
  78. package/views/config/logging.hbs +3 -1
  79. package/views/config/mcp.hbs +2 -0
  80. package/views/config/network.hbs +2 -0
  81. package/views/config/oauth/app.hbs +3 -3
  82. package/views/config/oauth/edit.hbs +1 -1
  83. package/views/config/oauth/new.hbs +1 -1
  84. package/views/config/security.hbs +2 -0
  85. package/views/config/service.hbs +2 -0
  86. package/views/config/smtp.hbs +2 -0
  87. package/views/config/webhooks.hbs +9 -6
  88. package/views/error.hbs +6 -0
  89. package/views/layout/app.hbs +6 -3
  90. package/views/layout/login.hbs +1 -1
  91. package/views/layout/prompt.hbs +1 -1
  92. package/views/layout/public.hbs +1 -1
  93. package/views/legal.hbs +1 -1
  94. package/views/partials/filter_editor_js.hbs +1 -1
  95. package/views/partials/gateway_js.hbs +7 -6
  96. package/views/partials/oauth_form.hbs +5 -5
  97. package/views/partials/ui/btn.hbs +8 -2
  98. package/views/partials/ui/confirm-modal.hbs +2 -3
  99. package/views/partials/ui/empty-state.hbs +25 -0
  100. package/views/partials/ui/env-managed-alert.hbs +19 -0
  101. package/views/partials/webhook_form.hbs +1 -1
  102. package/views/partials/webhooks_editor_functions.hbs +5 -5
  103. package/views/unsubscribe.hbs +6 -0
  104. package/workers/api.js +193 -81
  105. package/workers/imap.js +32 -3
  106. package/workers/smtp.js +7 -0
  107. package/workers/submit.js +25 -1
  108. package/workers/webhooks.js +13 -17
  109. package/lib/reconnection-manager.js +0 -106
@@ -8,7 +8,7 @@ const msgpack = require('../msgpack');
8
8
  const addressparser = require('nodemailer/lib/addressparser');
9
9
  const libmime = require('libmime');
10
10
  const he = require('he');
11
- const { BaseClient, metricsMeta } = require('./base-client');
11
+ const { BaseClient, metricsMeta, isTransientNetworkError } = require('./base-client');
12
12
  const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
13
13
  const { emitChangeEvent, toCamelCase, collectCidReferences, cidReferenceRegex, truncateTextContents } = require('../tools');
14
14
  const { Gateway } = require('../gateway');
@@ -33,6 +33,13 @@ const { pushHeaderValue } = require('../utils/header-map');
33
33
 
34
34
  const MAX_GMAIL_BATCH_SIZE = 50;
35
35
 
36
+ // Gmail rejects batchModify calls carrying more ids than this
37
+ const BATCH_MODIFY_MAX_IDS = 1000;
38
+
39
+ // System labels that act as folders and that the API lets a client remove: SENT and DRAFT can
40
+ // not be, and the remaining system labels are markers (STARRED, IMPORTANT) or Inbox tabs
41
+ const FOLDER_SYSTEM_LABELS = new Set(['INBOX', 'SPAM', 'TRASH']);
42
+
36
43
  // Labels to exclude from folder listings
37
44
  const SKIP_LABELS = ['UNREAD', 'STARRED', 'IMPORTANT', 'CHAT', 'CATEGORY_PERSONAL'];
38
45
 
@@ -269,6 +276,9 @@ class GmailClient extends BaseClient {
269
276
  constructor(account, options) {
270
277
  super(account, options);
271
278
 
279
+ // A failed init() is scheduled again by the worker, see BaseClient.scheduleInitRetry()
280
+ this.retriesInit = true;
281
+
272
282
  this.cachedAccessToken = null;
273
283
  this.cachedAccessTokenRaw = null;
274
284
 
@@ -310,6 +320,7 @@ class GmailClient extends BaseClient {
310
320
  opts = opts || {};
311
321
 
312
322
  this.state = 'connecting';
323
+ this.cancelInitRetry();
313
324
  await this.setStateVal();
314
325
 
315
326
  await this.getAccount();
@@ -373,6 +384,13 @@ class GmailClient extends BaseClient {
373
384
  profileRes = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/profile`);
374
385
  }
375
386
  } catch (err) {
387
+ if (isTransientNetworkError(err)) {
388
+ // The provider could not be reached - a connection problem, not a refused
389
+ // credential. Left unflagged so the worker retries init() instead of reporting
390
+ // an authentication error that only re-authorization could clear
391
+ throw err;
392
+ }
393
+
376
394
  this.state = 'authenticationError';
377
395
  await this.setStateVal();
378
396
 
@@ -475,6 +493,9 @@ class GmailClient extends BaseClient {
475
493
  // Schedule fallback polling in case Pub/Sub notifications are dropped
476
494
  this.lastNotificationTime = Date.now();
477
495
  this.setupFallbackPollingTimer();
496
+
497
+ // Lets getToken() re-arm the timers after an authentication error clears
498
+ this.backgroundTimersArmed = true;
478
499
  }
479
500
 
480
501
  // Determine if this is a reconnection after error
@@ -524,6 +545,7 @@ class GmailClient extends BaseClient {
524
545
  async close() {
525
546
  clearTimeout(this.renewWatchTimer);
526
547
  clearTimeout(this.fallbackPollingTimer);
548
+ this.cancelInitRetry();
527
549
  this.closed = true;
528
550
 
529
551
  // A graceful close means the in-flight history entry did not kill this
@@ -599,6 +621,7 @@ class GmailClient extends BaseClient {
599
621
  async delete() {
600
622
  clearTimeout(this.renewWatchTimer);
601
623
  clearTimeout(this.fallbackPollingTimer);
624
+ this.cancelInitRetry();
602
625
  this.closed = true;
603
626
 
604
627
  // Clean up cached data
@@ -1107,41 +1130,31 @@ class GmailClient extends BaseClient {
1107
1130
  throw this.unknownPathError(path);
1108
1131
  }
1109
1132
 
1110
- // Step 1. Resolve matching messages
1111
- let messages = [];
1112
- let cursor;
1113
-
1114
- let maxMessages = 1000;
1115
- let notDone = true;
1116
-
1117
- // Fetch all matching messages (up to limit)
1118
- while (notDone && !search.emailIds) {
1119
- let messageListResult = await this.listMessages(
1120
- {
1121
- path,
1122
- pageSize: 250,
1123
- search,
1124
- cursor
1125
- },
1126
- { metadataOnly: true }
1127
- );
1133
+ // Step 1. Resolve matching messages. Pages through the whole result set, as the IMAP
1134
+ // client does - the ids are applied in batchModify-sized chunks below
1135
+ let emailIds = search.emailIds;
1136
+ if (!emailIds) {
1137
+ emailIds = [];
1138
+ let cursor;
1139
+ do {
1140
+ let messageListResult = await this.listMessages(
1141
+ {
1142
+ path,
1143
+ pageSize: 250,
1144
+ search,
1145
+ cursor
1146
+ },
1147
+ { metadataOnly: true }
1148
+ );
1128
1149
 
1129
- if (messageListResult.messages) {
1130
- messages = messages.concat(messageListResult.messages);
1131
- if (messages.length >= maxMessages) {
1132
- messages = messages.slice(0, maxMessages);
1133
- break;
1150
+ for (let message of messageListResult?.messages || []) {
1151
+ emailIds.push(message.id);
1134
1152
  }
1135
- }
1136
1153
 
1137
- if (!messageListResult.nextPageCursor) {
1138
- break;
1139
- }
1140
- cursor = messageListResult.nextPageCursor;
1154
+ cursor = messageListResult?.nextPageCursor;
1155
+ } while (cursor);
1141
1156
  }
1142
1157
 
1143
- let emailIds = search.emailIds || messages.map(message => message.id);
1144
-
1145
1158
  if (!emailIds?.length) {
1146
1159
  // nothing to do here
1147
1160
  return updates;
@@ -1170,9 +1183,7 @@ class GmailClient extends BaseClient {
1170
1183
  return { flags: {}, labels: {} };
1171
1184
  }
1172
1185
 
1173
- let labelUpdates = {
1174
- ids: emailIds
1175
- };
1186
+ let labelUpdates = {};
1176
1187
 
1177
1188
  if (addLabelIds.size) {
1178
1189
  labelUpdates.addLabelIds = Array.from(addLabelIds);
@@ -1182,8 +1193,15 @@ class GmailClient extends BaseClient {
1182
1193
  labelUpdates.removeLabelIds = Array.from(removeLabelIds);
1183
1194
  }
1184
1195
 
1185
- // Batch modify all messages
1186
- await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/batchModify`, 'post', labelUpdates, { returnText: true });
1196
+ // Batch modify all messages, in the chunks the endpoint accepts
1197
+ for (let i = 0; i < emailIds.length; i += BATCH_MODIFY_MAX_IDS) {
1198
+ await this.request(
1199
+ `${GMAIL_API_BASE}/gmail/v1/users/me/messages/batchModify`,
1200
+ 'post',
1201
+ Object.assign({ ids: emailIds.slice(i, i + BATCH_MODIFY_MAX_IDS) }, labelUpdates),
1202
+ { returnText: true }
1203
+ );
1204
+ }
1187
1205
 
1188
1206
  return Object.assign({}, updates, {
1189
1207
  emailIds
@@ -1211,14 +1229,22 @@ class GmailClient extends BaseClient {
1211
1229
  let labelsUpdate = { add: [label.id] };
1212
1230
 
1213
1231
  let sourcePath = options.source?.path;
1214
-
1215
- let sourceLabel = sourcePath ? await this.getLabel(sourcePath) : null;
1216
- if (sourcePath && !sourceLabel) {
1217
- throw this.unknownPathError(sourcePath);
1218
- }
1219
-
1220
- if (sourceLabel) {
1232
+ if (sourcePath) {
1233
+ let sourceLabel = await this.getLabel(sourcePath);
1234
+ if (!sourceLabel) {
1235
+ throw this.unknownPathError(sourcePath);
1236
+ }
1221
1237
  labelsUpdate.delete = sourceLabel.id;
1238
+ } else {
1239
+ // No source folder given: leave the folder the message is filed in the way Gmail's
1240
+ // own "move to" does, by dropping the system folder labels it carries. User labels
1241
+ // stay - without a source there is no telling which of them the caller sees as the
1242
+ // folder. Adding the target alone used to leave the message in the Inbox
1243
+ let currentData = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${emailId}`, 'get', { format: 'minimal' });
1244
+ let folderLabels = (currentData?.labelIds || []).filter(labelId => FOLDER_SYSTEM_LABELS.has(labelId) && labelId !== label.id);
1245
+ if (folderLabels.length) {
1246
+ labelsUpdate.delete = folderLabels;
1247
+ }
1222
1248
  }
1223
1249
 
1224
1250
  await this.updateMessage(emailId, { labels: labelsUpdate });
@@ -1340,6 +1366,12 @@ class GmailClient extends BaseClient {
1340
1366
  }
1341
1367
  }
1342
1368
 
1369
+ // Bounces recorded against this message by processNew(). The sync path fetches new
1370
+ // messages through here as well and never reads the field, so it skips the lookup
1371
+ if (!options.skipBounces) {
1372
+ await this.attachBounces(formattedMessage);
1373
+ }
1374
+
1343
1375
  // Generate web-safe HTML if requested
1344
1376
  if (options.preProcessHtml && formattedMessage.text && (formattedMessage.text.html || formattedMessage.text.plain)) {
1345
1377
  formattedMessage.text.html = await messageWebSafeHtml(formattedMessage);
@@ -1450,7 +1482,10 @@ class GmailClient extends BaseClient {
1450
1482
  await this.prepare();
1451
1483
 
1452
1484
  // Decode text part references
1453
- const [emailId, textParts] = msgpack.decode(Buffer.from(textId, 'base64url'));
1485
+ const [emailId, textParts] = this.unpackApiId(
1486
+ textId,
1487
+ parts => parts.length >= 2 && Array.isArray(parts[1]) && Array.isArray(parts[1][0]) && Array.isArray(parts[1][1])
1488
+ );
1454
1489
 
1455
1490
  const bodyParts = new Map();
1456
1491
 
@@ -1697,7 +1732,15 @@ class GmailClient extends BaseClient {
1697
1732
  ? buildDraftSendRequest(data.draft.draftId)
1698
1733
  : buildSendRequest(raw, data?.reference?.threadId);
1699
1734
 
1700
- const submitInfo = await this.request(`${GMAIL_API_BASE}${targetEndpoint}`, 'post', payload, { contentType });
1735
+ let submitInfo;
1736
+ try {
1737
+ submitInfo = await this.request(`${GMAIL_API_BASE}${targetEndpoint}`, 'post', payload, { contentType });
1738
+ } catch (err) {
1739
+ // Report the failure the way the SMTP path does (messageDeliveryError webhook,
1740
+ // feedback key) before the job decides whether to retry
1741
+ await this.handleSubmitError(err, { data, jobData, queueId, envelope });
1742
+ throw err;
1743
+ }
1701
1744
 
1702
1745
  if (data.draft && !data.draft.draftId) {
1703
1746
  // The draft resource could not be resolved at queue time, so the draft was sent as
@@ -1983,7 +2026,7 @@ class GmailClient extends BaseClient {
1983
2026
  return this.accountObject;
1984
2027
  }
1985
2028
 
1986
- async getToken() {
2029
+ async getTokenData() {
1987
2030
  let tokenData;
1988
2031
  try {
1989
2032
  tokenData = await this.accountObject.getActiveAccessTokenData();
@@ -1992,6 +2035,15 @@ class GmailClient extends BaseClient {
1992
2035
  // But we just got a valid token, so we've recovered
1993
2036
  this.state = 'connected';
1994
2037
  await this.setStateVal();
2038
+
2039
+ // Both background timers stop re-arming themselves on an authentication error,
2040
+ // so the recovery has to start them again or the watch would never be renewed
2041
+ // and nothing would poll for missed notifications until a manual reconnect.
2042
+ // Each setup clears its previous timer, so a still-armed one is not doubled.
2043
+ if (this.backgroundTimersArmed) {
2044
+ this.setupRenewWatchTimer();
2045
+ this.setupFallbackPollingTimer();
2046
+ }
1995
2047
  }
1996
2048
 
1997
2049
  // Track successful token refresh (only if token was actually refreshed, not cached)
@@ -2021,7 +2073,8 @@ class GmailClient extends BaseClient {
2021
2073
 
2022
2074
  throw E;
2023
2075
  }
2024
- return tokenData.accessToken;
2076
+
2077
+ return { accessToken: tokenData.accessToken, cached: !!tokenData.cached };
2025
2078
  }
2026
2079
 
2027
2080
  async getClient(force) {
@@ -2653,7 +2706,7 @@ class GmailClient extends BaseClient {
2653
2706
  */
2654
2707
  async getAttachmentContent(attachmentId, options) {
2655
2708
  options = options || {};
2656
- const [emailId, contentType, disposition, filename, id] = msgpack.decode(Buffer.from(attachmentId, 'base64url'));
2709
+ const [emailId, contentType, disposition, filename, id] = this.unpackApiId(attachmentId, parts => parts.length >= 5);
2657
2710
 
2658
2711
  await this.prepare();
2659
2712
 
@@ -2694,21 +2747,6 @@ class GmailClient extends BaseClient {
2694
2747
  return term;
2695
2748
  }
2696
2749
 
2697
- /**
2698
- * Builds the canonical 404 error for a mailbox path that does not match any Gmail label
2699
- * @param {string} path - Requested mailbox path
2700
- * @returns {Error} Error object with code and statusCode set
2701
- */
2702
- unknownPathError(path) {
2703
- let error = new Error('Unknown path');
2704
- error.info = {
2705
- response: `Mailbox doesn't exist: ${path}`
2706
- };
2707
- error.code = 'NotFound';
2708
- error.statusCode = 404;
2709
- return error;
2710
- }
2711
-
2712
2750
  /**
2713
2751
  * Converts IMAP flags to Gmail label operations
2714
2752
  * @param {string} flag - IMAP flag
@@ -2829,6 +2867,13 @@ class GmailClient extends BaseClient {
2829
2867
  }
2830
2868
  }
2831
2869
 
2870
+ // Size limits, in bytes
2871
+ for (let key of ['larger', 'smaller']) {
2872
+ if (search[key]) {
2873
+ queryParts.push(`${key}:${Number(search[key]) || 0}`);
2874
+ }
2875
+ }
2876
+
2832
2877
  // Header searches
2833
2878
  for (let headerKey of Object.keys(search.header || {})) {
2834
2879
  switch (headerKey.toLowerCase().trim()) {
@@ -3212,7 +3257,19 @@ class GmailClient extends BaseClient {
3212
3257
  options.headers = 'headers' in options ? options.headers : false;
3213
3258
  }
3214
3259
 
3215
- let messageData = await this.getMessage(eventEntry.id, options);
3260
+ // The sync path never reads the bounces field
3261
+ options.skipBounces = true;
3262
+
3263
+ let messageData;
3264
+ try {
3265
+ messageData = await this.getMessage(eventEntry.id, options);
3266
+ } catch (err) {
3267
+ if (err.statusCode !== 404) {
3268
+ throw err;
3269
+ }
3270
+ // deleted before the history entry was processed - reported as missing below, the
3271
+ // way the IMAP path reports a FETCH that finds nothing
3272
+ }
3216
3273
 
3217
3274
  if (!messageData) {
3218
3275
  await this.notify(this, MESSAGE_MISSING_NOTIFY, {
@@ -22,7 +22,6 @@ const { bounceDetect, applyDeliveryReport } = require('../../bounce-detect');
22
22
  const { decodeHeaders } = require('../../utils/decode-headers');
23
23
  const { isUnsafeKey } = require('../../utils/unsafe-key');
24
24
  const { arfDetect, camelCaseComplaint } = require('../../arf-detect');
25
- const appendList = require('../../append-list');
26
25
  const { messageWebSafeHtml } = require('../../web-safe-html');
27
26
  const simpleParser = require('mailparser').simpleParser;
28
27
  const ical = require('ical.js');
@@ -526,13 +525,6 @@ class Mailbox {
526
525
  return this.mailboxStatusKey;
527
526
  }
528
527
 
529
- /**
530
- * Gets Redis key for storing bounce information
531
- */
532
- getBounceKey() {
533
- return `${REDIS_PREFIX}iar:b:${this.connection.account}`;
534
- }
535
-
536
528
  /**
537
529
  * Gets Redis key for tracking seen messages (HyperLogLog)
538
530
  */
@@ -1039,7 +1031,7 @@ class Mailbox {
1039
1031
  /*
1040
1032
  if (messageData.messageId) {
1041
1033
  try {
1042
- let deleted = await appendList.clear(this.connection.redis, this.getBounceKey(), messageData.messageId);
1034
+ let deleted = await appendList.clear(this.connection.redis, this.connection.getBounceKey(), messageData.messageId);
1043
1035
  if (deleted) {
1044
1036
  this.logger.error({
1045
1037
  msg: 'Cleared bounce log for message',
@@ -1314,24 +1306,8 @@ class Mailbox {
1314
1306
 
1315
1307
  let stored = 0;
1316
1308
  if (bounce.action && bounce.recipient && bounce.messageId) {
1317
- // Store bounce information for later retrieval
1318
- let storedBounce = {
1319
- i: messageInfo.id,
1320
- r: bounce.recipient,
1321
- t: Date.now(),
1322
- a: bounce.action
1323
- };
1324
-
1325
- if (bounce.response && bounce.response.message) {
1326
- storedBounce.m = bounce.response.message;
1327
- }
1328
-
1329
- if (bounce.response && bounce.response.status) {
1330
- storedBounce.s = bounce.response.status;
1331
- }
1332
-
1333
1309
  // Store bounce info associated with original message ID
1334
- stored = await appendList.append(this.connection.redis, this.getBounceKey(), bounce.messageId, storedBounce);
1310
+ stored = await this.connection.storeBounce(messageInfo.id, bounce);
1335
1311
 
1336
1312
  bounceNotifyInfo = Object.assign({ bounceMessage: messageInfo.id }, bounce);
1337
1313
 
@@ -1983,39 +1959,7 @@ class Mailbox {
1983
1959
  }
1984
1960
 
1985
1961
  // Fetch associated bounce information
1986
- try {
1987
- if (result.messageId) {
1988
- let bounces = await appendList.list(this.connection.redis, this.getBounceKey(), result.messageId);
1989
- if (bounces && bounces.length) {
1990
- result.bounces = bounces.map(row => {
1991
- let bounce = {
1992
- message: row.i,
1993
- recipient: row.r,
1994
- action: row.a
1995
- };
1996
- if (row.m || row.s) {
1997
- bounce.response = {};
1998
- }
1999
- if (row.m) {
2000
- bounce.response.message = row.m;
2001
- }
2002
- if (row.s) {
2003
- bounce.response.status = row.s;
2004
- }
2005
- bounce.date = new Date(row.t).toISOString();
2006
- return bounce;
2007
- });
2008
- }
2009
- }
2010
- } catch (E) {
2011
- this.logger.error({
2012
- msg: 'Failed to fetch bounces',
2013
- id: messageData.id,
2014
- uid: messageData.uid,
2015
- messageId: messageData.messageId,
2016
- err: E
2017
- });
2018
- }
1962
+ await this.connection.attachBounces(result);
2019
1963
 
2020
1964
  return result;
2021
1965
  }
@@ -2733,7 +2677,15 @@ class Mailbox {
2733
2677
  }
2734
2678
 
2735
2679
  if (partList.length) {
2680
+ let lock;
2736
2681
  try {
2682
+ // The lock taken for the FETCH above is released by now. Without one
2683
+ // another task can select a different mailbox on this connection first,
2684
+ // and the UID would then address whatever message carries it there
2685
+ if (!options.skipLock) {
2686
+ lock = await this.getMailboxLock(connectionClient, { description: `Download inline images: ${message.uid}` });
2687
+ }
2688
+
2737
2689
  // Download all referenced images in batch
2738
2690
  let contentParts = await connectionClient.downloadMany(messageInfo.uid, partList, {
2739
2691
  uid: true
@@ -2762,6 +2714,10 @@ class Mailbox {
2762
2714
  }
2763
2715
  } catch (err) {
2764
2716
  this.logger.error({ msg: 'Failed to download attachments', uid: messageInfo.uid, partList, err });
2717
+ } finally {
2718
+ if (lock) {
2719
+ lock.release();
2720
+ }
2765
2721
  }
2766
2722
  }
2767
2723
  }
@@ -3459,6 +3415,7 @@ class Mailbox {
3459
3415
  if (cursorType && type !== cursorType) {
3460
3416
  let error = new Error('Invalid cursor');
3461
3417
  error.code = 'InvalidCursorType';
3418
+ error.statusCode = 400;
3462
3419
  throw error;
3463
3420
  }
3464
3421
  }
@@ -3469,6 +3426,8 @@ class Mailbox {
3469
3426
  if (typeof cursorPage === 'number' && cursorPage >= 0) {
3470
3427
  return cursorPage;
3471
3428
  }
3429
+ // Well-formed but not a cursor this client issued - reported like a broken one
3430
+ throw new Error('Cursor does not carry a page number');
3472
3431
  } catch (err) {
3473
3432
  this.logger.warn({ msg: 'Failed to parse paging cursor', cursorStr, err });
3474
3433
 
@@ -454,12 +454,8 @@ class IMAPClient extends BaseClient {
454
454
  */
455
455
  async ensureMainMailbox() {
456
456
  let mainPath = this.main ? this.main.path : 'INBOX';
457
- if (this.mailbox && normalizePath(this.mailbox.path) === normalizePath(mainPath)) {
458
- // already selected
459
- return;
460
- }
461
457
 
462
- // start waiting for changes
458
+ // start waiting for changes (Mailbox.select() skips the SELECT when it is already open)
463
459
  await this.select(mainPath);
464
460
  }
465
461
 
@@ -571,6 +567,11 @@ class IMAPClient extends BaseClient {
571
567
  async unpackUid(id) {
572
568
  const packed = Buffer.isBuffer(id) ? id : Buffer.from(id, 'base64url');
573
569
 
570
+ if (packed.length < 8) {
571
+ // too short to hold a mailbox id and a UID - not an id this client issued
572
+ return false;
573
+ }
574
+
574
575
  let mailboxId = packed.readUInt32BE(0);
575
576
  let uid = packed.readUInt32BE(4);
576
577
 
@@ -1322,10 +1323,6 @@ class IMAPClient extends BaseClient {
1322
1323
 
1323
1324
  // Select main mailbox for IDLE monitoring
1324
1325
  let mainPath = this.main ? this.main.path : 'INBOX';
1325
- if (this.mailbox && normalizePath(this.mailbox.path) === normalizePath(mainPath)) {
1326
- // already selected
1327
- return;
1328
- }
1329
1326
 
1330
1327
  // Check if client disconnected before mailbox selection
1331
1328
  if (!this.imapClient || !this.imapClient.usable) {
@@ -2492,32 +2489,54 @@ class IMAPClient extends BaseClient {
2492
2489
  deleted: false // set to true if mailbox is actually deleted
2493
2490
  };
2494
2491
 
2492
+ // A refused SELECT or DELETE is reported the way createMailbox()/renameMailbox() report
2493
+ // theirs. Swallowing it returned deleted:false and still cleared the local index below,
2494
+ // which emitted mailboxDeleted for a folder that was still there and then re-synced it
2495
+ // from scratch once the listing found it again
2496
+ let mapDeleteError = err => {
2497
+ if (err.mailboxMissing) {
2498
+ return this.unknownPathError(path);
2499
+ }
2500
+ if (err.serverResponseCode || err.responseStatus === 'NO') {
2501
+ let error = new Error('Delete failed');
2502
+ error.info = {
2503
+ response: err.response && typeof err.response === 'string' && err.response.replace(/^[^\s]*\s*/, '')
2504
+ };
2505
+ error.code = err.serverResponseCode || 'DeleteFailed';
2506
+ error.statusCode = 400;
2507
+ return error;
2508
+ }
2509
+ return err;
2510
+ };
2511
+
2512
+ // Acquire lock to prevent concurrent operations on the mailbox
2513
+ let lock;
2495
2514
  try {
2496
- // Acquire lock to prevent concurrent operations on the mailbox
2497
- let lock = await connectionClient.getMailboxLock(path, { description: `Delete mailbox ${path}` });
2515
+ lock = await connectionClient.getMailboxLock(path, { description: `Delete mailbox ${path}` });
2516
+ } catch (err) {
2517
+ this.logger.debug({ msg: 'Mailbox select error', path, err });
2518
+ throw mapDeleteError(err);
2519
+ }
2498
2520
 
2521
+ try {
2522
+ await connectionClient.mailboxClose();
2499
2523
  try {
2500
- await connectionClient.mailboxClose();
2501
- try {
2502
- await connectionClient.mailboxDelete(path);
2503
- result.deleted = true;
2504
- } catch (err) {
2505
- // kind of ignore
2506
- }
2507
- } finally {
2508
- lock.release();
2509
- // mailboxClose() leaves the connection with no mailbox selected, and ImapFlow can
2510
- // only re-arm IDLE for a mailbox it is in - so on the primary this is what puts the
2511
- // account back to watching for new mail. The lock here is ImapFlow's own rather
2512
- // than Mailbox.getMailboxLock(), which is the one that clears completedTimer, so
2513
- // nothing else on this path would report the task.
2514
- this.onTaskCompleted(connectionClient);
2524
+ await connectionClient.mailboxDelete(path);
2525
+ result.deleted = true;
2526
+ } catch (err) {
2527
+ throw mapDeleteError(err);
2515
2528
  }
2516
- } catch (err) {
2517
- this.logger.debug({ msg: 'Mailbox select error', path, err });
2529
+ } finally {
2530
+ lock.release();
2531
+ // mailboxClose() leaves the connection with no mailbox selected, and ImapFlow can
2532
+ // only re-arm IDLE for a mailbox it is in - so on the primary this is what puts the
2533
+ // account back to watching for new mail. The lock here is ImapFlow's own rather
2534
+ // than Mailbox.getMailboxLock(), which is the one that clears completedTimer, so
2535
+ // nothing else on this path would report the task.
2536
+ this.onTaskCompleted(connectionClient);
2518
2537
  }
2519
2538
 
2520
- // Clean up local cache
2539
+ // Clean up local cache, now that the folder is gone from the server
2521
2540
  if (this.mailboxes.has(normalizePath(path))) {
2522
2541
  let mailbox = this.mailboxes.get(normalizePath(path));
2523
2542
  await mailbox.clear();
@@ -2839,6 +2858,11 @@ class IMAPClient extends BaseClient {
2839
2858
  }
2840
2859
  }
2841
2860
 
2861
+ if (err.mailboxMissing) {
2862
+ // The API clients answer an unknown target folder with a 404 as well
2863
+ throw this.unknownPathError(data.path);
2864
+ }
2865
+
2842
2866
  err.code = 'UploadFail';
2843
2867
  err.statusCode = 502;
2844
2868
  throw err;
@@ -97,8 +97,10 @@ class NotificationHandler {
97
97
  payload.path = path;
98
98
  }
99
99
 
100
- if (mailbox && mailbox.listingEntry && mailbox.listingEntry.specialUse) {
101
- payload.specialUse = mailbox.listingEntry.specialUse;
100
+ // An IMAP Mailbox carries its listing entry, the API clients pass a plain { path, specialUse }
101
+ const specialUse = mailbox && ((mailbox.listingEntry && mailbox.listingEntry.specialUse) || mailbox.specialUse);
102
+ if (specialUse) {
103
+ payload.specialUse = specialUse;
102
104
  }
103
105
 
104
106
  if (event) {
@@ -192,6 +194,13 @@ class NotificationHandler {
192
194
  queueFlow
193
195
  });
194
196
 
197
+ // A child that fails for good (the document store job or a custom-route delivery out
198
+ // of attempts) has to be moved to the parent's failed-dependencies set, otherwise the
199
+ // main webhook job sits in waiting-children until retention prunes it
200
+ for (let child of queueFlow) {
201
+ child.opts = Object.assign({ ignoreDependencyOnFailure: true }, child.opts);
202
+ }
203
+
195
204
  const jobOptions = this.buildJobOptions(queueKeep);
196
205
 
197
206
  await this.flowProducer.add(