emailengine-app 2.81.1 → 2.82.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 (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  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-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. package/workers/documents.js +0 -1128
package/lib/auth-token.js CHANGED
@@ -12,7 +12,7 @@ const tokenPermissions = require('./token-permissions');
12
12
  const tokenAuditLog = require('./token-audit-log');
13
13
  const { SURFACE_GRANTS } = require('./api-routes/permission-map');
14
14
  const { matchIp } = require('./utils/network');
15
- const { checkRateLimit, peekRateLimit } = require('./rate-limit');
15
+ const { windowBudget, reserveAttempts, releaseAttempts } = require('./rate-limit');
16
16
 
17
17
  // Reason-specific denial messages, shared verbatim by both auth handlers. The
18
18
  // generic "failed to authenticate" fallback and any protocol-specific error
@@ -40,51 +40,69 @@ const REASON_MESSAGES = {
40
40
  const AUTH_FAILURE_LIMIT = 20;
41
41
  const AUTH_FAILURE_WINDOW = 5 * 60; // seconds
42
42
 
43
+ // The per-username budget alone does not hold the shared password: that password is checked
44
+ // before the account is looked up, so rotating usernames buys a fresh budget per name. A second
45
+ // budget per client address, ignoring the username, bounds that. It only counts attempts whose
46
+ // password is not shaped like an API token, which is what keeps the property above: a stale
47
+ // token for one account never spends it, while a stale shared password breaks every account of
48
+ // that host anyway. Larger than the per-username one, as one address can front many accounts.
49
+ const AUTH_FAILURE_ADDRESS_LIMIT = 100;
50
+
51
+ const TOKEN_SHAPE = /^[0-9a-f]{64}$/i;
52
+
43
53
  const authFailureKey = (remoteAddress, account) => `auth:fail:${remoteAddress || 'unknown'}:${account || ''}`;
54
+ const authFailureAddressKey = remoteAddress => `auth:fail-addr:${remoteAddress || 'unknown'}`;
44
55
 
45
56
  /**
46
57
  * Runs a credential check under the client's failed-login budget.
47
58
  *
48
- * Looks before the attempt (a peek, so an accepted login spends nothing) and records only a
49
- * refusal. Everything `attempt` throws counts as one: the caller decides what belongs inside
50
- * the budget by what it puts in the function, so a refusal that is about the account rather
51
- * than the credential (an API-only account on the IMAP proxy) is left outside it.
59
+ * One attempt is reserved atomically before the check and given back when it is accepted, so
60
+ * only a refusal stays counted. Everything `attempt` throws counts as one: the caller decides what
61
+ * belongs inside the budget by what it puts in the function, so a refusal that is about the account
62
+ * rather than the credential (an API-only account on the IMAP proxy) is left outside it.
52
63
  *
53
64
  * @param {Object} client
54
65
  * @param {String} client.remoteAddress - client IP
55
66
  * @param {String} client.account - username the client is authenticating as
67
+ * @param {String} [client.password] - the presented password. When given, a password that is not
68
+ * token-shaped is also counted against the address budget, which ignores the username
56
69
  * @param {Function} attempt - async () => result; the credential check
57
70
  * @param {Function} limitedError - () => Error; the protocol-specific refusal for a spent budget
58
71
  * @returns {Promise<*>} whatever `attempt` resolves with
59
72
  */
60
- async function withAuthFailureBudget({ remoteAddress, account }, attempt, limitedError) {
61
- const key = authFailureKey(remoteAddress, account);
73
+ async function withAuthFailureBudget({ remoteAddress, account, password }, attempt, limitedError) {
74
+ const now = Date.now();
75
+ const budgets = [windowBudget(authFailureKey(remoteAddress, account), AUTH_FAILURE_LIMIT, AUTH_FAILURE_WINDOW, now)];
62
76
 
63
- let limit = await peekRateLimit(key, AUTH_FAILURE_LIMIT, AUTH_FAILURE_WINDOW);
64
- if (!limit.success) {
77
+ if (typeof password === 'string' && !TOKEN_SHAPE.test(password)) {
78
+ budgets.push(windowBudget(authFailureAddressKey(remoteAddress), AUTH_FAILURE_ADDRESS_LIMIT, AUTH_FAILURE_WINDOW, now));
79
+ }
80
+
81
+ // Reserved in every budget at once, or in none: INCR and the limit check are one step, so
82
+ // parallel connections cannot all read the same count and each go ahead
83
+ const { admitted, counts } = await reserveAttempts(budgets);
84
+ if (!admitted) {
65
85
  logger.warn({
66
86
  msg: 'Refusing authentication attempt, failure limit reached',
67
87
  remoteAddress,
68
88
  account,
69
- count: limit.count,
70
- allowed: limit.allowed,
71
- ttlReset: limit.ttlReset
89
+ count: counts[0],
90
+ allowed: AUTH_FAILURE_LIMIT,
91
+ addressCount: counts[1]
72
92
  });
73
93
  throw limitedError();
74
94
  }
75
95
 
76
- try {
77
- return await attempt();
78
- } catch (err) {
79
- // Never masks the refusal: a counter that could not be written is logged, and the
80
- // client still gets the error the attempt raised
81
- try {
82
- await checkRateLimit(key, 1, AUTH_FAILURE_LIMIT, AUTH_FAILURE_WINDOW);
83
- } catch (recordErr) {
84
- logger.error({ msg: 'Failed to record authentication failure', remoteAddress, account, err: recordErr });
85
- }
86
- throw err;
87
- }
96
+ // A refusal thrown here keeps its reservation: that is the recorded failure
97
+ const result = await attempt();
98
+
99
+ // Not awaited: an accepted login is neither held up by giving its reservation back nor failed
100
+ // by it. A reservation that could not be given back only costs this client one attempt
101
+ releaseAttempts(budgets.map(budget => budget.key)).catch(releaseErr => {
102
+ logger.error({ msg: 'Failed to release authentication attempt', remoteAddress, account, err: releaseErr });
103
+ });
104
+
105
+ return result;
88
106
  }
89
107
 
90
108
  /**
@@ -220,7 +238,9 @@ module.exports = {
220
238
  validateAuthToken,
221
239
  withAuthFailureBudget,
222
240
  authFailureKey,
241
+ authFailureAddressKey,
223
242
  AUTH_FAILURE_LIMIT,
243
+ AUTH_FAILURE_ADDRESS_LIMIT,
224
244
  AUTH_FAILURE_WINDOW,
225
245
  REASON_MESSAGES
226
246
  };
@@ -63,11 +63,15 @@ 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;
@@ -185,8 +189,8 @@ function getAppPassword(email, exchange, gt) {
185
189
 
186
190
  // Resolve the lowest-priority MX exchange for a domain (lowercased). Throws if the domain has no MX
187
191
  // 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);
192
+ async function resolveExchange(domain, resolverDns) {
193
+ let srvList = await (resolverDns || dns).resolveMx(domain);
190
194
  if (!srvList || !srvList.length) {
191
195
  throw new Error('No MX record found for domain');
192
196
  }
@@ -247,6 +251,9 @@ async function processAutoconfigFile(email, domain, text, source) {
247
251
  // So the first element that names a host wins, not simply the first of its type - taking the
248
252
  // first let a hostless one discard a usable sibling further down.
249
253
  const namesHost = entry => entry && Array.isArray(entry.hostname) && entry.hostname.some(value => value);
254
+ // <port> and <socketType> are optional as far as a hostile document is concerned: a missing one
255
+ // used to throw on `.filter` and discard the whole file, including a sibling entry that was fine
256
+ const firstValue = list => (Array.isArray(list) ? list.filter(entry => entry).shift() : undefined);
250
257
 
251
258
  let emailProviders = json && json.clientconfig && Array.isArray(json.clientconfig.emailprovider) ? json.clientconfig.emailprovider : [];
252
259
  let incomingServer = emailProviders
@@ -265,11 +272,8 @@ async function processAutoconfigFile(email, domain, text, source) {
265
272
  const firstHostname = incomingServer.hostname.filter(entry => entry).shift();
266
273
  const processedHostname = firstHostname.replace(/^%EMAILDOMAIN%$/, domain);
267
274
 
268
- imap = {
269
- host: processedHostname,
270
- port: Number(incomingServer.port.filter(entry => entry).shift()),
271
- secure: incomingServer.sockettype.filter(entry => entry).shift() === 'SSL'
272
- };
275
+ const port = Number(firstValue(incomingServer.port));
276
+ imap = Object.assign({ host: processedHostname }, port ? { port } : {}, { secure: firstValue(incomingServer.sockettype) === 'SSL' });
273
277
 
274
278
  if (Array.isArray(incomingServer.username) && incomingServer.username.length) {
275
279
  imap.auth = {
@@ -285,11 +289,8 @@ async function processAutoconfigFile(email, domain, text, source) {
285
289
  const firstHostname = outgoingServer.hostname.filter(entry => entry).shift();
286
290
  const processedHostname = firstHostname.replace(/^%EMAILDOMAIN%$/, domain);
287
291
 
288
- smtp = {
289
- host: processedHostname,
290
- port: Number(outgoingServer.port.filter(entry => entry).shift()),
291
- secure: outgoingServer.sockettype.filter(entry => entry).shift() === 'SSL'
292
- };
292
+ const port = Number(firstValue(outgoingServer.port));
293
+ smtp = Object.assign({ host: processedHostname }, port ? { port } : {}, { secure: firstValue(outgoingServer.sockettype) === 'SSL' });
293
294
 
294
295
  if (Array.isArray(outgoingServer.username) && outgoingServer.username.length) {
295
296
  smtp.auth = {
@@ -327,27 +328,43 @@ async function fetchAutodiscoveryResource(url, opts) {
327
328
  );
328
329
  }
329
330
 
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
331
+ /**
332
+ * Fills in the I/O a resolver uses. Every resolver takes a context rather than reaching for DNS and
333
+ * fetch directly, so the orchestration (the race, the time budget, the body cap) can be tested
334
+ * against stand-ins, and so the abort signal of the resolver's time budget reaches every request.
335
+ *
336
+ * Applied once, where a context enters: resolver() builds one per time budget, and
337
+ * runAutodiscovery() accepts a partial one from the tests that drive it directly. The resolvers
338
+ * themselves take the context as given.
339
+ *
340
+ * @param {Object} [ctx] - `{ dns, fetchResource, signal }`, any of them optional
341
+ * @returns {Object} Context with the production DNS and egress-policed fetch filled in
342
+ */
343
+ function withIo(ctx) {
344
+ const io = { dns, fetchResource: fetchAutodiscoveryResource };
345
+ for (const key of Object.keys(ctx || {})) {
346
+ // An explicit undefined keeps the production default; only a stand-in actually given wins
347
+ if (ctx[key] !== undefined) {
348
+ io[key] = ctx[key];
349
+ }
337
350
  }
351
+ return io;
352
+ }
353
+
354
+ // Reads a response body within the size budget; see MAX_AUTODISCOVERY_BODY
355
+ const readDocument = res => readBodyCapped(res, MAX_AUTODISCOVERY_BODY);
338
356
 
339
- let res = await fetchAutodiscoveryResource(`https://autoconfig.thunderbird.net/v1.1/${domain}`);
357
+ async function fetchAutoconfigDocument(url, ctx) {
358
+ let res = await ctx.fetchResource(url, { signal: ctx.signal });
340
359
 
341
360
  if (!res.ok) {
342
361
  throw new Error('Invalid response');
343
362
  }
344
363
 
345
- let text = await res.text();
346
-
347
- return await processAutoconfigFile(email, domain, text, source || 'mozilla');
364
+ return await readDocument(res);
348
365
  }
349
366
 
350
- async function resolveUsingAutoconfig(email, domain, source) {
367
+ async function resolveUsingMozillaDirectory(email, ctx, domain, source) {
351
368
  domain = domain || email.split('@').pop().trim().toLowerCase();
352
369
 
353
370
  try {
@@ -356,20 +373,12 @@ async function resolveUsingAutoconfig(email, domain, source) {
356
373
  //ignore
357
374
  }
358
375
 
359
- let res = await fetchAutodiscoveryResource(
360
- `https://autoconfig.${encodeURIComponent(domain)}/mail/config-v1.1.xml?emailaddress=${encodeURIComponent(email)}`
361
- );
362
-
363
- if (!res.ok) {
364
- throw new Error('Invalid response');
365
- }
366
-
367
- let text = await res.text();
376
+ let text = await fetchAutoconfigDocument(`https://autoconfig.thunderbird.net/v1.1/${domain}`, ctx);
368
377
 
369
- return await processAutoconfigFile(email, domain, text, source || 'autoconfig');
378
+ return await processAutoconfigFile(email, domain, text, source || 'mozilla');
370
379
  }
371
380
 
372
- async function resolveUsingWellKnown(email, domain, source) {
381
+ async function resolveUsingAutoconfig(email, ctx, domain, source) {
373
382
  domain = domain || email.split('@').pop().trim().toLowerCase();
374
383
 
375
384
  try {
@@ -378,18 +387,15 @@ async function resolveUsingWellKnown(email, domain, source) {
378
387
  //ignore
379
388
  }
380
389
 
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();
390
+ let text = await fetchAutoconfigDocument(
391
+ `https://autoconfig.${encodeURIComponent(domain)}/mail/config-v1.1.xml?emailaddress=${encodeURIComponent(email)}`,
392
+ ctx
393
+ );
388
394
 
389
- return await processAutoconfigFile(email, domain, text, source || 'well-known');
395
+ return await processAutoconfigFile(email, domain, text, source || 'autoconfig');
390
396
  }
391
397
 
392
- async function resolveUsingSRV(email, domain, source) {
398
+ async function resolveUsingWellKnown(email, ctx, domain, source) {
393
399
  domain = domain || email.split('@').pop().trim().toLowerCase();
394
400
 
395
401
  try {
@@ -398,71 +404,61 @@ async function resolveUsingSRV(email, domain, source) {
398
404
  //ignore
399
405
  }
400
406
 
401
- let imap = false;
402
- let smtp = false;
407
+ let text = await fetchAutoconfigDocument(`http://${encodeURIComponent(domain)}/.well-known/autoconfig/mail/config-v1.1.xml`, ctx);
408
+
409
+ return await processAutoconfigFile(email, domain, text, source || 'well-known');
410
+ }
403
411
 
412
+ // First record of an SRV lookup by priority, or null when the name has none. A missing record is
413
+ // an ordinary answer here (most domains publish none), so it must not end the whole resolver.
414
+ async function lookupSrv(ctx, name) {
404
415
  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
- }
416
+ let srvList = await ctx.dns.resolveSrv(name);
417
+ return (srvList || []).sort((a, b) => a.priority - b.priority).shift() || null;
414
418
  } catch (err) {
415
- //ignore
419
+ return null;
416
420
  }
421
+ }
417
422
 
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
- }
423
+ async function resolveUsingSRV(email, ctx, domain, source) {
424
+ domain = domain || email.split('@').pop().trim().toLowerCase();
433
425
 
434
426
  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
- }
427
+ domain = punycode.toASCII(domain);
444
428
  } catch (err) {
445
429
  //ignore
446
430
  }
447
431
 
448
- if (!smtp) {
449
- let srvList = await dns.resolveSrv(`_submission._tcp.${domain}`);
450
- let record = srvList.sort((a, b) => a.priority - b.priority).shift();
432
+ const lookupImap = async () => {
433
+ let record = await lookupSrv(ctx, `_imaps._tcp.${domain}`);
451
434
  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
- };
435
+ return { host: record.name, port: record.port, secure: true };
458
436
  }
459
- }
437
+ record = await lookupSrv(ctx, `_imap._tcp.${domain}`);
438
+ return record ? { host: record.name, port: record.port, secure: false } : false;
439
+ };
440
+
441
+ const lookupSmtp = async () => {
442
+ let record = await lookupSrv(ctx, `_submissions._tcp.${domain}`);
443
+ if (record) {
444
+ return { host: record.name, port: record.port, secure: true };
445
+ }
446
+ // Used to be the one lookup left unguarded, so a domain with IMAP records and no
447
+ // _submission one threw away the IMAP answer it had already found
448
+ record = await lookupSrv(ctx, `_submission._tcp.${domain}`);
449
+ // Some providers invalidly use _submission instead of _submissions
450
+ return record ? { host: record.name, port: record.port, secure: record.port === 465 } : false;
451
+ };
452
+
453
+ // The two chains are independent, and this resolver runs against a time budget it shares
454
+ // with four others, so they are not paid for one after the other
455
+ const [imap, smtp] = await Promise.all([lookupImap(), lookupSmtp()]);
460
456
 
461
457
  return { smtp, imap, _source: source || 'srv' };
462
458
  }
463
459
 
464
- async function resolveUsingMX(email, domain, gt) {
465
- domain = domain || email.split('@').pop().trim().toLowerCase();
460
+ async function resolveUsingMX(email, ctx, gt) {
461
+ let domain = email.split('@').pop().trim().toLowerCase();
466
462
 
467
463
  try {
468
464
  domain = punycode.toASCII(domain);
@@ -471,16 +467,16 @@ async function resolveUsingMX(email, domain, gt) {
471
467
  }
472
468
 
473
469
  // 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);
470
+ let exchange = await resolveExchange(domain, ctx.dns);
475
471
 
476
472
  let resolveConfig = async () => {
477
473
  // look for some well known MX servers
478
474
  if (/\bl\.google\.com$/i.test(exchange)) {
479
- return await resolveUsingSRV(email, 'gmail.com', 'mx');
475
+ return await resolveUsingSRV(email, ctx, 'gmail.com', 'mx');
480
476
  }
481
477
 
482
478
  if (/\bmx\.yandex\.net$/i.test(exchange)) {
483
- return await resolveUsingAutoconfig(email, 'yandex.ru', 'mx');
479
+ return await resolveUsingAutoconfig(email, ctx, 'yandex.ru', 'mx');
484
480
  }
485
481
 
486
482
  if (/^mx\d*\.zone\.eu$/i.test(exchange)) {
@@ -518,7 +514,7 @@ async function resolveUsingMX(email, domain, gt) {
518
514
  }
519
515
 
520
516
  if (/\bzonemx\.eu$/i.test(exchange)) {
521
- return await resolveUsingAutoconfig(email, 'zone.ee', 'mx');
517
+ return await resolveUsingAutoconfig(email, ctx, 'zone.ee', 'mx');
522
518
  }
523
519
 
524
520
  // AWS WorkMail
@@ -867,15 +863,10 @@ function secureOriginOf(url) {
867
863
  }
868
864
  }
869
865
 
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
866
+ async function resolveAutodiscoveryHost(domain, ctx) {
867
+ let record = await lookupSrv(ctx, `_autodiscover._tcp.${domain}`);
868
+ if (record) {
869
+ return `${record.name}${record.port !== 443 ? `:${record.port}` : ''}`;
879
870
  }
880
871
 
881
872
  return `autodiscover.${encodeURIComponent(domain)}`;
@@ -896,25 +887,28 @@ async function resolveAutodiscoveryHost(domain) {
896
887
  * @param {string} baseUrl - Origin of the autodiscovery host, no trailing slash
897
888
  * @param {string} email - Mailbox to look up
898
889
  * @param {Object} [credentials] - `{ user, pass }`; the lookup stays anonymous without it
899
- * @param {Function} [fetchResource] - Fetch to use, `(url, opts) => Promise<Response>`
890
+ * @param {Object} [ctx] - `{ fetchResource, signal }`: the fetch to use, `(url, opts) =>
891
+ * Promise<Response>`, and the signal that aborts every request of the lookup (the resolver's
892
+ * time budget). Either may be left out, this is an entry point of its own for the tests
900
893
  * @returns {Promise<Object>} `{ imap, smtp, _source }`
901
894
  * @throws {Error} When no endpoint returned anything usable
902
895
  */
903
- async function runAutodiscovery(baseUrl, email, credentials, fetchResource) {
904
- fetchResource = fetchResource || fetchAutodiscoveryResource;
896
+ async function runAutodiscovery(baseUrl, email, credentials, ctx) {
897
+ const { fetchResource, signal } = withIo(ctx);
905
898
 
906
899
  const poxBody = buildAutodiscoverRequest(email);
907
900
  const post = (origin, path, body, authorization) =>
908
901
  fetchResource(`${origin}${path}`, {
909
902
  method: 'post',
910
903
  headers: Object.assign({ 'Content-type': AUTODISCOVER_CONTENT_TYPE }, authorization ? { Authorization: authorization } : {}),
911
- body
904
+ body,
905
+ signal
912
906
  });
913
907
 
914
908
  // A server that answers without credentials is never asked for them
915
909
  let res = await post(baseUrl, '/autodiscover/autodiscover.xml', poxBody);
916
910
  if (res.ok) {
917
- let result = processAutodiscoverResponse(await res.text());
911
+ let result = processAutodiscoverResponse(await readDocument(res));
918
912
  if (hasResolvedHost(result)) {
919
913
  return result;
920
914
  }
@@ -924,7 +918,7 @@ async function runAutodiscovery(baseUrl, email, credentials, fetchResource) {
924
918
  }
925
919
 
926
920
  // Nothing here reads the body, and the retries below reuse this connection
927
- await res.text().catch(() => false);
921
+ await readDocument(res).catch(() => false);
928
922
 
929
923
  // Only a challenge that names Basic earns the password. A 404 from a wildcard-DNS parking host,
930
924
  // a 500, a CDN answering an unknown path, a server offering only NTLM - all answered without
@@ -949,7 +943,7 @@ async function runAutodiscovery(baseUrl, email, credentials, fetchResource) {
949
943
 
950
944
  const attempt = (path, body, processResponse) =>
951
945
  post(origin, path, body, authorization)
952
- .then(async res => (res.ok ? processResponse(await res.text()) : false))
946
+ .then(async res => (res.ok ? processResponse(await readDocument(res)) : false))
953
947
  .catch(() => false);
954
948
 
955
949
  // Both are in flight before either is awaited, and whichever answers first with a usable
@@ -977,7 +971,7 @@ async function runAutodiscovery(baseUrl, email, credentials, fetchResource) {
977
971
  }
978
972
  }
979
973
 
980
- async function resolveUsingAutodiscovery(email, credentials) {
974
+ async function resolveUsingAutodiscovery(email, ctx, credentials) {
981
975
  let domain = email.split('@').pop().trim().toLowerCase();
982
976
 
983
977
  try {
@@ -986,9 +980,9 @@ async function resolveUsingAutodiscovery(email, credentials) {
986
980
  //ignore
987
981
  }
988
982
 
989
- let discoveryDomain = await resolveAutodiscoveryHost(domain);
983
+ let discoveryDomain = await resolveAutodiscoveryHost(domain, ctx);
990
984
 
991
- return await runAutodiscovery(`https://${discoveryDomain}`, email, credentials);
985
+ return await runAutodiscovery(`https://${discoveryDomain}`, email, credentials, ctx);
992
986
  }
993
987
 
994
988
  function processAutodiscoverResponse(text, source) {
@@ -1061,13 +1055,38 @@ function processAutodiscoverResponse(text, source) {
1061
1055
  return { imap, smtp, _source: source || 'autodiscover' };
1062
1056
  }
1063
1057
 
1058
+ /**
1059
+ * Races a lookup against a time budget.
1060
+ *
1061
+ * Given a function, it is called with an AbortSignal that fires when the budget runs out, so the
1062
+ * requests still in flight are cancelled rather than left to stream into memory after the race
1063
+ * has been decided. A promise can only be raced, not cancelled.
1064
+ *
1065
+ * @param {Promise|Function} prom - The lookup, or `signal => Promise` to make it abortable
1066
+ * @param {number} timeout - Budget in milliseconds
1067
+ * @param {string} [source] - Resolver name, copied onto the timeout error
1068
+ * @returns {Promise<*>} Whatever the lookup resolves with
1069
+ */
1064
1070
  async function timedFunction(prom, timeout, source) {
1071
+ let controller;
1072
+ if (typeof prom === 'function') {
1073
+ controller = new AbortController();
1074
+ try {
1075
+ prom = Promise.resolve(prom(controller.signal));
1076
+ } catch (err) {
1077
+ prom = Promise.reject(err);
1078
+ }
1079
+ }
1080
+
1065
1081
  return new Promise((resolve, reject) => {
1066
1082
  const timer = setTimeout(() => {
1067
1083
  let err = new Error('Resolving requested resource timed out');
1068
1084
  if (source) {
1069
1085
  err._source = source;
1070
1086
  }
1087
+ if (controller) {
1088
+ controller.abort(err);
1089
+ }
1071
1090
  reject(err);
1072
1091
  }, timeout).unref();
1073
1092
 
@@ -1077,11 +1096,25 @@ async function timedFunction(prom, timeout, source) {
1077
1096
  });
1078
1097
  }
1079
1098
 
1080
- async function resolver(email, gt, credentials) {
1099
+ /**
1100
+ * Runs the resolvers: the MX one first, then the other five racing under their own time budget.
1101
+ *
1102
+ * @param {string} email - Address to look up
1103
+ * @param {Object} gt - gettext instance
1104
+ * @param {Object} [credentials] - `{ user, pass }`, see autodetectImapSettings()
1105
+ * @param {Object} [io] - `{ dns, fetchResource, timeout }` stand-ins for tests; production passes none
1106
+ * @returns {Promise<Object>} The first result that names a server
1107
+ */
1108
+ async function resolver(email, gt, credentials, io) {
1109
+ io = io || {};
1110
+ const timeout = io.timeout || RESOLV_TIMEOUT;
1111
+ // Each resolver gets its own signal, aborted by its own timer
1112
+ const ctx = signal => withIo({ dns: io.dns, fetchResource: io.fetchResource, signal });
1113
+
1081
1114
  let exchange;
1082
1115
  try {
1083
1116
  // prefer MX based resolver
1084
- let res = await timedFunction(resolveUsingMX(email, null, gt), RESOLV_TIMEOUT, 'mx');
1117
+ let res = await timedFunction(signal => resolveUsingMX(email, ctx(signal), gt), timeout, 'mx');
1085
1118
  return res;
1086
1119
  } catch (err) {
1087
1120
  if (err.exchange) {
@@ -1092,11 +1125,11 @@ async function resolver(email, gt, credentials) {
1092
1125
 
1093
1126
  return new Promise((resolve, reject) => {
1094
1127
  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')
1128
+ timedFunction(signal => resolveUsingSRV(email, ctx(signal)), timeout, 'srv'),
1129
+ timedFunction(signal => resolveUsingWellKnown(email, ctx(signal)), timeout, 'well-known'),
1130
+ timedFunction(signal => resolveUsingAutoconfig(email, ctx(signal)), timeout, 'autoconfig'),
1131
+ timedFunction(signal => resolveUsingMozillaDirectory(email, ctx(signal)), timeout, 'mozilla'),
1132
+ timedFunction(signal => resolveUsingAutodiscovery(email, ctx(signal), credentials), timeout, 'autodiscover')
1100
1133
  ];
1101
1134
 
1102
1135
  // The first resolver to come back with something wins. A resolver that answers but names
@@ -1166,3 +1199,10 @@ module.exports.escapeXml = escapeXml;
1166
1199
  // them, both endpoints in parallel) can be tested against an injected fetch rather than a live
1167
1200
  // Exchange server. Production callers pass no fetch and get the egress-policed one.
1168
1201
  module.exports.runAutodiscovery = runAutodiscovery;
1202
+
1203
+ // Exposed so the orchestration (the resolver race, the time budget and its abort, the body cap, the
1204
+ // SRV fallbacks) can be tested against stand-in DNS and fetch
1205
+ module.exports.resolver = resolver;
1206
+ module.exports.resolveUsingSRV = resolveUsingSRV;
1207
+ module.exports.timedFunction = timedFunction;
1208
+ module.exports.MAX_AUTODISCOVERY_BODY = MAX_AUTODISCOVERY_BODY;