emailengine-app 2.89.0 → 2.91.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 (120) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +73 -0
  4. package/Dockerfile +7 -3
  5. package/ENVIRONMENT.md +24 -23
  6. package/README.md +1 -1
  7. package/bin/healthcheck.js +1 -1
  8. package/copy-static-files.sh +0 -8
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +1 -4
  11. package/lib/account/field-codec.js +396 -0
  12. package/lib/account-assignment.js +26 -9
  13. package/lib/account.js +196 -462
  14. package/lib/api-routes/account-routes.js +49 -6
  15. package/lib/api-routes/route-metadata.js +5 -2
  16. package/lib/api-routes/submit-routes.js +15 -2
  17. package/lib/api-token-auth.js +342 -274
  18. package/lib/arf-detect.js +174 -149
  19. package/lib/attachment-size.js +29 -0
  20. package/lib/autodetect-imap-settings.js +482 -296
  21. package/lib/consts.js +5 -5
  22. package/lib/db.js +1 -4
  23. package/lib/email-client/base-client.js +907 -780
  24. package/lib/email-client/gmail-client.js +557 -450
  25. package/lib/email-client/imap/cid-parts.js +61 -0
  26. package/lib/email-client/imap/mailbox.js +376 -422
  27. package/lib/email-client/imap/sync-operations.js +239 -178
  28. package/lib/email-client/imap-client.js +5 -5
  29. package/lib/email-client/message-builder.js +4 -5
  30. package/lib/email-client/new-message-steps.js +168 -2
  31. package/lib/email-client/outlook/graph-message.js +266 -0
  32. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  33. package/lib/email-client/outlook-client.js +652 -808
  34. package/lib/get-raw-email.js +338 -232
  35. package/lib/get-secret.js +1 -4
  36. package/lib/imapproxy/imap-server.js +5 -5
  37. package/lib/license-subscription.js +60 -0
  38. package/lib/load-env.js +48 -0
  39. package/lib/logger-consts.js +37 -1
  40. package/lib/logger.js +1 -4
  41. package/lib/mail-probe.js +157 -0
  42. package/lib/mcp/tools.js +244 -207
  43. package/lib/metric-values.js +76 -0
  44. package/lib/metrics.js +320 -0
  45. package/lib/oauth/gmail.js +39 -120
  46. package/lib/oauth/http-request.js +195 -0
  47. package/lib/oauth/mail-ru.js +33 -60
  48. package/lib/oauth/outlook.js +37 -137
  49. package/lib/oauth/pubsub/google.js +176 -117
  50. package/lib/oauth2-apps.js +440 -463
  51. package/lib/openapi/build-document.js +10 -10
  52. package/lib/read-env-value.js +31 -7
  53. package/lib/redis-backend-warnings.js +70 -0
  54. package/lib/route-descriptors.js +78 -0
  55. package/lib/schemas.js +10 -1
  56. package/lib/sentry-integrations.js +299 -0
  57. package/lib/sentry.js +75 -27
  58. package/lib/sso-routes.js +249 -0
  59. package/lib/sso.js +29 -6
  60. package/lib/tools.js +17 -28
  61. package/lib/ui-routes/account-edit-form.js +198 -0
  62. package/lib/ui-routes/account-page.js +241 -0
  63. package/lib/ui-routes/account-routes.js +46 -349
  64. package/lib/ui-routes/account-setup.js +1 -1
  65. package/lib/ui-routes/auth-routes.js +10 -10
  66. package/lib/ui-routes/provider-signin.js +187 -0
  67. package/lib/ui-routes/route-helpers.js +1 -1
  68. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  69. package/lib/ui-view-context.js +328 -0
  70. package/lib/utils/public-suffix.js +22 -101
  71. package/lib/web-safe-html.js +20 -7
  72. package/lib/worker-metrics.js +82 -0
  73. package/list-generate.js +2 -5
  74. package/package.json +28 -24
  75. package/sbom.json +360 -1030
  76. package/scripts/refresh-test-tokens.js +1 -1
  77. package/server.js +400 -677
  78. package/static/css/flyonui.css +1 -1
  79. package/static/css/public.css +55 -1
  80. package/static/css/src/app.tailwind.css +18 -0
  81. package/static/js/ee-client.js +2619 -645
  82. package/static/js/ui.js +12 -2
  83. package/static/licenses.html +224 -764
  84. package/translations/de.mo +0 -0
  85. package/translations/de.po +429 -390
  86. package/translations/en.mo +0 -0
  87. package/translations/en.po +342 -257
  88. package/translations/es.mo +0 -0
  89. package/translations/es.po +440 -395
  90. package/translations/et.mo +0 -0
  91. package/translations/et.po +425 -375
  92. package/translations/fr.mo +0 -0
  93. package/translations/fr.po +425 -383
  94. package/translations/it.mo +0 -0
  95. package/translations/it.po +441 -394
  96. package/translations/ja.mo +0 -0
  97. package/translations/ja.po +408 -335
  98. package/translations/messages.pot +188 -130
  99. package/translations/nl.mo +0 -0
  100. package/translations/nl.po +419 -382
  101. package/translations/pl.mo +0 -0
  102. package/translations/pl.po +425 -379
  103. package/translations/sv.mo +0 -0
  104. package/translations/sv.po +440 -388
  105. package/translations/tr.mo +0 -0
  106. package/translations/tr.po +441 -387
  107. package/views/account-identity-error.hbs +1 -1
  108. package/views/account-workspace-error.hbs +2 -2
  109. package/views/accounts/browse.hbs +19 -1
  110. package/views/accounts/register/imap-server.hbs +22 -7
  111. package/views/accounts/register/imap.hbs +3 -0
  112. package/views/accounts/register/index.hbs +1 -27
  113. package/views/accounts/register/provider-signin.hbs +58 -0
  114. package/views/oauth-scope-error.hbs +1 -1
  115. package/views/partials/provider_signin_button.hbs +30 -0
  116. package/views/queues/index.hbs +1 -1
  117. package/views/redirect.hbs +1 -1
  118. package/views/unsubscribe.hbs +6 -6
  119. package/workers/api.js +20 -451
  120. package/data/public_suffix_list.dat +0 -16698
@@ -2,6 +2,7 @@
2
2
 
3
3
  const punycode = require('punycode.js');
