emailengine-app 2.77.0 → 2.78.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 (94) hide show
  1. package/.github/workflows/test.yml +80 -0
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +31 -0
  4. package/bin/emailengine.js +1 -1
  5. package/data/google-crawlers.json +1 -1
  6. package/encrypt.js +1 -1
  7. package/lib/account/expected-identity.js +88 -0
  8. package/lib/account.js +75 -26
  9. package/lib/api-reference/format.js +14 -0
  10. package/lib/api-reference/index.js +24 -7
  11. package/lib/api-reference/model.js +4 -2
  12. package/lib/api-routes/account-routes.js +19 -2
  13. package/lib/api-routes/behavior-notes.js +3 -0
  14. package/lib/append-list.js +3 -14
  15. package/lib/arf-detect.js +23 -1
  16. package/lib/autodetect-imap-settings.js +40 -16
  17. package/lib/base32.js +30 -0
  18. package/lib/bounce-detect.js +182 -62
  19. package/lib/egress-filter.js +89 -8
  20. package/lib/email-client/base-client.js +8 -72
  21. package/lib/email-client/gmail-client.js +3 -3
  22. package/lib/email-client/imap/listing-diff.js +3 -3
  23. package/lib/email-client/imap/mailbox.js +5 -69
  24. package/lib/email-client/imap-client.js +3 -2
  25. package/lib/email-client/message-builder.js +13 -13
  26. package/lib/email-client/outlook-client.js +1 -1
  27. package/lib/export.js +1 -1
  28. package/lib/gateway.js +1 -1
  29. package/lib/get-raw-email.js +1 -1
  30. package/lib/imapproxy/imap-core/lib/imap-connection.js +2 -2
  31. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  32. package/lib/imapproxy/imap-server.js +13 -3
  33. package/lib/license-beacon.js +1 -1
  34. package/lib/llm-pre-process.js +1 -1
  35. package/lib/msgpack.js +62 -0
  36. package/lib/oauth/decode-jwt-payload.js +39 -0
  37. package/lib/oauth/outlook-identity.js +61 -0
  38. package/lib/oauth/retry-setup.js +38 -0
  39. package/lib/oauth2-apps.js +1 -1
  40. package/lib/outbox.js +66 -3
  41. package/lib/pre-process.js +1 -1
  42. package/lib/read-env-value.js +37 -0
  43. package/lib/schemas.js +12 -0
  44. package/lib/templates.js +1 -1
  45. package/lib/tokens.js +1 -1
  46. package/lib/tools.js +117 -48
  47. package/lib/totp.js +67 -0
  48. package/lib/ui-routes/account-routes.js +91 -15
  49. package/lib/ui-routes/admin-config-routes.js +2 -7
  50. package/lib/ui-routes/auth-routes.js +6 -24
  51. package/lib/ui-routes/reference-routes.js +8 -5
  52. package/lib/ui-routes/route-helpers.js +28 -0
  53. package/lib/utils/is-email.js +34 -0
  54. package/lib/utils/to-camel-case.js +17 -0
  55. package/lib/webhook-egress.js +37 -0
  56. package/lib/webhooks.js +1 -1
  57. package/package.json +22 -24
  58. package/sbom.json +1 -0
  59. package/server.js +1 -1
  60. package/static/css/flyonui.css +1 -1
  61. package/static/css/public.css +3 -0
  62. package/static/css/src/app.tailwind.css +23 -0
  63. package/static/js/app.js +69 -0
  64. package/static/js/reference.js +286 -1
  65. package/static/licenses.html +656 -1558
  66. package/translations/README.md +64 -0
  67. package/translations/de.mo +0 -0
  68. package/translations/de.po +164 -120
  69. package/translations/en.po +200 -161
  70. package/translations/et.mo +0 -0
  71. package/translations/et.po +163 -120
  72. package/translations/fr.mo +0 -0
  73. package/translations/fr.po +163 -120
  74. package/translations/ja.mo +0 -0
  75. package/translations/ja.po +163 -120
  76. package/translations/messages.pot +76 -46
  77. package/translations/nl.mo +0 -0
  78. package/translations/nl.po +164 -120
  79. package/translations/pl.mo +0 -0
  80. package/translations/pl.po +163 -120
  81. package/views/account-identity-error.hbs +34 -0
  82. package/views/accounts/edit.hbs +1 -0
  83. package/views/accounts/register/imap.hbs +12 -2
  84. package/views/layout/app.hbs +29 -5
  85. package/views/oauth-scope-error.hbs +1 -1
  86. package/views/partials/reference/nav.hbs +36 -9
  87. package/views/partials/reference/operation.hbs +1 -1
  88. package/views/partials/reference/schema-node.hbs +1 -1
  89. package/views/partials/reference/token-alert.hbs +35 -10
  90. package/views/reference/index.hbs +1 -1
  91. package/workers/api.js +157 -87
  92. package/workers/imap.js +1 -1
  93. package/workers/submit.js +1 -1
  94. package/workers/webhooks.js +2 -13
