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.
- package/.ncurc.js +12 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +52 -0
- package/Dockerfile +4 -2
- package/bin/emailengine.js +28 -18
- package/config/default.toml +0 -5
- package/config/test.toml +0 -5
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +70 -42
- package/getswagger.sh +0 -4
- package/lib/account/account-state.js +2 -110
- package/lib/account/bounce-store-sweep.js +63 -0
- package/lib/account/expected-identity.js +1 -1
- package/lib/account-assignment.js +207 -0
- package/lib/account.js +374 -878
- package/lib/api-reference/index.js +2 -3
- package/lib/api-reference/schema-tree.js +53 -3
- package/lib/api-routes/account-routes.js +18 -29
- package/lib/api-routes/blocklist-routes.js +2 -2
- package/lib/api-routes/bull-board-routes.js +1 -6
- package/lib/api-routes/export-routes.js +2 -22
- package/lib/api-routes/gateway-routes.js +5 -14
- package/lib/api-routes/index.js +1 -13
- package/lib/api-routes/mailbox-routes.js +2 -7
- package/lib/api-routes/mcp-oauth-routes.js +2 -1
- package/lib/api-routes/mcp-routes.js +7 -7
- package/lib/api-routes/message-routes.js +44 -236
- package/lib/api-routes/mint-bounds.js +110 -0
- package/lib/api-routes/oauth2-app-routes.js +23 -32
- package/lib/api-routes/operation-impact.js +1 -1
- package/lib/api-routes/outbox-routes.js +2 -2
- package/lib/api-routes/permission-map.js +1 -7
- package/lib/api-routes/route-helpers.js +11 -5
- package/lib/api-routes/settings-routes.js +19 -19
- package/lib/api-routes/stats-routes.js +1 -1
- package/lib/api-routes/submit-routes.js +17 -18
- package/lib/api-routes/template-routes.js +4 -9
- package/lib/api-routes/token-routes.js +27 -5
- package/lib/api-token-scheme.js +71 -0
- package/lib/arf-detect.js +41 -7
- package/lib/auth-token.js +44 -24
- package/lib/autodetect-imap-settings.js +163 -123
- package/lib/bounce-detect.js +25 -16
- package/lib/calendar-event.js +78 -0
- package/lib/consts.js +51 -5
- package/lib/create-imap-client.js +24 -0
- package/lib/db.js +76 -17
- package/lib/delivery-error.js +2 -1
- package/lib/egress-fetch.js +54 -3
- package/lib/egress-filter.js +11 -0
- package/lib/email-client/api-retry.js +147 -0
- package/lib/email-client/base-client.js +628 -615
- package/lib/email-client/gmail/gmail-api.js +38 -125
- package/lib/email-client/gmail/send-request.js +1 -1
- package/lib/email-client/gmail-client.js +170 -84
- package/lib/email-client/imap/mailbox.js +244 -535
- package/lib/email-client/imap/stale-view.js +109 -0
- package/lib/email-client/imap/subconnection.js +46 -9
- package/lib/email-client/imap/sync-operations.js +5 -37
- package/lib/email-client/imap-client.js +188 -64
- package/lib/email-client/message-builder.js +9 -14
- package/lib/email-client/notification-handler.js +5 -219
- package/lib/email-client/outlook/graph-api.js +147 -126
- package/lib/email-client/outlook/send-request.js +10 -4
- package/lib/email-client/outlook-client.js +519 -617
- package/lib/email-client/smtp-pool-manager.js +3 -2
- package/lib/encrypt.js +184 -19
- package/lib/enum-descriptions.js +1 -2
- package/lib/export.js +144 -41
- package/lib/gateway.js +20 -6
- package/lib/get-raw-email.js +26 -44
- package/lib/handlebars-helpers.js +31 -10
- package/lib/imap-proxy-auth.js +13 -29
- package/lib/imapproxy/imap-core/README.md +1 -0
- package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
- package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
- package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
- package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
- package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
- package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
- package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
- package/lib/imapproxy/imap-server.js +17 -177
- package/lib/imapproxy/proxy-handoff.js +235 -0
- package/lib/imapproxy/response-error.js +33 -0
- package/lib/imapproxy/upstream-client.js +2 -2
- package/lib/license-beacon.js +3 -9
- package/lib/llm-pre-process.js +182 -43
- package/lib/logger.js +1 -1
- package/lib/lua/ee-export-queue-add.lua +39 -0
- package/lib/lua/ee-get-idempotency.lua +15 -3
- package/lib/lua/ee-release-attempts.lua +23 -0
- package/lib/lua/ee-reserve-attempts.lua +42 -0
- package/lib/lua/h-set-bigger.lua +12 -2
- package/lib/lua/s-list-accounts.lua +6 -3
- package/lib/mcp/index.js +1 -2
- package/lib/mcp/listen.js +221 -18
- package/lib/mcp/oauth.js +44 -5
- package/lib/mcp/resources.js +8 -2
- package/lib/mcp/tools.js +13 -0
- package/lib/message-port-stream.js +64 -6
- package/lib/msgpack.js +1 -6
- package/lib/oauth/external-account-signer.js +16 -13
- package/lib/oauth/gmail.js +22 -20
- package/lib/oauth/outlook.js +19 -16
- package/lib/oauth/pubsub/google.js +38 -2
- package/lib/oauth/scope-checker.js +4 -7
- package/lib/oauth/verify-app.js +2 -2
- package/lib/oauth2-apps.js +139 -44
- package/lib/openapi/build-document.js +1 -1
- package/lib/openapi/joi-schema.js +78 -9
- package/lib/parse-message.js +21 -0
- package/lib/payload-examples-webhooks.json +4 -7
- package/lib/pbkdf2-phc.js +101 -0
- package/lib/privileged-settings.js +0 -14
- package/lib/rate-limit.js +54 -15
- package/lib/redis-scan-delete.js +56 -29
- package/lib/redis-url.js +3 -1
- package/lib/respawn-backoff.js +5 -4
- package/lib/response-stream.js +25 -4
- package/lib/rewrite-text-nodes.js +27 -40
- package/lib/routes-ui.js +0 -5
- package/lib/schemas.js +129 -262
- package/lib/sentry.js +21 -5
- package/lib/settings.js +58 -59
- package/lib/smtp-auth.js +6 -2
- package/lib/smtp-message-processor.js +28 -7
- package/lib/sso.js +7 -3
- package/lib/stream-encrypt.js +14 -13
- package/lib/swagger-options.js +3 -1
- package/lib/tls/provision.js +69 -3
- package/lib/tls/store.js +14 -1
- package/lib/tools.js +113 -52
- package/lib/totp.js +16 -1
- package/lib/ui-routes/account-routes.js +27 -63
- package/lib/ui-routes/admin-config-routes.js +111 -134
- package/lib/ui-routes/admin-entities-routes.js +101 -191
- package/lib/ui-routes/ai-options.js +104 -0
- package/lib/ui-routes/auth-routes.js +98 -18
- package/lib/ui-routes/export-routes.js +3 -23
- package/lib/ui-routes/internals-routes.js +12 -9
- package/lib/ui-routes/network-config-routes.js +8 -18
- package/lib/ui-routes/oauth-config-routes.js +80 -214
- package/lib/ui-routes/route-helpers.js +40 -44
- package/lib/ui-routes/unsubscribe-routes.js +2 -2
- package/lib/utils/decode-headers.js +32 -5
- package/lib/utils/header-map.js +62 -1
- package/lib/utils/network.js +2 -0
- package/lib/web-safe-html.js +77 -4
- package/lib/webhook-request.js +9 -1
- package/lib/webhook-routing.js +27 -1
- package/lib/webhooks.js +120 -43
- package/lib/worker-rpc-error.js +43 -2
- package/list-generate.js +13 -2
- package/package.json +38 -46
- package/sbom.json +1 -1
- package/scripts/refresh-test-tokens.js +42 -14
- package/server.js +340 -336
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +7 -8
- package/static/js/ee-client.js +145 -70
- package/static/js/ui.js +350 -154
- package/static/licenses.html +460 -1861
- package/translations/messages.pot +99 -99
- package/views/accounts/browse.hbs +10 -4
- package/views/config/ai.hbs +49 -41
- package/views/config/oauth/app.hbs +2 -1
- package/views/dashboard.hbs +18 -16
- package/views/layout/app.hbs +0 -22
- package/views/layout/login.hbs +2 -1
- package/views/partials/filter_editor_js.hbs +4 -3
- package/views/partials/side_menu.hbs +0 -4
- package/views/partials/ui/account-picker.hbs +6 -32
- package/views/partials/ui/model-picker.hbs +31 -0
- package/views/partials/ui/pagination.hbs +6 -1
- package/views/partials/ui/picker.hbs +47 -0
- package/views/unsubscribe.hbs +1 -1
- package/workers/api.js +33 -23
- package/workers/export.js +55 -60
- package/workers/imap.js +134 -47
- package/workers/submit.js +3 -1
- package/workers/webhooks.js +46 -27
- package/.githooks/pre-commit +0 -80
- package/.github/CODE_OF_CONDUCT.md +0 -76
- package/.github/contributing.md +0 -17
- package/.github/dependabot.yml +0 -22
- package/.github/docker-smoke-test.sh +0 -61
- package/.github/workflows/deploy.yml +0 -215
- package/.github/workflows/e2e.yml +0 -55
- package/.github/workflows/release.yaml +0 -217
- package/.github/workflows/test.yml +0 -307
- package/lib/api-routes/chat-routes.js +0 -535
- package/lib/append-list.js +0 -63
- package/lib/document-store.js +0 -75
- package/lib/es.js +0 -757
- package/lib/generate-text-preview.js +0 -61
- package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
- package/lib/lua/h-push.lua +0 -32
- package/lib/pre-process.js +0 -196
- package/lib/threads.js +0 -155
- package/lib/ui-routes/document-store-routes.js +0 -806
- package/playwright.config.js +0 -47
- package/views/config/document-store/chat.hbs +0 -286
- package/views/config/document-store/index.hbs +0 -146
- package/views/config/document-store/mappings/index.hbs +0 -108
- package/views/config/document-store/mappings/new.hbs +0 -68
- package/views/config/document-store/pre-processing/index.hbs +0 -103
- package/views/partials/document_store_header.hbs +0 -30
- 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 {
|
|
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
|
-
*
|
|
49
|
-
* refusal. Everything `attempt` throws counts as one: the caller decides what
|
|
50
|
-
* the budget by what it puts in the function, so a refusal that is about the account
|
|
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
|
|
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
|
-
|
|
64
|
-
|
|
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:
|
|
70
|
-
allowed:
|
|
71
|
-
|
|
89
|
+
count: counts[0],
|
|
90
|
+
allowed: AUTH_FAILURE_LIMIT,
|
|
91
|
+
addressCount: counts[1]
|
|
72
92
|
});
|
|
73
93
|
throw limitedError();
|
|
74
94
|
}
|
|
75
95
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
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
|
-
|
|
269
|
-
|
|
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
|
-
|
|
289
|
-
|
|
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
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
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
|
-
|
|
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
|
-
|
|
346
|
-
|
|
347
|
-
return await processAutoconfigFile(email, domain, text, source || 'mozilla');
|
|
364
|
+
return await readDocument(res);
|
|
348
365
|
}
|
|
349
366
|
|
|
350
|
-
async function
|
|
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
|
|
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 || '
|
|
378
|
+
return await processAutoconfigFile(email, domain, text, source || 'mozilla');
|
|
370
379
|
}
|
|
371
380
|
|
|
372
|
-
async function
|
|
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
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
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 || '
|
|
395
|
+
return await processAutoconfigFile(email, domain, text, source || 'autoconfig');
|
|
390
396
|
}
|
|
391
397
|
|
|
392
|
-
async function
|
|
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
|
|
402
|
-
|
|
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(
|
|
406
|
-
|
|
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
|
-
|
|
419
|
+
return null;
|
|
416
420
|
}
|
|
421
|
+
}
|
|
417
422
|
|
|
418
|
-
|
|
419
|
-
|
|
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
|
-
|
|
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
|
-
|
|
449
|
-
let
|
|
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
|
-
|
|
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,
|
|
465
|
-
domain =
|
|
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
|
-
|
|
872
|
-
|
|
873
|
-
|
|
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 {
|
|
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,
|
|
904
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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,
|
|
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),
|
|
1096
|
-
timedFunction(resolveUsingWellKnown(email),
|
|
1097
|
-
timedFunction(resolveUsingAutoconfig(email),
|
|
1098
|
-
timedFunction(resolveUsingMozillaDirectory(email),
|
|
1099
|
-
timedFunction(resolveUsingAutodiscovery(email, credentials),
|
|
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;
|