4
4
  const dns = require('dns').promises;
5
+ const { getDomain } = require('tldts');
5
6
  const { XMLParser, XMLValidator } = require('fast-xml-parser');
6
7
  const packageData = require('../package.json');
7
8
 
@@ -62,9 +63,10 @@ const parseXml = text => parseWith(xmlParser, text);
62
63
  const parseSoapXml = text => parseWith(soapXmlParser, text);
63
64
 
64
65
  const { fetch: fetchCmd } = require('undici');
65
- const { httpAgent } = require('./tools');
66
+ const { httpAgent, getMailProxyUrl } = require('./tools');
66
67
  const { fetchWithVettedRedirects, readBodyCapped } = require('./egress-fetch');
67
68
  const { validateWebhookTarget } = require('./webhook-egress');
69
+ const { probeMailServer } = require('./mail-probe');
68
70
 
69
71
  const RESOLV_TIMEOUT = 5 * 1000;
70
72
 
@@ -98,6 +100,13 @@ function hasResolvedHost(res) {
98
100
  return !!(res && ((res.imap && res.imap.host) || (res.smtp && res.smtp.host)));
99
101
  }
100
102
 
103
+ // Google's inbound MX hosts: the classic `*.l.google.com` set, and `smtp.google.com`, the single MX
104
+ // Google Workspace has given domains set up since 2023
105
+ const GOOGLE_MX = /(?:\bl\.google\.com|^smtp\.google\.com)$/i;
106
+
107
+ // For lookups that only read the table's triggers, never its translated warning text
108
+ const NO_GETTEXT = { gettext: text => text };
109
+
101
110
  // use a function instead of const to prevent translations before locale is set
102
111
  // The canonical consumer domains are listed alongside the exchange regexes so a plain domain match
103
112
  // (getAppPassword with exchange=false) resolves the big providers without any MX lookup - each listed
