emailengine-app 2.79.9 → 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.
Files changed (75) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +49 -0
  3. package/config/default.toml +5 -1
  4. package/data/google-crawlers.json +1 -1
  5. package/encrypt.js +43 -0
  6. package/lib/account/account-state.js +62 -0
  7. package/lib/account.js +34 -2
  8. package/lib/api-routes/account-routes.js +20 -0
  9. package/lib/api-routes/index.js +1 -1
  10. package/lib/api-routes/settings-routes.js +17 -2
  11. package/lib/autodetect-imap-settings.js +349 -47
  12. package/lib/cert-handler.js +62 -0
  13. package/lib/consts.js +50 -6
  14. package/lib/db.js +12 -0
  15. package/lib/egress-fetch.js +21 -9
  16. package/lib/email-client/base-client.js +234 -66
  17. package/lib/email-client/credential-errors.js +118 -0
  18. package/lib/email-client/gmail/gmail-api.js +2 -1
  19. package/lib/email-client/gmail-client.js +70 -64
  20. package/lib/email-client/imap/connection-errors.js +52 -0
  21. package/lib/email-client/imap/listing-diff.js +47 -6
  22. package/lib/email-client/imap/mailbox.js +457 -379
  23. package/lib/email-client/imap/subconnection.js +15 -11
  24. package/lib/email-client/imap/sync-operations.js +46 -59
  25. package/lib/email-client/imap-client.js +136 -95
  26. package/lib/email-client/message-builder.js +11 -11
  27. package/lib/email-client/outlook/graph-api.js +2 -1
  28. package/lib/email-client/outlook-client.js +219 -106
  29. package/lib/imap-proxy-auth.js +58 -3
  30. package/lib/imapproxy/imap-server.js +53 -62
  31. package/lib/lua/h-del-if-equals.lua +39 -0
  32. package/lib/lua/h-set-if-equals.lua +39 -0
  33. package/lib/routes-ui.js +4 -34
  34. package/lib/schemas.js +32 -0
  35. package/lib/security-headers.js +15 -0
  36. package/lib/tls/context.js +376 -0
  37. package/lib/tls/der.js +223 -0
  38. package/lib/tls/provision.js +555 -0
  39. package/lib/tls/self-signed.js +282 -0
  40. package/lib/tls/status.js +431 -0
  41. package/lib/tls/store.js +666 -0
  42. package/lib/tools.js +72 -27
  43. package/lib/ui-routes/account-routes.js +43 -30
  44. package/lib/ui-routes/admin-config-routes.js +22 -1
  45. package/lib/ui-routes/auth-routes.js +16 -1
  46. package/lib/ui-routes/internals-routes.js +3 -5
  47. package/lib/ui-routes/network-config-routes.js +54 -45
  48. package/lib/ui-routes/tls-config-routes.js +581 -0
  49. package/lib/utils/mailbox-path.js +51 -0
  50. package/lib/utils/severity.js +31 -0
  51. package/package.json +4 -4
  52. package/sbom.json +1 -1
  53. package/server.js +16 -0
  54. package/static/css/flyonui.css +1 -1
  55. package/static/css/src/app.tailwind.css +11 -0
  56. package/static/js/app.js +34 -0
  57. package/static/js/public.js +6 -2
  58. package/static/js/ui.js +8 -25
  59. package/static/licenses.html +328 -1257
  60. package/translations/messages.pot +87 -87
  61. package/views/account/login-redirect.hbs +22 -0
  62. package/views/config/imap-proxy.hbs +0 -3
  63. package/views/config/smtp.hbs +0 -3
  64. package/views/config/tls-upload.hbs +81 -0
  65. package/views/config/tls.hbs +492 -0
  66. package/views/partials/side_menu.hbs +1 -0
  67. package/views/partials/tls_security_card.hbs +25 -53
  68. package/views/partials/ui/alert-banner.hbs +3 -2
  69. package/views/partials/ui/badge.hbs +6 -2
  70. package/views/partials/ui/btn.hbs +5 -2
  71. package/workers/api.js +93 -134
  72. package/workers/imap-proxy.js +4 -1
  73. package/workers/smtp.js +51 -44
  74. package/views/partials/tls_security_js.hbs +0 -64
  75. 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
