emailengine-app 2.81.2 → 2.82.1

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 (226) hide show
  1. package/.ncurc.js +33 -10
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +71 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/Dockerfile +2 -0
  6. package/bin/emailengine.js +105 -25
  7. package/config/default.toml +0 -5
  8. package/config/test.toml +0 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +70 -42
  11. package/getswagger.sh +0 -4
  12. package/lib/account/account-state.js +2 -110
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +138 -1
  15. package/lib/account.js +289 -869
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-binding.js +58 -0
  19. package/lib/api-routes/account-routes.js +65 -37
  20. package/lib/api-routes/behavior-notes.js +4 -0
  21. package/lib/api-routes/blocklist-routes.js +2 -2
  22. package/lib/api-routes/bull-board-routes.js +1 -6
  23. package/lib/api-routes/export-routes.js +2 -22
  24. package/lib/api-routes/gateway-routes.js +15 -16
  25. package/lib/api-routes/index.js +1 -13
  26. package/lib/api-routes/mailbox-routes.js +2 -7
  27. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  28. package/lib/api-routes/mcp-routes.js +7 -7
  29. package/lib/api-routes/message-routes.js +50 -238
  30. package/lib/api-routes/mint-bounds.js +110 -0
  31. package/lib/api-routes/oauth2-app-routes.js +23 -32
  32. package/lib/api-routes/operation-impact.js +1 -1
  33. package/lib/api-routes/outbox-routes.js +3 -3
  34. package/lib/api-routes/permission-map.js +1 -7
  35. package/lib/api-routes/route-helpers.js +11 -5
  36. package/lib/api-routes/settings-routes.js +20 -21
  37. package/lib/api-routes/stats-routes.js +1 -1
  38. package/lib/api-routes/submit-routes.js +17 -18
  39. package/lib/api-routes/template-routes.js +4 -9
  40. package/lib/api-routes/token-routes.js +28 -6
  41. package/lib/api-token-scheme.js +71 -0
  42. package/lib/arf-detect.js +33 -6
  43. package/lib/auth-token.js +44 -24
  44. package/lib/autodetect-imap-settings.js +305 -123
  45. package/lib/bounce-detect.js +25 -16
  46. package/lib/calendar-event.js +78 -0
  47. package/lib/consts.js +54 -5
  48. package/lib/create-imap-client.js +24 -0
  49. package/lib/db.js +77 -30
  50. package/lib/delivery-error.js +70 -2
  51. package/lib/egress-fetch.js +54 -3
  52. package/lib/egress-filter.js +11 -0
  53. package/lib/email-client/api-retry.js +147 -0
  54. package/lib/email-client/base-client.js +383 -536
  55. package/lib/email-client/credential-errors.js +21 -5
  56. package/lib/email-client/gmail/gmail-api.js +38 -125
  57. package/lib/email-client/gmail/send-request.js +1 -1
  58. package/lib/email-client/gmail-client.js +77 -51
  59. package/lib/email-client/imap/mailbox.js +158 -324
  60. package/lib/email-client/imap/stale-view.js +109 -0
  61. package/lib/email-client/imap/subconnection.js +46 -9
  62. package/lib/email-client/imap/sync-operations.js +5 -37
  63. package/lib/email-client/imap-client.js +190 -65
  64. package/lib/email-client/message-builder.js +50 -25
  65. package/lib/email-client/notification-handler.js +5 -219
  66. package/lib/email-client/outlook/graph-api.js +147 -126
  67. package/lib/email-client/outlook/send-request.js +10 -4
  68. package/lib/email-client/outlook-client.js +389 -463
  69. package/lib/email-client/smtp-pool-manager.js +3 -2
  70. package/lib/encrypt.js +184 -19
  71. package/lib/enum-descriptions.js +6 -3
  72. package/lib/export.js +141 -41
  73. package/lib/gateway.js +25 -6
  74. package/lib/get-raw-email.js +26 -44
  75. package/lib/get-secret.js +1 -21
  76. package/lib/handlebars-helpers.js +31 -10
  77. package/lib/imap-proxy-auth.js +13 -29
  78. package/lib/imapproxy/imap-core/README.md +1 -0
  79. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  80. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  81. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  82. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  83. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  84. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  85. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  86. package/lib/imapproxy/imap-server.js +17 -177
  87. package/lib/imapproxy/proxy-handoff.js +235 -0
  88. package/lib/imapproxy/response-error.js +33 -0
  89. package/lib/imapproxy/upstream-client.js +2 -2
  90. package/lib/license-beacon.js +3 -9
  91. package/lib/llm-pre-process.js +182 -43
  92. package/lib/logger.js +1 -1
  93. package/lib/lua/ee-export-queue-add.lua +39 -0
  94. package/lib/lua/ee-get-idempotency.lua +15 -3
  95. package/lib/lua/ee-release-attempts.lua +23 -0
  96. package/lib/lua/ee-reserve-attempts.lua +42 -0
  97. package/lib/lua/h-set-bigger.lua +12 -2
  98. package/lib/lua/s-list-accounts.lua +6 -3
  99. package/lib/mcp/index.js +1 -2
  100. package/lib/mcp/listen.js +221 -18
  101. package/lib/mcp/oauth.js +44 -5
  102. package/lib/mcp/resources.js +8 -2
  103. package/lib/mcp/tools.js +108 -36
  104. package/lib/message-port-stream.js +64 -6
  105. package/lib/oauth/external-account-signer.js +16 -13
  106. package/lib/oauth/gmail.js +64 -32
  107. package/lib/oauth/mail-ru.js +24 -17
  108. package/lib/oauth/outlook.js +53 -40
  109. package/lib/oauth/pubsub/google.js +38 -2
  110. package/lib/oauth/scope-checker.js +39 -8
  111. package/lib/oauth/scope-list.js +55 -0
  112. package/lib/oauth/token-fetch.js +47 -0
  113. package/lib/oauth/verify-app.js +2 -2
  114. package/lib/oauth2-apps.js +154 -90
  115. package/lib/openapi/build-document.js +1 -1
  116. package/lib/openapi/joi-schema.js +78 -9
  117. package/lib/outbox.js +2 -7
  118. package/lib/parse-message.js +21 -0
  119. package/lib/payload-examples-webhooks.json +4 -7
  120. package/lib/pbkdf2-phc.js +101 -0
  121. package/lib/privileged-settings.js +0 -14
  122. package/lib/queue-retention.js +4 -2
  123. package/lib/rate-limit.js +54 -15
  124. package/lib/read-env-value.js +33 -2
  125. package/lib/redis-scan-delete.js +56 -29
  126. package/lib/redis-url.js +3 -1
  127. package/lib/respawn-backoff.js +5 -4
  128. package/lib/response-stream.js +25 -4
  129. package/lib/rewrite-text-nodes.js +27 -40
  130. package/lib/routes-ui.js +0 -5
  131. package/lib/schemas.js +180 -253
  132. package/lib/sentry.js +21 -5
  133. package/lib/settings.js +58 -59
  134. package/lib/smtp-auth.js +6 -2
  135. package/lib/smtp-message-processor.js +28 -7
  136. package/lib/sso.js +7 -3
  137. package/lib/stream-encrypt.js +14 -13
  138. package/lib/swagger-options.js +3 -1
  139. package/lib/tls/provision.js +69 -3
  140. package/lib/tls/store.js +14 -1
  141. package/lib/token-audit-log.js +3 -2
  142. package/lib/tools.js +114 -53
  143. package/lib/totp.js +16 -1
  144. package/lib/ui-routes/account-routes.js +67 -70
  145. package/lib/ui-routes/admin-config-routes.js +111 -134
  146. package/lib/ui-routes/admin-entities-routes.js +101 -191
  147. package/lib/ui-routes/ai-options.js +104 -0
  148. package/lib/ui-routes/auth-routes.js +98 -18
  149. package/lib/ui-routes/export-routes.js +3 -23
  150. package/lib/ui-routes/internals-routes.js +12 -9
  151. package/lib/ui-routes/network-config-routes.js +8 -18
  152. package/lib/ui-routes/oauth-config-routes.js +83 -228
  153. package/lib/ui-routes/route-helpers.js +63 -67
  154. package/lib/ui-routes/special-use-paths.js +33 -0
  155. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  156. package/lib/utils/decode-headers.js +32 -5
  157. package/lib/utils/header-map.js +62 -1
  158. package/lib/utils/network.js +11 -17
  159. package/lib/web-safe-html.js +77 -4
  160. package/lib/webhook-request.js +9 -1
  161. package/lib/webhook-routing.js +27 -1
  162. package/lib/webhooks.js +120 -43
  163. package/lib/worker-rpc-error.js +43 -2
  164. package/list-generate.js +13 -2
  165. package/package.json +38 -46
  166. package/sbom.json +1 -1
  167. package/scripts/refresh-test-tokens.js +42 -14
  168. package/server.js +338 -292
  169. package/setup-production.sh +16 -7
  170. package/static/css/flyonui.css +1 -1
  171. package/static/css/src/app.tailwind.css +7 -8
  172. package/static/js/ee-client.js +145 -70
  173. package/static/js/ui.js +350 -154
  174. package/static/licenses.html +349 -1740
  175. package/translations/messages.pot +129 -111
  176. package/views/account-workspace-error.hbs +30 -0
  177. package/views/accounts/account.hbs +9 -4
  178. package/views/accounts/browse.hbs +10 -4
  179. package/views/accounts/edit.hbs +11 -2
  180. package/views/config/ai.hbs +49 -41
  181. package/views/config/oauth/app.hbs +2 -1
  182. package/views/dashboard.hbs +18 -16
  183. package/views/internals/index.hbs +1 -1
  184. package/views/layout/app.hbs +0 -22
  185. package/views/layout/login.hbs +2 -1
  186. package/views/partials/filter_editor_js.hbs +4 -3
  187. package/views/partials/gmail_api_scopes.hbs +16 -0
  188. package/views/partials/oauth_form.hbs +67 -94
  189. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  190. package/views/partials/scope_info.hbs +14 -23
  191. package/views/partials/side_menu.hbs +0 -4
  192. package/views/partials/ui/account-picker.hbs +6 -32
  193. package/views/partials/ui/model-picker.hbs +31 -0
  194. package/views/partials/ui/pagination.hbs +6 -1
  195. package/views/partials/ui/picker.hbs +47 -0
  196. package/views/unsubscribe.hbs +1 -1
  197. package/workers/api.js +82 -47
  198. package/workers/export.js +55 -60
  199. package/workers/imap.js +132 -49
  200. package/workers/submit.js +5 -6
  201. package/workers/webhooks.js +46 -27
  202. package/.githooks/pre-commit +0 -80
  203. package/.github/CODE_OF_CONDUCT.md +0 -76
  204. package/.github/contributing.md +0 -17
  205. package/.github/dependabot.yml +0 -22
  206. package/.github/docker-smoke-test.sh +0 -61
  207. package/.github/workflows/deploy.yml +0 -215
  208. package/.github/workflows/e2e.yml +0 -55
  209. package/.github/workflows/release.yaml +0 -217
  210. package/.github/workflows/test.yml +0 -307
  211. package/lib/api-routes/chat-routes.js +0 -535
  212. package/lib/document-store.js +0 -75
  213. package/lib/es.js +0 -757
  214. package/lib/generate-text-preview.js +0 -61
  215. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  216. package/lib/pre-process.js +0 -196
  217. package/lib/threads.js +0 -155
  218. package/lib/ui-routes/document-store-routes.js +0 -806
  219. package/playwright.config.js +0 -47
  220. package/views/config/document-store/chat.hbs +0 -286
  221. package/views/config/document-store/index.hbs +0 -146
  222. package/views/config/document-store/mappings/index.hbs +0 -108
  223. package/views/config/document-store/mappings/new.hbs +0 -68
  224. package/views/config/document-store/pre-processing/index.hbs +0 -103
  225. package/views/partials/document_store_header.hbs +0 -30
  226. package/workers/documents.js +0 -1128
