emailengine-app 2.74.2 → 2.76.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/.github/workflows/test.yml +0 -10
  2. package/CHANGELOG.md +40 -0
  3. package/config/e2e.toml +1 -1
  4. package/data/google-crawlers.json +1 -1
  5. package/lib/account.js +94 -18
  6. package/lib/api-routes/message-routes.js +3 -1
  7. package/lib/api-routes/route-helpers.js +3 -0
  8. package/lib/api-routes/submit-routes.js +159 -52
  9. package/lib/consts.js +6 -0
  10. package/lib/db.js +4 -1
  11. package/lib/egress-filter.js +220 -0
  12. package/lib/email-client/base-client.js +169 -27
  13. package/lib/email-client/gmail/send-request.js +16 -1
  14. package/lib/email-client/gmail-client.js +91 -10
  15. package/lib/email-client/imap/mailbox.js +3 -9
  16. package/lib/email-client/imap-client.js +103 -1
  17. package/lib/email-client/message-builder.js +24 -7
  18. package/lib/email-client/notification-handler.js +11 -12
  19. package/lib/email-client/outlook/send-request.js +18 -1
  20. package/lib/email-client/outlook-client.js +81 -9
  21. package/lib/imapproxy/imap-core/README.md +69 -0
  22. package/lib/oauth/external-account-config.js +41 -1
  23. package/lib/oauth/external-account-signer.js +7 -2
  24. package/lib/oauth/verify-app.js +18 -3
  25. package/lib/queue-retention.js +56 -0
  26. package/lib/respawn-backoff.js +95 -0
  27. package/lib/schemas.js +9 -2
  28. package/lib/settings.js +4 -1
  29. package/lib/tools.js +20 -0
  30. package/lib/ui-routes/admin-config-routes.js +22 -18
  31. package/lib/utils/network.js +122 -3
  32. package/lib/web-safe-html.js +401 -0
  33. package/lib/webhook-request.js +40 -2
  34. package/lib/webhooks.js +2 -3
  35. package/package.json +17 -20
  36. package/playwright.config.js +1 -1
  37. package/sbom.json +1 -1
  38. package/server.js +45 -8
  39. package/static/js/ee-client.js +55 -6
  40. package/static/js/ui.js +13 -0
  41. package/static/licenses.html +332 -292
  42. package/translations/messages.pot +52 -52
  43. package/views/config/webhooks.hbs +2 -2
  44. package/views/partials/webhooks_editor_functions.hbs +1 -1
  45. package/workers/api.js +32 -17
  46. package/workers/documents.js +6 -0
  47. package/workers/export.js +8 -1
  48. package/workers/imap.js +17 -19
  49. package/workers/submit.js +10 -0
  50. package/workers/webhooks.js +23 -2
  51. package/Gruntfile.js +0 -58
@@ -18,7 +18,7 @@ const settings = require('../../settings');
18
18
  const { bounceDetect } = require('../../bounce-detect');
19
19
  const { arfDetect } = require('../../arf-detect');
20
20
  const appendList = require('../../append-list');
21
- const { mimeHtml } = require('@postalsys/email-text-tools');
21
+ const { messageWebSafeHtml } = require('../../web-safe-html');
22
22
  const simpleParser = require('mailparser').simpleParser;
23
23
  const ical = require('ical.js');
24
24
  const addressparser = require('nodemailer/lib/addressparser');