- function parseXml(text) {
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,9 +54,13 @@ function parseXml(text) {
35
54
  throw err;
36
55
  }
37
56
 
38
- return xmlParser.parse(text);
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');
43
66
  const { fetchWithVettedRedirects } = require('./egress-fetch');
@@ -49,6 +72,23 @@ const RESOLV_TIMEOUT = 5 * 1000;
49
72
  // re-render and only produces a cosmetic label, so it must not stall the page for the full RESOLV_TIMEOUT.
50
73
  const APP_PASSWORD_MX_TIMEOUT = 1500;
51
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
+
52
92
  // use a function instead of const to prevent translations before locale is set
53
93
  // The canonical consumer domains are listed alongside the exchange regexes so a plain domain match
54
94
  // (getAppPassword with exchange=false) resolves the big providers without any MX lookup - each listed
@@ -201,22 +241,29 @@ async function processAutoconfigFile(email, domain, text, source) {
201
241
  }
202
242
  let json = parseXml(text);
203
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
+
204
251
  let emailProviders = json && json.clientconfig && Array.isArray(json.clientconfig.emailprovider) ? json.clientconfig.emailprovider : [];
205
252
  let incomingServer = emailProviders
206
253
  .flatMap(entry => (entry && Array.isArray(entry.incomingserver) ? entry.incomingserver : []))
207
254
  .filter(entry => entry && entry.$ && entry.$.type === 'imap')
208
- .shift();
255
+ .find(namesHost);
209
256
  let outgoingServer = emailProviders
210
257
  .flatMap(entry => (entry && Array.isArray(entry.outgoingserver) ? entry.outgoingserver : []))
211
258
  .filter(entry => entry && entry.$ && entry.$.type === 'smtp')
212
- .shift();
259
+ .find(namesHost);
213
260
 
214
261
  let imap = false;
215
262
  let smtp = false;
216
263
 
217
264
  if (incomingServer) {
218
265
  const firstHostname = incomingServer.hostname.filter(entry => entry).shift();
219
- const processedHostname = firstHostname ? firstHostname.replace(/^%EMAILDOMAIN%$/, domain) : undefined;
266
+ const processedHostname = firstHostname.replace(/^%EMAILDOMAIN%$/, domain);
220
267
 
221
268
  imap = {
222
269
  host: processedHostname,
@@ -236,7 +283,7 @@ async function processAutoconfigFile(email, domain, text, source) {
236
283
 
237
284
  if (outgoingServer) {
238
285
  const firstHostname = outgoingServer.hostname.filter(entry => entry).shift();
239
- const processedHostname = firstHostname ? firstHostname.replace(/^%EMAILDOMAIN%$/, domain) : undefined;
286
+ const processedHostname = firstHostname.replace(/^%EMAILDOMAIN%$/, domain);
240
287
 
241
288
  smtp = {
242
289
  host: processedHostname,
@@ -660,6 +707,17 @@ async function resolveUsingMX(email, domain, gt) {
660
707
  };
661
708
 
662
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
+
663
721
  let appPassword = getAppPassword(email, exchange, gt);
664
722
 
665
723
  return Object.assign({}, accountConfig, appPassword ? { appPassword } : {});
@@ -682,52 +740,258 @@ function escapeXml(unsafe) {
682
740
  });
683
741
  }
684
742
 
685
- async function resolveUsingAutodiscovery(email, domain, source) {
686
- domain = domain || email.split('@').pop().trim().toLowerCase();
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);
687
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);
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) {
688
862
  try {
689
- domain = punycode.toASCII(domain);
863
+ const parsed = new URL(url);
864
+ return parsed.protocol === 'https:' ? parsed.origin : false;
690
865
  } catch (err) {
691
- //ignore
866
+ return false;
692
867
  }
868
+ }
693
869
 
694
- let discoveryDomain = `autodiscover.${encodeURIComponent(domain)}`;
870
+ async function resolveAutodiscoveryHost(domain) {
695
871
  try {
696
872
  let srvList = await dns.resolveSrv(`_autodiscover._tcp.${domain}`);
697
873
  let record = srvList.sort((a, b) => a.priority - b.priority).shift();
698
874
  if (record) {
699
- discoveryDomain = `${record.name}${record.port !== 443 ? `:${record.port}` : ''}`;
875
+ return `${record.name}${record.port !== 443 ? `:${record.port}` : ''}`;
700
876
  }
701
877
  } catch (err) {
702
878
  //ignore
703
879
  }
704
880
 
705
- const body = `<?xml version="1.0" encoding="utf-8" ?>
706
- <Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006">
707
- <Request>
708
- <AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema>
709
- <EMailAddress>${escapeXml(email)}</EMailAddress>
710
- </Request>
711
- </Autodiscover>`;
881
+ return `autodiscover.${encodeURIComponent(domain)}`;
882
+ }
712
883
 
713
- let discoveryUrl = `https://${discoveryDomain}/autodiscover/autodiscover.xml`;
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
+ });
714
913
 