@@ -5,7 +5,7 @@ const crypto = require('crypto');
5
5
  const logger = require('../logger');
6
6
  const settings = require('../settings');
7
7
  const { isDocumentStoreEnabled } = require('../document-store');
8
- const msgpack = require('msgpack5')();
8
+ const msgpack = require('../msgpack');
9
9
  const { templates } = require('../templates');
10
10
  const { Gateway } = require('../gateway');
11
11
  const os = require('os');
@@ -17,11 +17,11 @@ const { addTrackers } = require('../add-trackers');
17
17
  const { getRawEmail } = require('../get-raw-email');
18
18
  const { getTemplate } = require('@postalsys/templates');
19
19
  const { deepEqual } = require('assert');
20
- const { arfDetect } = require('../arf-detect');
20
+ const { arfDetect, camelCaseComplaint } = require('../arf-detect');
21
21
  const { createTransaction } = require('../redis-operations');
22
22
  const simpleParser = require('mailparser').simpleParser;
23
23
  const libmime = require('libmime');
24
- const { bounceDetect } = require('../bounce-detect');
24
+ const { bounceDetect, applyDeliveryReport } = require('../bounce-detect');
25
25
  const ical = require('ical.js');
26
26
  const { llmPreProcess } = require('../llm-pre-process');
27
27
  const { oauth2Apps } = require('../oauth2-apps');
@@ -50,7 +50,8 @@ const {
50
50
  emitChangeEvent,
51
51
  filterEmptyObjectValues,
52
52
  getDateBuckets,
53
- resolveCredentials
53
+ resolveCredentials,
54
+ useAuthServerForOAuth2
54
55
  } = require('../tools');
55
56
 
56
57
  // Import application constants