@@ -1646,10 +1646,7 @@ class Mailbox {
1646
1646
  let notifyWebSafeHtml = await settings.get('notifyWebSafeHtml');
1647
1647
  if (notifyWebSafeHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
1648
1648
  // convert to web safe
1649
- messageInfo.text._generatedHtml = mimeHtml({
1650
- html: messageInfo.text.html,
1651
- text: messageInfo.text.plain
1652
- });
1649
+ messageInfo.text._generatedHtml = await messageWebSafeHtml(messageInfo);
1653
1650
  messageInfo.text.webSafe = true;
1654
1651
 
1655
1652
  // Embed images referenced by Content-ID
@@ -2680,10 +2677,7 @@ class Mailbox {
2680
2677
 
2681
2678
  // Convert to web-safe HTML if requested
2682
2679
  if (options.preProcessHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
2683
- messageInfo.text.html = mimeHtml({
2684
- html: messageInfo.text.html,
2685
- text: messageInfo.text.plain
2686
- });
2680
+ messageInfo.text.html = await messageWebSafeHtml(messageInfo);
2687
2681
  messageInfo.text.webSafe = true;
2688
2682
  }
2689
2683
 
@@ -26,6 +26,7 @@ const {
26
26
  readEnvValue,
27
27
  validUidValidity,
28
28
  getDuration,
29
+ download,
29
30
  LRUCache
30
31
  } = require('../tools');
31
32
  const { getLocalAddress } = require('../utils/network');
@@ -143,6 +144,14 @@ class IMAPClient extends BaseClient {
143
144
  // Secondary connection for commands that shouldn't interrupt IDLE
144
145
  this.commandClient = null;
145
146
 
147
+ // The client whose folder listing connect() already fetched and registered a
148
+ // Mailbox for. syncMailboxes() consumes it once to skip a listing refresh that
149
+ // would only re-issue the LIST connect() just ran. Keyed on the client rather
150
+ // than a plain flag so a marker that is never consumed - a setup that finished
151
+ // just as the account was paused - can not make an unrelated later sync, such
152
+ // as an operator-requested one, skip its refresh
153
+ this.listedClient = null;
154
+
146
155
  // Flag indicating if mailbox synchronization is in progress
147
156
  this.syncing = false;
148
157
 
@@ -908,6 +917,13 @@ class IMAPClient extends BaseClient {
908
917
  // Handle flag changes
909
918
  imapClient.on('flags', event => this.handleFlagsEvent(imapClient, event));
910
919
 
920
+ // The loop above registered a Mailbox for every listed folder, which is what
921
+ // processListing() would have done, so the sync that follows this call has
922
+ // nothing left to discover from a second listing. Keep the two registration
923
+ // paths in step - a filtering rule added to processListing() alone would never
924
+ // be applied during connection setup
925
+ this.listedClient = imapClient;
926
+
911
927
  return response;
912
928
  }
913
929
 
@@ -1179,13 +1195,37 @@ class IMAPClient extends BaseClient {
1179
1195
  clearTimeout(this.resyncTimer);
1180
1196
  clearTimeout(this.completedTimer);
1181
1197
 
1198
+ // Consumed unconditionally, so every later pass on this connection refreshes as
1199
+ // usual (see the field declaration for why this is keyed on the client)
1200
+ const listingIsFresh = this.listedClient === this.imapClient;
1201
+ this.listedClient = null;
1202
+
1182
1203
  if (!this.imapClient || !this.imapClient.usable) {
1183
1204
  this.logger.debug({ msg: 'Skipped syncing', reason: 'no imap client' });
1184
1205
  return;
1185
1206
  }
1186
1207
 
1187
1208
  // Refresh folder list and sync new folders
1188
- let synced = await this.refreshFolderList();
1209
+ let synced;
1210
+ if (!listingIsFresh) {
1211
+ try {
1212
+ synced = await this.refreshFolderList();
1213
+ } catch (err) {
1214
+ if (!err.responseStatus || !this.imapClient || !this.imapClient.usable || !this.mailboxes.size) {
1215
+ // Only a tagged command failure is tolerated. Network-level errors carry
1216
+ // no responseStatus and keep propagating (same rule as in mailbox.js), a
1217
+ // dead connection has to be re-established, and with no folder tracked
1218
+ // there would be nothing left to sync anyway
1219
+ throw err;
1220
+ }
1221
+ // The refresh only looks for folder changes - the folders already tracked
1222
+ // can be synced without it, and the next pass tries again. Some servers
1223
+ // refuse a repeated LIST on an otherwise healthy session (one Exchange-alike
1224
+ // answers "NO [SERVERBUG]"), and letting that throw used to tear down an
1225
+ // authenticated connection and reconnect on every attempt
1226
+ this.logger.warn({ msg: 'Failed to refresh folder list, syncing known folders', err });
1227
+ }
1228
+ }
1189
1229
 
1190
1230
  // Sync existing folders that weren't just synced
1191
1231
  for (let mailbox of this.mailboxes.values()) {
@@ -1498,6 +1538,13 @@ class IMAPClient extends BaseClient {
1498
1538
  this.imapClient = null;
1499
1539
  }
1500
1540
 
1541
+ if (prevImapClient === this.listedClient) {
1542
+ // Only reachable when this start() returns before connect() reassigns
1543
+ // the marker (e.g. an account with no usable credentials). Without it
1544
+ // the closed client stays referenced until some later setup or sync
1545
+ this.listedClient = null;
1546
+ }
1547
+
1501
1548
  // The close handler that maintains the connection count was removed
1502
1549
  // above, so update the tracking for the replaced client manually
1503
1550
  await this.untrackConnection(prevImapClient);
@@ -2310,6 +2357,61 @@ class IMAPClient extends BaseClient {
2310
2357
  return mailbox.getAttachment(message, false, options, connectionOptions);
2311
2358
  }
2312
2359
 
2360
+ /**
2361
+ * Resolves a stored draft message for sending
2362
+ * Verifies that the message is a draft and downloads its raw content
2363
+ * @param {string} id - API message id of the draft
2364
+ * @param {Object} connectionOptions - Connection options
2365
+ * @returns {Object} { raw: Buffer, draft: { message } }
2366
+ */
2367
+ async resolveDraftForSubmit(id, connectionOptions) {
2368
+ connectionOptions = connectionOptions || { allowSecondary: true };
2369
+
2370
+ this.checkIMAPConnection(connectionOptions);
2371
+
2372
+ let buf = Buffer.from(id, 'base64url');
2373
+ let message = await this.unpackUid(buf.subarray(0, 8));
2374
+ if (!message) {
2375
+ let err = new Error('Requested message was not found');
2376
+ err.code = 'MessageNotFound';
2377
+ err.statusCode = 404;
2378
+ throw err;
2379
+ }
2380
+
2381
+ // The message counts as a draft when it is stored in the Drafts folder or carries
2382
+ // the \Draft flag (covers accounts that keep drafts in a non-special-use folder)
2383
+ const inDraftsFolder = this.mailboxes.get(normalizePath(message.path))?.listingEntry?.specialUse === '\\Drafts';
2384
+ if (!inDraftsFolder) {
2385
+ // fetch flags only - nothing else from the message is needed for the check
2386
+ let messageData = await this.getMessage(id, { fields: { uid: true, flags: true } }, connectionOptions);
2387
+ if (!messageData) {
2388
+ let err = new Error('Requested message was not found');
2389
+ err.code = 'MessageNotFound';
2390
+ err.statusCode = 404;
2391
+ throw err;
2392
+ }
2393
+
2394
+ if (!(messageData.flags || []).includes('\\Draft')) {
2395
+ let err = new Error('Requested message is not a draft');
2396
+ err.code = 'MessageNotDraft';
2397
+ err.statusCode = 400;
2398
+ throw err;
2399
+ }
2400
+ }
2401
+
2402
+ let rawStream = await this.getRawMessage(id, {}, connectionOptions);
2403
+ if (!rawStream) {
2404
+ let err = new Error('Requested message was not found');
2405
+ err.code = 'MessageNotFound';
2406
+ err.statusCode = 404;
2407
+ throw err;
2408
+ }
2409
+
2410
+ let raw = await download(rawStream);
2411
+
2412
+ return { raw, draft: { message: id } };
2413
+ }
2414
+
2313
2415
  /**
2314
2416
  * Lists messages in a mailbox with pagination and search
2315
2417
  * @param {Object} options - Listing options including path, search criteria, pagination
@@ -511,6 +511,27 @@ class SmtpErrorBuilder {
511
511
  * Determines whether to copy sent message to Sent folder
512
512
  */
513
513
  class SentMailCopyDecider {
514
+ /**
515
+ * Whether the provider files SMTP-submitted messages into the Sent Mail folder on its
516
+ * own. True for Gmail and for non-delegated Outlook when no gateway is used - both store
517
+ * the sent message themselves, so an upload would duplicate it. Emails for delegated
518
+ * Outlook accounts are still uploaded as the sender is different (SMTP is disabled for
519
+ * shared mailboxes, so the message is sent using the main account).
520
+ * @param {Object} options - Decision options
521
+ * @param {Object} options.accountData - Account data
522
+ * @param {boolean} options.isGmail - Whether account is Gmail
523
+ * @param {boolean} options.isOutlook - Whether account is Outlook
524
+ * @param {Object} options.gatewayData - Gateway data if using gateway
525
+ * @returns {boolean} Whether the provider stores the sent copy itself
526
+ */
527
+ static providerSavesSentCopy(options) {
528
+ const { accountData, isGmail, isOutlook, gatewayData } = options;
529
+
530
+ const skipIfOutlook = isOutlook && (!accountData.oauth2 || !accountData.oauth2.auth || !accountData.oauth2.auth.delegatedUser);
531
+
532
+ return Boolean((isGmail || skipIfOutlook) && !gatewayData);
533
+ }
534
+
514
535
  /**
515
536
  * Determines if sent mail should be copied to Sent folder
516
537
  * @param {Object} options - Decision options
@@ -522,7 +543,7 @@ class SentMailCopyDecider {
522
543
  * @returns {boolean} Whether to copy to Sent folder
523
544
  */
524
545
  static shouldCopy(options) {
525
- const { accountData, data, isGmail, isOutlook, gatewayData } = options;
546
+ const { accountData, data } = options;
526
547
 
527
548
  // The default is to copy message to Sent Mail folder
528
549
  let shouldCopy = !Object.prototype.hasOwnProperty.call(accountData, 'copy');
@@ -532,14 +553,10 @@ class SentMailCopyDecider {
532
553
  shouldCopy = accountData.copy;
533
554
  }
534
555
 
535
- // Suppress uploads for Gmail and Outlook
556
+ // Suppress uploads when the provider stores the sent copy itself.
536
557
  // Unfortunately, previous default schema for all added accounts was copy=true,
537
558
  // so can't prefer account specific setting here
538
- // Emails for delegated accounts will be uploaded as the sender is different.
539
- // SMTP is disabled for shared mailboxes, so we need to send using the main account.
540
- const skipIfOutlook = isOutlook && (!accountData.oauth2 || !accountData.oauth2.auth || !accountData.oauth2.auth.delegatedUser);
541
-
542
- if ((isGmail || skipIfOutlook) && !gatewayData) {
559
+ if (this.providerSavesSentCopy(options)) {
543
560
  shouldCopy = false;
544
561
  }
545
562
 
@@ -6,6 +6,7 @@ const { webhooks: Webhooks } = require('../webhooks');
6
6
  const { getESClient, isDocumentStoreEnabled } = require('../document-store');
7
7
  const { getThread } = require('../threads');
8
8
  const settings = require('../settings');
9
+ const { buildRetentionPolicy } = require('../queue-retention');
9
10
 
10
11
  // Import notification-related constants
11
12
  const { MESSAGE_NEW_NOTIFY, MESSAGE_DELETED_NOTIFY, MESSAGE_UPDATED_NOTIFY, EMAIL_BOUNCE_NOTIFY, MAILBOX_DELETED_NOTIFY } = require('../consts');
@@ -227,9 +228,13 @@ class NotificationHandler {
227
228
  * Processes notification with document store sync only (no webhook)
228
229
  * @param {string} event - Event type
229
230
  * @param {Object} payload - Notification payload
231
+ * @param {boolean|number} queueKeep - Whether/how many jobs to keep
230
232
  */
231
- async processDocumentOnly(event, payload) {
232
- await this.documentsQueue.add(event, payload, DOCUMENT_JOB_OPTIONS);
233
+ async processDocumentOnly(event, payload, queueKeep) {
234
+ // Goes through buildJobOptions like every other enqueue. Passing DOCUMENT_JOB_OPTIONS
235
+ // straight through left this path on the hardcoded baseline: it ignored the queueKeep
236
+ // setting and, more importantly, never picked up the failed-entry floor.
237
+ await this.documentsQueue.add(event, payload, this.buildJobOptions(queueKeep).documents);
233
238
  }
234
239
 
235
240
  /**
@@ -238,17 +243,11 @@ class NotificationHandler {
238
243
  * @returns {Object} Job options for notify and documents queues
239
244
  */
240
245
  buildJobOptions(queueKeep) {
241
- const retention = typeof queueKeep === 'number' ? { age: 24 * 3600, count: queueKeep } : queueKeep;
246
+ const retention = buildRetentionPolicy(queueKeep);
242
247
 
243
- const notifyOptions = Object.assign({}, DEFAULT_JOB_OPTIONS, {
244
- removeOnComplete: retention,
245
- removeOnFail: retention
246
- });
248
+ const notifyOptions = Object.assign({}, DEFAULT_JOB_OPTIONS, retention);
247
249
 
248
- const documentOptions = Object.assign({}, DOCUMENT_JOB_OPTIONS, {
249
- removeOnComplete: retention,
250
- removeOnFail: retention
251
- });
250
+ const documentOptions = Object.assign({}, DOCUMENT_JOB_OPTIONS, retention);
252
251
 
253
252
  return {
254
253
  notify: notifyOptions,
@@ -300,7 +299,7 @@ class NotificationHandler {
300
299
  await this.processWebhookOnly(event, payload);
301
300
  } else if (addDocumentQueueJob) {
302
301
  // Document store only
303
- await this.processDocumentOnly(event, payload);
302
+ await this.processDocumentOnly(event, payload, queueKeep);
304
303
  }
305
304
  }
306
305
  }
@@ -45,4 +45,21 @@ function buildStructuredSendMailRequest(messagePayload, oauth2UserPath) {
45
45
  };
46
46
  }
47
47
 
48
- module.exports = { buildRawSendMailRequest, buildStructuredSendMailRequest };
48
+ /**
49
+ * Builds the request that sends an existing draft message. Graph requires an empty body
50
+ * (Content-Length: 0), answers 202 Accepted, and files the message into Sent Items itself.
51
+ *
52
+ * @param {String} emailId - Graph message id of the draft
53
+ * @param {String} oauth2UserPath - Graph user path ("me" or "users/<id>")
54
+ * @returns {Object} { path, body, options } for OutlookOauth.request()
55
+ */
56
+ function buildDraftSendRequest(emailId, oauth2UserPath) {
57
+ return {
58
+ path: `/${oauth2UserPath}/messages/${emailId}/send`,
59
+ // An empty Buffer keeps the request body at Content-Length: 0
60
+ body: Buffer.alloc(0),
61
+ options: { returnText: true }
62
+ };
63
+ }
64
+
65
+ module.exports = { buildRawSendMailRequest, buildStructuredSendMailRequest, buildDraftSendRequest };
@@ -9,14 +9,14 @@ const getSecret = require('../get-secret');
9
9
  const msgpack = require('msgpack5')();
10
10
  const he = require('he');
11
11
  const { emitChangeEvent, prepareUrl } = require('../tools');
12
- const { mimeHtml } = require('@postalsys/email-text-tools');
12
+ const { messageWebSafeHtml } = require('../web-safe-html');
13
13
  const crypto = require('crypto');
14
14
  const { Gateway } = require('../gateway');
15
15
  const { detectMimeType, detectExtension } = require('nodemailer/lib/mime-funcs/mime-types');
16
16
 
17
17
  // Import Graph API module for MS Graph API handling
18
18
  const graphApi = require('./outlook/graph-api');
19
- const { buildRawSendMailRequest, buildStructuredSendMailRequest } = require('./outlook/send-request');
19
+ const { buildRawSendMailRequest, buildStructuredSendMailRequest, buildDraftSendRequest } = require('./outlook/send-request');
20
20
 
21
21
  const {
22
22
  REDIS_PREFIX,
@@ -1760,10 +1760,7 @@ class OutlookClient extends BaseClient {
1760
1760
 
1761
1761
  // Generate web-safe HTML if requested
1762
1762
  if (options.preProcessHtml && formattedMessage.text && (formattedMessage.text.html || formattedMessage.text.plain)) {
1763
- formattedMessage.text.html = mimeHtml({
1764
- html: formattedMessage.text.html,
1765
- text: formattedMessage.text.plain
1766
- });
1763
+ formattedMessage.text.html = await messageWebSafeHtml(formattedMessage);
1767
1764
 
1768
1765
  formattedMessage.text.webSafe = true;
1769
1766
  }
@@ -2382,6 +2379,50 @@ class OutlookClient extends BaseClient {
2382
2379
  * Send an email message
2383
2380
  * Can use either Graph API sendMail endpoint or fall back to SMTP
2384
2381
  */
2382
+ /**
2383
+ * Resolves a stored draft message for sending
2384
+ * Verifies that the message is a Graph draft and downloads its raw content
2385
+ * @param {string} emailId - Graph message id of the draft
2386
+ * @returns {Object} { raw: Buffer, draft: { message } }
2387
+ */
2388
+ async resolveDraftForSubmit(emailId) {
2389
+ await this.prepare();
2390
+
2391
+ // The draft check and the raw download have no data dependency, so run them in parallel
2392
+ let messageData;
2393
+ let raw;
2394
+ try {
2395
+ [messageData, raw] = await Promise.all([
2396
+ this.request(`/${this.oauth2UserPath}/messages/${emailId}`, 'get', { $select: 'id,isDraft' }),
2397
+ this.getRawMessage(emailId)
2398
+ ]);
2399
+ } catch (err) {
2400
+ if (err.oauthRequest?.status === 404 || err.code === 'NotFound') {
2401
+ let error = new Error('Requested message was not found');
2402
+ error.code = 'MessageNotFound';
2403
+ error.statusCode = 404;
2404
+ throw error;
2405
+ }
2406
+ throw err;
2407
+ }
2408
+
2409
+ if (!messageData?.isDraft) {
2410
+ let err = new Error('Requested message is not a draft');
2411
+ err.code = 'MessageNotDraft';
2412
+ err.statusCode = 400;
2413
+ throw err;
2414
+ }
2415
+
2416
+ if (!raw) {
2417
+ let err = new Error('Requested message was not found');
2418
+ err.code = 'MessageNotFound';
2419
+ err.statusCode = 404;
2420
+ throw err;
2421
+ }
2422
+
2423
+ return { raw, draft: { message: emailId } };
2424
+ }
2425
+
2385
2426
  async submitMessage(data) {
2386
2427
  await this.prepare();
2387
2428
 
@@ -2429,9 +2470,40 @@ class OutlookClient extends BaseClient {
2429
2470
  return false;
2430
2471
  }
2431
2472
 
2432
- // Check if structured format should be used (opt-in)
2433
- // Default is raw MIME to preserve backward compatibility and calendar invites
2434
- if (data.useStructuredFormat) {
2473
+ // Three delivery shapes: an existing draft is sent via /messages/{id}/send, otherwise
2474
+ // the message goes through /sendMail as raw MIME (default - preserves calendar invites
2475
+ // and special MIME types) or as a structured JSON message (opt-in - respects the from
2476
+ // field for shared mailboxes)
2477
+ if (data.draft) {
2478
+ // Send the existing draft message - Graph files it into Sent Items itself
2479
+ try {
2480
+ let sendRequest = buildDraftSendRequest(data.draft.message, this.oauth2UserPath);
2481
+ await this.request(sendRequest.path, 'post', sendRequest.body, sendRequest.options);
2482
+ } catch (err) {
2483
+ switch (err.oauthRequest?.status) {
2484
+ case 400:
2485
+ case 404: {
2486
+ // the draft is gone or not sendable - retrying would not help
2487
+ let error = new Error(err.oauthRequest.status === 404 ? 'Draft message was not found' : 'Draft message can not be sent');
2488
+ error.info = {
2489
+ response: err.oauthRequest?.response?.error?.message || error.message
2490
+ };
2491
+ error.code = err.oauthRequest?.response?.error?.code || 'MessageNotFound';
2492
+ error.statusCode = 500; // do not retry sending
2493
+ throw error;
2494
+ }
2495
+
2496
+ default:
2497
+ this.logger.error({
2498
+ msg: 'Failed to submit draft message',
2499
+ messageId,
2500
+ draft: data.draft.message,
2501
+ err
2502
+ });
2503
+ throw err;
2504
+ }
2505
+ }
2506
+ } else if (data.useStructuredFormat) {
2435
2507
  // Parse raw message into structured format to properly handle 'from' address
2436
2508
  // Microsoft Graph API ignores the From header in raw MIME messages and uses
2437
2509
  // the authenticated user's address instead. By parsing and sending as structured
@@ -0,0 +1,69 @@
1
+ # imap-core (vendored fork)
2
+
3
+ This directory is a **vendored fork**, not a dependency. It is not listed in `package.json`, so
4
+ `npm update` never touches it and `npm audit` never sees it.
5
+
6
+ ## Provenance
7
+
8
+ Upstream: the `imap-core` module of [WildDuck](https://github.com/nodemailer/wildduck)
9
+ (`lib/imap-core` in that repository).
10
+
11
+ Imported into EmailEngine in `dd0d6e34` ("Added IMAP proxy server", 2022-08-23) and patched in
12
+ place since. It provides the IMAP protocol server that `lib/imapproxy/imap-server.js` builds on:
13
+ the command parser/compiler, the connection and command state machines, and the message indexer.
14
+
15
+ The WildDuck-specific parts of upstream (MongoDB-backed mailbox storage, the `test/prepare.sh`
16
+ fixture loader that talks to a WildDuck REST API) came along with the import and are not used
17
+ here.
18
+
19
+ ## Local patches
20
+
21
+ Everything below is EmailEngine-only and has no upstream equivalent. Re-syncing with upstream
22
+ means re-applying these.
23
+
24
+ | Commit | Date | Change |
25
+ | --- | --- | --- |
26
+ | `4453330a` | 2026-06-01 | Prevent IMAP proxy worker crashes and connection leaks (#596) |
27
+ | `3661dddb` | 2026-06-05 | Harden STARTTLS against command injection: reject pipelined data buffered before the TLS upgrade |
28
+ | `9fb8a5e3` | 2026-06-05 | Bound inbound line length in the parser, so an unterminated line cannot grow without limit |
29
+ | `627c6d47` | 2026-06-05 | Re-arm a generous idle timeout for proxied connections |
30
+ | `e97950e7` | 2026-06-05 | Close leaks and a worker crash found in the connection hardening review |
31
+ | `d51e92d2` | 2026-06-06 | Prevent post-BYE command dispatch during teardown |
32
+ | `31f6a590` | 2026-07-26 | Fix the dead teardown guard in the notification listener |
33
+
34
+ Earlier local changes (`09085d12`, `0a389560`, `7e2e94f3`, `04c2aa90`, `1d6df05e`, `612d9f96`,
35
+ `13edec58`, `2e0bf1ce`, `b9a3e06c`, `b58a827e`, `1813f089`) are maintenance: dependency swaps
36
+ (`punycode` to `punycode.js`, `wild-config` to `@zone-eu/wild-config`), the `fast` IMAP indexing
37
+ option, OAuth `useAuthServer` support, formatting and lint-glob fixes.
38
+
39
+ `git log -- lib/imapproxy/imap-core/` is the authoritative list; this table is a summary.
40
+
41
+ ## Tests
42
+
43
+ The `test/` directory is upstream's mocha suite. It is written for mocha, which is not a
44
+ dependency here, and had never been executed after the import.
45
+
46
+ The hermetic specs now run as part of the normal unit tier through
47
+ `test/imap-core-vendored-test.js`, which installs the mocha globals the specs expect and requires
48
+ them. **Do not edit the files under `test/` to make them run** - keeping them byte-identical to
49
+ upstream is what makes the patch list above reviewable. Adapt them from the EmailEngine side
50
+ instead.
51
+
52
+ Wired up and running:
53
+
54
+ - `imap-parser-test.js`
55
+ - `imap-compiler-test.js`
56
+ - `imap-compile-stream-test.js`
57
+ - `imap-indexer-test.js` (upstream has its `#rebuild` block commented out)
58
+ - `tools-test.js`
59
+
60
+ Not wired up, because they drive a live server via `test-server.js` and need MongoDB plus a
61
+ WildDuck REST API that does not exist in this repository:
62
+
63
+ - `protocol-test.js`
64
+ - `search-test.js`
65
+
66
+ That is a real coverage gap: `protocol-test.js` is the suite that exercises the connection and
67
+ command state machines, which is where most of the local patches above landed. The connection
68
+ handling that EmailEngine actually ships is covered instead by `test/dovecot/` (live IMAP against
69
+ Dovecot) and the IMAP proxy's own integration tests.
@@ -9,6 +9,42 @@
9
9
  const ACCEPTED_SUBJECT_TOKEN_TYPES = new Set(['urn:ietf:params:oauth:token-type:jwt', 'urn:ietf:params:oauth:token-type:id_token']);
10
10
  const IMPERSONATION_URL_RE = /\/v1\/projects\/-\/serviceAccounts\/([^/]+):generateAccessToken$/;
11
11
 
12
+ // Google STS is the only endpoint allowed to receive the subject token.
13
+ //
14
+ // The subject token is read from this host - a projected OIDC token file, or a metadata endpoint -
15
+ // and POSTed verbatim as the `subject_token` form field. A caller-chosen token_url therefore turns
16
+ // the credential source into an exfiltration channel: point it at your own server and whatever the
17
+ // configured file contains is delivered to you, and the response comes back in-band because
18
+ // /v1/oauth2/{app}/verify reports the endpoint's error_description. Pinning the host closes that
19
+ // channel, so the credential source can only ever be delivered to Google.
20
+ const STS_HOST = 'sts.googleapis.com';
21
+
22
+ // Regional STS endpoints, e.g. sts.europe-west1.rep.googleapis.com
23
+ const REGIONAL_STS_HOST_RE = /^sts\.[a-z0-9-]+\.rep\.googleapis\.com$/;
24
+
25
+ // Validates token_url against the Google STS endpoints. `allowedTokenHosts` is an injection point
26
+ // for tests that stand up a local STS double; production callers never pass it, which is the same
27
+ // arrangement as the signer's iamCredentialsBaseUrl option.
28
+ function assertTokenUrl(rawUrl, allowedTokenHosts) {
29
+ let url;
30
+ try {
31
+ url = new URL(rawUrl);
32
+ } catch (err) {
33
+ throw makeError('External account token_url is not a valid URL', 'EExternalAccountConfig');
34
+ }
35
+
36
+ if (allowedTokenHosts && allowedTokenHosts.includes(url.hostname)) {
37
+ return;
38
+ }
39
+
40
+ if (url.protocol !== 'https:' || !(url.hostname === STS_HOST || REGIONAL_STS_HOST_RE.test(url.hostname))) {
41
+ throw makeError(
42
+ `External account token_url must be a Google STS endpoint (https://${STS_HOST}/v1/token), got ${JSON.stringify(url.protocol + '//' + url.hostname)}`,
43
+ 'EExternalAccountConfig'
44
+ );
45
+ }
46
+ }
47
+
12
48
  function makeError(message, code, statusCode, extra) {
13
49
  let err = new Error(message);
14
50
  err.code = code;
@@ -25,7 +61,9 @@ function makeError(message, code, statusCode, extra) {
25
61
  // returns the derived target service account email. Throws an error tagged with
26
62
  // code 'EExternalAccountConfig' on any problem so callers can surface a clean
27
63
  // validation message instead of a late runtime failure.
28
- function validateConfig(config) {
64
+ function validateConfig(config, opts) {
65
+ const { allowedTokenHosts } = opts || {};
66
+
29
67
  if (!config || typeof config !== 'object') {
30
68
  throw makeError('External account configuration must be a JSON object', 'EExternalAccountConfig');
31
69
  }
@@ -41,6 +79,8 @@ function validateConfig(config) {
41
79
  }
42
80
  }
43
81
 
82
+ assertTokenUrl(config.token_url, allowedTokenHosts);
83
+
44
84
  if (!ACCEPTED_SUBJECT_TOKEN_TYPES.has(config.subject_token_type)) {
45
85
  throw makeError(
46
86
  `External account subject_token_type ${JSON.stringify(config.subject_token_type)} is not supported. ` +
@@ -19,7 +19,7 @@ class ExternalAccountSigner {
19
19
  constructor(opts) {
20
20
  opts = opts || {};
21
21
 
22
- let { targetServiceAccountEmail } = validateConfig(opts.config);
22
+ let { targetServiceAccountEmail } = validateConfig(opts.config, { allowedTokenHosts: opts.allowedTokenHosts });
23
23
 
24
24
  this.config = opts.config;
25
25
  // The service account whose Google-managed key signs the JWT. Exposed so
@@ -59,7 +59,12 @@ class ExternalAccountSigner {
59
59
  try {
60
60
  rawText = await this._readFile(source.file, 'utf8');
61
61
  } catch (err) {
62
- throw makeError(`Failed to read subject token file ${source.file}: ${err.message}`, 'ESubjectTokenRead', null, { cause: err });
62
+ // Report the errno rather than the raw message: the path came from the operator so
63
+ // echoing it back is useful, but the full fs message adds nothing and this string
64
+ // is surfaced in the verify report.
65
+ throw makeError(`Failed to read subject token file ${source.file}${err.code ? ` (${err.code})` : ''}`, 'ESubjectTokenRead', null, {
66
+ cause: err
67
+ });
63
68
  }
64
69
  return extractFromFormat(rawText, format);
65
70
  }
@@ -29,17 +29,29 @@ const withTimeout = (promise, ms, label) =>
29
29
  new Promise((resolve, reject) => setTimeout(() => reject(new Error(`${label} timed out after ${Math.round(ms / 1000)}s`)), ms).unref())
30
30
  ]);
31
31
 
32
+ // Upper bound on remote error text echoed into the verify report. These strings come from the
33
+ // remote endpoint, so they are reflected content: bound them rather than passing an
34
+ // arbitrarily long body through into the API response.
35
+ const MAX_REMOTE_DETAIL_LENGTH = 512;
36
+
37
+ function truncateDetail(value) {
38
+ if (typeof value !== 'string') {
39
+ return null;
40
+ }
41
+ return value.length > MAX_REMOTE_DETAIL_LENGTH ? `${value.slice(0, MAX_REMOTE_DETAIL_LENGTH)}...` : value;
42
+ }
43
+
32
44
  function describeResponse(err) {
33
45
  let resp = err && (err.response || (err.tokenRequest && err.tokenRequest.response));
34
46
  if (resp && typeof resp === 'object') {
35
47
  // Google API errors nest the detail under error.message; OAuth/STS errors
36
48
  // use top-level string error/error_description fields.
37
49
  if (resp.error && typeof resp.error === 'object' && resp.error.message) {
38
- return resp.error.message;
50
+ return truncateDetail(resp.error.message);
39
51
  }
40
- let parts = [resp.error, resp.error_description].filter(Boolean);
52
+ let parts = [resp.error, resp.error_description].filter(part => typeof part === 'string' && part);
41
53
  if (parts.length) {
42
- return parts.join(': ');
54
+ return truncateDetail(parts.join(': '));
43
55
  }
44
56
  }
45
57
  return null;
@@ -395,3 +407,6 @@ async function verifyOAuth2App(appId, opts) {
395
407
  }
396
408
 
397
409
  module.exports = { verifyOAuth2App };
410
+
411
+ // Exported for tests only; describeResponse reflects remote content into the verify report.
412
+ module.exports.__test__ = { describeResponse, MAX_REMOTE_DETAIL_LENGTH };