@@ -106,8 +115,10 @@ const getAppPasswords = gt => [
106
115
  {
107
116
  trigger: {
108
117
  domains: ['gmail.com', 'googlemail.com'],
109
- exchange: /\bl\.google\.com$/i
118
+ exchange: GOOGLE_MX
110
119
  },
120
+ // The OAuth2 provider id (as in GET /v1/oauth2) these mailboxes sign in with, see getProviderHint()
121
+ oauth2Provider: 'gmail',
111
122
  value: {
112
123
  required: true,
113
124
  provider: 'Gmail',
@@ -152,13 +163,14 @@ const getAppPasswords = gt => [
152
163
 
153
164
  {
154
165
  trigger: {
155
- domains: ['outlook.com', 'hotmail.com', 'live.com'],
166
+ domains: ['outlook.com', 'hotmail.com', 'live.com', 'msn.com'],
156
167
  exchange: /\.outlook\.com$/i
157
168
  },
169
+ oauth2Provider: 'outlook',
158
170
  value: {
159
171
  required: true,
160
172
  warning: gt.gettext(
161
- 'Microsoft has disabled password-based sign-ins (including app passwords) for Outlook.com, Hotmail.com, and Microsoft 365 email accounts. To continue, please use the "Sign in with Microsoft" button to securely connect your account.'
173
+ 'Microsoft no longer accepts passwords, including app passwords, for IMAP connections to Outlook.com, Hotmail.com, or Microsoft 365. Connect your account using Microsoft sign-in.'
162
174
  ),
163
175
  provider: 'Microsoft',
164
176
  instructions: 'https://support.microsoft.com/en-us/account-billing/how-to-get-and-use-app-passwords-5896ed9b-4263-e681-128a-a6f2979a7944'
@@ -178,18 +190,56 @@ const getAppPasswords = gt => [
178
190
  }
179
191
  ];
180
192
 
181
- function getAppPassword(email, exchange, gt) {
182
- let domain = email.split('@').pop().trim().toLowerCase();
193
+ const addressDomain = email =>
194
+ String(email || '')
195
+ .split('@')
196
+ .pop()
197
+ .trim()
198
+ .toLowerCase();
199
+
200
+ // The table entry the address matches: by domain first, then by MX exchange
201
+ function findAppPasswordEntry(email, exchange, gt) {
202
+ const domain = addressDomain(email);
203
+ return (
204
+ getAppPasswords(gt).find(
205
+ entry =>
206
+ (entry.trigger.domains && entry.trigger.domains.includes(domain)) ||
207
+ (exchange && entry.trigger.exchange && entry.trigger.exchange.test(exchange))
208
+ ) || null
209
+ );
210
+ }
183
211
 
184
- for (let appPassword of getAppPasswords(gt)) {
185
- if (appPassword.trigger.domains && appPassword.trigger.domains.includes(domain)) {
186
- return appPassword.value;
187
- }
188
- if (exchange && appPassword.trigger.exchange && appPassword.trigger.exchange.test(exchange)) {
189
- return appPassword.value;
190
- }
191
- }
192
- return false;
212
+ /**
213
+ * The OAuth2 provider an address signs in with (`oauth2Provider` of its app-password entry), so a
214
+ * setup flow can offer that sign-in instead of a password. The same table decides both, so the
215
+ * app-password hint and the sign-in offer never disagree about a mailbox.
216
+ *
217
+ * @param {string} email - Address
218
+ * @param {string} [exchange] - The domain's primary MX exchange, when known
219
+ * @returns {string|false} `gmail`, `outlook` or false
220
+ */
221
+ function getProviderHint(email, exchange) {
222
+ const entry = findAppPasswordEntry(email, exchange, NO_GETTEXT);
223
+ return (entry && entry.oauth2Provider) || false;
224
+ }
225
+
226
+ /**
227
+ * Whether the address is on one of the OAuth2 providers' own consumer domains (gmail.com,
228
+ * outlook.com, ...) rather than a custom domain of a Google Workspace or Microsoft 365
229
+ * organization. Decides which Outlook applications can sign it in: one limited to work accounts
230
+ * cannot.
231
+ *
232
+ * @param {string} email - Address
233
+ * @returns {boolean}
234
+ */
235
+ function isConsumerMailbox(email) {
236
+ const domain = addressDomain(email);
237
+ return getAppPasswords(NO_GETTEXT).some(entry => entry.oauth2Provider && entry.trigger.domains && entry.trigger.domains.includes(domain));
238
+ }
239
+
240
+ function getAppPassword(email, exchange, gt) {
241
+ const entry = findAppPasswordEntry(email, exchange, gt);
242
+ return entry ? entry.value : false;
193
243
  }
194
244
 
195
245
  // Resolve the lowest-priority MX exchange for a domain (lowercased). Throws if the domain has no MX
@@ -342,11 +392,11 @@ async function fetchAutodiscoveryResource(url, opts) {
342
392
  * runAutodiscovery() accepts a partial one from the tests that drive it directly. The resolvers
343
393
  * themselves take the context as given.
344
394
  *
345
- * @param {Object} [ctx] - `{ dns, fetchResource, signal }`, any of them optional
346
- * @returns {Object} Context with the production DNS and egress-policed fetch filled in
395
+ * @param {Object} [ctx] - `{ dns, fetchResource, probe, mailProxyUrl, signal, onAuthRequired }`, any of them optional
396
+ * @returns {Object} Context with the production DNS, egress-policed fetch and mail server probe filled in
347
397
  */
348
398
  function withIo(ctx) {
349
- const io = { dns, fetchResource: fetchAutodiscoveryResource };
399
+ const io = { dns, fetchResource: fetchAutodiscoveryResource, probe: probeMailServer, mailProxyUrl: getMailProxyUrl };
350
400
  for (const key of Object.keys(ctx || {})) {
351
401
  // An explicit undefined keeps the production default; only a stand-in actually given wins
352
402
  if (ctx[key] !== undefined) {
@@ -462,6 +512,91 @@ async function resolveUsingSRV(email, ctx, domain, source) {
462
512
  return { smtp, imap, _source: source || 'srv' };
463
513
  }
464
514
 
515
+ // A fixed answer for a provider whose servers are the same for every custom domain. IMAP is always
516
+ // implicit TLS on 993; SMTP is implicit TLS on 465 and STARTTLS on 587.
517
+ function staticConfig(imapHost, smtpHost, smtpPort) {
518
+ return {
519
+ imap: {
520
+ host: imapHost,
521
+ port: 993,
522
+ secure: true
523
+ },
524
+ smtp: {
525
+ host: smtpHost,
526
+ port: smtpPort,
527
+ secure: smtpPort === 465
528
+ },
529
+ _source: 'mx'
530
+ };
531
+ }
532
+
533
+ // Microsoft 365's IMAP and SMTP hosts and submission port, for the MX table and the fallback stage
534
+ const MICROSOFT_365_SERVERS = ['outlook.office365.com', 'smtp.office365.com', 587];
535
+
536
+ // Well known MX servers, checked in order and the first match wins. `match` is a pattern, or a
537
+ // string the exchange has to equal. An entry answers with `config` (static, built fresh for every
538
+ // lookup), `resolve` (delegates to another resolver) or `build` (derived from the match).
539
+ const MX_PROVIDERS = [
540
+ { match: GOOGLE_MX, resolve: (email, ctx) => resolveUsingSRV(email, ctx, 'gmail.com', 'mx') },
541
+ { match: /\bmx\.yandex\.net$/i, resolve: (email, ctx) => resolveUsingAutoconfig(email, ctx, 'yandex.ru', 'mx') },
542
+ // Zone.eu
543
+ { match: /^mx\d*\.zone\.eu$/i, config: ['mail.zone.ee', 'smtp.zone.ee', 465] },
544
+ // Lark Mail / ByteDance
545
+ { match: /\blarksuite\.com$/i, config: ['imap.larksuite.com', 'smtp.larksuite.com', 465] },
546
+ { match: /\bzonemx\.eu$/i, resolve: (email, ctx) => resolveUsingAutoconfig(email, ctx, 'zone.ee', 'mx') },
547
+ // AWS WorkMail
548
+ {
549
+ match: /^inbound-smtp\.([^.]+)\.amazonaws\.com$/,
550
+ build: awsMatch => {
551
+ let region = awsMatch[1].toLowerCase().trim();
552
+ return staticConfig(`imap.mail.${region}.awsapps.com`, `smtp.mail.${region}.awsapps.com`, 465);
553
+ }
554
+ },
555
+ // Zoho custom domain in EU
556
+ { match: /^mx\d*\.zoho\.eu$/i, config: ['imappro.zoho.eu', 'smtppro.zoho.eu', 465] },
557
+ // Zoho custom domain not in EU
558
+ { match: /^mx\d*\.zoho\.com$/i, config: ['imappro.zoho.com', 'smtppro.zoho.com', 465] },
559
+ // MS365: as autodiscovery is currently (2021-11-17) closed use a fixed response
560
+ { match: /\bprotection\.outlook\.com$/i, config: MICROSOFT_365_SERVERS },
561
+ // Inbox.com
562
+ { match: 'mx.dka.mailcore.net', config: ['imap.dka.mailcore.net', 'smtp.dka.mailcore.net', 587] },
563
+ { match: 'ekiri.ee', config: ['turvaline.ekiri.ee', 'turvaline.ekiri.ee', 465] },
564
+ // Alibaba Mail
565
+ { match: /^mx\d*\.sg\.aliyun\.com$/i, config: ['imap.sg.aliyun.com', 'smtp.sg.aliyun.com', 465] },
566
+ // ATT
567
+ { match: /mx-vip\d*\.prodigy\.net$/i, config: ['imap.mail.att.net', 'smtp.mail.att.net', 465] },
568
+ // Naver (kr)
569
+ { match: /^mx\d*\.naver\.com$/i, config: ['imap.naver.com', 'smtp.naver.com', 587] },
570
+ // QQ enterprise
571
+ { match: /^mxbiz\d*\.qq\.com$/i, config: ['imap.exmail.qq.com', 'smtp.exmail.qq.com', 465] }
572
+ ];
573
+
574
+ function matchMxProvider(provider, exchange) {
575
+ if (typeof provider.match === 'string') {
576
+ return exchange === provider.match ? [exchange] : null;
577
+ }
578
+ return provider.match.exec(exchange);
579
+ }
580
+
581
+ // Resolves the configuration of the first provider the exchange matches, or throws "Nothing found"
582
+ // carrying the exchange, which is what the app-password hint is matched on
583
+ async function resolveMxProviderConfig(email, ctx, exchange) {
584
+ const provider = MX_PROVIDERS.find(entry => matchMxProvider(entry, exchange));
585
+ if (!provider) {
586
+ let error = new Error('Nothing found');
587
+ error.exchange = exchange;
588
+ throw error;
589
+ }
590
+
591
+ if (provider.resolve) {
592
+ return await provider.resolve(email, ctx);
593
+ }
594
+ if (provider.build) {
595
+ return provider.build(matchMxProvider(provider, exchange));
596
+ }
597
+ return staticConfig(...provider.config);
598
+ }
599
+
465
600
  async function resolveUsingMX(email, ctx, gt) {
466
601
  let domain = email.split('@').pop().trim().toLowerCase();
467
602
 
@@ -474,240 +609,7 @@ async function resolveUsingMX(email, ctx, gt) {
474
609
  // do not catch potential error as there's nothing to do if we do not find the MX record
475
610
  let exchange = await resolveExchange(domain, ctx.dns);
476
611
 
477
- let resolveConfig = async () => {
478
- // look for some well known MX servers
479
- if (/\bl\.google\.com$/i.test(exchange)) {
480
- return await resolveUsingSRV(email, ctx, 'gmail.com', 'mx');
481
- }
482
-
483
- if (/\bmx\.yandex\.net$/i.test(exchange)) {
484
- return await resolveUsingAutoconfig(email, ctx, 'yandex.ru', 'mx');
485
- }
486
-
487
- if (/^mx\d*\.zone\.eu$/i.test(exchange)) {
488
- // Zoho custom domain not in EU
489
- return {
490
- imap: {
491
- host: 'mail.zone.ee',
492
- port: 993,
493
- secure: true
494
- },
495
- smtp: {
496
- host: 'smtp.zone.ee',
497
- port: 465,
498
- secure: true
499
- },
500
- _source: 'mx'
501
- };
502
- }
503
-
504
- if (/\blarksuite\.com$/i.test(exchange)) {
505
- // Lark Mail / ByteDance
506
- return {
507
- imap: {
508
- host: 'imap.larksuite.com',
509
- port: 993,
510
- secure: true
511
- },
512
- smtp: {
513
- host: 'smtp.larksuite.com',
514
- port: 465,
515
- secure: true
516
- },
517
- _source: 'mx'
518
- };
519
- }
520
-
521
- if (/\bzonemx\.eu$/i.test(exchange)) {
522
- return await resolveUsingAutoconfig(email, ctx, 'zone.ee', 'mx');
523
- }
524
-
525
- // AWS WorkMail
526
- let awsMatch = exchange.match(/inbound-smtp\.([^.]+)\.amazonaws.com/);
527
- if (awsMatch) {
528
- let region = awsMatch[1].toLowerCase().trim();
529
- return {
530
- imap: {
531
- host: `imap.mail.${region}.awsapps.com`,
532
- port: 993,
533
- secure: true
534
- },
535
- smtp: {
536
- host: `smtp.mail.${region}.awsapps.com`,
537
- port: 465,
538
- secure: true
539
- },
540
- _source: 'mx'
541
- };
542
- }
543
-
544
- // Zoho EU
545
- if (/^mx\d*\.zoho\.eu$/i.test(exchange)) {
546
- // Zoho custom domain in EU
547
- return {
548
- imap: {
549
- host: 'imappro.zoho.eu',
550
- port: 993,
551
- secure: true
552
- },
553
- smtp: {
554
- host: 'smtppro.zoho.eu',
555
- port: 465,
556
- secure: true
557
- },
558
- _source: 'mx'
559
- };
560
- }
561
-
562
- // Zoho international
563
- if (/^mx\d*\.zoho\.com$/i.test(exchange)) {
564
- // Zoho custom domain not in EU
565
- return {
566
- imap: {
567
- host: 'imappro.zoho.com',
568
- port: 993,
569
- secure: true
570
- },
571
- smtp: {
572
- host: 'smtppro.zoho.com',
573
- port: 465,
574
- secure: true
575
- },
576
- _source: 'mx'
577
- };
578
- }
579
-
580
- // MS365
581
- if (/\bprotection\.outlook\.com$/i.test(exchange)) {
582
- // outlook
583
- // as autodiscovery is currently (2021-11-17) closed use a fixed response
584
- return {
585
- imap: {
586
- host: 'outlook.office365.com',
587
- port: 993,
588
- secure: true
589
- },
590
- smtp: {
591
- host: 'smtp.office365.com',
592
- port: 587,
593
- secure: false
594
- },
595
- _source: 'mx'
596
- };
597
- }
598
-
599
- // Inbox.com
600
- if (exchange === 'mx.dka.mailcore.net') {
601
- return {
602
- imap: {
603
- host: 'imap.dka.mailcore.net',
604
- port: 993,
605
- secure: true
606
- },
607
- smtp: {
608
- host: 'smtp.dka.mailcore.net',
609
- port: 587,
610
- secure: false
611
- },
612
- _source: 'mx'
613
- };
614
- }
615
-
616
- if (exchange === 'ekiri.ee') {
617
- return {
618
- imap: {
619
- host: `turvaline.ekiri.ee`,
620
- port: 993,
621
- secure: true
622
- },
623
- smtp: {
624
- host: `turvaline.ekiri.ee`,
625
- port: 465,
626
- secure: true
627
- },
628
- _source: 'mx'
629
- };
630
- }
631
-
632
- // Alibaba Mail
633
- if (/^mx\d*\.sg\.aliyun\.com$/i.test(exchange)) {
634
- // Naver.com
635
- return {
636
- imap: {
637
- host: 'imap.sg.aliyun.com',
638
- port: 993,
639
- secure: true
640
- },
641
- smtp: {
642
- host: 'smtp.sg.aliyun.com',
643
- port: 465,
644
- secure: true
645
- },
646
- _source: 'mx'
647
- };
648
- }
649
-
650
- // ATT
651
- if (/mx-vip\d*\.prodigy\.net$/i.test(exchange)) {
652
- // ATT
653
- return {
654
- imap: {
655
- host: 'imap.mail.att.net',
656
- port: 993,
657
- secure: true
658
- },
659
- smtp: {
660
- host: 'smtp.mail.att.net',
661
- port: 465,
662
- secure: true
663
- },
664
- _source: 'mx'
665
- };
666
- }
667
-
668
- // Naver (kr)
669
- if (/^mx\d*\.naver\.com$/i.test(exchange)) {
670
- // Naver.com
671
- return {
672
- imap: {
673
- host: 'imap.naver.com',
674
- port: 993,
675
- secure: true
676
- },
677
- smtp: {
678
- host: 'smtp.naver.com',
679
- port: 587,
680
- secure: false
681
- },
682
- _source: 'mx'
683
- };
684
- }
685
-
686
- // QQ enterprise
687
- if (/^mxbiz\d*\.qq\.com$/i.test(exchange)) {
688
- // Naver.com
689
- return {
690
- imap: {
691
- host: 'imap.exmail.qq.com',
692
- port: 993,
693
- secure: true
694
- },
695
- smtp: {
696
- host: 'smtp.exmail.qq.com',
697
- port: 465,
698
- secure: true
699
- },
700
- _source: 'mx'
701
- };
702
- }
703
-
704
- let error = new Error('Nothing found');
705
- error.exchange = exchange;
706
-
707
- throw error;
708
- };
709
-
710
- let accountConfig = await resolveConfig();
612
+ let accountConfig = await resolveMxProviderConfig(email, ctx, exchange);
711
613
 
712
614
  if (!hasResolvedHost(accountConfig)) {
713
615
  // The exchange matched, but the config it delegated to named no server: the Gmail branch
@@ -719,9 +621,19 @@ async function resolveUsingMX(email, ctx, gt) {
719
621
  throw error;
720
622
  }
721
623
 
722
- let appPassword = getAppPassword(email, exchange, gt);
624
+ return withHints(accountConfig, email, exchange, gt);
625
+ }
723
626
 
724
- return Object.assign({}, accountConfig, appPassword ? { appPassword } : {});
627
+ /**
628
+ * Adds what the address and its MX exchange say beyond the server settings: the app-password
629
+ * requirement and the OAuth2 provider hint. A result that already carries either keeps its own.
630
+ *
631
+ * @returns {Object} A copy of the result with `appPassword` and `provider` where they apply
632
+ */
633
+ function withHints(res, email, exchange, gt) {
634
+ const appPassword = res.appPassword || getAppPassword(email, exchange, gt);
635
+ const provider = res.provider || getProviderHint(email, exchange);
636
+ return Object.assign({}, res, appPassword ? { appPassword } : {}, provider ? { provider } : {});
725
637
  }
726
638
 
727
639
  function escapeXml(unsafe) {
@@ -987,7 +899,7 @@ async function autodiscoverRedirectOrigin(domain, ctx) {
987
899
  * @throws {Error} When no endpoint returned anything usable
988
900
  */
989
901
  async function runAutodiscovery(baseUrl, email, credentials, ctx, redirectsLeft = MAX_AUTODISCOVER_REDIRECTS) {
990
- const { fetchResource, signal } = withIo(ctx);
902
+ const { fetchResource, signal, onAuthRequired } = withIo(ctx);
991
903
 
992
904
  const poxBody = buildAutodiscoverRequest(email);
993
905
  const post = (origin, path, body, authorization) =>
@@ -1034,6 +946,14 @@ async function runAutodiscovery(baseUrl, email, credentials, ctx, redirectsLeft
1034
946
  throw new Error('Invalid response');
1035
947
  }
1036
948
 
949
+ // Recorded as it happens rather than read off the rejection: a sibling lookup that outlives the
950
+ // time budget turns the whole race into a timeout, which would hide that this host asked. The
951
+ // fallback stage must not guess a server for a mailbox that is behind a password-protected
952
+ // autodiscovery endpoint, see resolveUsingFallbacks()
953
+ if (onAuthRequired) {
954
+ onAuthRequired();
955
+ }
956
+
1037
957
  if (!credentials || !credentials.pass) {
1038
958
  throw new Error('Invalid response');
1039
959
  }
@@ -1223,6 +1143,233 @@ function processAutodiscoverResponse(text, source) {
1223
1143
  return { imap, smtp, _source: source || 'autodiscover' };
1224
1144
  }
1225
1145
 
1146
+ // ---------------------------------------------------------------------------------------------
1147
+ // Fallback stage: domains that publish nothing about their mail
1148
+ //
1149
+ // Most domains on small hosting providers have no SRV records, no autoconfig document and no
1150
+ // autodiscovery, so every resolver above comes back empty. resolveUsingFallbacks() runs only then,
1151
+ // and works from what the domain's DNS does say: where its MX points, what its mail names are
1152
+ // aliases of, and what its SPF record authorizes.
1153
+ // ---------------------------------------------------------------------------------------------
1154
+
1155
+ // Hosts probed per protocol, most likely first. Each protocol is probed in one round with all of its
1156
+ // candidates at once, so this is also the most connections a lookup opens at a time.
1157
+ const MAX_PROBE_CANDIDATES = 6;
1158
+
1159
+ // The names whose CNAME targets are probed, see probeCandidates()
1160
+ const ALIAS_NAMES = ['imap', 'mail', 'smtp', 'webmail'];
1161
+
1162
+ const MICROSOFT_AUTODISCOVER = /^autodiscover\.outlook\.com\.?$/i;
1163
+ const MICROSOFT_SPF = /(?:^|\s)include:spf\.protection\.outlook\.com(?:\s|$)/i;
1164
+
1165
+ // Lowercased, without a trailing dot, in its ASCII form
1166
+ function asciiDomain(domain) {
1167
+ domain = String(domain || '')
1168
+ .trim()
1169
+ .toLowerCase()
1170
+ .replace(/\.$/, '');
1171
+ try {
1172
+ return punycode.toASCII(domain);
1173
+ } catch (err) {
1174
+ return domain;
1175
+ }
1176
+ }
1177
+
1178
+ // A name that does not resolve is one of the ordinary answers here, never an error
1179
+ async function lookupOrEmpty(lookup) {
1180
+ try {
1181
+ return (await lookup()) || [];
1182
+ } catch (err) {
1183
+ return [];
1184
+ }
1185
+ }
1186
+
1187
+ /**
1188
+ * The domains an MX host sits under, most specific first, down to its registrable domain:
1189
+ * `mx1.mail.ovh.net` gives `mail.ovh.net` and `ovh.net`.
1190
+ *
1191
+ * @param {string} [exchange] - MX host
1192
+ * @returns {string[]} Parent domains
1193
+ */
1194
+ function exchangeParents(exchange) {
1195
+ const base = exchange && getDomain(exchange);
1196
+ if (!base || base === exchange) {
1197
+ return [];
1198
+ }
1199
+
1200
+ const labels = exchange.split('.');
1201
+ const parents = [];
1202
+ for (let i = 1; i < labels.length; i++) {
1203
+ const parent = labels.slice(i).join('.');
1204
+ parents.push(parent);
1205
+ if (parent === base) {
1206
+ break;
1207
+ }
1208
+ }
1209
+ return parents;
1210
+ }
1211
+
1212
+ function microsoft365Config(gt) {
1213
+ const appPassword = getAppPasswords(gt).find(entry => entry.value.provider === 'Microsoft');
1214
+ return Object.assign(staticConfig(...MICROSOFT_365_SERVERS), { _source: 'microsoft365', appPassword: appPassword.value, provider: 'outlook' });
1215
+ }
1216
+
1217
+ /**
1218
+ * The Thunderbird directory, asked for the domains the MX host sits under rather than for the
1219
+ * address domain. This is a step of Thunderbird's own lookup sequence that the racing
1220
+ * resolveUsingMozillaDirectory() does not take: OVH lists `ovh.net`, and every OVH MX Plan domain
1221
+ * has its MX under it. The address domain still fills `%EMAILDOMAIN%`, as in Thunderbird.
1222
+ *
1223
+ * @returns {Promise<Object|null>} The most specific parent's entry that names a server
1224
+ */
1225
+ async function lookupDirectoryByMx(email, domain, parents, ctx) {
1226
+ const answers = await Promise.all(
1227
+ parents.map(parent =>
1228
+ fetchAutoconfigDocument(`https://autoconfig.thunderbird.net/v1.1/${encodeURIComponent(parent)}`, ctx)
1229
+ .then(text => processAutoconfigFile(email, domain, text, 'mozilla-mx'))
1230
+ .catch(() => null)
1231
+ )
1232
+ );
1233
+ return answers.find(hasResolvedHost) || null;
1234
+ }
1235
+
1236
+ /**
1237
+ * Collects what the fallback stage decides on. Only DNS reads and the directory request, nothing
1238
+ * that touches the domain's own servers, so it runs alongside the resolver race and costs that
1239
+ * race nothing; resolver() throws it away when the race wins.
1240
+ *
1241
+ * @param {string} email - Address to look up
1242
+ * @param {string} [exchange] - Primary MX host, when the domain has one
1243
+ * @param {Object} ctx - `{ dns, fetchResource, signal }`
1244
+ * @returns {Promise<Object>} The facts resolveUsingFallbacks() works from
1245
+ */
1246
+ async function gatherFallbackFacts(email, exchange, ctx) {
1247
+ const domain = asciiDomain(email.split('@').pop());
1248
+ exchange = exchange ? asciiDomain(exchange) : null;
1249
+ const parents = exchangeParents(exchange).filter(parent => parent !== domain);
1250
+
1251
+ const cname = name => lookupOrEmpty(() => ctx.dns.resolveCname(name)).then(list => list.map(asciiDomain).filter(Boolean));
1252
+
1253
+ const [autodiscoverTargets, txtRecords, aliasEntries, directory] = await Promise.all([
1254
+ cname(`autodiscover.${domain}`),
1255
+ lookupOrEmpty(() => ctx.dns.resolveTxt(domain)),
1256
+ Promise.all(ALIAS_NAMES.map(async name => [name, await cname(`${name}.${domain}`)])),
1257
+ lookupDirectoryByMx(email, domain, parents, ctx)
1258
+ ]);
1259
+
1260
+ return {
1261
+ domain,
1262
+ exchange,
1263
+ parents,
1264
+ microsoftAutodiscover: autodiscoverTargets.some(target => MICROSOFT_AUTODISCOVER.test(target)),
1265
+ microsoftSpf: txtRecords.map(chunks => [].concat(chunks).join('')).some(record => MICROSOFT_SPF.test(record)),
1266
+ aliases: Object.fromEntries(aliasEntries),
1267
+ directory
1268
+ };
1269
+ }
1270
+
1271
+ /**
1272
+ * The hosts worth probing, most likely first: for IMAP the MX host itself, `imap.`/`mail.` of the
1273
+ * domain, whatever its mail names are aliases of (probed under the target's own name, since the
1274
+ * alias carries the provider's certificate), and `imap.` under the MX host's domains. SMTP starts
1275
+ * from the submission names and then tries the IMAP list, as the same host often serves both.
1276
+ *
1277
+ * @param {Object} facts - From gatherFallbackFacts()
1278
+ * @returns {{imap: string[], smtp: string[]}} Candidates, at most MAX_PROBE_CANDIDATES each
1279
+ */
1280
+ function probeCandidates(facts) {
1281
+ const { domain, exchange, parents, aliases } = facts;
1282
+ const firstUnique = list => [...new Set(list.filter(Boolean))].slice(0, MAX_PROBE_CANDIDATES);
1283
+
1284
+ const imap = firstUnique([
1285
+ exchange,
1286
+ `imap.${domain}`,
1287
+ `mail.${domain}`,
1288
+ ...aliases.imap,
1289
+ ...aliases.mail,
1290
+ ...aliases.smtp,
1291
+ ...aliases.webmail,
1292
+ ...parents.map(parent => `imap.${parent}`)
1293
+ ]);
1294
+ const smtp = firstUnique([`smtp.${domain}`, ...aliases.smtp, ...parents.map(parent => `smtp.${parent}`), ...imap]);
1295
+
1296
+ return { imap, smtp };
1297
+ }
1298
+
1299
+ /**
1300
+ * Probes the candidates and builds a configuration from the first IMAP server that answered,
1301
+ * paired with an SMTP server: the IMAP host itself when it also answered on 465, otherwise the
1302
+ * first SMTP candidate that did. SMTP is probed only once an IMAP server answered, since without
1303
+ * one the result is thrown away; each round probes its candidates all at once.
1304
+ *
1305
+ * @returns {Promise<Object|null>} `{ imap, smtp, _source: 'probe' }`, or null when no IMAP server answered
1306
+ */
1307
+ async function probeLikelyHosts(facts, ctx) {
1308
+ const candidates = probeCandidates(facts);
1309
+ const proxyUrl = await ctx.mailProxyUrl();
1310
+ const greeted = async (hosts, port) => {
1311
+ const answered = await Promise.all(hosts.map(host => ctx.probe(host, port, { signal: ctx.signal, proxyUrl }).catch(() => false)));
1312
+ return hosts.filter((host, i) => answered[i]);
1313
+ };
1314
+
1315
+ const imapHosts = await greeted(candidates.imap, 993);
1316
+ if (!imapHosts.length) {
1317
+ return null;
1318
+ }
1319
+ const imapHost = imapHosts[0];
1320
+
1321
+ const smtpHosts = await greeted(candidates.smtp, 465);
1322
+ const smtpHost = smtpHosts.includes(imapHost) ? imapHost : smtpHosts[0];
1323
+
1324
+ return {
1325
+ imap: { host: imapHost, port: 993, secure: true },
1326
+ smtp: smtpHost ? { host: smtpHost, port: 465, secure: true } : false,
1327
+ _source: 'probe'
1328
+ };
1329
+ }
1330
+
1331
+ /**
1332
+ * The last autodiscovery stage, run only once every resolver above has come back empty. In order:
1333
+ *
1334
+ * 1. `autodiscover.<domain>` is an alias of Microsoft's: Microsoft 365 behind a mail filter, whose
1335
+ * MX names the filter (Mailinblack, Hornetsecurity, Proofpoint) so the MX table never sees it.
1336
+ * 2. An autodiscovery host asked for the mailbox password: hosted Exchange. Nothing is guessed,
1337
+ * since OVH and others run Exchange and plain IMAP mailboxes behind the same MX and a guess
1338
+ * would name the wrong server. The caller has to supply the password instead.
1339
+ * 3. The Thunderbird directory lists one of the MX host's domains.
1340
+ * 4. A probe of the likely hosts finds a mail server (see probeCandidates()).
1341
+ * 5. The SPF record authorizes Microsoft 365, and nothing above found a server of the domain's
1342
+ * own. Sending through Microsoft says little about where the mailboxes are, so this is last.
1343
+ *
1344
+ * @param {string} email - Address to look up
1345
+ * @param {Object} facts - From gatherFallbackFacts()
1346
+ * @param {Object} ctx - `{ probe, signal }` plus what the probe needs
1347
+ * @param {Object} gt - gettext instance
1348
+ * @param {boolean} authRequired - An autodiscovery host answered with a Basic challenge
1349
+ * @returns {Promise<Object>} `{ imap, smtp, _source }`
1350
+ * @throws {Error} When none of them found a server
1351
+ */
1352
+ async function resolveUsingFallbacks(email, facts, ctx, gt, authRequired) {
1353
+ if (facts.microsoftAutodiscover) {
1354
+ return microsoft365Config(gt);
1355
+ }
1356
+
1357
+ if (authRequired) {
1358
+ throw new Error('Nothing found');
1359
+ }
1360
+
1361
+ const found = facts.directory || (await probeLikelyHosts(facts, ctx));
1362
+ if (found) {
1363
+ return withHints(found, email, facts.exchange, gt);
1364
+ }
1365
+
1366
+ if (facts.microsoftSpf) {
1367
+ return microsoft365Config(gt);
1368
+ }
1369
+
1370
+ throw new Error('Nothing found');
1371
+ }
1372
+
1226
1373
  /**
1227
1374
  * Races a lookup against a time budget.
1228
1375
  *
@@ -1265,19 +1412,69 @@ async function timedFunction(prom, timeout, source) {
1265
1412
  }
1266
1413
 
1267
1414
  /**
1268
- * Runs the resolvers: the MX one first, then the other five racing under their own time budget.
1415
+ * The race of the five resolvers that run when the MX table has no answer. The first to come back
1416
+ * with something wins. A resolver that answers but names no host counts as a loss, not a win:
1417
+ * several of them parse a response that turned out to describe nothing, and resolving on that
1418
+ * would beat a slower resolver that had the real answer.
1419
+ *
1420
+ * @returns {Promise<Object>} The first result that names a server
1421
+ * @throws {Error} Marked `_is_last` once every resolver has lost
1422
+ */
1423
+ function raceResolvers(email, ctx, credentials, timeout) {
1424
+ const resolvers = {
1425
+ srv: resolveUsingSRV,
1426
+ 'well-known': resolveUsingWellKnown,
1427
+ autoconfig: resolveUsingAutoconfig,
1428
+ mozilla: resolveUsingMozillaDirectory,
1429
+ autodiscover: (email, ctx) => resolveUsingAutodiscovery(email, ctx, credentials)
1430
+ };
1431
+ const promises = Object.entries(resolvers).map(([source, resolve]) => timedFunction(signal => resolve(email, ctx(signal)), timeout, source));
1432
+
1433
+ return new Promise((resolve, reject) => {
1434
+ let runCount = 0;
1435
+ const settle = err => {
1436
+ if (++runCount === promises.length) {
1437
+ err = err || new Error('Nothing found');
1438
+ err._is_last = true;
1439
+ reject(err);
1440
+ }
1441
+ };
1442
+
1443
+ for (let prom of promises) {
1444
+ prom.then(res => {
1445
+ if (!hasResolvedHost(res)) {
1446
+ return settle();
1447
+ }
1448
+ runCount++;
1449
+ resolve(res);
1450
+ }).catch(settle);
1451
+ }
1452
+ });
1453
+ }
1454
+
1455
+ /**
1456
+ * Runs the resolvers: the MX one first, then the other five racing under their own time budget,
1457
+ * and when none of them names a server, the fallback stage (resolveUsingFallbacks()) under a
1458
+ * budget of its own. What that stage decides on is gathered while the race runs, so a domain
1459
+ * that publishes nothing does not wait for its DNS twice.
1269
1460
  *
1270
1461
  * @param {string} email - Address to look up
1271
1462
  * @param {Object} gt - gettext instance
1272
1463
  * @param {Object} [credentials] - `{ user, pass }`, see autodetectImapSettings()
1273
- * @param {Object} [io] - `{ dns, fetchResource, timeout }` stand-ins for tests; production passes none
1464
+ * @param {Object} [io] - `{ dns, fetchResource, probe, mailProxyUrl, timeout }` stand-ins for tests; production passes none
1274
1465
  * @returns {Promise<Object>} The first result that names a server
1275
1466
  */
1276
1467
  async function resolver(email, gt, credentials, io) {
1277
1468
  io = io || {};
1278
1469
  const timeout = io.timeout || RESOLV_TIMEOUT;
1470
+
1471
+ let authRequired = false;
1472
+ const onAuthRequired = () => {
1473
+ authRequired = true;
1474
+ };
1475
+
1279
1476
  // Each resolver gets its own signal, aborted by its own timer
1280
- const ctx = signal => withIo({ dns: io.dns, fetchResource: io.fetchResource, signal });
1477
+ const ctx = signal => withIo({ dns: io.dns, fetchResource: io.fetchResource, probe: io.probe, mailProxyUrl: io.mailProxyUrl, onAuthRequired, signal });
1281
1478
 
1282
1479
  let exchange;
1283
1480
  try {
@@ -1291,45 +1488,28 @@ async function resolver(email, gt, credentials, io) {
1291
1488
  // nothing useful found
1292
1489
  }
1293
1490
 
1294
- return new Promise((resolve, reject) => {
1295
- let promises = [
1296
- timedFunction(signal => resolveUsingSRV(email, ctx(signal)), timeout, 'srv'),
1297
- timedFunction(signal => resolveUsingWellKnown(email, ctx(signal)), timeout, 'well-known'),
1298
- timedFunction(signal => resolveUsingAutoconfig(email, ctx(signal)), timeout, 'autoconfig'),
1299
- timedFunction(signal => resolveUsingMozillaDirectory(email, ctx(signal)), timeout, 'mozilla'),
1300
- timedFunction(signal => resolveUsingAutodiscovery(email, ctx(signal), credentials), timeout, 'autodiscover')
1301
- ];
1302
-
1303
- // The first resolver to come back with something wins. A resolver that answers but names
1304
- // neither a host counts as a loss, not a win: several of them parse a response that turned
1305
- // out to describe nothing, and resolving on that would beat a slower resolver that had the
1306
- // real answer.
1307
- let runCount = 0;
1308
- let settle = err => {
1309
- if (++runCount === promises.length) {
1310
- err = err || new Error('Nothing found');
1311
- err._is_last = true;
1312
- reject(err);
1313
- }
1314
- };
1315
-
1316
- for (let prom of promises) {
1317
- prom.then(res => {
1318
- if (!hasResolvedHost(res)) {
1319
- return settle();
1320
- }
1321
-
1322
- runCount++;
1323
-
1324
- let appPassword = getAppPassword(email, exchange, gt);
1325
- if (appPassword) {
1326
- res = Object.assign({}, res, { appPassword });
1327
- }
1491
+ // Only DNS reads and the directory requests, cancelled when the race wins
1492
+ const factsAbort = new AbortController();
1493
+ const facts = timedFunction(signal => gatherFallbackFacts(email, exchange, ctx(AbortSignal.any([signal, factsAbort.signal]))), timeout, 'fallback').catch(
1494
+ () => null
1495
+ );
1328
1496
 
1329
- resolve(res);
1330
- }).catch(settle);
1497
+ let res;
1498
+ try {
1499
+ res = await raceResolvers(email, ctx, credentials, timeout);
1500
+ } catch (err) {
1501
+ const known = await facts;
1502
+ if (!known) {
1503
+ throw err;
1331
1504
  }
1332
- });
1505
+ // The race's own failure is the one callers already know how to read
1506
+ return await timedFunction(signal => resolveUsingFallbacks(email, known, ctx(signal), gt, authRequired), timeout, 'fallback').catch(() => {
1507
+ throw err;
1508
+ });
1509
+ }
1510
+ factsAbort.abort();
1511
+
1512
+ return withHints(res, email, exchange, gt);
1333
1513
  }
1334
1514
 
1335
1515
  /**
@@ -1343,7 +1523,8 @@ async function resolver(email, gt, credentials, io) {
1343
1523
  * the hosted setup form, and `POST /v1/autoconfig` for an integrator running its own form.
1344
1524
  * `GET /v1/autoconfig` takes the address in a query string, where a password must never go, so
1345
1525
  * it stays anonymous and an Exchange domain stays unresolvable there - use the POST instead.
1346
- * @returns {Promise<Object>} `{ imap, smtp, _source }`, plus `appPassword` where one applies
1526
+ * @returns {Promise<Object>} `{ imap, smtp, _source }`, plus `appPassword` and the OAuth2 `provider`
1527
+ * hint (see getProviderHint()) where they apply
1347
1528
  */
1348
1529
  async function autodetectImapSettings(email, gt, credentials) {
1349
1530
  return await resolver(email, gt, credentials);
@@ -1360,6 +1541,8 @@ module.exports.buildAutodiscoverRequest = buildAutodiscoverRequest;
1360
1541
  module.exports.buildAutodiscoverSoapRequest = buildAutodiscoverSoapRequest;
1361
1542
  module.exports.hasResolvedHost = hasResolvedHost;
1362
1543
  module.exports.getAppPassword = getAppPassword;
1544
+ module.exports.getProviderHint = getProviderHint;
1545
+ module.exports.isConsumerMailbox = isConsumerMailbox;
1363
1546
  module.exports.resolveAppPassword = resolveAppPassword;
1364
1547
  module.exports.escapeXml = escapeXml;
1365
1548
 
@@ -1371,6 +1554,9 @@ module.exports.runAutodiscovery = runAutodiscovery;
1371
1554
  // Exposed so the orchestration (the resolver race, the time budget and its abort, the body cap, the
1372
1555
  // SRV fallbacks) can be tested against stand-in DNS and fetch
1373
1556
  module.exports.resolver = resolver;
1557
+ module.exports.exchangeParents = exchangeParents;
1558
+ module.exports.probeCandidates = probeCandidates;
1559
+ module.exports.MAX_PROBE_CANDIDATES = MAX_PROBE_CANDIDATES;
1374
1560
  module.exports.resolveUsingSRV = resolveUsingSRV;
1375
1561
  module.exports.timedFunction = timedFunction;
1376
1562
  module.exports.MAX_AUTODISCOVERY_BODY = MAX_AUTODISCOVERY_BODY;