emailengine-app 2.79.8 → 2.80.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.
- package/.github/dependabot.yml +22 -0
- package/.github/workflows/test.yml +39 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +69 -0
- package/DOCKER_DEPLOYMENT.md +6 -7
- package/Dockerfile +35 -11
- package/config/default.toml +7 -2
- package/copy-static-files.sh +23 -5
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +43 -0
- package/lib/account/account-state.js +62 -0
- package/lib/account.js +60 -3
- package/lib/api-routes/account-routes.js +20 -0
- package/lib/api-routes/bull-board-routes.js +3 -2
- package/lib/api-routes/index.js +1 -1
- package/lib/api-routes/route-helpers.js +8 -0
- package/lib/api-routes/settings-routes.js +17 -2
- package/lib/auth-token.js +73 -2
- package/lib/autodetect-imap-settings.js +379 -69
- package/lib/cert-handler.js +62 -0
- package/lib/consts.js +58 -7
- package/lib/db.js +12 -0
- package/lib/egress-fetch.js +145 -0
- package/lib/email-client/base-client.js +234 -66
- package/lib/email-client/credential-errors.js +118 -0
- package/lib/email-client/gmail/gmail-api.js +2 -1
- package/lib/email-client/gmail-client.js +70 -64
- package/lib/email-client/imap/connection-errors.js +52 -0
- package/lib/email-client/imap/listing-diff.js +47 -6
- package/lib/email-client/imap/mailbox.js +457 -379
- package/lib/email-client/imap/subconnection.js +15 -11
- package/lib/email-client/imap/sync-operations.js +46 -59
- package/lib/email-client/imap-client.js +136 -95
- package/lib/email-client/message-builder.js +11 -11
- package/lib/email-client/outlook/graph-api.js +2 -1
- package/lib/email-client/outlook-client.js +219 -106
- package/lib/export.js +35 -2
- package/lib/handlebars-helpers.js +129 -0
- package/lib/imap-proxy-auth.js +96 -21
- package/lib/imapproxy/imap-core/README.md +1 -0
- package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
- package/lib/imapproxy/imap-server.js +56 -66
- package/lib/lua/h-del-if-equals.lua +39 -0
- package/lib/lua/h-set-if-equals.lua +39 -0
- package/lib/openapi/index.js +3 -0
- package/lib/outbox.js +28 -3
- package/lib/rate-limit.js +23 -4
- package/lib/routes-ui.js +4 -34
- package/lib/schemas.js +42 -3
- package/lib/security-headers.js +411 -0
- package/lib/sentry.js +36 -4
- package/lib/smtp-auth.js +86 -7
- package/lib/tls/context.js +376 -0
- package/lib/tls/der.js +223 -0
- package/lib/tls/provision.js +555 -0
- package/lib/tls/self-signed.js +282 -0
- package/lib/tls/status.js +431 -0
- package/lib/tls/store.js +666 -0
- package/lib/tools.js +337 -147
- package/lib/ui-routes/account-routes.js +47 -33
- package/lib/ui-routes/admin-config-routes.js +22 -1
- package/lib/ui-routes/auth-routes.js +16 -1
- package/lib/ui-routes/export-routes.js +4 -0
- package/lib/ui-routes/internals-routes.js +3 -5
- package/lib/ui-routes/mcp-consent-routes.js +7 -0
- package/lib/ui-routes/network-config-routes.js +58 -48
- package/lib/ui-routes/route-helpers.js +24 -8
- package/lib/ui-routes/smtp-test-routes.js +7 -0
- package/lib/ui-routes/tls-config-routes.js +581 -0
- package/lib/utils/mailbox-path.js +51 -0
- package/lib/utils/severity.js +31 -0
- package/lib/webhook-egress.js +5 -0
- package/package.json +21 -24
- package/sbom.json +1 -1
- package/server.js +53 -36
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +11 -0
- package/static/js/ace/css/ace.css +1462 -0
- package/static/js/ace/css/kuroir-1.png +0 -0
- package/static/js/ace/css/kuroir-2.png +0 -0
- package/static/js/ace/css/main-1.png +0 -0
- package/static/js/ace/css/main-10.svg +4 -0
- package/static/js/ace/css/main-11.svg +5 -0
- package/static/js/ace/css/main-12.svg +4 -0
- package/static/js/ace/css/main-13.png +0 -0
- package/static/js/ace/css/main-14.png +0 -0
- package/static/js/ace/css/main-15.png +0 -0
- package/static/js/ace/css/main-16.png +0 -0
- package/static/js/ace/css/main-17.png +0 -0
- package/static/js/ace/css/main-18.png +0 -0
- package/static/js/ace/css/main-19.png +0 -0
- package/static/js/ace/css/main-2.png +0 -0
- package/static/js/ace/css/main-20.png +0 -0
- package/static/js/ace/css/main-21.png +0 -0
- package/static/js/ace/css/main-22.png +0 -0
- package/static/js/ace/css/main-23.png +0 -0
- package/static/js/ace/css/main-24.png +0 -0
- package/static/js/ace/css/main-25.svg +1 -0
- package/static/js/ace/css/main-26.png +0 -0
- package/static/js/ace/css/main-3.png +0 -0
- package/static/js/ace/css/main-4.png +0 -0
- package/static/js/ace/css/main-5.svg +7 -0
- package/static/js/ace/css/main-6.svg +9 -0
- package/static/js/ace/css/main-7.svg +7 -0
- package/static/js/ace/css/main-8.svg +9 -0
- package/static/js/ace/css/main-9.svg +6 -0
- package/static/js/ace/css/theme/kuroir.css +78 -0
- package/static/js/ace/css/theme/tomorrow_night.css +128 -0
- package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
- package/static/js/ace/css/theme/xcode.css +106 -0
- package/static/js/ace/css/tomorrow_night-1.png +0 -0
- package/static/js/ace/css/tomorrow_night-2.png +0 -0
- package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
- package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
- package/static/js/ace/css/xcode-1.png +0 -0
- package/static/js/ace/css/xcode-2.png +0 -0
- package/static/js/app.js +34 -0
- package/static/js/ee-client.js +256 -102
- package/static/js/public.js +13 -2
- package/static/js/ui.js +40 -25
- package/static/licenses.html +393 -1282
- package/static/vendor/simplewebauthn/browser.min.js +2 -2
- package/translations/messages.pot +203 -157
- package/views/account/login-redirect.hbs +22 -0
- package/views/accounts/account.hbs +15 -37
- package/views/accounts/browse.hbs +3 -1
- package/views/accounts/edit.hbs +1 -1
- package/views/accounts/register/imap-server.hbs +1 -1
- package/views/config/ai.hbs +1 -1
- package/views/config/branding.hbs +2 -2
- package/views/config/document-store/chat.hbs +1 -1
- package/views/config/document-store/index.hbs +1 -1
- package/views/config/imap-proxy.hbs +1 -4
- package/views/config/license.hbs +1 -1
- package/views/config/mcp.hbs +1 -1
- package/views/config/network.hbs +14 -16
- package/views/config/oauth/app.hbs +2 -2
- package/views/config/service.hbs +1 -1
- package/views/config/smtp.hbs +1 -4
- package/views/config/tls-upload.hbs +81 -0
- package/views/config/tls.hbs +492 -0
- package/views/config/webhooks.hbs +2 -2
- package/views/error.hbs +4 -2
- package/views/internals/index.hbs +1 -1
- package/views/layout/app.hbs +3 -11
- package/views/mcp/authorize.hbs +1 -1
- package/views/partials/ace_assets.hbs +13 -0
- package/views/partials/add_account_modal.hbs +1 -1
- package/views/partials/address_list.hbs +4 -4
- package/views/partials/filter_editor_js.hbs +2 -2
- package/views/partials/gateway_js.hbs +1 -1
- package/views/partials/oauth_form.hbs +1 -1
- package/views/partials/public_theme_init.hbs +1 -1
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/template_form.hbs +2 -2
- package/views/partials/test_send.hbs +7 -4
- package/views/partials/theme_init.hbs +1 -1
- package/views/partials/tls_security_card.hbs +25 -53
- package/views/partials/ui/alert-banner.hbs +3 -2
- package/views/partials/ui/badge.hbs +6 -2
- package/views/partials/ui/btn.hbs +5 -2
- package/views/partials/ui/details.hbs +2 -2
- package/views/partials/webhooks_editor_functions.hbs +1 -1
- package/views/reference/redirect.hbs +1 -1
- package/views/templates/template.hbs +2 -2
- package/views/tokens/new.hbs +1 -1
- package/views/unsubscribe.hbs +1 -1
- package/views/webhooks/webhook.hbs +2 -2
- package/workers/api.js +131 -242
- package/workers/export.js +1 -5
- package/workers/imap-proxy.js +4 -1
- package/workers/imap.js +1 -3
- package/workers/smtp.js +59 -83
- package/workers/submit.js +6 -12
- package/workers/webhooks.js +6 -17
- package/static/front/EmailEngine_logo_horiz.png +0 -0
- package/static/front/EmailEngine_logo_vert.png +0 -0
- package/static/front/index.html +0 -57
- package/static/front/logo.png +0 -0
- package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
- package/views/partials/tls_security_js.hbs +0 -64
- package/views/partials/tls_security_modal.hbs +0 -22
|
@@ -22,7 +22,26 @@ const xmlParser = new XMLParser({
|
|
|
22
22
|
htmlEntities: true
|
|
23
23
|
});
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
// Exchange repeats a connection entry once per client access server, and returns a lone
|
|
26
|
+
// `usersetting` object when only one setting was asked for; both have to read as lists
|
|
27
|
+
const SOAP_ARRAY_TAGS = new Set(['usersetting', 'protocolconnection']);
|
|
28
|
+
|
|
29
|
+
// The SOAP autodiscovery response prefixes almost every element (`s:Envelope`, `a:Request`), and
|
|
30
|
+
// the settings are read by name rather than by shape, so this parser strips the prefixes instead of
|
|
31
|
+
// mirroring xml2js. Kept separate from `xmlParser` so the Mozilla-autoconfig and POX trees, which
|
|
32
|
+
// several callers and their tests depend on, keep the shape they have always had.
|
|
33
|
+
const soapXmlParser = new XMLParser({
|
|
34
|
+
ignoreDeclaration: true,
|
|
35
|
+
ignoreAttributes: true,
|
|
36
|
+
removeNSPrefix: true,
|
|
37
|
+
transformTagName: tag => tag.toLowerCase(),
|
|
38
|
+
parseTagValue: false,
|
|
39
|
+
trimValues: true,
|
|
40
|
+
htmlEntities: true,
|
|
41
|
+
isArray: name => SOAP_ARRAY_TAGS.has(name)
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
function parseWith(parser, text) {
|
|
26
45
|
if (!text || !text.trim()) {
|
|
27
46
|
// xml2js resolved an empty document to null instead of erroring, callers check for it
|
|
28
47
|
return null;
|
|
@@ -35,11 +54,17 @@ function parseXml(text) {
|
|
|
35
54
|
throw err;
|
|
36
55
|
}
|
|
37
56
|
|
|
38
|
-
return
|
|
57
|
+
return parser.parse(text);
|
|
39
58
|
}
|
|
40
59
|
|
|
60
|
+
// Two grammars, named so a call site says which one it is reading
|
|
61
|
+
const parseXml = text => parseWith(xmlParser, text);
|
|
62
|
+
const parseSoapXml = text => parseWith(soapXmlParser, text);
|
|
63
|
+
|
|
41
64
|
const { fetch: fetchCmd } = require('undici');
|
|
42
65
|
const { httpAgent } = require('./tools');
|
|
66
|
+
const { fetchWithVettedRedirects } = require('./egress-fetch');
|
|
67
|
+
const { validateWebhookTarget } = require('./webhook-egress');
|
|
43
68
|
|
|
44
69
|
const RESOLV_TIMEOUT = 5 * 1000;
|
|
45
70
|
|
|
@@ -47,6 +72,23 @@ const RESOLV_TIMEOUT = 5 * 1000;
|
|
|
47
72
|
// re-render and only produces a cosmetic label, so it must not stall the page for the full RESOLV_TIMEOUT.
|
|
48
73
|
const APP_PASSWORD_MX_TIMEOUT = 1500;
|
|
49
74
|
|
|
75
|
+
/**
|
|
76
|
+
* Does a resolver result actually name a server? Asked by every branch that has to decide whether
|
|
77
|
+
* a lookup answered, so they all decide it the same way.
|
|
78
|
+
*
|
|
79
|
+
* The presence of an `imap` or `smtp` entry is not the same question. The parsers used to build one
|
|
80
|
+
* out of whatever the document carried, so a description of no server at all came back as an object
|
|
81
|
+
* that was truthy and named nothing - which won the resolver race against a slower branch holding
|
|
82
|
+
* the real settings, and rendered the hosted setup form with empty server fields. They now refuse
|
|
83
|
+
* such an entry at the source; this is what the branches ask.
|
|
84
|
+
*
|
|
85
|
+
* @param {Object} res - Result of one resolver, `{ imap, smtp }`
|
|
86
|
+
* @returns {Boolean} True when at least one protocol names a host
|
|
87
|
+
*/
|
|
88
|
+
function hasResolvedHost(res) {
|
|
89
|
+
return !!(res && ((res.imap && res.imap.host) || (res.smtp && res.smtp.host)));
|
|
90
|
+
}
|
|
91
|
+
|
|
50
92
|
// use a function instead of const to prevent translations before locale is set
|
|
51
93
|
// The canonical consumer domains are listed alongside the exchange regexes so a plain domain match
|
|
52
94
|
// (getAppPassword with exchange=false) resolves the big providers without any MX lookup - each listed
|
|
@@ -199,22 +241,29 @@ async function processAutoconfigFile(email, domain, text, source) {
|
|
|
199
241
|
}
|
|
200
242
|
let json = parseXml(text);
|
|
201
243
|
|
|
244
|
+
// A server element with an empty <hostname> describes no server at all. Building the entry
|
|
245
|
+
// anyway produced an object that was truthy and named nothing, which every caller read as an
|
|
246
|
+
// answer: the resolver race was won by it and the hosted setup form rendered empty fields.
|
|
247
|
+
// So the first element that names a host wins, not simply the first of its type - taking the
|
|
248
|
+
// first let a hostless one discard a usable sibling further down.
|
|
249
|
+
const namesHost = entry => entry && Array.isArray(entry.hostname) && entry.hostname.some(value => value);
|
|
250
|
+
|
|
202
251
|
let emailProviders = json && json.clientconfig && Array.isArray(json.clientconfig.emailprovider) ? json.clientconfig.emailprovider : [];
|
|
203
252
|
let incomingServer = emailProviders
|
|
204
253
|
.flatMap(entry => (entry && Array.isArray(entry.incomingserver) ? entry.incomingserver : []))
|
|
205
254
|
.filter(entry => entry && entry.$ && entry.$.type === 'imap')
|
|
206
|
-
.
|
|
255
|
+
.find(namesHost);
|
|
207
256
|
let outgoingServer = emailProviders
|
|
208
257
|
.flatMap(entry => (entry && Array.isArray(entry.outgoingserver) ? entry.outgoingserver : []))
|
|
209
258
|
.filter(entry => entry && entry.$ && entry.$.type === 'smtp')
|
|
210
|
-
.
|
|
259
|
+
.find(namesHost);
|
|
211
260
|
|
|
212
261
|
let imap = false;
|
|
213
262
|
let smtp = false;
|
|
214
263
|
|
|
215
264
|
if (incomingServer) {
|
|
216
265
|
const firstHostname = incomingServer.hostname.filter(entry => entry).shift();
|
|
217
|
-
const processedHostname = firstHostname
|
|
266
|
+
const processedHostname = firstHostname.replace(/^%EMAILDOMAIN%$/, domain);
|
|
218
267
|
|
|
219
268
|
imap = {
|
|
220
269
|
host: processedHostname,
|
|
@@ -234,7 +283,7 @@ async function processAutoconfigFile(email, domain, text, source) {
|
|
|
234
283
|
|
|
235
284
|
if (outgoingServer) {
|
|
236
285
|
const firstHostname = outgoingServer.hostname.filter(entry => entry).shift();
|
|
237
|
-
const processedHostname = firstHostname
|
|
286
|
+
const processedHostname = firstHostname.replace(/^%EMAILDOMAIN%$/, domain);
|
|
238
287
|
|
|
239
288
|
smtp = {
|
|
240
289
|
host: processedHostname,
|
|
@@ -255,6 +304,29 @@ async function processAutoconfigFile(email, domain, text, source) {
|
|
|
255
304
|
return { imap, smtp, _source: source };
|
|
256
305
|
}
|
|
257
306
|
|
|
307
|
+
// Every HTTP lookup below reaches a destination derived from the email address a caller typed:
|
|
308
|
+
// autoconfig.<domain>, <domain>/.well-known, an autodiscover host a DNS SRV record names, port
|
|
309
|
+
// included. That is the same class of destination as a webhook target, so the requests go through
|
|
310
|
+
// the same egress policy (lib/webhook-egress.js): the policy-bound dispatcher resolves the name at
|
|
311
|
+
// connect time, the pre-check refuses a blocked address up front, and each redirect hop is vetted
|
|
312
|
+
// before it is taken. Without this, a DNS record under the caller's control pointed the lookup at
|
|
313
|
+
// the cloud metadata service or at whatever else the host can route to.
|
|
314
|
+
//
|
|
315
|
+
// Not the retrying dispatcher: a lookup that fails is skipped in favor of the next resolver, and
|
|
316
|
+
// the retry agent would only stretch the timeout budget of a dead one.
|
|
317
|
+
async function fetchAutodiscoveryResource(url, opts) {
|
|
318
|
+
opts = opts || {};
|
|
319
|
+
return await fetchWithVettedRedirects(
|
|
320
|
+
fetchCmd,
|
|
321
|
+
url,
|
|
322
|
+
Object.assign({}, opts, {
|
|
323
|
+
headers: Object.assign({ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})` }, opts.headers),
|
|
324
|
+
dispatcher: httpAgent.webhook,
|
|
325
|
+
validateTarget: validateWebhookTarget
|
|
326
|
+
})
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
|
|
258
330
|
async function resolveUsingMozillaDirectory(email, domain, source) {
|
|
259
331
|
domain = domain || email.split('@').pop().trim().toLowerCase();
|
|
260
332
|
|
|
@@ -264,12 +336,7 @@ async function resolveUsingMozillaDirectory(email, domain, source) {
|
|
|
264
336
|
//ignore
|
|
265
337
|
}
|
|
266
338
|
|
|
267
|
-
let res = await
|
|
268
|
-
headers: {
|
|
269
|
-
'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
|
|
270
|
-
},
|
|
271
|
-
dispatcher: httpAgent.retry
|
|
272
|
-
});
|
|
339
|
+
let res = await fetchAutodiscoveryResource(`https://autoconfig.thunderbird.net/v1.1/${domain}`);
|
|
273
340
|
|
|
274
341
|
if (!res.ok) {
|
|
275
342
|
throw new Error('Invalid response');
|
|
@@ -289,12 +356,9 @@ async function resolveUsingAutoconfig(email, domain, source) {
|
|
|
289
356
|
//ignore
|
|
290
357
|
}
|
|
291
358
|
|
|
292
|
-
let res = await
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
},
|
|
296
|
-
dispatcher: httpAgent.retry
|
|
297
|
-
});
|
|
359
|
+
let res = await fetchAutodiscoveryResource(
|
|
360
|
+
`https://autoconfig.${encodeURIComponent(domain)}/mail/config-v1.1.xml?emailaddress=${encodeURIComponent(email)}`
|
|
361
|
+
);
|
|
298
362
|
|
|
299
363
|
if (!res.ok) {
|
|
300
364
|
throw new Error('Invalid response');
|
|
@@ -314,12 +378,7 @@ async function resolveUsingWellKnown(email, domain, source) {
|
|
|
314
378
|
//ignore
|
|
315
379
|
}
|
|
316
380
|
|
|
317
|
-
let res = await
|
|
318
|
-
headers: {
|
|
319
|
-
'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
|
|
320
|
-
},
|
|
321
|
-
dispatcher: httpAgent.retry
|
|
322
|
-
});
|
|
381
|
+
let res = await fetchAutodiscoveryResource(`http://${encodeURIComponent(domain)}/.well-known/autoconfig/mail/config-v1.1.xml`);
|
|
323
382
|
|
|
324
383
|
if (!res.ok) {
|
|
325
384
|
throw new Error('Invalid response');
|
|
@@ -648,6 +707,17 @@ async function resolveUsingMX(email, domain, gt) {
|
|
|
648
707
|
};
|
|
649
708
|
|
|
650
709
|
let accountConfig = await resolveConfig();
|
|
710
|
+
|
|
711
|
+
if (!hasResolvedHost(accountConfig)) {
|
|
712
|
+
// The exchange matched, but the config it delegated to named no server: the Gmail branch
|
|
713
|
+
// reads SRV records and the Yandex one an autoconfig file, and either can come back empty.
|
|
714
|
+
// Reported as a miss rather than returned, so the racing resolvers get their turn - and
|
|
715
|
+
// carrying the exchange, which is what the app-password hint is matched on.
|
|
716
|
+
let error = new Error('Nothing found');
|
|
717
|
+
error.exchange = exchange;
|
|
718
|
+
throw error;
|
|
719
|
+
}
|
|
720
|
+
|
|
651
721
|
let appPassword = getAppPassword(email, exchange, gt);
|
|
652
722
|
|
|
653
723
|
return Object.assign({}, accountConfig, appPassword ? { appPassword } : {});
|
|
@@ -670,56 +740,258 @@ function escapeXml(unsafe) {
|
|
|
670
740
|
});
|
|
671
741
|
}
|
|
672
742
|
|
|
673
|
-
|
|
674
|
-
|
|
743
|
+
// Exchange answers `application/xml` with 415 before it looks at the body, on both autodiscovery
|
|
744
|
+
// endpoints. Every request below has to be announced as text/xml.
|
|
745
|
+
const AUTODISCOVER_CONTENT_TYPE = 'text/xml; charset=utf-8';
|
|
746
|
+
|
|
747
|
+
/**
|
|
748
|
+
* Builds the legacy ("POX") autodiscovery request.
|
|
749
|
+
*
|
|
750
|
+
* The child order is load-bearing: the request schema declares a sequence, and Exchange answers
|
|
751
|
+
* `<ErrorCode>600</ErrorCode>` ("Invalid Request") when `AcceptableResponseSchema` arrives ahead of
|
|
752
|
+
* `EMailAddress`, which is the order this used to send.
|
|
753
|
+
*
|
|
754
|
+
* @param {string} email - Address to look up
|
|
755
|
+
* @returns {string} Request document
|
|
756
|
+
*/
|
|
757
|
+
function buildAutodiscoverRequest(email) {
|
|
758
|
+
return `<?xml version="1.0" encoding="utf-8"?>
|
|
759
|
+
<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006">
|
|
760
|
+
<Request>
|
|
761
|
+
<EMailAddress>${escapeXml(email)}</EMailAddress>
|
|
762
|
+
<AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema>
|
|
763
|
+
</Request>
|
|
764
|
+
</Autodiscover>`;
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* Builds a SOAP `GetUserSettings` request for the mailbox's external IMAP and SMTP endpoints.
|
|
769
|
+
*
|
|
770
|
+
* This is the modern autodiscovery service (Exchange 2010 and later). It is asked in addition to
|
|
771
|
+
* the POX endpoint because Exchange populates the two from different places: POX commonly answers
|
|
772
|
+
* with nothing but the `WEB` (Outlook on the web) protocol, while these settings are the ones the
|
|
773
|
+
* webmail "POP and IMAP settings" page shows.
|
|
774
|
+
*
|
|
775
|
+
* @param {string} email - Mailbox to look up
|
|
776
|
+
* @returns {string} Request document
|
|
777
|
+
*/
|
|
778
|
+
function buildAutodiscoverSoapRequest(email) {
|
|
779
|
+
return `<?xml version="1.0" encoding="utf-8"?>
|
|
780
|
+
<soap:Envelope xmlns:a="http://schemas.microsoft.com/exchange/2010/Autodiscover" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing">
|
|
781
|
+
<soap:Header>
|
|
782
|
+
<a:RequestedServerVersion>Exchange2013</a:RequestedServerVersion>
|
|
783
|
+
<wsa:Action>http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetUserSettings</wsa:Action>
|
|
784
|
+
</soap:Header>
|
|
785
|
+
<soap:Body>
|
|
786
|
+
<a:GetUserSettingsRequestMessage>
|
|
787
|
+
<a:Request>
|
|
788
|
+
<a:Users><a:User><a:Mailbox>${escapeXml(email)}</a:Mailbox></a:User></a:Users>
|
|
789
|
+
<a:RequestedSettings>
|
|
790
|
+
<a:Setting>ExternalImap4Connections</a:Setting>
|
|
791
|
+
<a:Setting>ExternalSmtpConnections</a:Setting>
|
|
792
|
+
</a:RequestedSettings>
|
|
793
|
+
</a:Request>
|
|
794
|
+
</a:GetUserSettingsRequestMessage>
|
|
795
|
+
</soap:Body>
|
|
796
|
+
</soap:Envelope>`;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// "SSL" is implicit TLS, "TLS" is STARTTLS on the cleartext port, "None" is neither
|
|
800
|
+
const isImplicitTls = entry => /^ssl$/i.test(entry.encryptionmethod);
|
|
801
|
+
|
|
802
|
+
/**
|
|
803
|
+
* Picks one connection out of a `ProtocolConnectionCollectionSetting`.
|
|
804
|
+
*
|
|
805
|
+
* Exchange lists the same endpoint once per client access server, so the collection arrives with
|
|
806
|
+
* dozens of interchangeable entries, and it offers both the implicit-TLS and the STARTTLS port. The
|
|
807
|
+
* implicit-TLS one is preferred: it is what the provider's own documentation tells users to use,
|
|
808
|
+
* and it needs no upgrade step that a middlebox can strip.
|
|
809
|
+
*
|
|
810
|
+
* @param {Array} [connections] - Parsed `protocolconnection` entries
|
|
811
|
+
* @returns {Object|Boolean} `{ host, port, secure }`, or false when nothing usable was listed
|
|
812
|
+
*/
|
|
813
|
+
function pickProtocolConnection(connections) {
|
|
814
|
+
let picked = null;
|
|
815
|
+
|
|
816
|
+
for (let entry of connections || []) {
|
|
817
|
+
if (!entry || !entry.hostname || !Number(entry.port)) {
|
|
818
|
+
continue;
|
|
819
|
+
}
|
|
820
|
+
if (isImplicitTls(entry)) {
|
|
821
|
+
picked = entry;
|
|
822
|
+
break;
|
|
823
|
+
}
|
|
824
|
+
picked = picked || entry;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
return picked ? { host: picked.hostname, port: Number(picked.port), secure: isImplicitTls(picked) } : false;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* Reads IMAP and SMTP settings out of a SOAP `GetUserSettings` response.
|
|
832
|
+
*
|
|
833
|
+
* @param {string} text - Response document
|
|
834
|
+
* @returns {Object} `{ imap, smtp, _source }`, either entry false when it was not listed
|
|
835
|
+
*/
|
|
836
|
+
function processAutodiscoverSoapResponse(text) {
|
|
837
|
+
let json = parseSoapXml(text);
|
|
838
|
+
|
|
839
|
+
let settings = json?.envelope?.body?.getusersettingsresponsemessage?.response?.userresponses?.userresponse?.usersettings?.usersetting || [];
|
|
840
|
+
|
|
841
|
+
let connectionsFor = name =>
|
|
842
|
+
pickProtocolConnection(settings.find(entry => String(entry?.name).toLowerCase() === name)?.protocolconnections?.protocolconnection);
|
|
675
843
|
|
|
844
|
+
return {
|
|
845
|
+
imap: connectionsFor('externalimap4connections'),
|
|
846
|
+
smtp: connectionsFor('externalsmtpconnections'),
|
|
847
|
+
_source: 'autodiscover'
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* Resolves the host that answers autodiscovery for a domain.
|
|
853
|
+
*
|
|
854
|
+
* @param {string} domain - Punycode domain
|
|
855
|
+
* @returns {Promise<string>} Host, with a port appended when the SRV record names a non-default one
|
|
856
|
+
*/
|
|
857
|
+
// The origin of a URL, but only when it is one a password may be sent to. A redirect is allowed to
|
|
858
|
+
// lead to http (the anonymous lookup carries nothing worth protecting), so the host that ends up
|
|
859
|
+
// issuing the challenge is not necessarily on https, and Basic over cleartext would hand the
|
|
860
|
+
// mailbox password to anyone on the path.
|
|
861
|
+
function secureOriginOf(url) {
|
|
676
862
|
try {
|
|
677
|
-
|
|
863
|
+
const parsed = new URL(url);
|
|
864
|
+
return parsed.protocol === 'https:' ? parsed.origin : false;
|
|
678
865
|
} catch (err) {
|
|
679
|
-
|
|
866
|
+
return false;
|
|
680
867
|
}
|
|
868
|
+
}
|
|
681
869
|
|
|
682
|
-
|
|
870
|
+
async function resolveAutodiscoveryHost(domain) {
|
|
683
871
|
try {
|
|
684
872
|
let srvList = await dns.resolveSrv(`_autodiscover._tcp.${domain}`);
|
|
685
873
|
let record = srvList.sort((a, b) => a.priority - b.priority).shift();
|
|
686
874
|
if (record) {
|
|
687
|
-
|
|
875
|
+
return `${record.name}${record.port !== 443 ? `:${record.port}` : ''}`;
|
|
688
876
|
}
|
|
689
877
|
} catch (err) {
|
|
690
878
|
//ignore
|
|
691
879
|
}
|
|
692
880
|
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
<Request>
|
|
696
|
-
<AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema>
|
|
697
|
-
<EMailAddress>${escapeXml(email)}</EMailAddress>
|
|
698
|
-
</Request>
|
|
699
|
-
</Autodiscover>`;
|
|
881
|
+
return `autodiscover.${encodeURIComponent(domain)}`;
|
|
882
|
+
}
|
|
700
883
|
|
|
701
|
-
|
|
884
|
+
/**
|
|
885
|
+
* Runs autodiscovery against one host.
|
|
886
|
+
*
|
|
887
|
+
* Both endpoints answer a mailbox lookup with 401 on a hosted Exchange, so the password is what
|
|
888
|
+
* makes them usable at all. It is offered only once the server has answered with a challenge that
|
|
889
|
+
* names Basic: never on the first request, never to a host that answered some other way, and only
|
|
890
|
+
* ever over https - a challenge that reached us over http is refused rather than answered.
|
|
891
|
+
*
|
|
892
|
+
* The two endpoints are asked at the same time rather than one after the other: they are answered
|
|
893
|
+
* from different Exchange configuration, either can be the one that carries IMAP settings, and the
|
|
894
|
+
* whole resolver runs against a five second budget shared with four other lookups.
|
|
895
|
+
*
|
|
896
|
+
* @param {string} baseUrl - Origin of the autodiscovery host, no trailing slash
|
|
897
|
+
* @param {string} email - Mailbox to look up
|
|
898
|
+
* @param {Object} [credentials] - `{ user, pass }`; the lookup stays anonymous without it
|
|
899
|
+
* @param {Function} [fetchResource] - Fetch to use, `(url, opts) => Promise<Response>`
|
|
900
|
+
* @returns {Promise<Object>} `{ imap, smtp, _source }`
|
|
901
|
+
* @throws {Error} When no endpoint returned anything usable
|
|
902
|
+
*/
|
|
903
|
+
async function runAutodiscovery(baseUrl, email, credentials, fetchResource) {
|
|
904
|
+
fetchResource = fetchResource || fetchAutodiscoveryResource;
|
|
905
|
+
|
|
906
|
+
const poxBody = buildAutodiscoverRequest(email);
|
|
907
|
+
const post = (origin, path, body, authorization) =>
|
|
908
|
+
fetchResource(`${origin}${path}`, {
|
|
909
|
+
method: 'post',
|
|
910
|
+
headers: Object.assign({ 'Content-type': AUTODISCOVER_CONTENT_TYPE }, authorization ? { Authorization: authorization } : {}),
|
|
911
|
+
body
|
|
912
|
+
});
|
|
702
913
|
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
914
|
+
// A server that answers without credentials is never asked for them
|
|
915
|
+
let res = await post(baseUrl, '/autodiscover/autodiscover.xml', poxBody);
|
|
916
|
+
if (res.ok) {
|
|
917
|
+
let result = processAutodiscoverResponse(await res.text());
|
|
918
|
+
if (hasResolvedHost(result)) {
|
|
919
|
+
return result;
|
|
920
|
+
}
|
|
921
|
+
// It answered anonymously, just with nothing usable. It never asked for a password, so it
|
|
922
|
+
// is not given one.
|
|
923
|
+
throw new Error('Invalid response');
|
|
924
|
+
}
|
|
712
925
|
|
|
713
|
-
|
|
926
|
+
// Nothing here reads the body, and the retries below reuse this connection
|
|
927
|
+
await res.text().catch(() => false);
|
|
928
|
+
|
|
929
|
+
// Only a challenge that names Basic earns the password. A 404 from a wildcard-DNS parking host,
|
|
930
|
+
// a 500, a CDN answering an unknown path, a server offering only NTLM - all answered without
|
|
931
|
+
// asking for one, and Basic would be no use to the last of them anyway.
|
|
932
|
+
if (res.status !== 401 || !/\bbasic\b/i.test(res.headers?.get('www-authenticate') || '')) {
|
|
714
933
|
throw new Error('Invalid response');
|
|
715
934
|
}
|
|
716
935
|
|
|
717
|
-
|
|
936
|
+
if (!credentials || !credentials.pass) {
|
|
937
|
+
throw new Error('Invalid response');
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
// Ask the host that actually answered. Following the redirect again for each retry would repeat
|
|
941
|
+
// every hop, and a cross-origin one strips the very header the retry exists to carry. A
|
|
942
|
+
// challenge that arrived over http is refused rather than answered on the original host: the
|
|
943
|
+
// host that asked for the password is the one that would have to receive it.
|
|
944
|
+
const origin = secureOriginOf(res.url || baseUrl);
|
|
945
|
+
if (!origin) {
|
|
946
|
+
throw new Error('Invalid response');
|
|
947
|
+
}
|
|
948
|
+
const authorization = `Basic ${Buffer.from(`${credentials.user || email}:${credentials.pass}`).toString('base64')}`;
|
|
949
|
+
|
|
950
|
+
const attempt = (path, body, processResponse) =>
|
|
951
|
+
post(origin, path, body, authorization)
|
|
952
|
+
.then(async res => (res.ok ? processResponse(await res.text()) : false))
|
|
953
|
+
.catch(() => false);
|
|
954
|
+
|
|
955
|
+
// Both are in flight before either is awaited, and whichever answers first with a usable
|
|
956
|
+
// configuration wins. Collecting them into an array first - `[await pox, await soap]` - looked
|
|
957
|
+
// like it did that but awaited both, so a stalled endpoint held up an answer the other one had
|
|
958
|
+
// already given, and the five second budget this resolver shares could run out with the
|
|
959
|
+
// settings sitting in a resolved promise. The two are populated from different Exchange
|
|
960
|
+
// configuration, so either can be the one that has them.
|
|
961
|
+
//
|
|
962
|
+
// An answer that names no server is a loss rather than a win, which is what makes this the same
|
|
963
|
+
// policy resolver() applies to the five lookups above it. POX still wins a tie, because both
|
|
964
|
+
// are already settled by then and reactions run in the order they were subscribed, and it is
|
|
965
|
+
// the only one of the two that names the login to use.
|
|
966
|
+
const pox = attempt('/autodiscover/autodiscover.xml', poxBody, processAutodiscoverResponse);
|
|
967
|
+
const soap = attempt('/autodiscover/autodiscover.svc', buildAutodiscoverSoapRequest(email), processAutodiscoverSoapResponse);
|
|
968
|
+
|
|
969
|
+
const usable = result => (hasResolvedHost(result) ? result : Promise.reject(new Error('Invalid response')));
|
|
970
|
+
|
|
971
|
+
try {
|
|
972
|
+
return await Promise.any([pox.then(usable), soap.then(usable)]);
|
|
973
|
+
} catch (err) {
|
|
974
|
+
// Both came back with nothing usable, which Promise.any reports as an AggregateError over
|
|
975
|
+
// the two rejections above
|
|
976
|
+
throw new Error('Invalid response', { cause: err });
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
async function resolveUsingAutodiscovery(email, credentials) {
|
|
981
|
+
let domain = email.split('@').pop().trim().toLowerCase();
|
|
982
|
+
|
|
983
|
+
try {
|
|
984
|
+
domain = punycode.toASCII(domain);
|
|
985
|
+
} catch (err) {
|
|
986
|
+
//ignore
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
let discoveryDomain = await resolveAutodiscoveryHost(domain);
|
|
718
990
|
|
|
719
|
-
return await
|
|
991
|
+
return await runAutodiscovery(`https://${discoveryDomain}`, email, credentials);
|
|
720
992
|
}
|
|
721
993
|
|
|
722
|
-
|
|
994
|
+
function processAutodiscoverResponse(text, source) {
|
|
723
995
|
let json = parseXml(text);
|
|
724
996
|
|
|
725
997
|
let imap = false;
|
|
@@ -750,11 +1022,13 @@ async function processAutodiscoverResponse(text, source) {
|
|
|
750
1022
|
}
|
|
751
1023
|
|
|
752
1024
|
let getStructureFromObject = entry => {
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
1025
|
+
if (!entry.server || typeof entry.server !== 'string') {
|
|
1026
|
+
// A <Protocol> with a <Type> and no <Server> names nothing, and an entry
|
|
1027
|
+
// that names nothing is not a result - see hasResolvedHost()
|
|
1028
|
+
return false;
|
|
757
1029
|
}
|
|
1030
|
+
|
|
1031
|
+
let res = { host: entry.server };
|
|
758
1032
|
if (entry.port && (typeof entry.port === 'string' || (typeof entry.port === 'number' && !isNaN(entry.port)))) {
|
|
759
1033
|
res.port = Number(entry.port);
|
|
760
1034
|
}
|
|
@@ -767,13 +1041,17 @@ async function processAutodiscoverResponse(text, source) {
|
|
|
767
1041
|
return res;
|
|
768
1042
|
};
|
|
769
1043
|
|
|
770
|
-
|
|
1044
|
+
// First usable entry wins. Exchange emits several <Protocol> blocks of the same
|
|
1045
|
+
// type (internal and external variants, and Type-only blocks naming no server at
|
|
1046
|
+
// all), and overwriting on every match let a hostless sibling further down discard
|
|
1047
|
+
// the one that actually named a host
|
|
1048
|
+
if (/^IMAP$/i.test(entry.type) && !imap) {
|
|
771
1049
|
// imap entry
|
|
772
1050
|
imap = getStructureFromObject(entry);
|
|
773
1051
|
}
|
|
774
1052
|
|
|
775
|
-
if (/^SMTP$/i.test(entry.type)) {
|
|
776
|
-
//
|
|
1053
|
+
if (/^SMTP$/i.test(entry.type) && !smtp) {
|
|
1054
|
+
// smtp entry
|
|
777
1055
|
smtp = getStructureFromObject(entry);
|
|
778
1056
|
}
|
|
779
1057
|
});
|
|
@@ -799,7 +1077,7 @@ async function timedFunction(prom, timeout, source) {
|
|
|
799
1077
|
});
|
|
800
1078
|
}
|
|
801
1079
|
|
|
802
|
-
async function resolver(email, gt) {
|
|
1080
|
+
async function resolver(email, gt, credentials) {
|
|
803
1081
|
let exchange;
|
|
804
1082
|
try {
|
|
805
1083
|
// prefer MX based resolver
|
|
@@ -818,12 +1096,28 @@ async function resolver(email, gt) {
|
|
|
818
1096
|
timedFunction(resolveUsingWellKnown(email), RESOLV_TIMEOUT, 'well-known'),
|
|
819
1097
|
timedFunction(resolveUsingAutoconfig(email), RESOLV_TIMEOUT, 'autoconfig'),
|
|
820
1098
|
timedFunction(resolveUsingMozillaDirectory(email), RESOLV_TIMEOUT, 'mozilla'),
|
|
821
|
-
timedFunction(resolveUsingAutodiscovery(email), RESOLV_TIMEOUT, 'autodiscover')
|
|
1099
|
+
timedFunction(resolveUsingAutodiscovery(email, credentials), RESOLV_TIMEOUT, 'autodiscover')
|
|
822
1100
|
];
|
|
823
1101
|
|
|
1102
|
+
// The first resolver to come back with something wins. A resolver that answers but names
|
|
1103
|
+
// neither a host counts as a loss, not a win: several of them parse a response that turned
|
|
1104
|
+
// out to describe nothing, and resolving on that would beat a slower resolver that had the
|
|
1105
|
+
// real answer.
|
|
824
1106
|
let runCount = 0;
|
|
1107
|
+
let settle = err => {
|
|
1108
|
+
if (++runCount === promises.length) {
|
|
1109
|
+
err = err || new Error('Nothing found');
|
|
1110
|
+
err._is_last = true;
|
|
1111
|
+
reject(err);
|
|
1112
|
+
}
|
|
1113
|
+
};
|
|
1114
|
+
|
|
825
1115
|
for (let prom of promises) {
|
|
826
1116
|
prom.then(res => {
|
|
1117
|
+
if (!hasResolvedHost(res)) {
|
|
1118
|
+
return settle();
|
|
1119
|
+
}
|
|
1120
|
+
|
|
827
1121
|
runCount++;
|
|
828
1122
|
|
|
829
1123
|
let appPassword = getAppPassword(email, exchange, gt);
|
|
@@ -832,19 +1126,26 @@ async function resolver(email, gt) {
|
|
|
832
1126
|
}
|
|
833
1127
|
|
|
834
1128
|
resolve(res);
|
|
835
|
-
}).catch(
|
|
836
|
-
runCount++;
|
|
837
|
-
if (runCount === promises.length) {
|
|
838
|
-
err._is_last = true;
|
|
839
|
-
reject(err);
|
|
840
|
-
}
|
|
841
|
-
});
|
|
1129
|
+
}).catch(settle);
|
|
842
1130
|
}
|
|
843
1131
|
});
|
|
844
1132
|
}
|
|
845
1133
|
|
|
846
|
-
|
|
847
|
-
|
|
1134
|
+
/**
|
|
1135
|
+
* Discovers the IMAP and SMTP settings for an email address.
|
|
1136
|
+
*
|
|
1137
|
+
* @param {string} email - Address to look up
|
|
1138
|
+
* @param {Object} gt - gettext instance, for the app-password hints
|
|
1139
|
+
* @param {Object} [credentials] - `{ user, pass }` for the mailbox. Only used to answer an
|
|
1140
|
+
* autodiscovery endpoint that refuses to respond anonymously, which is how hosted Exchange
|
|
1141
|
+
* behaves; every other resolver is unauthenticated. The hosted setup form is the one caller that
|
|
1142
|
+
* holds a password, so it is the one that passes this. `GET /v1/autoconfig` takes the address in
|
|
1143
|
+
* a query string and can never carry one, which is why an Exchange domain stays unresolvable
|
|
1144
|
+
* there - deliberately, rather than for want of a credential-carrying endpoint.
|
|
1145
|
+
* @returns {Promise<Object>} `{ imap, smtp, _source }`, plus `appPassword` where one applies
|
|
1146
|
+
*/
|
|
1147
|
+
async function autodetectImapSettings(email, gt, credentials) {
|
|
1148
|
+
return await resolver(email, gt, credentials);
|
|
848
1149
|
}
|
|
849
1150
|
|
|
850
1151
|
module.exports.autodetectImapSettings = autodetectImapSettings;
|
|
@@ -853,6 +1154,15 @@ module.exports.autodetectImapSettings = autodetectImapSettings;
|
|
|
853
1154
|
// network side effects, so they can be exercised directly without mocking DNS or HTTP.
|
|
854
1155
|
module.exports.processAutoconfigFile = processAutoconfigFile;
|
|
855
1156
|
module.exports.processAutodiscoverResponse = processAutodiscoverResponse;
|
|
1157
|
+
module.exports.processAutodiscoverSoapResponse = processAutodiscoverSoapResponse;
|
|
1158
|
+
module.exports.buildAutodiscoverRequest = buildAutodiscoverRequest;
|
|
1159
|
+
module.exports.buildAutodiscoverSoapRequest = buildAutodiscoverSoapRequest;
|
|
1160
|
+
module.exports.hasResolvedHost = hasResolvedHost;
|
|
856
1161
|
module.exports.getAppPassword = getAppPassword;
|
|
857
1162
|
module.exports.resolveAppPassword = resolveAppPassword;
|
|
858
1163
|
module.exports.escapeXml = escapeXml;
|
|
1164
|
+
|
|
1165
|
+
// Exposed so the request sequence (anonymous first, credentials only once the server has asked for
|
|
1166
|
+
// them, both endpoints in parallel) can be tested against an injected fetch rather than a live
|
|
1167
|
+
// Exchange server. Production callers pass no fetch and get the egress-policed one.
|
|
1168
|
+
module.exports.runAutodiscovery = runAutodiscovery;
|