emailengine-app 2.90.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 (64) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +29 -0
  3. package/Dockerfile +2 -2
  4. package/ENVIRONMENT.md +24 -23
  5. package/README.md +1 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account-assignment.js +26 -9
  8. package/lib/account.js +38 -9
  9. package/lib/api-routes/account-routes.js +7 -0
  10. package/lib/autodetect-imap-settings.js +401 -64
  11. package/lib/consts.js +4 -0
  12. package/lib/email-client/imap-client.js +5 -5
  13. package/lib/email-client/message-builder.js +4 -5
  14. package/lib/imapproxy/imap-server.js +5 -5
  15. package/lib/logger-consts.js +37 -1
  16. package/lib/mail-probe.js +157 -0
  17. package/lib/oauth/mail-ru.js +9 -2
  18. package/lib/read-env-value.js +30 -6
  19. package/lib/redis-backend-warnings.js +70 -0
  20. package/lib/tools.js +17 -28
  21. package/lib/ui-routes/account-routes.js +34 -31
  22. package/lib/ui-routes/account-setup.js +1 -1
  23. package/lib/ui-routes/provider-signin.js +187 -0
  24. package/lib/ui-routes/route-helpers.js +1 -1
  25. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  26. package/package.json +13 -13
  27. package/sbom.json +231 -260
  28. package/server.js +80 -1
  29. package/static/css/public.css +55 -1
  30. package/static/licenses.html +126 -148
  31. package/translations/de.mo +0 -0
  32. package/translations/de.po +429 -390
  33. package/translations/en.mo +0 -0
  34. package/translations/en.po +342 -257
  35. package/translations/es.mo +0 -0
  36. package/translations/es.po +440 -395
  37. package/translations/et.mo +0 -0
  38. package/translations/et.po +425 -375
  39. package/translations/fr.mo +0 -0
  40. package/translations/fr.po +425 -383
  41. package/translations/it.mo +0 -0
  42. package/translations/it.po +441 -394
  43. package/translations/ja.mo +0 -0
  44. package/translations/ja.po +408 -335
  45. package/translations/messages.pot +136 -89
  46. package/translations/nl.mo +0 -0
  47. package/translations/nl.po +419 -382
  48. package/translations/pl.mo +0 -0
  49. package/translations/pl.po +425 -379
  50. package/translations/sv.mo +0 -0
  51. package/translations/sv.po +440 -388
  52. package/translations/tr.mo +0 -0
  53. package/translations/tr.po +441 -387
  54. package/views/account-identity-error.hbs +1 -1
  55. package/views/account-workspace-error.hbs +2 -2
  56. package/views/accounts/register/imap-server.hbs +22 -7
  57. package/views/accounts/register/imap.hbs +3 -0
  58. package/views/accounts/register/index.hbs +1 -27
  59. package/views/accounts/register/provider-signin.hbs +58 -0
  60. package/views/oauth-scope-error.hbs +1 -1
  61. package/views/partials/provider_signin_button.hbs +30 -0
  62. package/views/queues/index.hbs +1 -1
  63. package/views/redirect.hbs +1 -1
  64. package/views/unsubscribe.hbs +6 -6
@@ -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) {
@@ -480,11 +530,14 @@ function staticConfig(imapHost, smtpHost, smtpPort) {
480
530
  };
481
531
  }
482
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
+
483
536
  // Well known MX servers, checked in order and the first match wins. `match` is a pattern, or a
484
537
  // string the exchange has to equal. An entry answers with `config` (static, built fresh for every
485
538
  // lookup), `resolve` (delegates to another resolver) or `build` (derived from the match).
486
539
  const MX_PROVIDERS = [
487
- { match: /\bl\.google\.com$/i, resolve: (email, ctx) => resolveUsingSRV(email, ctx, 'gmail.com', 'mx') },
540
+ { match: GOOGLE_MX, resolve: (email, ctx) => resolveUsingSRV(email, ctx, 'gmail.com', 'mx') },
488
541
  { match: /\bmx\.yandex\.net$/i, resolve: (email, ctx) => resolveUsingAutoconfig(email, ctx, 'yandex.ru', 'mx') },
489
542
  // Zone.eu
490
543
  { match: /^mx\d*\.zone\.eu$/i, config: ['mail.zone.ee', 'smtp.zone.ee', 465] },
@@ -504,7 +557,7 @@ const MX_PROVIDERS = [
504
557
  // Zoho custom domain not in EU
505
558
  { match: /^mx\d*\.zoho\.com$/i, config: ['imappro.zoho.com', 'smtppro.zoho.com', 465] },
506
559
  // MS365: as autodiscovery is currently (2021-11-17) closed use a fixed response
507
- { match: /\bprotection\.outlook\.com$/i, config: ['outlook.office365.com', 'smtp.office365.com', 587] },
560
+ { match: /\bprotection\.outlook\.com$/i, config: MICROSOFT_365_SERVERS },
508
561
  // Inbox.com
509
562
  { match: 'mx.dka.mailcore.net', config: ['imap.dka.mailcore.net', 'smtp.dka.mailcore.net', 587] },
510
563
  { match: 'ekiri.ee', config: ['turvaline.ekiri.ee', 'turvaline.ekiri.ee', 465] },
@@ -568,9 +621,19 @@ async function resolveUsingMX(email, ctx, gt) {
568
621
  throw error;
569
622
  }
570
623
 
571
- let appPassword = getAppPassword(email, exchange, gt);
624
+ return withHints(accountConfig, email, exchange, gt);
625
+ }
572
626
 
573
- 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 } : {});
574
637
  }
