emailengine-app 2.79.7 → 2.79.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/.github/dependabot.yml +22 -0
  2. package/.github/workflows/test.yml +39 -0
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +37 -0
  5. package/DOCKER_DEPLOYMENT.md +8 -7
  6. package/Dockerfile +35 -11
  7. package/bin/emailengine.js +29 -13
  8. package/config/default.toml +15 -4
  9. package/copy-static-files.sh +23 -5
  10. package/data/google-crawlers.json +7 -1
  11. package/docker-compose.yml +12 -3
  12. package/install.sh +2 -0
  13. package/lib/account.js +26 -1
  14. package/lib/api-routes/account-routes.js +14 -3
  15. package/lib/api-routes/bull-board-routes.js +3 -2
  16. package/lib/api-routes/mailbox-routes.js +4 -1
  17. package/lib/api-routes/message-routes.js +6 -5
  18. package/lib/api-routes/outbox-routes.js +7 -4
  19. package/lib/api-routes/route-helpers.js +8 -0
  20. package/lib/api-routes/settings-routes.js +34 -25
  21. package/lib/api-routes/stats-routes.js +8 -1
  22. package/lib/api-routes/submit-routes.js +2 -1
  23. package/lib/api-routes/template-routes.js +3 -2
  24. package/lib/auth-token.js +73 -2
  25. package/lib/autodetect-imap-settings.js +33 -25
  26. package/lib/bounce-detect.js +45 -0
  27. package/lib/consts.js +13 -2
  28. package/lib/egress-fetch.js +133 -0
  29. package/lib/egress-filter.js +39 -4
  30. package/lib/email-client/base-client.js +274 -24
  31. package/lib/email-client/gmail/gmail-api.js +15 -7
  32. package/lib/email-client/gmail-client.js +121 -64
  33. package/lib/email-client/imap/mailbox.js +18 -59
  34. package/lib/email-client/imap-client.js +53 -29
  35. package/lib/email-client/notification-handler.js +11 -2
  36. package/lib/email-client/outlook/graph-api.js +106 -90
  37. package/lib/email-client/outlook-client.js +222 -106
  38. package/lib/export.js +35 -2
  39. package/lib/generate-text-preview.js +10 -5
  40. package/lib/handlebars-helpers.js +129 -0
  41. package/lib/headers-rewriter.js +1 -1
  42. package/lib/imap-proxy-auth.js +41 -21
  43. package/lib/imapproxy/imap-core/README.md +1 -0
  44. package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
  45. package/lib/imapproxy/imap-server.js +9 -10
  46. package/lib/llm-pre-process.js +4 -1
  47. package/lib/mcp/json-schema.js +50 -2
  48. package/lib/openapi/index.js +3 -0
  49. package/lib/outbox.js +50 -8
  50. package/lib/pre-process.js +4 -1
  51. package/lib/rate-limit.js +23 -4
  52. package/lib/rewrite-text-nodes.js +12 -1
  53. package/lib/schemas.js +37 -8
  54. package/lib/security-headers.js +396 -0
  55. package/lib/sentry.js +36 -4
  56. package/lib/settings.js +19 -1
  57. package/lib/smtp-auth.js +86 -7
  58. package/lib/sso.js +13 -3
  59. package/lib/submit-progress.js +29 -0
  60. package/lib/templates.js +11 -0
  61. package/lib/tools.js +361 -173
  62. package/lib/ui-routes/account-routes.js +73 -13
  63. package/lib/ui-routes/admin-config-routes.js +7 -21
  64. package/lib/ui-routes/admin-entities-routes.js +42 -12
  65. package/lib/ui-routes/auth-routes.js +87 -28
  66. package/lib/ui-routes/dashboard-routes.js +1 -1
  67. package/lib/ui-routes/export-routes.js +4 -0
  68. package/lib/ui-routes/internals-routes.js +2 -0
  69. package/lib/ui-routes/mcp-consent-routes.js +12 -2
  70. package/lib/ui-routes/network-config-routes.js +6 -5
  71. package/lib/ui-routes/oauth-config-routes.js +12 -1
  72. package/lib/ui-routes/route-helpers.js +65 -14
  73. package/lib/ui-routes/settings-page.js +10 -0
  74. package/lib/ui-routes/smtp-test-routes.js +7 -0
  75. package/lib/ui-routes/suppression-list-routes.js +16 -5
  76. package/lib/ui-routes/unsubscribe-routes.js +22 -3
  77. package/lib/webhook-egress.js +5 -0
  78. package/lib/webhooks.js +14 -2
  79. package/package.json +23 -26
  80. package/sbom.json +1 -1
  81. package/server.js +100 -71
  82. package/static/css/flyonui.css +1 -1
  83. package/static/js/ace/css/ace.css +1462 -0
  84. package/static/js/ace/css/kuroir-1.png +0 -0
  85. package/static/js/ace/css/kuroir-2.png +0 -0
  86. package/static/js/ace/css/main-1.png +0 -0
  87. package/static/js/ace/css/main-10.svg +4 -0
  88. package/static/js/ace/css/main-11.svg +5 -0
  89. package/static/js/ace/css/main-12.svg +4 -0
  90. package/static/js/ace/css/main-13.png +0 -0
  91. package/static/js/ace/css/main-14.png +0 -0
  92. package/static/js/ace/css/main-15.png +0 -0
  93. package/static/js/ace/css/main-16.png +0 -0
  94. package/static/js/ace/css/main-17.png +0 -0
  95. package/static/js/ace/css/main-18.png +0 -0
  96. package/static/js/ace/css/main-19.png +0 -0
  97. package/static/js/ace/css/main-2.png +0 -0
  98. package/static/js/ace/css/main-20.png +0 -0
  99. package/static/js/ace/css/main-21.png +0 -0
  100. package/static/js/ace/css/main-22.png +0 -0
  101. package/static/js/ace/css/main-23.png +0 -0
  102. package/static/js/ace/css/main-24.png +0 -0
  103. package/static/js/ace/css/main-25.svg +1 -0
  104. package/static/js/ace/css/main-26.png +0 -0
  105. package/static/js/ace/css/main-3.png +0 -0
  106. package/static/js/ace/css/main-4.png +0 -0
  107. package/static/js/ace/css/main-5.svg +7 -0
  108. package/static/js/ace/css/main-6.svg +9 -0
  109. package/static/js/ace/css/main-7.svg +7 -0
  110. package/static/js/ace/css/main-8.svg +9 -0
  111. package/static/js/ace/css/main-9.svg +6 -0
  112. package/static/js/ace/css/theme/kuroir.css +78 -0
  113. package/static/js/ace/css/theme/tomorrow_night.css +128 -0
  114. package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
  115. package/static/js/ace/css/theme/xcode.css +106 -0
  116. package/static/js/ace/css/tomorrow_night-1.png +0 -0
  117. package/static/js/ace/css/tomorrow_night-2.png +0 -0
  118. package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
  119. package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
  120. package/static/js/ace/css/xcode-1.png +0 -0
  121. package/static/js/ace/css/xcode-2.png +0 -0
  122. package/static/js/ee-client.js +256 -102
  123. package/static/js/public.js +7 -0
  124. package/static/js/ui.js +32 -0
  125. package/static/licenses.html +338 -298
  126. package/static/vendor/simplewebauthn/browser.min.js +2 -2
  127. package/translations/messages.pot +158 -112
  128. package/views/account/passkeys.hbs +8 -0
  129. package/views/account/password.hbs +11 -0
  130. package/views/account/security.hbs +18 -7
  131. package/views/accounts/account.hbs +21 -38
  132. package/views/accounts/browse.hbs +3 -1
  133. package/views/accounts/edit.hbs +1 -1
  134. package/views/accounts/register/imap-server.hbs +11 -3
  135. package/views/config/ai.hbs +3 -1
  136. package/views/config/branding.hbs +4 -2
  137. package/views/config/document-store/chat.hbs +1 -1
  138. package/views/config/document-store/index.hbs +1 -1
  139. package/views/config/email-processing.hbs +2 -0
  140. package/views/config/imap-proxy.hbs +3 -1
  141. package/views/config/license.hbs +1 -1
  142. package/views/config/logging.hbs +3 -1
  143. package/views/config/mcp.hbs +3 -1
  144. package/views/config/network.hbs +16 -16
  145. package/views/config/oauth/app.hbs +4 -4
  146. package/views/config/security.hbs +2 -0
  147. package/views/config/service.hbs +3 -1
  148. package/views/config/smtp.hbs +3 -1
  149. package/views/config/webhooks.hbs +4 -2
  150. package/views/error.hbs +10 -2
  151. package/views/internals/index.hbs +1 -1
  152. package/views/layout/app.hbs +9 -14
  153. package/views/layout/login.hbs +1 -1
  154. package/views/layout/prompt.hbs +1 -1
  155. package/views/layout/public.hbs +1 -1
  156. package/views/legal.hbs +1 -1
  157. package/views/mcp/authorize.hbs +1 -1
  158. package/views/partials/ace_assets.hbs +13 -0
  159. package/views/partials/add_account_modal.hbs +1 -1
  160. package/views/partials/address_list.hbs +4 -4
  161. package/views/partials/filter_editor_js.hbs +3 -3
  162. package/views/partials/gateway_js.hbs +1 -1
  163. package/views/partials/oauth_form.hbs +6 -6
  164. package/views/partials/public_theme_init.hbs +1 -1
  165. package/views/partials/template_form.hbs +2 -2
  166. package/views/partials/test_send.hbs +7 -4
  167. package/views/partials/theme_init.hbs +1 -1
  168. package/views/partials/ui/details.hbs +2 -2
  169. package/views/partials/ui/env-managed-alert.hbs +19 -0
  170. package/views/partials/webhook_form.hbs +1 -1
  171. package/views/partials/webhooks_editor_functions.hbs +1 -1
  172. package/views/reference/redirect.hbs +1 -1
  173. package/views/templates/template.hbs +2 -2
  174. package/views/tokens/new.hbs +1 -1
  175. package/views/unsubscribe.hbs +7 -1
  176. package/views/webhooks/webhook.hbs +2 -2
  177. package/workers/api.js +179 -175
  178. package/workers/export.js +1 -5
  179. package/workers/imap.js +33 -6
  180. package/workers/smtp.js +19 -43
  181. package/workers/submit.js +31 -13
  182. package/workers/webhooks.js +9 -24
  183. package/lib/reconnection-manager.js +0 -106
  184. package/static/front/EmailEngine_logo_horiz.png +0 -0
  185. package/static/front/EmailEngine_logo_vert.png +0 -0
  186. package/static/front/index.html +0 -57
  187. package/static/front/logo.png +0 -0
  188. package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const { BaseClient, metricsMeta } = require('./base-client');