@@ -63,15 +63,24 @@ const parseSoapXml = text => parseWith(soapXmlParser, text);
63
63
 
64
64
  const { fetch: fetchCmd } = require('undici');
65
65
  const { httpAgent } = require('./tools');
66
- const { fetchWithVettedRedirects } = require('./egress-fetch');
66
+ const { fetchWithVettedRedirects, readBodyCapped } = require('./egress-fetch');
67
67
  const { validateWebhookTarget } = require('./webhook-egress');
68
68
 
69
69
  const RESOLV_TIMEOUT = 5 * 1000;
70
70
 
71
+ // Largest autodiscovery document read. A real autoconfig file or autodiscovery response is a few
72
+ // kilobytes; the host serving it is named by the address domain, so its size is not ours to trust.
73
+ const MAX_AUTODISCOVERY_BODY = 256 * 1024;
74
+
71
75
  // Shorter cap for the app-password hint MX lookup: it runs on the hosted form's validation-error
72
76
  // re-render and only produces a cosmetic label, so it must not stall the page for the full RESOLV_TIMEOUT.
73
77
  const APP_PASSWORD_MX_TIMEOUT = 1500;
74
78
 
79
+ // How many times an autodiscovery response may name another endpoint instead of answering. Each hop
80
+ // is a request on the critical path of a resolver that shares a five second budget, and a loop
81
+ // between two endpoints that redirect to each other would otherwise spend all of it.
82
+ const MAX_AUTODISCOVER_REDIRECTS = 2;
83
+
75
84
  /**
76
85
  * Does a resolver result actually name a server? Asked by every branch that has to decide whether
77
86
  * a lookup answered, so they all decide it the same way.
@@ -185,8 +194,8 @@ function getAppPassword(email, exchange, gt) {
185
194
 
186
195
  // Resolve the lowest-priority MX exchange for a domain (lowercased). Throws if the domain has no MX
187
196
  // record (callers decide whether that is fatal or just "no exchange-based match").
188
- async function resolveExchange(domain) {
189
- let srvList = await dns.resolveMx(domain);
197
+ async function resolveExchange(domain, resolverDns) {
198
+ let srvList = await (resolverDns || dns).resolveMx(domain);
190
199
  if (!srvList || !srvList.length) {
191
200
  throw new Error('No MX record found for domain');
192
201
  }
@@ -247,6 +256,9 @@ async function processAutoconfigFile(email, domain, text, source) {
247
256
  // So the first element that names a host wins, not simply the first of its type - taking the
248
257
  // first let a hostless one discard a usable sibling further down.
249
258
  const namesHost = entry => entry && Array.isArray(entry.hostname) && entry.hostname.some(value => value);
259
+ // <port> and <socketType> are optional as far as a hostile document is concerned: a missing one
260
+ // used to throw on `.filter` and discard the whole file, including a sibling entry that was fine
261
+ const firstValue = list => (Array.isArray(list) ? list.filter(entry => entry).shift() : undefined);
250
262
 
251
263
  let emailProviders = json && json.clientconfig && Array.isArray(json.clientconfig.emailprovider) ? json.clientconfig.emailprovider : [];
252
264
  let incomingServer = emailProviders
@@ -265,11 +277,8 @@ async function processAutoconfigFile(email, domain, text, source) {
265
277
  const firstHostname = incomingServer.hostname.filter(entry => entry).shift();
266
278
  const processedHostname = firstHostname.replace(/^%EMAILDOMAIN%$/, domain);
267
279
 
268
- imap = {
269
- host: processedHostname,
270
- port: Number(incomingServer.port.filter(entry => entry).shift()),
271
- secure: incomingServer.sockettype.filter(entry => entry).shift() === 'SSL'
272
- };
280
+ const port = Number(firstValue(incomingServer.port));
281
+ imap = Object.assign({ host: processedHostname }, port ? { port } : {}, { secure: firstValue(incomingServer.sockettype) === 'SSL' });
273
282
 
274
283
  if (Array.isArray(incomingServer.username) && incomingServer.username.length) {
275
284
  imap.auth = {
@@ -285,11 +294,8 @@ async function processAutoconfigFile(email, domain, text, source) {
285
294
  const firstHostname = outgoingServer.hostname.filter(entry => entry).shift();
286
295
  const processedHostname = firstHostname.replace(/^%EMAILDOMAIN%$/, domain);
287
296
 
288
- smtp = {
289
- host: processedHostname,
290
- port: Number(outgoingServer.port.filter(entry => entry).shift()),
291
- secure: outgoingServer.sockettype.filter(entry => entry).shift() === 'SSL'
292
- };
297
+ const port = Number(firstValue(outgoingServer.port));
298
+ smtp = Object.assign({ host: processedHostname }, port ? { port } : {}, { secure: firstValue(outgoingServer.sockettype) === 'SSL' });
293
299
 
294
300
  if (Array.isArray(outgoingServer.username) && outgoingServer.username.length) {
295
301
  smtp.auth = {
@@ -327,27 +333,43 @@ async function fetchAutodiscoveryResource(url, opts) {
327
333
  );
328
334
  }
329
335
 
330
- async function resolveUsingMozillaDirectory(email, domain, source) {
331
- domain = domain || email.split('@').pop().trim().toLowerCase();
332
-
333
- try {
334
- domain = punycode.toASCII(domain);
335
- } catch (err) {
336
- //ignore
336
+ /**
337
+ * Fills in the I/O a resolver uses. Every resolver takes a context rather than reaching for DNS and
338
+ * fetch directly, so the orchestration (the race, the time budget, the body cap) can be tested
339
+ * against stand-ins, and so the abort signal of the resolver's time budget reaches every request.
340
+ *
341
+ * Applied once, where a context enters: resolver() builds one per time budget, and
342
+ * runAutodiscovery() accepts a partial one from the tests that drive it directly. The resolvers
343
+ * themselves take the context as given.
344
+ *
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
347
+ */
348
+ function withIo(ctx) {
349
+ const io = { dns, fetchResource: fetchAutodiscoveryResource };
350
+ for (const key of Object.keys(ctx || {})) {
351
+ // An explicit undefined keeps the production default; only a stand-in actually given wins
352
+ if (ctx[key] !== undefined) {
353
+ io[key] = ctx[key];
354
+ }
337
355
  }
356
+ return io;
357
+ }
358
+
359
+ // Reads a response body within the size budget; see MAX_AUTODISCOVERY_BODY
360
+ const readDocument = res => readBodyCapped(res, MAX_AUTODISCOVERY_BODY);
338
361
 
