emailengine-app 2.82.0 → 2.82.2
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 +23 -1
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +51 -0
- package/DOCKER_DEPLOYMENT.md +13 -12
- package/bin/emailengine.js +77 -7
- package/data/google-crawlers.json +1 -1
- package/lib/account.js +35 -10
- package/lib/api-routes/account-binding.js +58 -0
- package/lib/api-routes/account-routes.js +48 -9
- package/lib/api-routes/behavior-notes.js +4 -0
- package/lib/api-routes/gateway-routes.js +10 -2
- package/lib/api-routes/message-routes.js +10 -3
- package/lib/api-routes/outbox-routes.js +1 -1
- package/lib/api-routes/settings-routes.js +1 -2
- package/lib/api-routes/token-routes.js +1 -1
- package/lib/autodetect-imap-settings.js +146 -4
- package/lib/consts.js +12 -0
- package/lib/db.js +1 -19
- package/lib/delivery-error.js +68 -1
- package/lib/email-client/base-client.js +6 -13
- package/lib/email-client/credential-errors.js +21 -5
- package/lib/email-client/gmail-client.js +2 -2
- package/lib/email-client/imap-client.js +2 -1
- package/lib/email-client/message-builder.js +41 -11
- package/lib/email-client/outlook-client.js +263 -84
- package/lib/email-client/outlook-fallback-poll.js +30 -0
- package/lib/enum-descriptions.js +5 -1
- package/lib/export.js +8 -2
- package/lib/gateway.js +5 -0
- package/lib/get-secret.js +1 -21
- package/lib/mcp/tools.js +95 -36
- package/lib/oauth/gmail.js +42 -12
- package/lib/oauth/mail-ru.js +24 -17
- package/lib/oauth/outlook.js +34 -24
- package/lib/oauth/scope-checker.js +35 -1
- package/lib/oauth/scope-list.js +55 -0
- package/lib/oauth/token-fetch.js +47 -0
- package/lib/oauth2-apps.js +16 -47
- package/lib/outbox.js +2 -7
- package/lib/queue-retention.js +4 -2
- package/lib/read-env-value.js +33 -2
- package/lib/schemas.js +62 -15
- package/lib/token-audit-log.js +3 -2
- package/lib/tools.js +1 -1
- package/lib/ui-routes/account-routes.js +40 -7
- package/lib/ui-routes/oauth-config-routes.js +3 -14
- package/lib/ui-routes/outlook-subscription-view.js +36 -0
- package/lib/ui-routes/route-helpers.js +25 -37
- package/lib/ui-routes/special-use-paths.js +33 -0
- package/lib/utils/network.js +9 -17
- package/package.json +18 -18
- package/sbom.json +1 -1
- package/server.js +21 -3
- package/setup-production.sh +16 -7
- package/static/licenses.html +30 -20
- package/translations/messages.pot +74 -56
- package/views/account-workspace-error.hbs +30 -0
- package/views/accounts/account.hbs +14 -6
- package/views/accounts/edit.hbs +11 -2
- package/views/internals/index.hbs +1 -1
- package/views/partials/gmail_api_scopes.hbs +16 -0
- package/views/partials/oauth_form.hbs +67 -94
- package/views/partials/oauth_pubsub_app_select.hbs +43 -0
- package/views/partials/scope_info.hbs +14 -23
- package/workers/api.js +62 -27
- package/workers/imap.js +6 -3
- package/workers/submit.js +2 -5
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The scope list an OAuth2 application actually requests, derived from what is stored on it. Kept in a
|
|
4
|
+
// leaf module because two callers need it from opposite ends of the dependency graph: lib/oauth2-apps.js
|
|
5
|
+
// builds the authentication URL from it, and lib/oauth/scope-checker.js decides from it what an
|
|
6
|
+
// application can do - the latter must not pull the Redis chain in to ask.
|
|
7
|
+
|
|
8
|
+
// The last path segment of a scope URL, which is the short name the scope presets on the OAuth2 app
|
|
9
|
+
// form write into skipScopes ("Mail.ReadWrite", "gmail.modify"). Derived from the scope's own prefix
|
|
10
|
+
// rather than compared against a list of hosts: the Outlook defaults are requested under
|
|
11
|
+
// graph.microsoft.com on the global cloud but under graph.microsoft.us, dod-graph.microsoft.us or
|
|
12
|
+
// microsoftgraph.chinacloudapi.cn on GCC High, DoD and China, and a host list that named only the
|
|
13
|
+
// global one left every default scope of such an application in place.
|
|
14
|
+
function shortScopeName(scope) {
|
|
15
|
+
const separator = scope.lastIndexOf('/');
|
|
16
|
+
return separator < 0 ? scope : scope.slice(separator + 1);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function formatExtraScopes(extraScopes, baseScopes, defaultScopesList, skipScopes, scopePrefix) {
|
|
20
|
+
let defaultScopes;
|
|
21
|
+
|
|
22
|
+
// An empty entry would match the short name of a scope URL ending in a slash
|
|
23
|
+
skipScopes = [].concat(skipScopes || []).filter(entry => entry);
|
|
24
|
+
|
|
25
|
+
if (Array.isArray(defaultScopesList)) {
|
|
26
|
+
defaultScopes = defaultScopesList;
|
|
27
|
+
} else {
|
|
28
|
+
defaultScopes = (baseScopes && defaultScopesList[baseScopes]) || defaultScopesList.imap;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (!extraScopes && !skipScopes.length) {
|
|
32
|
+
return defaultScopes;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
extraScopes = extraScopes || [];
|
|
36
|
+
|
|
37
|
+
let extras = [];
|
|
38
|
+
for (let extraScope of extraScopes) {
|
|
39
|
+
if (defaultScopes.includes(extraScope) || (scopePrefix && defaultScopes.includes(`${scopePrefix}/${extraScope}`))) {
|
|
40
|
+
// skip existing
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
extras.push(extraScope);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
let result = extras.length ? extras.concat(defaultScopes) : defaultScopes;
|
|
47
|
+
|
|
48
|
+
if (skipScopes.length) {
|
|
49
|
+
result = result.filter(scope => !skipScopes.some(skipScope => scope === skipScope || shortScopeName(scope) === skipScope));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return result;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
module.exports = { shortScopeName, formatExtraScopes };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { fetch: fetchCmd } = require('undici');
|
|
4
|
+
const { httpAgent } = require('../tools');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Performs a token-endpoint request, and says which endpoint failed when the request never got there.
|
|
8
|
+
*
|
|
9
|
+
* A rejected response is already described in detail by each provider client (`ETokenRefresh`, the
|
|
10
|
+
* status, the parsed body). A request that never reaches the endpoint is not: undici rejects a failed
|
|
11
|
+
* fetch with a bare `fetch failed` whose own `code` is unset, the reason (ENOTFOUND, ECONNREFUSED,
|
|
12
|
+
* UND_ERR_CONNECT_TIMEOUT, a TLS failure) sitting on `err.cause`. Such a failure is correctly treated
|
|
13
|
+
* as transient - the account reports a connectError and keeps retrying rather than being parked - but
|
|
14
|
+
* the webhook then carried "fetch failed" and no serverResponseCode, which is indistinguishable from
|
|
15
|
+
* the mail server itself being unreachable. That is the one thing it is not.
|
|
16
|
+
*
|
|
17
|
+
* The error is ANNOTATED rather than replaced. Its code and cause are what isTransientNetworkError()
|
|
18
|
+
* reads (lib/email-client/credential-errors.js), and a token endpoint that could not be reached has
|
|
19
|
+
* not refused the refresh token: a replacement error carrying a code of its own would be read as an
|
|
20
|
+
* authentication failure and would park the account.
|
|
21
|
+
*
|
|
22
|
+
* @param {String} url - the token endpoint
|
|
23
|
+
* @param {Object} options - fetch options; the retrying dispatcher is applied here and cannot be overridden
|
|
24
|
+
* @param {Object} context - what to record about the attempt, as the rejected-response path records it.
|
|
25
|
+
* The method is read from `options`, so the two cannot disagree
|
|
26
|
+
* @returns {Promise<Response>} the response, whatever its status
|
|
27
|
+
*/
|
|
28
|
+
async function fetchTokenRequest(url, options, context) {
|
|
29
|
+
try {
|
|
30
|
+
// The dispatcher is applied last, so this helper really is the one place that decides it -
|
|
31
|
+
// with the default first, a caller that passed one would silently lose the retrying agent
|
|
32
|
+
return await fetchCmd(url, Object.assign({}, options, { dispatcher: httpAgent.retry }));
|
|
33
|
+
} catch (err) {
|
|
34
|
+
// The cause carries the actionable code. Promoted onto the error itself so the connectError
|
|
35
|
+
// webhook has something to report - the transient check consults both, so no verdict changes.
|
|
36
|
+
if (!err.code && err.cause && err.cause.code) {
|
|
37
|
+
err.code = err.cause.code;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
err.tokenRequest = Object.assign({ url, method: (options && options.method) || 'get', error: err.message, errorCode: err.code }, context);
|
|
41
|
+
err.message = `Token request to ${url} failed${err.code ? ` [${err.code}]` : ''}: ${(err.cause && err.cause.message) || err.message}`;
|
|
42
|
+
|
|
43
|
+
throw err;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
module.exports = { fetchTokenRequest };
|
package/lib/oauth2-apps.js
CHANGED
|
@@ -44,8 +44,9 @@ function recordTokenMetric(status, provider, statusCode) {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
const { OutlookOauth, outlookScopes } = require('./oauth/outlook');
|
|
47
|
-
const { GmailOauth, GMAIL_SCOPES, parseExternalAccountConfig } = require('./oauth/gmail');
|
|
47
|
+
const { GmailOauth, GMAIL_SCOPES, GMAIL_PROVIDERS, parseExternalAccountConfig } = require('./oauth/gmail');
|
|
48
48
|
const { ExternalAccountSigner } = require('./oauth/external-account-signer');
|
|
49
|
+
const { formatExtraScopes } = require('./oauth/scope-list');
|
|
49
50
|
const crypto = require('crypto');
|
|
50
51
|
const { MailRuOauth, MAIL_RU_SCOPES } = require('./oauth/mail-ru');
|
|
51
52
|
|
|
@@ -121,7 +122,13 @@ function oauth2ProviderData(provider, selector) {
|
|
|
121
122
|
name: 'OAuth2',
|
|
122
123
|
provider,
|
|
123
124
|
caseName,
|
|
124
|
-
comment: OAUTH_PROVIDERS[provider] || caseName
|
|
125
|
+
comment: OAUTH_PROVIDERS[provider] || caseName,
|
|
126
|
+
// Whether this provider can reach Gmail over the HTTP API instead of IMAP, which is what
|
|
127
|
+
// `baseScopes: 'api'` selects. True of both Gmail providers: isApiBasedApp() keys on that
|
|
128
|
+
// field and not on the provider, so a service account delegated gmail.modify is as API-based
|
|
129
|
+
// as an interactive app. The form guards the controls that only make sense in that mode - the
|
|
130
|
+
// scope presets, the Pub/Sub service account - on this rather than on one provider name.
|
|
131
|
+
gmailApi: GMAIL_PROVIDERS.has(provider)
|
|
125
132
|
};
|
|
126
133
|
|
|
127
134
|
switch (provider) {
|
|
@@ -220,50 +227,6 @@ function oauth2ProviderData(provider, selector) {
|
|
|
220
227
|
return providerData;
|
|
221
228
|
}
|
|
222
229
|
|
|
223
|
-
function formatExtraScopes(extraScopes, baseScopes, defaultScopesList, skipScopes, scopePrefix) {
|
|
224
|
-
let defaultScopes;
|
|
225
|
-
|
|
226
|
-
skipScopes = [].concat(skipScopes || []);
|
|
227
|
-
|
|
228
|
-
if (Array.isArray(defaultScopesList)) {
|
|
229
|
-
defaultScopes = defaultScopesList;
|
|
230
|
-
} else {
|
|
231
|
-
defaultScopes = (baseScopes && defaultScopesList[baseScopes]) || defaultScopesList.imap;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
if (!extraScopes && !skipScopes.length) {
|
|
235
|
-
return defaultScopes;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
extraScopes = extraScopes || [];
|
|
239
|
-
|
|
240
|
-
let extras = [];
|
|
241
|
-
for (let extraScope of extraScopes) {
|
|
242
|
-
if (defaultScopes.includes(extraScope) || (scopePrefix && defaultScopes.includes(`${scopePrefix}/${extraScope}`))) {
|
|
243
|
-
// skip existing
|
|
244
|
-
continue;
|
|
245
|
-
}
|
|
246
|
-
extras.push(extraScope);
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
let result = extras.length ? extras.concat(defaultScopes) : defaultScopes;
|
|
250
|
-
|
|
251
|
-
if (skipScopes.length) {
|
|
252
|
-
result = result.filter(
|
|
253
|
-
scope =>
|
|
254
|
-
!skipScopes.some(
|
|
255
|
-
skipScope =>
|
|
256
|
-
scope === skipScope ||
|
|
257
|
-
scope === `https://outlook.office.com/${skipScope}` ||
|
|
258
|
-
scope === `https://graph.microsoft.com/${skipScope}` ||
|
|
259
|
-
scope === `https://www.googleapis.com/auth/${skipScope}`
|
|
260
|
-
)
|
|
261
|
-
);
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
return result;
|
|
265
|
-
}
|
|
266
|
-
|
|
267
230
|
class OAuth2AppsHandler {
|
|
268
231
|
constructor(options) {
|
|
269
232
|
this.options = options || {};
|
|
@@ -1918,7 +1881,13 @@ class OAuth2AppsHandler {
|
|
|
1918
1881
|
}
|
|
1919
1882
|
}
|
|
1920
1883
|
|
|
1921
|
-
//
|
|
1884
|
+
// Whether an app's accounts connect through a provider API rather than IMAP.
|
|
1885
|
+
//
|
|
1886
|
+
// Being a service-account provider does not decide it: a gmailService app with the default
|
|
1887
|
+
// `baseScopes: 'imap'` exchanges its JWT for an IMAP XOAUTH2 credential, which is why the provider
|
|
1888
|
+
// name alone is not on this list. `baseScopes: 'api'` is what makes one API-based, for gmailService as
|
|
1889
|
+
// much as for the interactive gmail app - the schema accepts it, verifyGmailService() probes the Gmail
|
|
1890
|
+
// API for exactly that combination, and these accounts get the Gmail API client.
|
|
1922
1891
|
function isApiBasedApp(app) {
|
|
1923
1892
|
return app && (app.baseScopes === 'api' || app.provider === 'outlookService');
|
|
1924
1893
|
}
|
package/lib/outbox.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const { submitQueue, redis } = require('./db');
|
|
4
4
|
const { REDIS_PREFIX } = require('../lib/consts');
|
|
5
5
|
const msgpack = require('./msgpack');
|
|
6
|
+
const { nextAttemptOfStoredJob } = require('./delivery-error');
|
|
6
7
|
|
|
7
8
|
// Job reads and removals are issued in bounded batches. ioredis writes each command as it is
|
|
8
9
|
// issued, so a batch costs one round trip rather than one per job, while the bound keeps an account
|
|
@@ -48,13 +49,7 @@ function decodeQueueEntry(entryBuf) {
|
|
|
48
49
|
function formatQueueEntry(job) {
|
|
49
50
|
let scheduled = job.timestamp + (Number(job.opts.delay) || 0);
|
|
50
51
|
|
|
51
|
-
let
|
|
52
|
-
// attemptsMade already includes the failed attempt, so the retry delay is 2^(attemptsMade-1) * base
|
|
53
|
-
let nextAttempt = job.attemptsMade ? Math.round(job.processedOn + Math.pow(2, job.attemptsMade - 1) * backoffDelay) : scheduled;
|
|
54
|
-
|
|
55
|
-
if (job.opts.attempts <= job.attemptsMade) {
|
|
56
|
-
nextAttempt = false;
|
|
57
|
-
}
|
|
52
|
+
let nextAttempt = nextAttemptOfStoredJob(job, scheduled);
|
|
58
53
|
|
|
59
54
|
return Object.assign(job.data, {
|
|
60
55
|
created: new Date(Number(job.data.created || job.timestamp)).toISOString(),
|
package/lib/queue-retention.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const { readEnvValue } = require('./read-env-value');
|
|
4
|
+
|
|
3
5
|
// Retention policies for BullMQ job entries.
|
|
4
6
|
//
|
|
5
7
|
// This module is deliberately dependency-free (no Redis, no settings) so it can be unit tested
|
|
@@ -17,8 +19,8 @@ const COMPLETED_JOB_RETENTION_AGE = 24 * 3600;
|
|
|
17
19
|
// Both are overridable because the right bound depends on payload size: a `messageNew` webhook
|
|
18
20
|
// carries up to `notifyTextSize` (2MB by default) of message text, and a receiver that is down
|
|
19
21
|
// turns every event into a retained entry.
|
|
20
|
-
const FAILED_JOB_RETENTION_AGE = Number(
|
|
21
|
-
const FAILED_JOB_RETENTION_COUNT = Number(
|
|
22
|
+
const FAILED_JOB_RETENTION_AGE = Number(readEnvValue('EENGINE_QUEUE_KEEP_FAILED_AGE')) || 7 * 24 * 3600;
|
|
23
|
+
const FAILED_JOB_RETENTION_COUNT = Number(readEnvValue('EENGINE_QUEUE_KEEP_FAILED')) || 500;
|
|
22
24
|
|
|
23
25
|
/**
|
|
24
26
|
* Builds the `removeOnComplete` / `removeOnFail` pair for a queue job.
|
package/lib/read-env-value.js
CHANGED
|
@@ -7,11 +7,27 @@
|
|
|
7
7
|
const Fs = require('fs');
|
|
8
8
|
const logger = require('./logger');
|
|
9
9
|
|
|
10
|
+
// The keys that lib/db.js and lib/get-secret.js used to resolve through private copies of this
|
|
11
|
+
// function. Those copies stripped a single trailing newline and nothing else, so for a file carrying
|
|
12
|
+
// any other surrounding whitespace the value they produced is not the value this helper produces.
|
|
13
|
+
// EENGINE_SECRET is the one that matters: a different secret means every stored credential fails to
|
|
14
|
+
// decrypt, and nothing can repair it automatically, because the old value is the one the data was
|
|
15
|
+
// encrypted with and only the operator knows whether the whitespace belongs to it. So the difference
|
|
16
|
+
// is reported rather than guessed at.
|
|
17
|
+
//
|
|
18
|
+
// The list is closed, not a registry to extend: no other key ever had the old behavior, so warning
|
|
19
|
+
// about one would claim a change that never happened, and no future key can acquire it, because
|
|
20
|
+
// test/read-env-value-guardrail-test.js fails on any module that re-implements the file fallback.
|
|
21
|
+
// It can be deleted outright once upgrading from a release before 2.82.1 is no longer supported.
|
|
22
|
+
const LEGACY_UNTRIMMED_KEYS = new Set(['EENGINE_SECRET', 'EENGINE_REDIS', 'REDIS_URL']);
|
|
23
|
+
|
|
10
24
|
/**
|
|
11
25
|
* Reads an environment value, falling back to the contents of the `<KEY>_FILE` variable.
|
|
12
26
|
*
|
|
13
27
|
* The file form is how secrets are handed to containerized deployments; the resolved value is
|
|
14
|
-
* written back into process.env so the file is read at most once.
|
|
28
|
+
* written back into process.env so the file is read at most once. Surrounding whitespace is trimmed,
|
|
29
|
+
* which is what makes `echo value > file` work, and line endings are normalized so a file written on
|
|
30
|
+
* Windows resolves to the same value as one written anywhere else.
|
|
15
31
|
*
|
|
16
32
|
* @param {string} key - Environment variable name
|
|
17
33
|
* @returns {string|undefined} The value, or undefined when neither form is set
|
|
@@ -24,7 +40,22 @@ function readEnvValue(key) {
|
|
|
24
40
|
if (typeof process.env[`${key}_FILE`] === 'string' && process.env[`${key}_FILE`]) {
|
|
25
41
|
try {
|
|
26
42
|
// try to load from file
|
|
27
|
-
|
|
43
|
+
const contents = Fs.readFileSync(process.env[`${key}_FILE`], 'utf-8');
|
|
44
|
+
const value = contents.replace(/\r?\n/g, '\n').trim();
|
|
45
|
+
process.env[key] = value;
|
|
46
|
+
|
|
47
|
+
// What the private copies in lib/db.js and lib/get-secret.js resolved the same file to.
|
|
48
|
+
// Neither the value nor the whitespace around it is logged: the key and the file are what
|
|
49
|
+
// the operator needs to find it, and the value is what the warning exists to protect.
|
|
50
|
+
const legacyValue = contents.replace(/\r?\n$/, '');
|
|
51
|
+
if (LEGACY_UNTRIMMED_KEYS.has(key) && value !== legacyValue) {
|
|
52
|
+
logger.warn({
|
|
53
|
+
msg: 'Environment value read from file carries whitespace that is now trimmed, so it resolves differently than in earlier releases. Set the variable itself rather than the file to keep the old value, as one given in the environment is used verbatim.',
|
|
54
|
+
key,
|
|
55
|
+
file: process.env[`${key}_FILE`]
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
28
59
|
logger.trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
|
|
29
60
|
} catch (err) {
|
|
30
61
|
logger.error({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
|
package/lib/schemas.js
CHANGED
|
@@ -32,7 +32,7 @@ function formBoolean() {
|
|
|
32
32
|
return Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', '0', 0, '');
|
|
33
33
|
}
|
|
34
34
|
const config = require('@zone-eu/wild-config');
|
|
35
|
-
const { getByteSize } = require('./tools');
|
|
35
|
+
const { getByteSize, readEnvValue } = require('./tools');
|
|
36
36
|
const { COLLAPSE_CLASS, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
|
|
37
37
|
const { locales } = require('./translations');
|
|
38
38
|
const { OAUTH_PROVIDERS } = require('./oauth2-apps');
|
|
@@ -69,7 +69,9 @@ config.api = config.api || {
|
|
|
69
69
|
};
|
|
70
70
|
|
|
71
71
|
const DEFAULT_MAX_ATTACHMENT_SIZE = 5 * 1024 * 1024;
|
|
72
|
-
|
|
72
|
+
// readEnvValue() rather than process.env, so EENGINE_MAX_SIZE_FILE raises the schema's maximum and not
|
|
73
|
+
// only the listener limit that server.js and workers/api.js resolve the same variable for
|
|
74
|
+
const MAX_ATTACHMENT_SIZE = getByteSize(readEnvValue('EENGINE_MAX_SIZE') || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
|
|
73
75
|
|
|
74
76
|
const accountIdSchema = Joi.string().empty('').trim().max(MAX_ACCOUNT_ID_LENGTH).example('user123').description('Unique identifier for the email account');
|
|
75
77
|
|
|
@@ -443,7 +445,7 @@ const settingsSchema = {
|
|
|
443
445
|
.max(1024)
|
|
444
446
|
.example('verysecret')
|
|
445
447
|
.description('Password for SMTP authentication (null = disable authentication)'),
|
|
446
|
-
smtpServerTLSEnabled: formBoolean().description('
|
|
448
|
+
smtpServerTLSEnabled: formBoolean().description('Serve the SMTP submission server over implicit TLS. STARTTLS is never offered'),
|
|
447
449
|
|
|
448
450
|
/* ────────────── TLS Certificates ────────────── */
|
|
449
451
|
|
|
@@ -607,7 +609,19 @@ const settingsSchema = {
|
|
|
607
609
|
|
|
608
610
|
exportMaxMessages: Joi.number().integer().min(1).max(10000000).example(500000).description('Maximum number of messages per export (default: 500000)'),
|
|
609
611
|
|
|
610
|
-
exportMaxSize: Joi.number().integer().min(1).example(10737418240).description('Maximum export file size in bytes (default: 10GB)')
|
|
612
|
+
exportMaxSize: Joi.number().integer().min(1).example(10737418240).description('Maximum export file size in bytes (default: 10GB)'),
|
|
613
|
+
|
|
614
|
+
exportMaxMessageSize: Joi.number()
|
|
615
|
+
.integer()
|
|
616
|
+
.min(1)
|
|
617
|
+
.example(52428800)
|
|
618
|
+
.description('Maximum size of a single message included in an export, in bytes. Larger messages are skipped (default: 50MB)'),
|
|
619
|
+
|
|
620
|
+
exportMaxAge: Joi.number()
|
|
621
|
+
.integer()
|
|
622
|
+
.min(60000)
|
|
623
|
+
.example(86400000)
|
|
624
|
+
.description('How long a finished export is kept before it is deleted, in milliseconds (default: 24 hours)')
|
|
611
625
|
};
|
|
612
626
|
|
|
613
627
|
const addressSchema = Joi.object({
|
|
@@ -618,7 +632,25 @@ const addressSchema = Joi.object({
|
|
|
618
632
|
.label('EmailAddress');
|
|
619
633
|
|
|
620
634
|
// generate a list of boolean values
|
|
621
|
-
|
|
635
|
+
/**
|
|
636
|
+
* Whether a setting is hidden from the published document, which is how a deprecated key stays
|
|
637
|
+
* accepted without being advertised. The one spelling of the check: lib/api-routes/settings-routes.js
|
|
638
|
+
* reads it too, to decide which settings the MCP tools offer.
|
|
639
|
+
*
|
|
640
|
+
* @param {String} key - a settingsSchema key
|
|
641
|
+
* @returns {Boolean}
|
|
642
|
+
*/
|
|
643
|
+
const isHiddenSetting = key => !!settingsSchema[key] && (settingsSchema[key].describe().metas || []).some(meta => meta && meta.swaggerHidden);
|
|
644
|
+
|
|
645
|
+
// The selectors GET /v1/settings takes, one per setting. Built from a fresh apiBoolean(), so the
|
|
646
|
+
// hidden marker on the setting itself did not carry over and the document offered a query argument for
|
|
647
|
+
// every removed feature whose setting is still accepted (documentStoreEnabled and two others).
|
|
648
|
+
const settingsQuerySchema = Object.fromEntries(
|
|
649
|
+
Object.keys(Object.assign({ eventTypes: true }, settingsSchema)).map(key => {
|
|
650
|
+
const selector = apiBoolean().default(false);
|
|
651
|
+
return [key, isHiddenSetting(key) ? selector.meta({ swaggerHidden: true }) : selector];
|
|
652
|
+
})
|
|
653
|
+
);
|
|
622
654
|
|
|
623
655
|
const imapSchema = {
|
|
624
656
|
auth: Joi.object({
|
|
@@ -1311,7 +1343,9 @@ const lastErrorSchema = Joi.object({
|
|
|
1311
1343
|
url: Joi.string().example('https://oauth2.googleapis.com/token').description('OAuth2 token endpoint URL').label('OAuthTokenUrl'),
|
|
1312
1344
|
method: Joi.string().example('post').description('HTTP method used for the token request').label('OAuthTokenMethod'),
|
|
1313
1345
|
grant: Joi.string()
|
|
1314
|
-
|
|
1346
|
+
// client_credentials is what an Outlook application-permission app requests, and the
|
|
1347
|
+
// enum did not admit it although getClientCredentialsToken() has always recorded it
|
|
1348
|
+
.valid('refresh_token', 'authorization_code', 'client_credentials')
|
|
1315
1349
|
.example('refresh_token')
|
|
1316
1350
|
.description('OAuth2 grant type being requested')
|
|
1317
1351
|
.label('OAuthGrant'),
|
|
@@ -1343,6 +1377,16 @@ const lastErrorSchema = Joi.object({
|
|
|
1343
1377
|
.example('AAABhaBPHscAAAAH')
|
|
1344
1378
|
.description('Value of the authorization code or error code related to the failure')
|
|
1345
1379
|
.label('OAuthTokenErrorCode'),
|
|
1380
|
+
// Set instead of `status` when the request never reached the endpoint, so there is no
|
|
1381
|
+
// response to report (fetchTokenRequest() in lib/oauth/token-fetch.js)
|
|
1382
|
+
error: Joi.string()
|
|
1383
|
+
.example('fetch failed')
|
|
1384
|
+
.description('Transport failure message, set when the token endpoint could not be reached at all')
|
|
1385
|
+
.label('OAuthTokenTransportError'),
|
|
1386
|
+
errorCode: Joi.string()
|
|
1387
|
+
.example('ECONNREFUSED')
|
|
1388
|
+
.description('Transport failure code, set when the token endpoint could not be reached at all')
|
|
1389
|
+
.label('OAuthTokenTransportErrorCode'),
|
|
1346
1390
|
flag: Joi.object({
|
|
1347
1391
|
message: Joi.string().example('Please verify the OAuth2 application credentials').description('Description of the application-level problem'),
|
|
1348
1392
|
code: Joi.string().example('INVALID_CLIENT_SECRET').description('Machine-readable code of the application-level problem'),
|
|
@@ -2205,7 +2249,7 @@ const outboxEntrySchema = Joi.object({
|
|
|
2205
2249
|
proxy: Joi.string().allow(null).example('socks5://proxy.example.com:1080').description('Proxy URL used for delivery, or null when no proxy is set'),
|
|
2206
2250
|
localAddress: Joi.string().allow(null).example('198.51.100.24').description('Local IP address used for delivery, or null when not set'),
|
|
2207
2251
|
idempotencyKey: Joi.string().allow(null).max(1024).example('submit-12345').description('Idempotency key provided when the message was submitted'),
|
|
2208
|
-
useStructuredFormat: Joi.boolean().description('Whether
|
|
2252
|
+
useStructuredFormat: Joi.boolean().description('Whether this message is sent to MS Graph as structured JSON instead of raw MIME'),
|
|
2209
2253
|
|
|
2210
2254
|
created: Joi.date().iso().example('2021-02-17T13:43:18.860Z').description('When this message was added to the queue'),
|
|
2211
2255
|
scheduled: Joi.date().iso().example('2021-02-17T13:43:18.860Z').description('Scheduled delivery time'),
|
|
@@ -2235,16 +2279,18 @@ const outboxEntrySchema = Joi.object({
|
|
|
2235
2279
|
error: Joi.object({
|
|
2236
2280
|
message: Joi.string().example('Authentication failed').description('Error description'),
|
|
2237
2281
|
code: Joi.string().example('EAUTH').description('Error code'),
|
|
2238
|
-
statusCode: Joi.number().integer().example(502).description('SMTP response code')
|
|
2239
|
-
networkRouting: Joi.object()
|
|
2240
|
-
.unknown()
|
|
2241
|
-
.allow(null)
|
|
2242
|
-
.example({ localAddress: '198.51.100.24', name: 'relay.example.com' })
|
|
2243
|
-
.description('Network routing information for the failed delivery attempt')
|
|
2244
|
-
.label('OutboxErrorNetworkRouting')
|
|
2282
|
+
statusCode: Joi.number().integer().example(502).description('SMTP response code')
|
|
2245
2283
|
})
|
|
2246
2284
|
.label('OutboxListProgressError')
|
|
2247
|
-
.description('Error details (when status is "error")')
|
|
2285
|
+
.description('Error details (when status is "error")'),
|
|
2286
|
+
// The submit worker writes this beside `error`, not inside it (workers/submit.js). It was
|
|
2287
|
+
// declared one level deeper here, so a client reading the documented location found nothing
|
|
2288
|
+
networkRouting: Joi.object()
|
|
2289
|
+
.unknown()
|
|
2290
|
+
.allow(null)
|
|
2291
|
+
.example({ localAddress: '198.51.100.24', name: 'relay.example.com' })
|
|
2292
|
+
.description('Network routing information for the failed delivery attempt (when status is "error")')
|
|
2293
|
+
.label('OutboxErrorNetworkRouting')
|
|
2248
2294
|
}).label('OutboxEntryProgress')
|
|
2249
2295
|
}).label('OutboxEntry');
|
|
2250
2296
|
|
|
@@ -2603,6 +2649,7 @@ module.exports = {
|
|
|
2603
2649
|
accountSchemas,
|
|
2604
2650
|
addressSchema,
|
|
2605
2651
|
settingsQuerySchema,
|
|
2652
|
+
isHiddenSetting,
|
|
2606
2653
|
imapSchema,
|
|
2607
2654
|
smtpSchema,
|
|
2608
2655
|
oauth2Schema,
|
package/lib/token-audit-log.js
CHANGED
|
@@ -24,6 +24,7 @@ const msgpack = require('./msgpack');
|
|
|
24
24
|
const settings = require('./settings');
|
|
25
25
|
const { REDIS_PREFIX, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
|
|
26
26
|
const { extractMultiError } = require('./redis-operations');
|
|
27
|
+
const { readEnvValue } = require('./read-env-value');
|
|
27
28
|
|
|
28
29
|
// Both overrides below are whole counts that have to be at least 1, and anything else falls back to
|
|
29
30
|
// the default rather than being clamped towards it - "0" is not a request for the smallest possible
|
|
@@ -42,12 +43,12 @@ function positiveInt(value, fallback) {
|
|
|
42
43
|
// per token, so a thousand active tokens cost about 170MB - entries carrying a maximum-length
|
|
43
44
|
// account run some three times that. Raise it against those figures, and against the fact that a log
|
|
44
45
|
// of who read whose mail carries the sensitivity of the mail itself.
|
|
45
|
-
const LOG_ENTRIES = positiveInt(
|
|
46
|
+
const LOG_ENTRIES = positiveInt(readEnvValue('EENGINE_TOKEN_LOG_ENTRIES'), 1000);
|
|
46
47
|
|
|
47
48
|
// How long a token's log survives its last use, in seconds. Refreshed on every write, so this bounds
|
|
48
49
|
// how long a log outlives the credential's activity rather than how long each entry lives - which is
|
|
49
50
|
// the useful bound, because a token nobody has used is a log nobody needs.
|
|
50
|
-
const LOG_AGE = positiveInt(
|
|
51
|
+
const LOG_AGE = positiveInt(readEnvValue('EENGINE_TOKEN_LOG_AGE'), 7 * 24 * 3600);
|
|
51
52
|
|
|
52
53
|
// The largest page the log route will serve. Deliberately not the retention cap: one bounds a single
|
|
53
54
|
// response, the other bounds stored data, and while they were the same constant raising retention
|
package/lib/tools.js
CHANGED
|
@@ -708,7 +708,7 @@ module.exports = {
|
|
|
708
708
|
* notifyTextSize / maxBytes cap is silently ignored on API accounts.
|
|
709
709
|
* Mutates the passed object; only the "plain" and "html" keys are touched,
|
|
710
710
|
* so an id reference or a flag riding on the same object is never clipped.
|
|
711
|
-
* For byte-exact UTF-8 truncation see
|
|
711
|
+
* For byte-exact UTF-8 truncation see capText in lib/mcp/tools.js,
|
|
712
712
|
* a different contract that is kept separate on purpose.
|
|
713
713
|
* @param {Object} textContents Object carrying plain and/or html strings
|
|
714
714
|
* @param {Number} maxBytes Size limit per text type, falsy means no limit
|
|
@@ -18,6 +18,8 @@ const getSecret = require('../get-secret');
|
|
|
18
18
|
const capa = require('../capa');
|
|
19
19
|
const { Account, authFailureDisabledAt, isOperatorDisabled } = require('../account');
|
|
20
20
|
const { formatGmailWatch } = require('../account/account-state');
|
|
21
|
+
const { SPECIAL_USE_PATH_FIELDS } = require('./special-use-paths');
|
|
22
|
+
|
|
21
23
|
const { Gateway } = require('../gateway');
|
|
22
24
|
const { autodetectImapSettings, resolveAppPassword, getAppPassword } = require('../autodetect-imap-settings');
|
|
23
25
|
const { atomicIncrement } = require('../redis-operations');
|
|
@@ -1636,6 +1638,7 @@ function init(args) {
|
|
|
1636
1638
|
|
|
1637
1639
|
menuAccounts: true,
|
|
1638
1640
|
account: accountData,
|
|
1641
|
+
specialUsePathFields: SPECIAL_USE_PATH_FIELDS,
|
|
1639
1642
|
accountAlert,
|
|
1640
1643
|
accountParked: !!disabledByAuthFailureAt,
|
|
1641
1644
|
logs: logInfo,
|
|
@@ -2141,6 +2144,7 @@ function init(args) {
|
|
|
2141
2144
|
|
|
2142
2145
|
menuAccounts: true,
|
|
2143
2146
|
account: request.params.account,
|
|
2147
|
+
specialUsePathFields: SPECIAL_USE_PATH_FIELDS,
|
|
2144
2148
|
values,
|
|
2145
2149
|
availablePaths: JSON.stringify(mailboxes.map(entry => entry.path)),
|
|
2146
2150
|
|
|
@@ -2220,12 +2224,33 @@ function init(args) {
|
|
|
2220
2224
|
|
|
2221
2225
|
let updateKeys = {};
|
|
2222
2226
|
|
|
2223
|
-
for (let key of ['host', 'port', 'disabled'
|
|
2227
|
+
for (let key of ['host', 'port', 'disabled']) {
|
|
2224
2228
|
if (`imap_${key}` in request.payload) {
|
|
2225
2229
|
updateKeys[key] = request.payload[`imap_${key}`];
|
|
2226
2230
|
}
|
|
2227
2231
|
}
|
|
2228
2232
|
|
|
2233
|
+
// The special-use folder overrides. An empty input means "no override" and has to
|
|
2234
|
+
// be written as null to unset one, while a field the form never showed must not be
|
|
2235
|
+
// written at all: these inputs live inside the IMAP section, which is hidden for an
|
|
2236
|
+
// account whose IMAP the operator switched off. The schema therefore allows the
|
|
2237
|
+
// empty string instead of defaulting to null - a default is inserted by joi for
|
|
2238
|
+
// every key the browser did not send, which made the presence check below always
|
|
2239
|
+
// true, so an unrelated save (a rename, a new webhook URL) wiped every override set
|
|
2240
|
+
// over PUT /v1/account/{account}. Same presence test imap_auth_user relies on.
|
|
2241
|
+
for (const field of SPECIAL_USE_PATH_FIELDS) {
|
|
2242
|
+
const payloadKey = `imap_${field.key}`;
|
|
2243
|
+
if (!(payloadKey in request.payload)) {
|
|
2244
|
+
continue;
|
|
2245
|
+
}
|
|
2246
|
+
const value = request.payload[payloadKey] || null;
|
|
2247
|
+
// Written only when the effective value changes, like the TLS flags below: an
|
|
2248
|
+
// untouched save must not add keys, because any imap diff forces a reconnect
|
|
2249
|
+
if (value !== ((oldData.imap && oldData.imap[field.key]) || null)) {
|
|
2250
|
+
updateKeys[field.key] = value;
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
|
|
2229
2254
|
if ('imap_auth_user' in request.payload) {
|
|
2230
2255
|
let imapAuth = Object.assign((oldData.imap && oldData.imap.auth) || {}, { user: request.payload.imap_auth_user });
|
|
2231
2256
|
if (request.payload.imap_auth_pass) {
|
|
@@ -2304,6 +2329,7 @@ function init(args) {
|
|
|
2304
2329
|
|
|
2305
2330
|
menuAccounts: true,
|
|
2306
2331
|
account: request.params.account,
|
|
2332
|
+
specialUsePathFields: SPECIAL_USE_PATH_FIELDS,
|
|
2307
2333
|
// re-render the form from the submitted payload (the field names
|
|
2308
2334
|
// match the template values); without this the form comes back
|
|
2309
2335
|
// blank and the IMAP/SMTP cards disappear entirely
|
|
@@ -2361,6 +2387,7 @@ function init(args) {
|
|
|
2361
2387
|
|
|
2362
2388
|
menuAccounts: true,
|
|
2363
2389
|
account: request.params.account,
|
|
2390
|
+
specialUsePathFields: SPECIAL_USE_PATH_FIELDS,
|
|
2364
2391
|
errors,
|
|
2365
2392
|
// re-render the form from the (raw, unvalidated) submitted
|
|
2366
2393
|
// payload so the entered values and the IMAP/SMTP cards
|
|
@@ -2422,12 +2449,18 @@ function init(args) {
|
|
|
2422
2449
|
|
|
2423
2450
|
imap_resyncDelay: Joi.number().integer().empty(''),
|
|
2424
2451
|
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
.
|
|
2429
|
-
|
|
2430
|
-
|
|
2452
|
+
// allow('') rather than empty('').default(null): see the write loop above, where the
|
|
2453
|
+
// presence of the key is what says the form showed the field at all
|
|
2454
|
+
...Object.fromEntries(
|
|
2455
|
+
SPECIAL_USE_PATH_FIELDS.map(field => [
|
|
2456
|
+
`imap_${field.key}`,
|
|
2457
|
+
Joi.string()
|
|
2458
|
+
.allow('', null)
|
|
2459
|
+
.max(1024)
|
|
2460
|
+
.example(field.label)
|
|
2461
|
+
.description(`${field.description} Leave empty to use the folder EmailEngine detects.`)
|
|
2462
|
+
])
|
|
2463
|
+
),
|
|
2431
2464
|
|
|
2432
2465
|
webhooks: Joi.string()
|
|
2433
2466
|
.uri({
|
|
@@ -17,6 +17,7 @@ const getSecret = require('../get-secret');
|
|
|
17
17
|
const { Account } = require('../account');
|
|
18
18
|
const { oauth2Apps, OAUTH_PROVIDERS, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
|
|
19
19
|
const { verifyOAuth2App } = require('../oauth/verify-app');
|
|
20
|
+
const { isSendOnlyGmailApp } = require('../oauth/scope-checker');
|
|
20
21
|
const { oauthCreateSchema, oauthUpdateSchema, accountIdSchema, formBoolean } = require('../schemas');
|
|
21
22
|
const { throwAsBoom, adminUrl, submittedValues, windowedPageLinks } = require('./route-helpers');
|
|
22
23
|
|
|
@@ -433,20 +434,8 @@ function init(args) {
|
|
|
433
434
|
disabledScopes.Gmail_Modify = true;
|
|
434
435
|
}
|
|
435
436
|
|
|
436
|
-
//
|
|
437
|
-
let isSendOnlyGmail =
|
|
438
|
-
if (app.provider === 'gmail' && app.baseScopes === 'api') {
|
|
439
|
-
// Build scope list from extraScopes (short form or full URLs)
|
|
440
|
-
const scopes = (app.extraScopes || []).map(scope => (scope.startsWith('https://') ? scope : `https://www.googleapis.com/auth/${scope}`));
|
|
441
|
-
|
|
442
|
-
// Use Account class helper to check scopes - no need to create full Account instance
|
|
443
|
-
const accountHelper = new Account({ redis, secret: await getSecret() });
|
|
444
|
-
const { hasSendScope, hasReadScope } = accountHelper.checkAccountScopes('gmail', scopes);
|
|
445
|
-
|
|
446
|
-
if (hasSendScope && !hasReadScope) {
|
|
447
|
-
isSendOnlyGmail = true;
|
|
448
|
-
}
|
|
449
|
-
}
|
|
437
|
+
// Covers both Gmail providers: the mode is decided by baseScopes, not by the provider
|
|
438
|
+
let isSendOnlyGmail = isSendOnlyGmailApp(app);
|
|
450
439
|
|
|
451
440
|
if (app.pubSubApp) {
|
|
452
441
|
let pubSubApp = await oauth2Apps.get(app.pubSubApp);
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { FALLBACK_POLL_INTERVAL } = require('../email-client/outlook-fallback-poll');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Adds the fields the account page renders for a Graph change subscription, in place
|
|
7
|
+
* @param {Object} subscription - The account's stored `outlookSubscription`
|
|
8
|
+
* @param {string} accountState - The account's connection state
|
|
9
|
+
* @returns {Object} The same subscription object
|
|
10
|
+
*/
|
|
11
|
+
function formatOutlookSubscription(subscription, accountState) {
|
|
12
|
+
const state = subscription.state || {};
|
|
13
|
+
const expires = subscription.expirationDateTime;
|
|
14
|
+
|
|
15
|
+
subscription.subscriptionExpiresStr = expires ? expires.toISOString() : false;
|
|
16
|
+
subscription.isValid = state.state !== 'error' && expires && expires > new Date();
|
|
17
|
+
|
|
18
|
+
subscription.stateLabel = (state.state || '').replace(/^./, c => c.toUpperCase());
|
|
19
|
+
if ((state.state === 'created' && !expires) || expires < new Date()) {
|
|
20
|
+
subscription.stateLabel = 'Expired';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// See OutlookClient.reportSubscriptionFailure()
|
|
24
|
+
subscription.polling = state.state === 'error' && accountState === 'connected' && !!FALLBACK_POLL_INTERVAL;
|
|
25
|
+
|
|
26
|
+
// One severity for the badge and the alert: a failure the poller stands in for is a warning
|
|
27
|
+
if (subscription.isValid) {
|
|
28
|
+
subscription.variant = 'success';
|
|
29
|
+
} else {
|
|
30
|
+
subscription.variant = state.state === 'error' && !subscription.polling ? 'error' : 'warning';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return subscription;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
module.exports = { formatOutlookSubscription };
|