3
+ const { BaseClient, metricsMeta, isTransientNetworkError } = require('./base-client');
4
4
  const { Account } = require('../account');
5
5
  const { checkAccountScopes } = require('../oauth/scope-checker');
6
6
  const settings = require('../settings');
@@ -91,10 +91,20 @@ Supported operations status:
91
91
  * OutlookClient handles email operations through Microsoft Graph API
92
92
  * Extends BaseClient to provide OAuth2-based email access for Outlook/Office365 accounts
93
93
  */
94
+ // Status for a Graph failure the caller did not map to a code of its own. The transport passes
95
+ // the provider status through (a mapped Graph error carries its own), so a throttled or failing
96
+ // provider is reported as such instead of as the caller's bad request
97
+ function graphFailureStatus(err) {
98
+ return Number(err?.statusCode) >= 400 ? Number(err.statusCode) : 400;
99
+ }
100
+
94
101
  class OutlookClient extends BaseClient {
95
102
  constructor(account, options) {
96
103
  super(account, options);
97
104
 
105
+ // A failed init() is scheduled again by the worker, see BaseClient.scheduleInitRetry()
106
+ this.retriesInit = true;
107
+
98
108
  // Token caching to avoid repeated auth calls
99
109
  this.cachedAccessToken = null;
100
110
  this.cachedAccessTokenRaw = null;
@@ -235,6 +245,7 @@ class OutlookClient extends BaseClient {
235
245
  this.state = 'connecting';
236
246
  clearTimeout(this.renewWatchTimer);
237
247
  clearTimeout(this.renewRetryTimer);
248
+ this.cancelInitRetry();
238
249
  await this.setStateVal();
239
250
 
240
251
  await this.getAccount();
@@ -284,6 +295,13 @@ class OutlookClient extends BaseClient {
284
295
  try {
285
296
  profileRes = await this.request(`/${this.oauth2UserPath}`, 'get', {});
286
297
  } catch (err) {
298
+ if (isTransientNetworkError(err)) {
299
+ // The provider could not be reached - a connection problem, not a refused
300
+ // credential. Left unflagged so the worker retries init() instead of reporting
301
+ // an authentication error that only re-authorization could clear
302
+ throw err;
303
+ }
304
+
287
305
  this.state = 'authenticationError';
288
306
  await this.setStateVal();
289
307
 
@@ -412,6 +430,7 @@ class OutlookClient extends BaseClient {
412
430
  async close() {
413
431
  clearTimeout(this.renewWatchTimer);
414
432
  clearTimeout(this.renewRetryTimer);
433
+ this.cancelInitRetry();
415
434
  this.closed = true;
416
435
 
417
436
  if (['init', 'connecting', 'syncing', 'connected'].includes(this.state)) {
@@ -458,6 +477,7 @@ class OutlookClient extends BaseClient {
458
477
  async delete() {
459
478
  clearTimeout(this.renewWatchTimer);
460
479
  clearTimeout(this.renewRetryTimer);
480
+ this.cancelInitRetry();
461
481
  this.closed = true;
462
482
 
463
483
  // Best-effort: delete MS Graph subscription
@@ -904,10 +924,30 @@ class OutlookClient extends BaseClient {
904
924
  };
905
925
  }
906
926
 
927
+ // A message already in Deleted Items is purged instead of being "moved" there again,
928
+ // matching what deleteMessages() does for that folder. The folder listing is read once
929
+ // for both resolutions, the way deleteMessages() reads it
930
+ let mailboxListing;
931
+ let sourceFolder;
932
+ try {
933
+ let currentData = await this.request(`/${this.oauth2UserPath}/messages/${emailId}`, 'get', { $select: 'parentFolderId' });
934
+ if (currentData?.parentFolderId) {
935
+ mailboxListing = (await this.getCachedMailboxListing()) || (await this.getMailboxListing());
936
+ sourceFolder = await this.resolveFolder(currentData.parentFolderId, { byId: true, mailboxListing });
937
+ }
938
+ } catch (err) {
939
+ // the move below reports a missing message on its own
940
+ this.logger.debug({ msg: 'Failed to resolve the source folder of a message', emailId, err });
941
+ }
942
+
943
+ if (sourceFolder?.specialUse === '\\Trash') {
944
+ return await this.deleteMessage(emailId, true);
945
+ }
946
+
907
947
  // Move to trash (soft delete)
908
948
  let messageData;
909
949
  try {
910
- messageData = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/move`, 'post', {
950
+ messageData = await this.requestWithRetry(`/${this.oauth2UserPath}/messages/${emailId}/move`, 'post', {
911
951
  destinationId: 'deleteditems'
912
952
  });
913
953
  if (!messageData) {
@@ -925,7 +965,7 @@ class OutlookClient extends BaseClient {
925
965
  // Resolve the destination folder for the response
926
966
  let folder;
927
967
  try {
928
- folder = await this.resolveFolder(messageData.parentFolderId, { byId: true });
968
+ folder = await this.resolveFolder(messageData.parentFolderId, { byId: true, mailboxListing });
929
969
  } catch (err) {
930
970
  this.logger.warn({
931
971
  msg: 'Failed to resolve folder for message',
@@ -1279,14 +1319,19 @@ class OutlookClient extends BaseClient {
1279
1319
  }
1280
1320
  }
1281
1321
  } catch (err) {
1322
+ // Without the current categories the PATCH below would replace every
1323
+ // message's category list with just the added labels, so a failed fetch
1324
+ // has to abort the update instead of being logged past
1282
1325
  this.logger.error({
1283
1326
  msg: 'Failed to fetch current categories',
1284
1327
  account: this.account,
1285
1328
  err
1286
1329
  });
1330
+ throw err;
1331
+ } finally {
1332
+ fetchBatch = [];
1333
+ fetchMessageMap = new Map();
1287
1334
  }
1288
- fetchBatch = [];
1289
- fetchMessageMap = new Map();
1290
1335
  };
1291
1336
 
1292
1337
  for (let emailId of emailIds) {
@@ -1397,6 +1442,11 @@ class OutlookClient extends BaseClient {
1397
1442
 
1398
1443
  // Process messages in batches
1399
1444
  for (let emailId of emailIds) {
1445
+ if (needsCurrentCategories && !currentCategories.has(emailId)) {
1446
+ // The category fetch for this message failed (logged above) - skipping it
1447
+ // keeps its existing categories instead of overwriting them with the additions
1448
+ continue;
1449
+ }
1400
1450
  batch.push(formatRequest(emailId));
1401
1451
  // submit batch when it reaches max size
1402
1452
  if (batch.length >= MAX_BATCH_SIZE) {
@@ -1432,7 +1482,7 @@ class OutlookClient extends BaseClient {
1432
1482
 
1433
1483
  let messageData;
1434
1484
  try {
1435
- messageData = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/move`, 'post', {
1485
+ messageData = await this.requestWithRetry(`/${this.oauth2UserPath}/messages/${emailId}/move`, 'post', {
1436
1486
  destinationId: targetFolder.id
1437
1487
  });
1438
1488
  if (!messageData) {
@@ -1462,7 +1512,7 @@ class OutlookClient extends BaseClient {
1462
1512
  response: err?.oauthRequest?.response?.error?.message || err?.message
1463
1513
  };
1464
1514
  error.code = err?.oauthRequest?.response?.error?.code || err?.code;
1465
- error.statusCode = 400;
1515
+ error.statusCode = graphFailureStatus(err);
1466
1516
  throw error;
1467
1517
  }
1468
1518
  }
@@ -1768,6 +1818,12 @@ class OutlookClient extends BaseClient {
1768
1818
  }
1769
1819
  }
1770
1820
 
1821
+ // Bounces recorded against this message by processNew(). The sync path fetches new
1822
+ // messages through here as well and never reads the field, so it skips the lookup
1823
+ if (!options.skipBounces) {
1824
+ await this.attachBounces(formattedMessage);
1825
+ }
1826
+
1771
1827
  // Generate web-safe HTML if requested
1772
1828
  if (options.preProcessHtml && formattedMessage.text && (formattedMessage.text.html || formattedMessage.text.plain)) {
1773
1829
  formattedMessage.text.html = await messageWebSafeHtml(formattedMessage);
@@ -2432,57 +2488,17 @@ class OutlookClient extends BaseClient {
2432
2488
  return { raw, draft: { message: emailId } };
2433
2489
  }
2434
2490
 
2435
- async submitMessage(data) {
2436
- await this.prepare();
2437
-
2438
- let accountData = await this.accountObject.loadAccountData();
2439
- if (!accountData.smtp && !accountData.oauth2 && !data.gateway) {
2440
- // can not make connection
2441
- let err = new Error('SMTP configuration not found');
2442
- err.code = 'SMTPUnavailable';
2443
- err.statusCode = 404;
2444
- throw err;
2445
- }
2446
-
2447
- let { raw, messageId, queueId, job: jobData, envelope } = data;
2448
-
2449
- if (raw?.buffer) {
2450
- // convert from a Uint8Array to a Buffer
2451
- raw = Buffer.from(raw);
2452
- }
2453
-
2454
- // Check if we should use SMTP gateway instead
2455
- let gatewayData;
2456
- let gatewayObject;
2457
- if (data.gateway) {
2458
- gatewayObject = new Gateway({ gateway: data.gateway, redis: this.redis, secret: this.secret });
2459
- try {
2460
- gatewayData = await gatewayObject.loadGatewayData();
2461
- } catch (err) {
2462
- this.logger.warn({ msg: 'Failed to load gateway data', messageId: data.messageId, gateway: data.gateway, err });
2463
- }
2464
- }
2465
-
2466
- if (gatewayData) {
2467
- // Send via SMTP (fall back to base class implementation)
2468
- return await super.submitMessage(data);
2469
- }
2470
-
2471
- // Get job entry for progress updates
2472
- const submitJobEntry = await this.submitQueue.getJob(jobData.id);
2473
- if (!submitJobEntry) {
2474
- // already failed?
2475
- this.logger.error({
2476
- msg: 'Submit job was not found',
2477
- job: jobData.id
2478
- });
2479
- return false;
2480
- }
2491
+ /**
2492
+ * Sends a queued message through Graph. Three delivery shapes: an existing draft is sent
2493
+ * via /messages/{id}/send, otherwise the message goes through /sendMail as raw MIME
2494
+ * (default - preserves calendar invites and special MIME types) or as a structured JSON
2495
+ * message (opt-in - respects the from field for shared mailboxes)
2496
+ * @param {Object} data - Submission payload
2497
+ * @param {Buffer} raw - Raw message source
2498
+ */
2499
+ async sendGraphMessage(data, raw) {
2500
+ let { messageId } = data;
2481
2501
 
2482
- // Three delivery shapes: an existing draft is sent via /messages/{id}/send, otherwise
2483
- // the message goes through /sendMail as raw MIME (default - preserves calendar invites
2484
- // and special MIME types) or as a structured JSON message (opt-in - respects the from
2485
- // field for shared mailboxes)
2486
2502
  if (data.draft) {
2487
2503
  // Send the existing draft message - Graph files it into Sent Items itself
2488
2504
  try {
@@ -2590,6 +2606,63 @@ class OutlookClient extends BaseClient {
2590
2606
  }
2591
2607
  }
2592
2608
  }
2609
+ }
2610
+
2611
+ async submitMessage(data) {
2612
+ await this.prepare();
2613
+
2614
+ let accountData = await this.accountObject.loadAccountData();
2615
+ if (!accountData.smtp && !accountData.oauth2 && !data.gateway) {
2616
+ // can not make connection
2617
+ let err = new Error('SMTP configuration not found');
2618
+ err.code = 'SMTPUnavailable';
2619
+ err.statusCode = 404;
2620
+ throw err;
2621
+ }
2622
+
2623
+ let { raw, messageId, queueId, job: jobData, envelope } = data;
2624
+
2625
+ if (raw?.buffer) {
2626
+ // convert from a Uint8Array to a Buffer
2627
+ raw = Buffer.from(raw);
2628
+ }
2629
+
2630
+ // Check if we should use SMTP gateway instead
2631
+ let gatewayData;
2632
+ let gatewayObject;
2633
+ if (data.gateway) {
2634
+ gatewayObject = new Gateway({ gateway: data.gateway, redis: this.redis, secret: this.secret });
2635
+ try {
2636
+ gatewayData = await gatewayObject.loadGatewayData();
2637
+ } catch (err) {
2638
+ this.logger.warn({ msg: 'Failed to load gateway data', messageId: data.messageId, gateway: data.gateway, err });
2639
+ }
2640
+ }
2641
+
2642
+ if (gatewayData) {
2643
+ // Send via SMTP (fall back to base class implementation)
2644
+ return await super.submitMessage(data);
2645
+ }
2646
+
2647
+ // Get job entry for progress updates
2648
+ const submitJobEntry = await this.submitQueue.getJob(jobData.id);
2649
+ if (!submitJobEntry) {
2650
+ // already failed?
2651
+ this.logger.error({
2652
+ msg: 'Submit job was not found',
2653
+ job: jobData.id
2654
+ });
2655
+ return false;
2656
+ }
2657
+
2658
+ try {
2659
+ await this.sendGraphMessage(data, raw);
2660
+ } catch (err) {
2661
+ // Report the failure the way the SMTP path does (messageDeliveryError webhook,
2662
+ // feedback key) before the job decides whether to retry
2663
+ await this.handleSubmitError(err, { data, jobData, queueId, envelope });
2664
+ throw err;
2665
+ }
2593
2666
 
2594
2667
  // Update job progress
2595
2668
  try {
@@ -2667,7 +2740,7 @@ class OutlookClient extends BaseClient {
2667
2740
 
2668
2741
  let mailbox;
2669
2742
  try {
2670
- mailbox = await this.request(reqUrl, 'post', {
2743
+ mailbox = await this.requestWithRetry(reqUrl, 'post', {
2671
2744
  displayName,
2672
2745
  isHidden: false
2673
2746
  });
@@ -2689,7 +2762,7 @@ class OutlookClient extends BaseClient {
2689
2762
  response: err?.oauthRequest?.response?.error?.message
2690
2763
  };
2691
2764
  error.code = err?.oauthRequest?.response?.error?.code;
2692
- error.statusCode = 400;
2765
+ error.statusCode = graphFailureStatus(err);
2693
2766
  throw error;
2694
2767
  }
2695
2768
  }
@@ -2767,7 +2840,22 @@ class OutlookClient extends BaseClient {
2767
2840
 
2768
2841
  let destinationParentFolder;
2769
2842
  if (sourceParentPath !== destinationParentPath) {
2770
- destinationParentFolder = await this.resolveFolder(destinationParentPath);
2843
+ if (!destinationParentPath) {
2844
+ // Moving to the top level: Graph addresses the root through its well-known name
2845
+ destinationParentFolder = { id: 'msgfolderroot' };
2846
+ } else {
2847
+ destinationParentFolder = await this.resolveFolder(destinationParentPath);
2848
+ if (!destinationParentFolder) {
2849
+ // Resolved before the rename step so a bad target leaves the folder untouched
2850
+ let error = new Error('Rename failed');
2851
+ error.info = {
2852
+ response: 'Not able to find the destination parent folder'
2853
+ };
2854
+ error.code = 'NotFound';
2855
+ error.statusCode = 404;
2856
+ throw error;
2857
+ }
2858
+ }
2771
2859
  }
2772
2860
 
2773
2861
  // Step 1. Rename if name changed
@@ -2959,7 +3047,7 @@ class OutlookClient extends BaseClient {
2959
3047
  /**
2960
3048
  * Get OAuth2 access token from account or delegated account
2961
3049
  */
2962
- async getToken() {
3050
+ async getTokenData() {
2963
3051
  let tokenData;
2964
3052
  try {
2965
3053
  tokenData = await (this.delegatedAccountObject || this.accountObject).getActiveAccessTokenData();
@@ -3006,7 +3094,7 @@ class OutlookClient extends BaseClient {
3006
3094
  throw E;
3007
3095
  }
3008
3096
 
3009
- return tokenData.accessToken;
3097
+ return { accessToken: tokenData.accessToken, cached: !!tokenData.cached };
3010
3098
  }
3011
3099
 
3012
3100
  /**
@@ -3894,7 +3982,7 @@ class OutlookClient extends BaseClient {
3894
3982
  options = options || {};
3895
3983
 
3896
3984
  // Decode compound attachment ID
3897
- const [emailId, id] = msgpack.decode(Buffer.from(attachmentId, 'base64url'));
3985
+ const [emailId, id] = this.unpackApiId(attachmentId, parts => parts.length >= 2);
3898
3986
 
3899
3987
  await this.prepare();
3900
3988
 
@@ -4025,20 +4113,26 @@ class OutlookClient extends BaseClient {
4025
4113
 
4026
4114
  newMessageOptions.showPath = true;
4027
4115
 
4028
- let messageData = await this.prepareNewMessage(event.message, newMessageOptions);
4029
- if (messageData) {
4030
- // When an email is sent, multiple "created" events are triggered: one for the draft and one for the sent mail folder.
4031
- // However, since we process the event with a delay, we only observe the message stored in the Sent Mail folder.
4032
- // This happens because the message was already moved there by the time we began processing the initial event from the drafts folder.
4033
-
4034
- // Check rolling bucket lock to see if we recently processed the same new email event for the same folder
4035
- let recentlySeen = await this.rollingBucketLock(`${messageData.id}:created`, messageData.path);
4036
- if (recentlySeen) {
4037
- this.logger.debug({ msg: 'Ignore recently seen new email event', type: 'history-event', emailId: event.message });
4038
- break;
4039
- }
4116
+ try {
4117
+ let messageData = await this.prepareNewMessage(event.message, newMessageOptions);
4118
+ if (messageData) {
4119
+ // When an email is sent, multiple "created" events are triggered: one for the draft and one for the sent mail folder.
4120
+ // However, since we process the event with a delay, we only observe the message stored in the Sent Mail folder.
4121
+ // This happens because the message was already moved there by the time we began processing the initial event from the drafts folder.
4122
+
4123
+ // Check rolling bucket lock to see if we recently processed the same new email event for the same folder
4124
+ let recentlySeen = await this.rollingBucketLock(`${messageData.id}:created`, messageData.path);
4125
+ if (recentlySeen) {
4126
+ this.logger.debug({ msg: 'Ignore recently seen new email event', type: 'history-event', emailId: event.message });
4127
+ break;
4128
+ }
4040
4129
 
4041
- await this.processNew(messageData, newMessageOptions);
4130
+ await this.processNew(messageData, newMessageOptions);
4131
+ }
4132
+ } catch (err) {
4133
+ // The event is already off the queue, so a failure here must not abort the
4134
+ // drain and lose the events behind it (the other branches catch their own)
4135
+ this.logger.error({ msg: 'Failed to process new message event', type: 'history-event', emailId: event.message, err });
4042
4136
  }
4043
4137
  break;
4044
4138
  }
@@ -4325,7 +4419,19 @@ class OutlookClient extends BaseClient {
4325
4419
  options.headers = 'headers' in options ? options.headers : false;
4326
4420
  }
4327
4421
 
4328
- let messageData = await this.getMessage(emailId, options);
4422
+ // The sync path never reads the bounces field
4423
+ options.skipBounces = true;
4424
+
4425
+ let messageData;
4426
+ try {
4427
+ messageData = await this.getMessage(emailId, options);
4428
+ } catch (err) {
4429
+ if (err.statusCode !== 404) {
4430
+ throw err;
4431
+ }
4432
+ // deleted before the notification was processed - reported as missing below, the
4433
+ // way the IMAP path reports a FETCH that finds nothing
4434
+ }
4329
4435
 
4330
4436
  if (!messageData) {
4331
4437
  await this.notify(this, MESSAGE_MISSING_NOTIFY, {
@@ -4345,13 +4451,12 @@ class OutlookClient extends BaseClient {
4345
4451
  * Used for bulk operations
4346
4452
  */
4347
4453
  async searchEmailIds(path, search) {
4348
- let messages = [];
4454
+ // Pages through the whole result set, as the IMAP client does - the callers apply the
4455
+ // change in Graph-sized batches. Only ids are needed, so the listing is the minimal one
4456
+ let emailIds = [];
4349
4457
  let cursor;
4350
4458
 
4351
- let maxMessages = 1000;
4352
- let notDone = true;
4353
-
4354
- while (notDone) {
4459
+ do {
4355
4460
  let messageListResult = await this.listMessages(
4356
4461
  {
4357
4462
  path,
@@ -4359,25 +4464,17 @@ class OutlookClient extends BaseClient {
4359
4464
  search,
4360
4465
  cursor
4361
4466
  },
4362
- { metadataOnly: true }
4467
+ { minimalFields: true }
4363
4468
  );
4364
4469
 
4365
- if (messageListResult?.messages?.length) {
4366
- // Use push instead of concat to avoid O(n^2) memory allocation
4367
- messages.push(...messageListResult.messages);
4368
- if (messages.length >= maxMessages) {
4369
- messages.length = maxMessages; // Truncate in place
4370
- break;
4371
- }
4470
+ for (let message of messageListResult?.messages || []) {
4471
+ emailIds.push(message.id);
4372
4472
  }
4373
4473
 
4374
- if (!messageListResult.nextPageCursor) {
4375
- break;
4376
- }
4377
- cursor = messageListResult.nextPageCursor;
4378
- }
4474
+ cursor = messageListResult?.nextPageCursor;
4475
+ } while (cursor);
4379
4476
 
4380
- return messages.map(message => message.id);
4477
+ return emailIds;
4381
4478
  }
4382
4479
 
4383
4480
  /**
@@ -4389,7 +4486,7 @@ class OutlookClient extends BaseClient {
4389
4486
 
4390
4487
  const searchParts = [];
4391
4488
 
4392
- const enabledKeys = ['to', 'cc', 'bcc', 'larger', 'smaller', 'body', 'before', 'sentBefore', 'since', 'sentSince'];
4489
+ const enabledKeys = ['from', 'to', 'cc', 'bcc', 'subject', 'larger', 'smaller', 'body', 'before', 'sentBefore', 'since', 'sentSince'];
4393
4490
 
4394
4491
  // not supported search terms
4395
4492
  for (let key of Object.keys(search)) {
@@ -4428,12 +4525,20 @@ class OutlookClient extends BaseClient {
4428
4525
  }
4429
4526
  }
4430
4527
 
4431
- if (search.before || search.sentBefore) {
4432
- searchParts.push(`received<=${escapeString(search.before || search.sentBefore)}`);
4528
+ if (search.before) {
4529
+ searchParts.push(`received<=${escapeString(search.before)}`);
4530
+ }
4531
+
4532
+ if (search.sentBefore) {
4533
+ searchParts.push(`sent<=${escapeString(search.sentBefore)}`);
4534
+ }
4535
+
4536
+ if (search.since) {
4537
+ searchParts.push(`received>=${escapeString(search.since)}`);
4433
4538
  }
4434
4539
 
4435
- if (search.since || search.sentSince) {
4436
- searchParts.push(`sent>=${escapeString(search.since || search.sentSince)}`);
4540
+ if (search.sentSince) {
4541
+ searchParts.push(`sent>=${escapeString(search.sentSince)}`);
4437
4542
  }
4438
4543
 
4439
4544
  if (search.smaller) {
@@ -4530,12 +4635,20 @@ class OutlookClient extends BaseClient {
4530
4635
  filterParts.push(`conversationId eq ${this.formatSearchTerm(search.threadId)}`);
4531
4636
  }
4532
4637
 
4533
- if (search.before || search.sentBefore) {
4534
- filterParts.push(`receivedDateTime lt ${this.formatSearchTerm(search.before || search.sentBefore, false)}`);
4638
+ if (search.before) {
4639
+ filterParts.push(`receivedDateTime lt ${this.formatSearchTerm(search.before, false)}`);
4535
4640
  }
4536
4641
 
4537
- if (search.since || search.sentSince) {
4538
- filterParts.push(`receivedDateTime gt ${this.formatSearchTerm(search.since || search.sentSince, false)}`);
4642
+ if (search.sentBefore) {
4643
+ filterParts.push(`sentDateTime lt ${this.formatSearchTerm(search.sentBefore, false)}`);
4644
+ }
4645
+
4646
+ if (search.since) {
4647
+ filterParts.push(`receivedDateTime gt ${this.formatSearchTerm(search.since, false)}`);
4648
+ }
4649
+
4650
+ if (search.sentSince) {
4651
+ filterParts.push(`sentDateTime gt ${this.formatSearchTerm(search.sentSince, false)}`);
4539
4652
  }
4540
4653
 
4541
4654
  // Category (label) filters - "has" matches messages tagged with the category, "not" excludes them
@@ -4618,7 +4731,7 @@ class OutlookClient extends BaseClient {
4618
4731
  * Handles proper escaping and date formatting
4619
4732
  */
4620
4733
  formatSearchTerm(term, quot = "'") {
4621
- if (typeof term === 'object' && term && Object.prototype.toString.apply(new Date()) === '[object Date]') {
4734
+ if (typeof term === 'object' && term && Object.prototype.toString.apply(term) === '[object Date]') {
4622
4735
  term = term.toISOString();
4623
4736
  }
4624
4737
 
@@ -4649,6 +4762,7 @@ class OutlookClient extends BaseClient {
4649
4762
  if (cursorType && type !== cursorType) {
4650
4763
  let error = new Error('Invalid cursor');
4651
4764
  error.code = 'InvalidCursorType';
4765
+ error.statusCode = 400;
4652
4766
  throw error;
4653
4767
  }
4654
4768
  }
@@ -4658,6 +4772,8 @@ class OutlookClient extends BaseClient {
4658
4772
  if (typeof cursorPage === 'number' && cursorPage >= 0) {
4659
4773
  return { cursorPage, skipToken };
4660
4774
  }
4775
+ // Well-formed but not a cursor this client issued - reported like a broken one
4776
+ throw new Error('Cursor does not carry a page number');
4661
4777
  } catch (err) {
4662
4778
  this.logger.warn({ msg: 'Failed to parse paging cursor', cursorStr, err });
4663
4779
 
package/lib/export.js CHANGED
@@ -89,6 +89,31 @@ function parseActiveEntry(entry) {
89
89
  return { account, exportId };
90
90
  }
91
91
 
92
+ const EXPORT_FILE_EXTENSION = '.ndjson.gz';
93
+ const EXPORT_FILE_EXTENSION_ENCRYPTED = '.ndjson.gz.enc';
94
+
95
+ /**
96
+ * Tells whether a stored file path is the export's own file.
97
+ *
98
+ * `filePath` is read back from Redis by the download and delete paths. Nothing but this module
99
+ * writes it, but a path trusted only because it was stored is exactly the field a later bug, or
100
+ * write access to Redis, would use to make the download route serve or the delete route unlink
101
+ * an arbitrary file. The basename is checked rather than the directory, because the export
102
+ * directory setting can change between an export and its download, and an older export still
103
+ * lives where it was written.
104
+ *
105
+ * @param {string} exportId - Export id the record belongs to
106
+ * @param {string} filePath - Stored path
107
+ * @returns {boolean} true when the path names the export's own file
108
+ */
109
+ function isOwnExportFile(exportId, filePath) {
110
+ if (!exportId || typeof filePath !== 'string') {
111
+ return false;
112
+ }
113
+ const base = pathlib.basename(filePath);
114
+ return [EXPORT_FILE_EXTENSION, EXPORT_FILE_EXTENSION_ENCRYPTED].some(ext => base === `${exportId}${ext}`);
115
+ }
116
+
92
117
  function generateExportId() {
93
118
  return EXPORT_ID_PREFIX + crypto.randomBytes(12).toString('hex');
94
119
  }
@@ -278,7 +303,7 @@ class Export {
278
303
 
279
304
  const secret = await getSecret();
280
305
  const isEncrypted = !!secret;
281
- const fileExtension = isEncrypted ? '.ndjson.gz.enc' : '.ndjson.gz';
306
+ const fileExtension = isEncrypted ? EXPORT_FILE_EXTENSION_ENCRYPTED : EXPORT_FILE_EXTENSION;
282
307
  const filePath = pathlib.join(exportPath, `${exportId}${fileExtension}`);
283
308
  const startDate = toTimestamp(options.startDate);
284
309
  const endDate = toTimestamp(options.endDate);
@@ -432,8 +457,10 @@ class Export {
432
457
  if (!isActive) {
433
458
  await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId)).exec();
434
459
 
435
- if (data.filePath) {
460
+ if (isOwnExportFile(exportId, data.filePath)) {
436
461
  await fs.promises.unlink(data.filePath).catch(() => {});
462
+ } else if (data.filePath) {
463
+ logger.error({ msg: 'Refusing to delete a file that is not the export file', account, exportId, filePath: data.filePath });
437
464
  }
438
465
  }
439
466
 
@@ -671,6 +698,11 @@ class Export {
671
698
  throw createError('Export file not found', 'FileNotFound', 404);
672
699
  }
673
700
 
701
+ if (!isOwnExportFile(exportId, data.filePath)) {
702
+ logger.error({ msg: 'Refusing to serve a file that is not the export file', account, exportId, filePath: data.filePath });
703
+ throw createError('Export file not found', 'FileNotFound', 404);
704
+ }
705
+
674
706
  try {
675
707
  await fs.promises.access(data.filePath, fs.constants.R_OK);
676
708
  } catch {
@@ -690,6 +722,7 @@ class Export {
690
722
  module.exports = {
691
723
  Export,
692
724
  generateExportId,
725
+ isOwnExportFile,
693
726
  calculateScore,
694
727
  getExportKey,
695
728
  getExportQueueKey,
@@ -44,11 +44,16 @@ function generateTextPreview(textContent, maxLength) {
44
44
  return text.replace(/[\u034f\u200c\u00a0]+/g, ' ').trim();
45
45
  }
46
46
 
47
- return text
48
- .substring(0, maxLength)
49
- .replace(/([^\s.!?]*)$/, '')
50
- .replace(/[\u034f\u200c\u00a0]+/g, ' ')
51
- .trim();
47
+ let truncated = text.substring(0, maxLength);
48
+
49
+ // Drop the word the cut landed in, unless the chunk is one unbroken run (a long URL or
50
+ // token), in which case the hard cut is the only preview there is
51
+ let preview = truncated.replace(/([^\s.!?]*)$/, '');
52
+ if (!preview.trim()) {
53
+ preview = truncated;
54
+ }
55
+
56
+ return preview.replace(/[\u034f\u200c\u00a0]+/g, ' ').trim();
52
57
  }
53
58
 
54
59
  module.exports = { generateTextPreview };