339
- let res = await fetchAutodiscoveryResource(`https://autoconfig.thunderbird.net/v1.1/${domain}`);
362
+ async function fetchAutoconfigDocument(url, ctx) {
363
+ let res = await ctx.fetchResource(url, { signal: ctx.signal });
340
364
 
341
365
  if (!res.ok) {
342
366
  throw new Error('Invalid response');
343
367
  }
344
368
 
345
- let text = await res.text();
346
-
347
- return await processAutoconfigFile(email, domain, text, source || 'mozilla');
369
+ return await readDocument(res);
348
370
  }
349
371
 
350
- async function resolveUsingAutoconfig(email, domain, source) {
372
+ async function resolveUsingMozillaDirectory(email, ctx, domain, source) {
351
373
  domain = domain || email.split('@').pop().trim().toLowerCase();
352
374
 
353
375
  try {
@@ -356,20 +378,12 @@ async function resolveUsingAutoconfig(email, domain, source) {
356
378
  //ignore
357
379
  }
358
380
 
359
- let res = await fetchAutodiscoveryResource(
360
- `https://autoconfig.${encodeURIComponent(domain)}/mail/config-v1.1.xml?emailaddress=${encodeURIComponent(email)}`
361
- );
381
+ let text = await fetchAutoconfigDocument(`https://autoconfig.thunderbird.net/v1.1/${domain}`, ctx);
362
382
 
363
- if (!res.ok) {
364
- throw new Error('Invalid response');
365
- }
366
-
367
- let text = await res.text();
368
-
369
- return await processAutoconfigFile(email, domain, text, source || 'autoconfig');
383
+ return await processAutoconfigFile(email, domain, text, source || 'mozilla');
370
384
  }
371
385
 
372
- async function resolveUsingWellKnown(email, domain, source) {
386
+ async function resolveUsingAutoconfig(email, ctx, domain, source) {
373
387
  domain = domain || email.split('@').pop().trim().toLowerCase();
374
388
 
375
389
  try {
@@ -378,18 +392,15 @@ async function resolveUsingWellKnown(email, domain, source) {
378
392
  //ignore
379
393
  }
380
394
 
381
- let res = await fetchAutodiscoveryResource(`http://${encodeURIComponent(domain)}/.well-known/autoconfig/mail/config-v1.1.xml`);
382
-
383
- if (!res.ok) {
384
- throw new Error('Invalid response');
385
- }
386
-
387
- let text = await res.text();
395
+ let text = await fetchAutoconfigDocument(
396
+ `https://autoconfig.${encodeURIComponent(domain)}/mail/config-v1.1.xml?emailaddress=${encodeURIComponent(email)}`,
397
+ ctx
398
+ );
388
399
 
389
- return await processAutoconfigFile(email, domain, text, source || 'well-known');
400
+ return await processAutoconfigFile(email, domain, text, source || 'autoconfig');
390
401
  }
391
402
 
392
- async function resolveUsingSRV(email, domain, source) {
403
+ async function resolveUsingWellKnown(email, ctx, domain, source) {
393
404
  domain = domain || email.split('@').pop().trim().toLowerCase();
394
405
 
395
406
  try {
@@ -398,71 +409,61 @@ async function resolveUsingSRV(email, domain, source) {
398
409
  //ignore
399
410
  }
400
411
 
401
- let imap = false;
402
- let smtp = false;
412
+ let text = await fetchAutoconfigDocument(`http://${encodeURIComponent(domain)}/.well-known/autoconfig/mail/config-v1.1.xml`, ctx);
403
413
 
414
+ return await processAutoconfigFile(email, domain, text, source || 'well-known');
415
+ }
416
+
417
+ // First record of an SRV lookup by priority, or null when the name has none. A missing record is
418
+ // an ordinary answer here (most domains publish none), so it must not end the whole resolver.
419
+ async function lookupSrv(ctx, name) {
404
420
  try {
405
- let srvList = await dns.resolveSrv(`_imaps._tcp.${domain}`);
406
- let record = srvList.sort((a, b) => a.priority - b.priority).shift();
407
- if (record) {
408
- imap = {
409
- host: record.name,
410
- port: record.port,
411
- secure: true
412
- };
413
- }
421
+ let srvList = await ctx.dns.resolveSrv(name);
422
+ return (srvList || []).sort((a, b) => a.priority - b.priority).shift() || null;
414
423
  } catch (err) {
415
- //ignore
424
+ return null;
416
425
  }
426
+ }
417
427
 
418
- if (!imap) {
419
- try {
420
- let srvList = await dns.resolveSrv(`_imap._tcp.${domain}`);
421
- let record = srvList.sort((a, b) => a.priority - b.priority).shift();
422
- if (record) {
423
- imap = {
424
- host: record.name,
425
- port: record.port,
426
- secure: false
427
- };
428
- }
429
- } catch (err) {
430
- //ignore
431
- }
432
- }
428
+ async function resolveUsingSRV(email, ctx, domain, source) {
429
+ domain = domain || email.split('@').pop().trim().toLowerCase();
433
430
 
434
431
  try {
435
- let srvList = await dns.resolveSrv(`_submissions._tcp.${domain}`);
436
- let record = srvList.sort((a, b) => a.priority - b.priority).shift();
437
- if (record) {
438
- smtp = {
439
- host: record.name,
440
- port: record.port,
441
- secure: true
442
- };
443
- }
432
+ domain = punycode.toASCII(domain);
444
433
  } catch (err) {
445
434
  //ignore
446
435
  }
447
436
 
448
- if (!smtp) {
449
- let srvList = await dns.resolveSrv(`_submission._tcp.${domain}`);
450
- let record = srvList.sort((a, b) => a.priority - b.priority).shift();
437
+ const lookupImap = async () => {
438
+ let record = await lookupSrv(ctx, `_imaps._tcp.${domain}`);
451
439
  if (record) {
452
- smtp = {
453
- host: record.name,
454
- port: record.port,
455
- // Some providers invalidly use _submission instead of _submissions
456
- secure: record.port === 465
457
- };
440
+ return { host: record.name, port: record.port, secure: true };
458
441
  }
459
- }
442
+ record = await lookupSrv(ctx, `_imap._tcp.${domain}`);
443
+ return record ? { host: record.name, port: record.port, secure: false } : false;
444
+ };
445
+
446
+ const lookupSmtp = async () => {
447
+ let record = await lookupSrv(ctx, `_submissions._tcp.${domain}`);
448
+ if (record) {
449
+ return { host: record.name, port: record.port, secure: true };
450
+ }
451
+ // Used to be the one lookup left unguarded, so a domain with IMAP records and no
452
+ // _submission one threw away the IMAP answer it had already found
453
+ record = await lookupSrv(ctx, `_submission._tcp.${domain}`);
454
+ // Some providers invalidly use _submission instead of _submissions
455
+ return record ? { host: record.name, port: record.port, secure: record.port === 465 } : false;
456
+ };
457
+
458
+ // The two chains are independent, and this resolver runs against a time budget it shares
459
+ // with four others, so they are not paid for one after the other
460
+ const [imap, smtp] = await Promise.all([lookupImap(), lookupSmtp()]);
460
461
 
461
462
  return { smtp, imap, _source: source || 'srv' };
462
463
  }
463
464
 
464
- async function resolveUsingMX(email, domain, gt) {
465
- domain = domain || email.split('@').pop().trim().toLowerCase();
465
+ async function resolveUsingMX(email, ctx, gt) {
466
+ let domain = email.split('@').pop().trim().toLowerCase();
466
467
 
467
468
  try {
468
469
  domain = punycode.toASCII(domain);
@@ -471,16 +472,16 @@ async function resolveUsingMX(email, domain, gt) {
471
472
  }
472
473
 
473
474
  // do not catch potential error as there's nothing to do if we do not find the MX record
474
- let exchange = await resolveExchange(domain);
475
+ let exchange = await resolveExchange(domain, ctx.dns);
475
476
 
476
477
  let resolveConfig = async () => {
477
478
  // look for some well known MX servers
478
479
  if (/\bl\.google\.com$/i.test(exchange)) {
479
- return await resolveUsingSRV(email, 'gmail.com', 'mx');
480
+ return await resolveUsingSRV(email, ctx, 'gmail.com', 'mx');
480
481
  }
481
482
 
482
483
  if (/\bmx\.yandex\.net$/i.test(exchange)) {
483
- return await resolveUsingAutoconfig(email, 'yandex.ru', 'mx');
484
+ return await resolveUsingAutoconfig(email, ctx, 'yandex.ru', 'mx');
484
485
  }
485
486
 
486
487
  if (/^mx\d*\.zone\.eu$/i.test(exchange)) {
@@ -518,7 +519,7 @@ async function resolveUsingMX(email, domain, gt) {
518
519
  }
519
520
 
520
521
  if (/\bzonemx\.eu$/i.test(exchange)) {
521
- return await resolveUsingAutoconfig(email, 'zone.ee', 'mx');
522
+ return await resolveUsingAutoconfig(email, ctx, 'zone.ee', 'mx');
522
523
  }
523
524
 
524
525
  // AWS WorkMail
@@ -858,6 +859,54 @@ function processAutodiscoverSoapResponse(text) {
858
859
  // lead to http (the anonymous lookup carries nothing worth protecting), so the host that ends up
859
860
  // issuing the challenge is not necessarily on https, and Basic over cleartext would hand the
860
861
  // mailbox password to anyone on the path.
862
+ /**
863
+ * The endpoint a POX response names instead of answering.
864
+ *
865
+ * Microsoft's sequence lets a server say "ask over there" rather than return settings:
866
+ * `<Action>redirectUrl</Action>` with a `<RedirectUrl>` names another endpoint for the same mailbox.
867
+ * processAutodiscoverResponse() reads `Account > Protocol` only, so such a response parsed as naming
868
+ * no server and the lookup stopped there.
869
+ *
870
+ * `<RedirectAddr>` is deliberately NOT followed. It names a different ADDRESS, so following it would
871
+ * restart the lookup for a mailbox the caller did not ask about. A response carrying only a
872
+ * RedirectAddr stays a loss.
873
+ *
874
+ * The endpoint this does name is asked anonymously - see the call site in runAutodiscovery().
875
+ *
876
+ * @param {String} text - The POX response body
877
+ * @returns {String|false} The URL the response names, or false
878
+ */
879
+ function poxRedirectUrl(text) {
880
+ let json;
881
+ try {
882
+ // Only reached after processAutodiscoverResponse() has already parsed the same body, so a
883
+ // document that does not parse cannot get here in production - guarded so the helper is still
884
+ // safe called on its own
885
+ json = parseXml(text);
886
+ } catch (err) {
887
+ return false;
888
+ }
889
+ const responses = json && json.autodiscover && Array.isArray(json.autodiscover.response) ? json.autodiscover.response : [];
890
+
891
+ for (const responseRow of responses) {
892
+ if (!responseRow || !Array.isArray(responseRow.account)) {
893
+ continue;
894
+ }
895
+ for (const accountRow of responseRow.account) {
896
+ const action = accountRow && Array.isArray(accountRow.action) ? accountRow.action[0] : null;
897
+ const redirectUrl = accountRow && Array.isArray(accountRow.redirecturl) ? accountRow.redirecturl[0] : null;
898
+
899
+ // The action is what makes it a redirect; a document that carries a stray RedirectUrl
900
+ // without saying so is not one
901
+ if (typeof action === 'string' && /^redirecturl$/i.test(action.trim()) && typeof redirectUrl === 'string' && redirectUrl.trim()) {
902
+ return redirectUrl.trim();
903
+ }
904
+ }
905
+ }
906
+
907
+ return false;
908
+ }
909
+
861
910
  function secureOriginOf(url) {
862
911
  try {
863
912
  const parsed = new URL(url);
@@ -867,20 +916,53 @@ function secureOriginOf(url) {
867
916
  }
868
917
  }
869
918
 
870
- async function resolveAutodiscoveryHost(domain) {
871
- try {
872
- let srvList = await dns.resolveSrv(`_autodiscover._tcp.${domain}`);
873
- let record = srvList.sort((a, b) => a.priority - b.priority).shift();
874
- if (record) {
875
- return `${record.name}${record.port !== 443 ? `:${record.port}` : ''}`;
876
- }
877
- } catch (err) {
878
- //ignore
919
+ async function resolveAutodiscoveryHost(domain, ctx) {
920
+ let record = await lookupSrv(ctx, `_autodiscover._tcp.${domain}`);
921
+ if (record) {
922
+ return `${record.name}${record.port !== 443 ? `:${record.port}` : ''}`;
879
923
  }
880
924
 
881
925
  return `autodiscover.${encodeURIComponent(domain)}`;
882
926
  }
883
927
 
928
+ /**
929
+ * The https endpoint that the subdomain's plain-http redirect names.
930
+ *
931
+ * Microsoft's sequence has a step before the POSTs: an unauthenticated GET to
932
+ * `http://autodiscover.<domain>/autodiscover/autodiscover.xml`, whose 302 names the endpoint that
933
+ * actually answers. It used to be skipped entirely, and for a provider that publishes nothing else
934
+ * the lookup then had nowhere to go: IONOS/1&1 hosted mail points `autodiscover.<domain>` at a
935
+ * redirector that listens on port 80 only, so the https POST could not connect and the whole
936
+ * Exchange branch failed for every domain on that provider.
937
+ *
938
+ * Anonymous, and it stays anonymous: no credential is attached to an http request, and only an https
939
+ * origin is returned, so a redirect that lands on http names nothing. The target is chosen by a
940
+ * server the address domain's DNS points at, so the hop goes through the same vetted-redirect fetch
941
+ * as every other request here and `fetchWithVettedRedirects` drops credentials on a cross-origin hop.
942
+ *
943
+ * @param {String} domain - The address domain, already punycoded
944
+ * @param {Object} ctx - `{ fetchResource, signal }`
945
+ * @returns {Promise<String|false>} An https origin, or false when the lookup names nothing new
946
+ */
947
+ async function autodiscoverRedirectOrigin(domain, ctx) {
948
+ const { fetchResource, signal } = withIo(ctx);
949
+ const subdomain = `autodiscover.${encodeURIComponent(domain)}`;
950
+
951
+ try {
952
+ const res = await fetchResource(`http://${subdomain}/autodiscover/autodiscover.xml`, { method: 'get', signal });
953
+ // Nothing reads the body - only where the request ended up - but it is drained so the
954
+ // keep-alive socket goes back to the pool
955
+ await readDocument(res).catch(() => false);
956
+
957
+ const origin = secureOriginOf(res.url || '');
958
+ // A plain http-to-https upgrade on the same host names nothing new: that origin is already
959
+ // one of the candidates raced below
960
+ return origin && origin !== `https://${subdomain}` ? origin : false;
961
+ } catch (err) {
962
+ return false;
963
+ }
964
+ }
965
+
884
966
  /**
885
967
  * Runs autodiscovery against one host.
886
968
  *
@@ -896,35 +978,54 @@ async function resolveAutodiscoveryHost(domain) {
896
978
  * @param {string} baseUrl - Origin of the autodiscovery host, no trailing slash
897
979
  * @param {string} email - Mailbox to look up
898
980
  * @param {Object} [credentials] - `{ user, pass }`; the lookup stays anonymous without it
899
- * @param {Function} [fetchResource] - Fetch to use, `(url, opts) => Promise<Response>`
981
+ * @param {Object} [ctx] - `{ fetchResource, signal }`: the fetch to use, `(url, opts) =>
982
+ * Promise<Response>`, and the signal that aborts every request of the lookup (the resolver's
983
+ * time budget). Either may be left out, this is an entry point of its own for the tests
984
+ * @param {Number} [redirectsLeft] - How many more times a response may name another endpoint
985
+ * instead of answering; see MAX_AUTODISCOVER_REDIRECTS
900
986
  * @returns {Promise<Object>} `{ imap, smtp, _source }`
901
987
  * @throws {Error} When no endpoint returned anything usable
902
988
  */
903
- async function runAutodiscovery(baseUrl, email, credentials, fetchResource) {
904
- fetchResource = fetchResource || fetchAutodiscoveryResource;
989
+ async function runAutodiscovery(baseUrl, email, credentials, ctx, redirectsLeft = MAX_AUTODISCOVER_REDIRECTS) {
990
+ const { fetchResource, signal } = withIo(ctx);
905
991
 
906
992
  const poxBody = buildAutodiscoverRequest(email);
907
993
  const post = (origin, path, body, authorization) =>
908
994
  fetchResource(`${origin}${path}`, {
909
995
  method: 'post',
910
996
  headers: Object.assign({ 'Content-type': AUTODISCOVER_CONTENT_TYPE }, authorization ? { Authorization: authorization } : {}),
911
- body
997
+ body,
998
+ signal
912
999
  });
913
1000
 
914
1001
  // A server that answers without credentials is never asked for them
915
1002
  let res = await post(baseUrl, '/autodiscover/autodiscover.xml', poxBody);
916
1003
  if (res.ok) {
917
- let result = processAutodiscoverResponse(await res.text());
1004
+ const body = await readDocument(res);
1005
+ let result = processAutodiscoverResponse(body);
918
1006
  if (hasResolvedHost(result)) {
919
1007
  return result;
920
1008
  }
1009
+
1010
+ // The response can name another endpoint for the same mailbox instead of answering, which read
1011
+ // as "no server" before. Asked ANONYMOUSLY, whatever credentials this lookup holds: the origin
1012
+ // is named by the body of a server that answered 200 without asking for anything, and an
1013
+ // anonymous 200 carrying no settings is exactly the case that must end the lookup rather than
1014
+ // escalate it. Passing the password on here would let any host the address domain points at
1015
+ // choose where that password goes, which is the one thing the rules around it prevent. https
1016
+ // only, for the same reason the 401 retry is.
1017
+ const redirectOrigin = redirectsLeft > 0 && secureOriginOf(poxRedirectUrl(body) || '');
1018
+ if (redirectOrigin) {
1019
+ return await runAutodiscovery(redirectOrigin, email, undefined, ctx, redirectsLeft - 1);
1020
+ }
1021
+
921
1022
  // It answered anonymously, just with nothing usable. It never asked for a password, so it
922
1023
  // is not given one.
923
1024
  throw new Error('Invalid response');
924
1025
  }
925
1026
 
926
1027
  // Nothing here reads the body, and the retries below reuse this connection
927
- await res.text().catch(() => false);
1028
+ await readDocument(res).catch(() => false);
928
1029
 
929
1030
  // Only a challenge that names Basic earns the password. A 404 from a wildcard-DNS parking host,
930
1031
  // a 500, a CDN answering an unknown path, a server offering only NTLM - all answered without
@@ -949,7 +1050,7 @@ async function runAutodiscovery(baseUrl, email, credentials, fetchResource) {
949
1050
 
950
1051
  const attempt = (path, body, processResponse) =>
951
1052
  post(origin, path, body, authorization)
952
- .then(async res => (res.ok ? processResponse(await res.text()) : false))
1053
+ .then(async res => (res.ok ? processResponse(await readDocument(res)) : false))
953
1054
  .catch(() => false);
954
1055
 
955
1056
  // Both are in flight before either is awaited, and whichever answers first with a usable
@@ -977,7 +1078,7 @@ async function runAutodiscovery(baseUrl, email, credentials, fetchResource) {
977
1078
  }
978
1079
  }
979
1080
 
980
- async function resolveUsingAutodiscovery(email, credentials) {
1081
+ async function resolveUsingAutodiscovery(email, ctx, credentials) {
981
1082
  let domain = email.split('@').pop().trim().toLowerCase();
982
1083
 
983
1084
  try {
@@ -986,9 +1087,37 @@ async function resolveUsingAutodiscovery(email, credentials) {
986
1087
  //ignore
987
1088
  }
988
1089
 
989
- let discoveryDomain = await resolveAutodiscoveryHost(domain);
1090
+ // Microsoft's sequence names three places a provider may publish autodiscovery, and a provider
1091
+ // can publish only one of them: the root domain, the autodiscover subdomain (or whatever the
1092
+ // _autodiscover._tcp SRV record names instead), and the endpoint that the subdomain's plain-http
1093
+ // redirect names. Only the second was ever tried.
1094
+ //
1095
+ // Raced rather than walked in order, for the same reason the two endpoints of one host already
1096
+ // are: this resolver shares a five second budget with four others, and a domain that publishes
1097
+ // none of them fails slowly - a DNS name that does not exist, a port that refuses the connection
1098
+ // and a host that answers 404 are three waits, not three answers.
1099
+ const subdomainOrigin = `https://${await resolveAutodiscoveryHost(domain, ctx)}`;
1100
+ const rootOrigin = `https://${encodeURIComponent(domain)}`;
1101
+
1102
+ const attempts = [...new Set([subdomainOrigin, rootOrigin])].map(origin => runAutodiscovery(origin, email, credentials, ctx));
1103
+
1104
+ // One request behind the others, so it is started here rather than awaited first
1105
+ attempts.push(
1106
+ autodiscoverRedirectOrigin(domain, ctx).then(origin => {
1107
+ if (!origin) {
1108
+ throw new Error('Invalid response');
1109
+ }
1110
+ return runAutodiscovery(origin, email, credentials, ctx);
1111
+ })
1112
+ );
990
1113
 
991
- return await runAutodiscovery(`https://${discoveryDomain}`, email, credentials);
1114
+ try {
1115
+ // Every attempt rejects unless it has a usable configuration (runAutodiscovery throws on
1116
+ // anything else), so the first to resolve is the first real answer
1117
+ return await Promise.any(attempts);
1118
+ } catch (err) {
1119
+ throw new Error('Invalid response', { cause: err });
1120
+ }
992
1121
  }
993
1122
 
994
1123
  function processAutodiscoverResponse(text, source) {
@@ -1061,13 +1190,38 @@ function processAutodiscoverResponse(text, source) {
1061
1190
  return { imap, smtp, _source: source || 'autodiscover' };
1062
1191
  }
1063
1192
 
1193
+ /**
1194
+ * Races a lookup against a time budget.
1195
+ *
1196
+ * Given a function, it is called with an AbortSignal that fires when the budget runs out, so the
1197
+ * requests still in flight are cancelled rather than left to stream into memory after the race
1198
+ * has been decided. A promise can only be raced, not cancelled.
1199
+ *
1200
+ * @param {Promise|Function} prom - The lookup, or `signal => Promise` to make it abortable
1201
+ * @param {number} timeout - Budget in milliseconds
1202
+ * @param {string} [source] - Resolver name, copied onto the timeout error
1203
+ * @returns {Promise<*>} Whatever the lookup resolves with
1204
+ */
1064
1205
  async function timedFunction(prom, timeout, source) {
1206
+ let controller;
1207
+ if (typeof prom === 'function') {
1208
+ controller = new AbortController();
1209
+ try {
1210
+ prom = Promise.resolve(prom(controller.signal));
1211
+ } catch (err) {
1212
+ prom = Promise.reject(err);
1213
+ }
1214
+ }
1215
+
1065
1216
  return new Promise((resolve, reject) => {
1066
1217
  const timer = setTimeout(() => {
1067
1218
  let err = new Error('Resolving requested resource timed out');
1068
1219
  if (source) {
1069
1220
  err._source = source;
1070
1221
  }
1222
+ if (controller) {
1223
+ controller.abort(err);
1224
+ }
1071
1225
  reject(err);
1072
1226
  }, timeout).unref();
1073
1227
 
@@ -1077,11 +1231,25 @@ async function timedFunction(prom, timeout, source) {
1077
1231
  });
1078
1232
  }
1079
1233
 
1080
- async function resolver(email, gt, credentials) {
1234
+ /**
1235
+ * Runs the resolvers: the MX one first, then the other five racing under their own time budget.
1236
+ *
1237
+ * @param {string} email - Address to look up
1238
+ * @param {Object} gt - gettext instance
1239
+ * @param {Object} [credentials] - `{ user, pass }`, see autodetectImapSettings()
1240
+ * @param {Object} [io] - `{ dns, fetchResource, timeout }` stand-ins for tests; production passes none
1241
+ * @returns {Promise<Object>} The first result that names a server
1242
+ */
1243
+ async function resolver(email, gt, credentials, io) {
1244
+ io = io || {};
1245
+ const timeout = io.timeout || RESOLV_TIMEOUT;
1246
+ // Each resolver gets its own signal, aborted by its own timer
1247
+ const ctx = signal => withIo({ dns: io.dns, fetchResource: io.fetchResource, signal });
1248
+
1081
1249
  let exchange;
1082
1250
  try {
1083
1251
  // prefer MX based resolver
1084
- let res = await timedFunction(resolveUsingMX(email, null, gt), RESOLV_TIMEOUT, 'mx');
1252
+ let res = await timedFunction(signal => resolveUsingMX(email, ctx(signal), gt), timeout, 'mx');
1085
1253
  return res;
1086
1254
  } catch (err) {
1087
1255
  if (err.exchange) {
@@ -1092,11 +1260,11 @@ async function resolver(email, gt, credentials) {
1092
1260
 
1093
1261
  return new Promise((resolve, reject) => {
1094
1262
  let promises = [
1095
- timedFunction(resolveUsingSRV(email), RESOLV_TIMEOUT, 'srv', exchange),
1096
- timedFunction(resolveUsingWellKnown(email), RESOLV_TIMEOUT, 'well-known'),
1097
- timedFunction(resolveUsingAutoconfig(email), RESOLV_TIMEOUT, 'autoconfig'),
1098
- timedFunction(resolveUsingMozillaDirectory(email), RESOLV_TIMEOUT, 'mozilla'),
1099
- timedFunction(resolveUsingAutodiscovery(email, credentials), RESOLV_TIMEOUT, 'autodiscover')
1263
+ timedFunction(signal => resolveUsingSRV(email, ctx(signal)), timeout, 'srv'),
1264
+ timedFunction(signal => resolveUsingWellKnown(email, ctx(signal)), timeout, 'well-known'),
1265
+ timedFunction(signal => resolveUsingAutoconfig(email, ctx(signal)), timeout, 'autoconfig'),
1266
+ timedFunction(signal => resolveUsingMozillaDirectory(email, ctx(signal)), timeout, 'mozilla'),
1267
+ timedFunction(signal => resolveUsingAutodiscovery(email, ctx(signal), credentials), timeout, 'autodiscover')
1100
1268
  ];
1101
1269
 
1102
1270
  // The first resolver to come back with something wins. A resolver that answers but names
@@ -1166,3 +1334,17 @@ module.exports.escapeXml = escapeXml;
1166
1334
  // them, both endpoints in parallel) can be tested against an injected fetch rather than a live
1167
1335
  // Exchange server. Production callers pass no fetch and get the egress-policed one.
1168
1336
  module.exports.runAutodiscovery = runAutodiscovery;
1337
+
1338
+ // Exposed so the orchestration (the resolver race, the time budget and its abort, the body cap, the
1339
+ // SRV fallbacks) can be tested against stand-in DNS and fetch
1340
+ module.exports.resolver = resolver;
1341
+ module.exports.resolveUsingSRV = resolveUsingSRV;
1342
+ module.exports.timedFunction = timedFunction;
1343
+ module.exports.MAX_AUTODISCOVERY_BODY = MAX_AUTODISCOVERY_BODY;
1344
+
1345
+ // Exposed so the two steps of Microsoft's sequence that used to be missing can be tested on their
1346
+ // own: the plain-http GET whose redirect names the real endpoint, and the in-response redirect
1347
+ module.exports.autodiscoverRedirectOrigin = autodiscoverRedirectOrigin;
1348
+ module.exports.poxRedirectUrl = poxRedirectUrl;
1349
+ module.exports.resolveUsingAutodiscovery = resolveUsingAutodiscovery;
1350
+ module.exports.MAX_AUTODISCOVER_REDIRECTS = MAX_AUTODISCOVER_REDIRECTS;