715
- let res = await fetchAutodiscoveryResource(discoveryUrl, {
716
- method: 'post',
717
- headers: { 'Content-type': 'application/xml' },
718
- body
719
- });
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
+ }
720
925
 
721
- if (!res.ok) {
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') || '')) {
722
933
  throw new Error('Invalid response');
723
934
  }
724
935
 
725
- let text = await res.text();
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();
726
982
 
727
- return await processAutodiscoverResponse(text, source);
983
+ try {
984
+ domain = punycode.toASCII(domain);
985
+ } catch (err) {
986
+ //ignore
987
+ }
988
+
989
+ let discoveryDomain = await resolveAutodiscoveryHost(domain);
990
+
991
+ return await runAutodiscovery(`https://${discoveryDomain}`, email, credentials);
728
992
  }
729
993
 
730
- async function processAutodiscoverResponse(text, source) {
994
+ function processAutodiscoverResponse(text, source) {
731
995
  let json = parseXml(text);
732
996
 
733
997
  let imap = false;
@@ -758,11 +1022,13 @@ async function processAutodiscoverResponse(text, source) {
758
1022
  }
759
1023
 
760
1024
  let getStructureFromObject = entry => {
761
- // imap entry
762
- let res = {};
763
- if (entry.server && typeof entry.server === 'string') {
764
- res.host = entry.server;
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;
765
1029
  }
1030
+
1031
+ let res = { host: entry.server };
766
1032
  if (entry.port && (typeof entry.port === 'string' || (typeof entry.port === 'number' && !isNaN(entry.port)))) {
767
1033
  res.port = Number(entry.port);
768
1034
  }
@@ -775,13 +1041,17 @@ async function processAutodiscoverResponse(text, source) {
775
1041
  return res;
776
1042
  };
777
1043
 
778
- if (/^IMAP$/i.test(entry.type)) {
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) {
779
1049
  // imap entry
780
1050
  imap = getStructureFromObject(entry);
781
1051
  }
782
1052
 
783
- if (/^SMTP$/i.test(entry.type)) {
784
- // imap entry
1053
+ if (/^SMTP$/i.test(entry.type) && !smtp) {
1054
+ // smtp entry
785
1055
  smtp = getStructureFromObject(entry);
786
1056
  }
787
1057
  });
@@ -807,7 +1077,7 @@ async function timedFunction(prom, timeout, source) {
807
1077
  });
808
1078
  }
809
1079
 
810
- async function resolver(email, gt) {
1080
+ async function resolver(email, gt, credentials) {
811
1081
  let exchange;
812
1082
  try {
813
1083
  // prefer MX based resolver
@@ -826,12 +1096,28 @@ async function resolver(email, gt) {
826
1096
  timedFunction(resolveUsingWellKnown(email), RESOLV_TIMEOUT, 'well-known'),
827
1097
  timedFunction(resolveUsingAutoconfig(email), RESOLV_TIMEOUT, 'autoconfig'),
828
1098
  timedFunction(resolveUsingMozillaDirectory(email), RESOLV_TIMEOUT, 'mozilla'),
829
- timedFunction(resolveUsingAutodiscovery(email), RESOLV_TIMEOUT, 'autodiscover')
1099
+ timedFunction(resolveUsingAutodiscovery(email, credentials), RESOLV_TIMEOUT, 'autodiscover')
830
1100
  ];
831
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.
832
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
+
833
1115
  for (let prom of promises) {
834
1116
  prom.then(res => {
1117
+ if (!hasResolvedHost(res)) {
1118
+ return settle();
1119
+ }
1120
+
835
1121
  runCount++;
836
1122
 
837
1123
  let appPassword = getAppPassword(email, exchange, gt);
@@ -840,19 +1126,26 @@ async function resolver(email, gt) {
840
1126
  }
841
1127
 
842
1128
  resolve(res);
843
- }).catch(err => {
844
- runCount++;
845
- if (runCount === promises.length) {
846
- err._is_last = true;
847
- reject(err);
848
- }
849
- });
1129
+ }).catch(settle);
850
1130
  }
851
1131
  });