575
638
 
576
639
  function escapeXml(unsafe) {
@@ -836,7 +899,7 @@ async function autodiscoverRedirectOrigin(domain, ctx) {
836
899
  * @throws {Error} When no endpoint returned anything usable
837
900
  */
838
901
  async function runAutodiscovery(baseUrl, email, credentials, ctx, redirectsLeft = MAX_AUTODISCOVER_REDIRECTS) {
839
- const { fetchResource, signal } = withIo(ctx);
902
+ const { fetchResource, signal, onAuthRequired } = withIo(ctx);
840
903
 
841
904
  const poxBody = buildAutodiscoverRequest(email);
842
905
  const post = (origin, path, body, authorization) =>
@@ -883,6 +946,14 @@ async function runAutodiscovery(baseUrl, email, credentials, ctx, redirectsLeft
883
946
  throw new Error('Invalid response');
884
947
  }
885
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
+
886
957
  if (!credentials || !credentials.pass) {
887
958
  throw new Error('Invalid response');
888
959
  }
@@ -1072,6 +1143,233 @@ function processAutodiscoverResponse(text, source) {
1072
1143
  return { imap, smtp, _source: source || 'autodiscover' };
1073
1144
  }
1074
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
+
1075
1373
  /**
1076
1374
  * Races a lookup against a time budget.
1077
1375
  *
@@ -1114,19 +1412,69 @@ async function timedFunction(prom, timeout, source) {
1114
1412
  }
1115
1413
 
1116
1414
  /**
1117
- * 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.
1118
1460
  *
1119
1461
  * @param {string} email - Address to look up
1120
1462
  * @param {Object} gt - gettext instance
1121
1463
  * @param {Object} [credentials] - `{ user, pass }`, see autodetectImapSettings()
1122
- * @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
1123
1465
  * @returns {Promise<Object>} The first result that names a server
1124
1466
  */
1125
1467
  async function resolver(email, gt, credentials, io) {
1126
1468
  io = io || {};
1127
1469
  const timeout = io.timeout || RESOLV_TIMEOUT;
1470
+
1471
+ let authRequired = false;
1472
+ const onAuthRequired = () => {
1473
+ authRequired = true;
1474
+ };
1475
+
1128
1476
  // Each resolver gets its own signal, aborted by its own timer
1129
- 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 });
1130
1478
 
1131
1479
  let exchange;
1132
1480
  try {
@@ -1140,45 +1488,28 @@ async function resolver(email, gt, credentials, io) {
1140
1488
  // nothing useful found
1141
1489
  }
1142
1490
 
1143
- return new Promise((resolve, reject) => {
1144
- let promises = [
1145
- timedFunction(signal => resolveUsingSRV(email, ctx(signal)), timeout, 'srv'),
1146
- timedFunction(signal => resolveUsingWellKnown(email, ctx(signal)), timeout, 'well-known'),
1147
- timedFunction(signal => resolveUsingAutoconfig(email, ctx(signal)), timeout, 'autoconfig'),
1148
- timedFunction(signal => resolveUsingMozillaDirectory(email, ctx(signal)), timeout, 'mozilla'),
1149
- timedFunction(signal => resolveUsingAutodiscovery(email, ctx(signal), credentials), timeout, 'autodiscover')
1150
- ];
1151
-
1152
- // The first resolver to come back with something wins. A resolver that answers but names
1153
- // neither a host counts as a loss, not a win: several of them parse a response that turned
1154
- // out to describe nothing, and resolving on that would beat a slower resolver that had the
1155
- // real answer.
1156
- let runCount = 0;
1157
- let settle = err => {
1158
- if (++runCount === promises.length) {
1159
- err = err || new Error('Nothing found');
1160
- err._is_last = true;
1161
- reject(err);
1162
- }
1163
- };
1164
-
1165
- for (let prom of promises) {
1166
- prom.then(res => {
1167
- if (!hasResolvedHost(res)) {
1168
- return settle();
1169
- }
1170
-
1171
- runCount++;
1172
-
1173
- let appPassword = getAppPassword(email, exchange, gt);
1174
- if (appPassword) {
1175
- res = Object.assign({}, res, { appPassword });
1176
- }
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
+ );
1177
1496
 
1178
- resolve(res);
1179
- }).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;
1180
1504
  }
1181
- });
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);
1182
1513
  }
1183
1514
 