@@ -581,7 +582,7 @@ class BaseClient {
581
582
  // An external authentication server owns this account's tokens, so EmailEngine must ask for
582
583
  // one instead of renewing from a stored refresh token (it has none). The app is still
583
584
  // resolved above, because the caller needs it for the provider's host and port.
584
- if (accountData.oauth2.useAuthServer) {
585
+ if (await useAuthServerForOAuth2(accountData.oauth2, ctx.logger, { account: accountObject.account, target })) {
585
586
  try {
586
587
  let authData = await resolveCredentials(accountObject.account, target);
587
588
  // The auth server owns the credentials, but a shared mailbox is still addressed by
@@ -2457,17 +2458,7 @@ class BaseClient {
2457
2458
 
2458
2459
  if (report && report.arf && report.arf['original-rcpt-to'] && report.arf['original-rcpt-to'].length) {
2459
2460
  // can send report
2460
- let complaint = {};
2461
-
2462
- // Convert headers to camelCase
2463
- for (let subKey of ['arf', 'headers']) {
2464
- for (let key of Object.keys(report[subKey])) {
2465
- if (!complaint[subKey]) {
2466
- complaint[subKey] = {};
2467
- }
2468
- complaint[subKey][key.replace(/-(.)/g, (o, c) => c.toUpperCase())] = report[subKey][key];
2469
- }
2470
- }
2461
+ let complaint = camelCaseComplaint(report);
2471
2462
 
2472
2463
  complaintNotifyInfo = Object.assign({ complaintMessage: messageData.id }, complaint);
2473
2464
 
@@ -2497,62 +2488,7 @@ class BaseClient {
2497
2488
  let parsed = await simpleParser(raw, { keepDeliveryStatus: true });
2498
2489
  if (parsed) {
2499
2490
  content = { parsed };
2500
-
2501
- // Extract delivery status attachment
2502
- let deliveryStatus = parsed.attachments.find(attachment => attachment.contentType === 'message/delivery-status');
2503
- if (deliveryStatus) {
2504
- let deliveryEntries = libmime.decodeHeaders((deliveryStatus.content || '').toString().trim());
2505
- let structured = {};
2506
-
2507
- // Parse delivery status fields
2508
- for (let key of Object.keys(deliveryEntries)) {
2509
- if (!key) {
2510
- continue;
2511
- }
2512
- let displayKey = key.replace(/-(.)/g, (m, c) => c.toUpperCase());
2513
- let value = deliveryEntries[key].at(-1);
2514
- if (typeof value === 'string') {
2515
- // Parse structured fields
2516
- let m = value.match(/^([^\s;]+);/);
2517
- if (m) {
2518
- value = {
2519
- label: m[1],
2520
- value: value.substring(m[0].length).trim()
2521
- };
2522
- } else {
2523
- switch (key) {
2524
- case 'arrival-date': {
2525
- value.trim();
2526
- let date = new Date(value);
2527
- if (date.toString() !== 'Invalid Date') {
2528
- value = date.toISOString();
2529
- }
2530
- structured[displayKey] = value;
2531
- break;
2532
- }
2533
- default:
2534
- structured[displayKey] = value.trim();
2535
- }
2536
- }
2537
- } else {
2538
- // ???
2539
- structured[displayKey] = value;
2540
- }
2541
- }
2542
-
2543
- // Check if this is a delivery or delay notification
2544
- if (/^delivered|^delayed/i.test(structured.action)) {
2545
- this.logger.debug({
2546
- msg: 'Detected delivery report',
2547
- id: messageData.id,
2548
- uid: messageData.uid,
2549
- messageId: messageData.messageId,
2550
- report: structured
2551
- });
2552
-
2553
- messageData.deliveryReport = structured;
2554
- }
2555
- }
2491
+ applyDeliveryReport(parsed, messageData, this.logger);
2556
2492
  }
2557
2493
  } catch (err) {
2558
2494
  this.logger.error({
@@ -4,13 +4,13 @@ const { Account } = require('../account');
4
4
  const { oauth2Apps } = require('../oauth2-apps');
5
5
  const { checkAccountScopes, isSendOnlyByScopes } = require('../oauth/scope-checker');
6
6
  const getSecret = require('../get-secret');
7
- const msgpack = require('msgpack5')();
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
11
  const { BaseClient, metricsMeta } = require('./base-client');
12
12
  const { messageWebSafeHtml } = require('../web-safe-html');
13
- const { emitChangeEvent } = require('../tools');
13
+ const { emitChangeEvent, toCamelCase } = require('../tools');
14
14
  const { Gateway } = require('../gateway');
15
15
 
16
16
  const {
@@ -2292,7 +2292,7 @@ class GmailClient extends BaseClient {
2292
2292
  for (let header of messageData.payload.headers.filter(header => header.name.toLowerCase() === key)) {
2293
2293
  let parsed = addressparser(header.value, { flatten: true });
2294
2294
 
2295
- let envelopekey = key.toLowerCase().replace(/-(.)/g, (o, c) => c.toUpperCase());
2295
+ let envelopekey = toCamelCase(key.toLowerCase());
2296
2296
 
2297
2297
  envelope[envelopekey] = [].concat(envelope[envelopekey] || []).concat(parsed || []);
2298
2298
  }
@@ -12,7 +12,7 @@
12
12
  // Folder paths are compared through normalizePath(), which case-folds INBOX so a server that
13
13
  // reports "Inbox" one pass and "INBOX" the next does not look like a delete plus an add.
14
14
 
15
- const msgpack = require('msgpack5')();
15
+ const msgpack = require('../../msgpack');
16
16
  const { normalizePath } = require('../../tools');
17
17
  const { STORED_MAILBOX_FIELDS } = require('../../consts');
18
18
 
@@ -26,8 +26,8 @@ const COMPARED_MAILBOX_FIELDS = STORED_MAILBOX_FIELDS.filter(field => field !==
26
26
  * value is unusable. Callers drop a false entry rather than failing: a single corrupt value must
27
27
  * not take down the sync (or the mailboxes API response) for every other folder in the account.
28
28
  *
29
- * The shape check is not redundant with the try/catch. msgpack5 only throws on input it can not
30
- * parse at all - a corrupt buffer whose first byte happens to be a valid type marker decodes to
29
+ * The shape check is not redundant with the try/catch. The msgpack decoder only throws on input
30
+ * it can not parse at all - a corrupt buffer whose first byte is a valid type marker decodes to
31
31
  * a plain number or string instead. Such an entry has no `path`, so downstream it would register
32
32
  * as a phantom mailbox keyed `undefined` and (via Object.assign onto a primitive) surface as a
33
33
  * boxed Number in the mailboxes API response.
@@ -11,12 +11,12 @@ const {
11
11
  mailboxPathHash,
12
12
  getMailboxStatusKey
13
13
  } = require('../../tools');
14
- const msgpack = require('msgpack5')();
14
+ const msgpack = require('../../msgpack');
15
15
  const he = require('he');
16
16
  const libmime = require('libmime');
17
17
  const settings = require('../../settings');
18
- const { bounceDetect } = require('../../bounce-detect');
19
- const { arfDetect } = require('../../arf-detect');
18
+ const { bounceDetect, applyDeliveryReport } = require('../../bounce-detect');
19
+ const { arfDetect, camelCaseComplaint } = require('../../arf-detect');
20
20
  const appendList = require('../../append-list');
21
21
  const { messageWebSafeHtml } = require('../../web-safe-html');
22
22
  const simpleParser = require('mailparser').simpleParser;
@@ -1086,16 +1086,7 @@ class Mailbox {
1086
1086
 
1087
1087
  if (report && report.arf && report.arf['original-rcpt-to'] && report.arf['original-rcpt-to'].length) {
1088
1088
  // Valid complaint found - prepare notification data
1089
- let complaint = {};
1090
- for (let subKey of ['arf', 'headers']) {
1091
- for (let key of Object.keys(report[subKey])) {
1092
- if (!complaint[subKey]) {
1093
- complaint[subKey] = {};
1094
- }
1095
- // Convert kebab-case to camelCase
1096
- complaint[subKey][key.replace(/-(.)/g, (o, c) => c.toUpperCase())] = report[subKey][key];
1097
- }
1098
- }
1089
+ let complaint = camelCaseComplaint(report);
1099
1090
 
1100
1091
  complaintNotifyInfo = Object.assign({ complaintMessage: messageInfo.id }, complaint);
1101
1092
 
@@ -1128,62 +1119,7 @@ class Mailbox {
1128
1119
  let parsed = await simpleParser(sourceStream, { keepDeliveryStatus: true });
1129
1120
  if (parsed) {
1130
1121
  content = { parsed };
1131
-
1132
- // Extract delivery status information
1133
- let deliveryStatus = parsed.attachments.find(attachment => attachment.contentType === 'message/delivery-status');
1134
- if (deliveryStatus) {
1135
- let deliveryEntries = libmime.decodeHeaders((deliveryStatus.content || '').toString().trim());
1136
- let structured = {};
1137
-
1138
- // Parse delivery status headers
1139
- for (let key of Object.keys(deliveryEntries)) {
1140
- if (!key) {
1141
- continue;
1142
- }
1143
- let displayKey = key.replace(/-(.)/g, (m, c) => c.toUpperCase());
1144
- let value = deliveryEntries[key].at(-1);
1145
- if (typeof value === 'string') {
1146
- // Parse structured values like "rfc822;example.com"
1147
- let m = value.match(/^([^\s;]+);/);
1148
- if (m) {
1149
- value = {
1150
- label: m[1],
1151
- value: value.substring(m[0].length).trim()
1152
- };
1153
- } else {
1154
- switch (key) {
1155
- case 'arrival-date': {
1156
- value.trim();
1157
- let date = new Date(value);
1158
- if (date.toString() !== 'Invalid Date') {
1159
- value = date.toISOString();
1160
- }
1161
- structured[displayKey] = value;
1162
- break;
1163
- }
1164
- default:
1165
- structured[displayKey] = value.trim();
1166
- }
1167
- }
1168
- } else {
1169
- // ???
1170
- structured[displayKey] = value;
1171
- }
1172
- }
1173
-
1174
- // Only consider as delivery report if action indicates delivery or delay
1175
- if (/^delivered|^delayed/i.test(structured.action)) {
1176
- this.logger.debug({
1177
- msg: 'Detected delivery report',
1178
- id: messageInfo.id,
1179
- uid: messageInfo.uid,
1180
- messageId: messageInfo.messageId,
1181
- report: structured
1182
- });
1183
-
1184
- messageInfo.deliveryReport = structured;
1185
- }
1186
- }
1122
+ applyDeliveryReport(parsed, messageInfo, this.logger);
1187
1123
  }
1188
1124
  } catch (err) {
1189
1125
  this.logger.error({
@@ -6,7 +6,7 @@ const { Mailbox } = require('./imap/mailbox');
6
6
  const logger = require('../logger');
7
7
  const packageData = require('../../package.json');
8
8
  const { backOff } = require('exponential-backoff');
9
- const msgpack = require('msgpack5')();
9
+ const msgpack = require('../msgpack');
10
10
 
11
11
  const { oauth2ProviderData } = require('../oauth2-apps');
12
12
  const { BaseClient } = require('./base-client');
@@ -20,6 +20,7 @@ const { ReconnectBackoff } = require('./reconnect-backoff');
20
20
  const {
21
21
  normalizePath,
22
22
  resolveCredentials,
23
+ useAuthServerForConnection,
23
24
  emitChangeEvent,
24
25
  getByteSize,
25
26
  getBoolean,
@@ -1387,7 +1388,7 @@ class IMAPClient extends BaseClient {
1387
1388
  }
1388
1389
 
1389
1390
  // If authentication server is set then it overrides authentication data
1390
- if (imapConnectionConfig.useAuthServer) {
1391
+ if (await useAuthServerForConnection(imapConnectionConfig, ctx.logger, { account: this.account, target: 'imap' })) {
1391
1392
  try {
1392
1393
  imapConnectionConfig.auth = await resolveCredentials(this.account, 'imap');
1393
1394
  } catch (err) {
@@ -2,7 +2,7 @@
2
2
 
3
3
  const { Gateway } = require('../gateway');
4
4
  const { oauth2ProviderData } = require('../oauth2-apps');
5
- const { resolveCredentials } = require('../tools');
5
+ const { resolveCredentials, useAuthServerForConnection } = require('../tools');
6
6
  const { getLocalAddress } = require('../utils/network');
7
7
  const settings = require('../settings');
8
8
  const { TLS_DEFAULTS } = require('../consts');
@@ -133,20 +133,20 @@ class SmtpConfigBuilder {
133
133
  * @returns {Promise<Object|null>} Resolved auth credentials
134
134
  */
135
135
  async resolveAuthServer(smtpConnectionConfig) {
136
- if (!smtpConnectionConfig.useAuthServer) {
137
- return smtpConnectionConfig.auth;
136
+ if (await useAuthServerForConnection(smtpConnectionConfig, this.logger, { account: this.account, target: 'smtp' })) {
137
+ try {
138
+ return await resolveCredentials(this.account, 'smtp');
139
+ } catch (err) {
140
+ err.authenticationFailed = true;
141
+ this.logger.error({
142
+ account: this.account,
143
+ err
144
+ });
145
+ throw err;
146
+ }
138
147
  }
139
148
 
140
- try {
141
- return await resolveCredentials(this.account, 'smtp');
142
- } catch (err) {
143
- err.authenticationFailed = true;
144
- this.logger.error({
145
- account: this.account,
146
- err
147
- });
148
- throw err;
149
- }
149
+ return smtpConnectionConfig.auth;
150
150
  }
151
151
 
152
152
  /**
@@ -6,7 +6,7 @@ const { checkAccountScopes } = require('../oauth/scope-checker');
6
6
  const settings = require('../settings');
7
7
  const { oauth2Apps } = require('../oauth2-apps');
8
8
  const getSecret = require('../get-secret');
9
- const msgpack = require('msgpack5')();
9
+ const msgpack = require('../msgpack');
10
10
  const he = require('he');
11
11
  const { emitChangeEvent, prepareUrl } = require('../tools');
12
12
  const { messageWebSafeHtml } = require('../web-safe-html');
package/lib/export.js CHANGED
@@ -4,7 +4,7 @@ const os = require('os');
4
4
  const crypto = require('crypto');
5
5
  const fs = require('fs');
6
6
  const pathlib = require('path');
7
- const msgpack = require('msgpack5')();
7
+ const msgpack = require('./msgpack');
8
8
  const { redis, exportQueue } = require('./db');
9
9
  const settings = require('./settings');
10
10
  const logger = require('./logger');
package/lib/gateway.js CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const msgpack = require('msgpack5')();
3
+ const msgpack = require('./msgpack');
4
4
  const Boom = require('@hapi/boom');
5
5
  const { REDIS_PREFIX } = require('./consts');
6
6
  const logger = require('./logger');
@@ -10,7 +10,7 @@ const { randomUUID: uuid } = require('crypto');
10
10
  const os = require('os');
11
11
  const libmime = require('libmime');
12
12
  const { getBoolean, genBaseBoundary } = require('./tools');
13
- const msgpack = require('msgpack5')();
13
+ const msgpack = require('./msgpack');
14
14
  const crypto = require('crypto');
15
15
  const simpleParser = require('mailparser').simpleParser;
16
16
 
@@ -8,7 +8,7 @@ const search = require('./search');
8
8
  const dns = require('dns');
9
9
  const crypto = require('crypto');
10
10
  const os = require('os');
11
- const base32 = require('base32.js');
11
+ const { base32Encode } = require('../../../base32');
12
12
  const EventEmitter = require('events').EventEmitter;
13
13
  const packageInfo = require('../../../../package');
14
14
 
@@ -33,7 +33,7 @@ class IMAPConnection extends EventEmitter {
33
33
 
34
34
  options = options || {};
35
35
  // Random session ID, used for logging
36
- this.id = options.id || base32.encode(crypto.randomBytes(10)).toLowerCase();
36
+ this.id = options.id || base32Encode(crypto.randomBytes(10)).toLowerCase();
37
37
 
38
38
  this.ignore = options.ignore;
39
39
 
@@ -8,7 +8,7 @@ const tlsOptions = require('./tls-options');
8
8
  const EventEmitter = require('events').EventEmitter;
9
9
  const shared = require('nodemailer/lib/shared');
10
10
  const punycode = require('punycode.js');
11
- const base32 = require('base32.js');
11
+ const { base32Encode } = require('../../../base32');
12
12
 
13
13
  const CLOSE_TIMEOUT = 1 * 1000; // how much to wait until pending connections are terminated
14
14
 
@@ -208,7 +208,7 @@ class IMAPServer extends EventEmitter {
208
208
 
209
209
  _handleProxy(socket, callback) {
210
210
  let socketOptions = {
211
- id: base32.encode(crypto.randomBytes(10)).toLowerCase()
211
+ id: base32Encode(crypto.randomBytes(10)).toLowerCase()
212
212
  };
213
213
 
214
214
  if (
@@ -6,7 +6,17 @@ const config = require('@zone-eu/wild-config');
6
6
  const logger = require('../logger');
7
7
  const { oauth2Apps, oauth2ProviderData } = require('../oauth2-apps');
8
8
 
9
- const { getDuration, getBoolean, resolveCredentials, hasEnvValue, readEnvValue, emitChangeEvent, loadTlsConfig } = require('../tools');
9
+ const {
10
+ getDuration,
11
+ getBoolean,
12
+ resolveCredentials,
13
+ useAuthServerForOAuth2,
14
+ useAuthServerForConnection,
15
+ hasEnvValue,
16
+ readEnvValue,
17
+ emitChangeEvent,
18
+ loadTlsConfig
19
+ } = require('../tools');
10
20
  const { getLocalAddress } = require('../utils/network');
11
21
 
12
22
  const { redis } = require('../db');
@@ -176,7 +186,7 @@ async function onAuth(auth, session) {
176
186
  // load OAuth2 tokens
177
187
  let imapAuth;
178
188
 
179
- if (accountData.oauth2.useAuthServer) {
189
+ if (await useAuthServerForOAuth2(accountData.oauth2, logger, { account, target: 'imap' })) {
180
190
  // An external authentication server owns this account's tokens, so ask it for one
181
191
  // rather than renewing from a stored refresh token (there is none). The response is
182
192
  // already in the { user, accessToken } shape the connection config expects.
@@ -210,7 +220,7 @@ async function onAuth(auth, session) {
210
220
  }
211
221
 
212
222
  // If authentication server is set then it overrides authentication data
213
- if (imapConnectionConfig.useAuthServer) {
223
+ if (await useAuthServerForConnection(imapConnectionConfig, logger, { account, target: 'imap' })) {
214
224
  try {
215
225
  imapConnectionConfig.auth = await resolveCredentials(account, 'imap');
216
226
  } catch (err) {
@@ -16,7 +16,7 @@
16
16
  // The caller is expected to also time-box this with withTimeout().
17
17
 
18
18
  const crypto = require('crypto');
19
- const msgpack = require('msgpack5')();
19
+ const msgpack = require('./msgpack');
20
20
 
21
21
  const settings = require('./settings');
22
22
  const { getCounterValues, hasEnvValue, readEnvValue, getBoolean } = require('./tools');
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { redis } = require('./db');
4
- const msgpack = require('msgpack5')();
4
+ const msgpack = require('./msgpack');
5
5
  const logger = require('./logger');
6
6
  const { REDIS_PREFIX } = require('./consts');
7
7
  const settings = require('./settings');
package/lib/msgpack.js ADDED
@@ -0,0 +1,62 @@
1
+ 'use strict';
2
+
3
+ // Wrapper around @msgpack/msgpack that keeps the call-site contract of the deprecated
4
+ // msgpack5 package this codebase used before:
5
+ // - encode() returns a Buffer (call sites chain .toString('base64url'), Buffer.concat and
6
+ // hsetBuffer on it) and omits undefined object properties instead of encoding nil
7
+ // - decode() reads the first value and ignores trailing bytes - graceful-degradation guards
8
+ // for corrupt stored blobs rely on a parseable prefix decoding instead of throwing
9
+ // - decode() returns Buffers for bin values where @msgpack/msgpack yields Uint8Array -
10
+ // call sites use .toString('hex')/.toString('base64') which are Buffer-only
11
+ // The wire format is plain spec msgpack in both directions, so blobs persisted by earlier
12
+ // msgpack5-based releases stay readable and vice versa.
13
+
14
+ const { Encoder, Decoder } = require('@msgpack/msgpack');
15
+
16
+ // shared instances so the per-call codec setup (internal 2KB encode buffer, decoder stack pool)
17
+ // amortizes across calls - decode runs on every API token check and mailbox listing entry.
18
+ // The library guards re-entrancy itself by cloning when an instance is already in use.
19
+ const encoder = new Encoder({ ignoreUndefined: true });
20
+ const decoder = new Decoder();
21
+
22
+ function bufferize(value) {
23
+ if (value instanceof Uint8Array) {
24
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
25
+ }
26
+
27
+ if (Array.isArray(value)) {
28
+ for (let i = 0; i < value.length; i++) {
29
+ value[i] = bufferize(value[i]);
30
+ }
31
+ return value;
32
+ }
33
+
34
+ if (value && typeof value === 'object' && !(value instanceof Date)) {
35
+ for (let key of Object.keys(value)) {
36
+ value[key] = bufferize(value[key]);
37
+ }
38
+ return value;
39
+ }
40
+
41
+ return value;
42
+ }
43
+
44
+ function encode(value) {
45
+ // copy into a standalone Buffer - encodeSharedRef() returns a view over the reused internal buffer
46
+ return Buffer.from(encoder.encodeSharedRef(value));
47
+ }
48
+
49
+ function decode(buf) {
50
+ for (let value of decoder.decodeMulti(buf)) {
51
+ return bufferize(value);
52
+ }
53
+ // empty input yields no values instead of throwing
54
+ throw new Error('Unable to decode msgpack value');
55
+ }
56
+
57
+ // Decodes a byte stream of concatenated msgpack values (append-list hash fields)
58
+ function decodeMulti(buf) {
59
+ return Array.from(decoder.decodeMulti(buf), bufferize);
60
+ }
61
+
62
+ module.exports = { encode, decode, decodeMulti };
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+
3
+ // Maximum size of the encoded payload segment we are willing to decode. Real id_tokens are a few
4
+ // hundred bytes of claims; anything larger is malformed or hostile, and the segment reaches us from a
5
+ // provider response we do not otherwise bound.
6
+ const MAX_PAYLOAD_LENGTH = 16 * 1024;
7
+
8
+ // Decode the claims of a JWT WITHOUT verifying its signature, returning null for anything that does not
9
+ // parse. Never throws - callers treat a null payload as "no claims available" and fall back.
10
+ //
11
+ // Not verifying is deliberate and only safe at the sites that use it: every caller obtained the token
12
+ // from the provider's token endpoint over a direct TLS back-channel POST (lib/oauth/*.js getToken), so
13
+ // authenticity comes from the transport, not from the token. The claims are trustworthy for that reason
14
+ // alone. Do NOT reuse this for a token that arrived through the browser or any other front channel -
15
+ // there the signature is the only thing standing between you and attacker-authored claims.
16
+ function decodeJwtPayload(token) {
17
+ if (!token || typeof token !== 'string') {
18
+ return null;
19
+ }
20
+
21
+ const [, encodedPayload] = token.split('.');
22
+ if (!encodedPayload || encodedPayload.length > MAX_PAYLOAD_LENGTH) {
23
+ return null;
24
+ }
25
+
26
+ try {
27
+ const payload = JSON.parse(Buffer.from(encodedPayload, 'base64url').toString());
28
+ // A JWT payload is a JSON object. Anything else (a bare string, a number, null, an array) is not
29
+ // a claims set, and returning it would hand callers a value that fails on property access.
30
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
31
+ return null;
32
+ }
33
+ return payload;
34
+ } catch (err) {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ module.exports = { decodeJwtPayload, MAX_PAYLOAD_LENGTH };
@@ -0,0 +1,61 @@
1
+ 'use strict';
2
+
3
+ const { isEmail } = require('../utils/is-email');
4
+
5
+ // Resolves the Microsoft account identity from the sources the OAuth2 callback can have. Split out of
6
+ // workers/api.js because this is a TRUST BOUNDARY, and a trust boundary that exists only as an ordering
7
+ // of assignments inside a 300-line switch is one nobody can test or review.
8
+ //
9
+ // The sources are not equal:
10
+ //
11
+ // clientInfo - Microsoft's `client_info` blob. EmailEngine asks for it (lib/oauth/outlook.js sets
12
+ // client_info=1) and it comes back as a query parameter on the FRONT channel, i.e.
13
+ // through the user's browser. It is not signed and nothing verifies it, so whoever
14
+ // drives the callback URL chooses its contents.
15
+ // idTokenPayload - claims from the id_token returned by the token endpoint. Unverified as a token, but
16
+ // fetched over a direct TLS POST (see lib/oauth/decode-jwt-payload.js).
17
+ // profile - the MS Graph /v1.0/me response, also a back-channel request.
18
+ //
19
+ // Callers pass only the sources their branch actually has: the legacy IMAP-scope branch has clientInfo
20
+ // and the id_token, the Graph branch has the profile.
21
+ //
22
+ // `verifiedIdentities` therefore NEVER contains a clientInfo value. It is the only field callers may use
23
+ // to decide whether an authenticated identity satisfies an expected identity. Both the mailbox address
24
+ // and the user principal name are offered, because either can be the stable identity for a tenant and
25
+ // they routinely differ (user@contoso.com vs user@contoso.onmicrosoft.com).
26
+ //
27
+ // `email` prefers a verified value and falls back to clientInfo only when no back-channel source produced
28
+ // one. That fallback exists for OAuth2 apps predating the User.Read scope; it is rarely reached now, since
29
+ // the id_token carries preferred_username whenever `openid profile` is granted. The precedence matters
30
+ // beyond the identity check: accountData.email is persisted, shown in the admin UI, and used as the
31
+ // default From address, so a spoofable value winning there is a bug in its own right.
32
+ //
33
+ // `username` is the credential EmailEngine authenticates with (XOAUTH2), so it is verified-only with no
34
+ // clientInfo fallback. The profile's userPrincipalName is taken as-is rather than filtered as an address,
35
+ // matching the previous behavior - a tenant whose UPN is not email-shaped must still be able to log in.
36
+ function resolveOutlookUserInfo(sources) {
37
+ const { clientInfo, idTokenPayload, profile } = sources || {};
38
+
39
+ // isEmail already rejects non-strings, so these only normalize a miss to null.
40
+ const asEmail = value => isEmail(value) || null;
41
+ const asString = value => (typeof value === 'string' && value ? value : null);
42
+
43
+ const profileUpn = asString(profile && profile.userPrincipalName);
44
+ const idTokenUpn = asEmail(idTokenPayload && idTokenPayload.preferred_username);
45
+
46
+ // One list in preference order does both jobs: membership answers "did the provider return this
47
+ // address", and the first entry is the best address to show. Keeping two orderings in sync by hand
48
+ // would be a silent bug the moment they drifted.
49
+ const verifiedIdentities = [
50
+ ...new Set([asEmail(profile && profile.mail), asEmail(idTokenPayload && idTokenPayload.email), idTokenUpn, asEmail(profileUpn)].filter(Boolean))
51
+ ];
52
+
53
+ return {
54
+ name: asString(idTokenPayload && idTokenPayload.name) || asString(profile && profile.displayName) || asString(clientInfo && clientInfo.name),
55
+ email: verifiedIdentities[0] || asEmail(clientInfo && clientInfo.preferred_username),
56
+ username: idTokenUpn || profileUpn,
57
+ verifiedIdentities
58
+ };
59
+ }
60
+
61
+ module.exports = { resolveOutlookUserInfo };