852
1132
  }
853
1133
 
854
- async function autodetectImapSettings(email, gt) {
855
- return await resolver(email, gt);
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);
856
1149
  }
857
1150
 
858
1151
  module.exports.autodetectImapSettings = autodetectImapSettings;
@@ -861,6 +1154,15 @@ module.exports.autodetectImapSettings = autodetectImapSettings;
861
1154
  // network side effects, so they can be exercised directly without mocking DNS or HTTP.
862
1155
  module.exports.processAutoconfigFile = processAutoconfigFile;
863
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;
864
1161
  module.exports.getAppPassword = getAppPassword;
865
1162
  module.exports.resolveAppPassword = resolveAppPassword;
866
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;
@@ -0,0 +1,62 @@
1
+ 'use strict';
2
+
3
+ const { Certs } = require('@postalsys/certs');
4
+
5
+ const { redis } = require('./db');
6
+ const getSecret = require('./get-secret');
7
+ const { encrypt, decrypt } = require('./encrypt');
8
+ const { httpAgent } = require('./tools');
9
+ const { REDIS_PREFIX, ACME_ENVIRONMENT, ACME_DIRECTORY_URL, ACME_OVERRIDE_PARTIAL } = require('./consts');
10
+
11
+ /**
12
+ * Builds the Let's Encrypt certificate handler.
13
+ *
14
+ * Three workers need one: the API worker, which is the only one that provisions, and the SMTP
15
+ * server and the IMAP proxy, which read what it stored. Every argument is the same in all three, so
16
+ * this exists rather than the same twenty lines written out three times. That is not only about
17
+ * repetition: `environment` and `directoryUrl` belong inside the `acme` block, and two of the three
18
+ * copies used to pass `environment` at the top level, where the constructor never reads it. Nothing
19
+ * failed, because those two never provision, and nothing would have until one of them did.
20
+ *
21
+ * @param {Object} logger worker logger; the handler logs under `sub: 'acme'`
22
+ * @returns {Object} a `Certs` instance
23
+ */
24
+ function createCertHandler(logger) {
25
+ if (ACME_OVERRIDE_PARTIAL) {
26
+ // Nothing here can tell which of the two was meant - an operator rehearsing against staging
27
+ // and one running a private CA under the default account name are the same instruction from
28
+ // here - so it is reported rather than repaired
29
+ logger.warn({
30
+ msg: 'Only one half of the ACME override is set, certificate orders will most likely be rejected',
31
+ environment: ACME_ENVIRONMENT,
32
+ directoryUrl: ACME_DIRECTORY_URL
33
+ });
34
+ }
35
+
36
+ return new Certs({
37
+ redis,
38
+ namespace: `${REDIS_PREFIX}`,
39
+
40
+ acme: {
41
+ environment: ACME_ENVIRONMENT,
42
+ directoryUrl: ACME_DIRECTORY_URL
43
+ },
44
+
45
+ // long-lived client, see LiveDispatcher in lib/tools.js
46
+ dispatcher: httpAgent.live,
47
+
48
+ logger: logger.child({ sub: 'acme' }),
49
+
50
+ encryptFn: async value => {
51
+ const encryptSecret = await getSecret();
52
+ return encrypt(value, encryptSecret);
53
+ },
54
+
55
+ decryptFn: async value => {
56
+ const encryptSecret = await getSecret();
57
+ return decrypt(value, encryptSecret);
58
+ }
59
+ });
60
+ }
61
+
62
+ module.exports = { createCertHandler };