1184
1515
  /**
@@ -1192,7 +1523,8 @@ async function resolver(email, gt, credentials, io) {
1192
1523
  * the hosted setup form, and `POST /v1/autoconfig` for an integrator running its own form.
1193
1524
  * `GET /v1/autoconfig` takes the address in a query string, where a password must never go, so
1194
1525
  * it stays anonymous and an Exchange domain stays unresolvable there - use the POST instead.
1195
- * @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
1196
1528
  */
1197
1529
  async function autodetectImapSettings(email, gt, credentials) {
1198
1530
  return await resolver(email, gt, credentials);
@@ -1209,6 +1541,8 @@ module.exports.buildAutodiscoverRequest = buildAutodiscoverRequest;
1209
1541
  module.exports.buildAutodiscoverSoapRequest = buildAutodiscoverSoapRequest;
1210
1542
  module.exports.hasResolvedHost = hasResolvedHost;
1211
1543
  module.exports.getAppPassword = getAppPassword;
1544
+ module.exports.getProviderHint = getProviderHint;
1545
+ module.exports.isConsumerMailbox = isConsumerMailbox;
1212
1546
  module.exports.resolveAppPassword = resolveAppPassword;
1213
1547
  module.exports.escapeXml = escapeXml;
1214
1548
 
@@ -1220,6 +1554,9 @@ module.exports.runAutodiscovery = runAutodiscovery;
1220
1554
  // Exposed so the orchestration (the resolver race, the time budget and its abort, the body cap, the
1221
1555
  // SRV fallbacks) can be tested against stand-in DNS and fetch
1222
1556
  module.exports.resolver = resolver;
1557
+ module.exports.exchangeParents = exchangeParents;
1558
+ module.exports.probeCandidates = probeCandidates;
1559
+ module.exports.MAX_PROBE_CANDIDATES = MAX_PROBE_CANDIDATES;
1223
1560
  module.exports.resolveUsingSRV = resolveUsingSRV;
1224
1561
  module.exports.timedFunction = timedFunction;
1225
1562
  module.exports.MAX_AUTODISCOVERY_BODY = MAX_AUTODISCOVERY_BODY;
package/lib/consts.js CHANGED
@@ -270,6 +270,10 @@ module.exports = {
270
270
  // see lib/email-client/imap/session-expiry.js
271
271
  OAUTH_TOKEN_MIN_VALIDITY: 30 * 1000,
272
272
 
273
+ // Delay before Account.notifyWorker() sends a failed `update` or `reconnect` a second time: long
274
+ // enough for a short main-thread stall to clear
275
+ DISPATCH_RETRY_DELAY: 5 * 1000,
276
+
273
277
  MAX_INLINE_ATTACHMENT_SIZE: 2 * 1024 * 1024,
274
278
 
275
279
  // How many times processing of the same Gmail history entry may start
@@ -46,7 +46,8 @@ const {
46
46
  validUidValidity,
47
47
  getDuration,
48
48
  download,
49
- LRUCache
49
+ LRUCache,
50
+ getMailProxyUrl
50
51
  } = require('../tools');
51
52
  const { getLocalAddress } = require('../utils/network');
52
53
 
@@ -1779,10 +1780,9 @@ class IMAPClient extends BaseClient {
1779
1780
  if (accountData.proxy) {
1780
1781
  imapConfig.proxy = accountData.proxy;
1781
1782
  } else {
1782
- let proxyUrl = await settings.get('proxyUrl');
1783
- let proxyEnabled = await settings.get('proxyEnabled');
1784
- if (proxyEnabled && proxyUrl && !imapConfig.proxy) {
1785
- imapConfig.proxy = proxyUrl;
1783
+ let mailProxyUrl = await getMailProxyUrl();
1784
+ if (mailProxyUrl && !imapConfig.proxy) {
1785
+ imapConfig.proxy = mailProxyUrl;
1786
1786
  }
1787
1787
  }
1788
1788
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  const { Gateway, gatewaySmtpConfig } = require('../gateway');
4
4
  const { oauth2ProviderData } = require('../oauth2-apps');
5
- const { useAuthServerForConnection, redactUrlCredentials } = require('../tools');
5
+ const { useAuthServerForConnection, redactUrlCredentials, getMailProxyUrl } = require('../tools');
6
6
  const { resolveAuthServerCredentials } = require('./credential-errors');
7
7
  const { getLocalAddress } = require('../utils/network');
8
8
  const { applyRequireTls } = require('../utils/require-tls');
@@ -258,10 +258,9 @@ class SmtpConfigBuilder {
258
258
  } else if (accountData.proxy) {
259
259
  smtpSettings.proxy = accountData.proxy;
260
260
  } else {
261
- const proxyUrl = await settings.get('proxyUrl');
262
- const proxyEnabled = await settings.get('proxyEnabled');
263
- if (proxyEnabled && proxyUrl && !smtpSettings.proxy) {
264
- smtpSettings.proxy = proxyUrl;
261
+ const mailProxyUrl = await getMailProxyUrl();
262
+ if (mailProxyUrl && !smtpSettings.proxy) {
263
+ smtpSettings.proxy = mailProxyUrl;
265
264
  }
266
265
  }
267
266
  }