emailengine-app 2.77.0 → 2.78.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/.github/workflows/test.yml +80 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +31 -0
- package/bin/emailengine.js +1 -1
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +1 -1
- package/lib/account/expected-identity.js +88 -0
- package/lib/account.js +75 -26
- package/lib/api-reference/format.js +14 -0
- package/lib/api-reference/index.js +24 -7
- package/lib/api-reference/model.js +4 -2
- package/lib/api-routes/account-routes.js +19 -2
- package/lib/api-routes/behavior-notes.js +3 -0
- package/lib/append-list.js +3 -14
- package/lib/arf-detect.js +23 -1
- package/lib/autodetect-imap-settings.js +40 -16
- package/lib/base32.js +30 -0
- package/lib/bounce-detect.js +182 -62
- package/lib/egress-filter.js +89 -8
- package/lib/email-client/base-client.js +8 -72
- package/lib/email-client/gmail-client.js +3 -3
- package/lib/email-client/imap/listing-diff.js +3 -3
- package/lib/email-client/imap/mailbox.js +5 -69
- package/lib/email-client/imap-client.js +3 -2
- package/lib/email-client/message-builder.js +13 -13
- package/lib/email-client/outlook-client.js +1 -1
- package/lib/export.js +1 -1
- package/lib/gateway.js +1 -1
- package/lib/get-raw-email.js +1 -1
- package/lib/imapproxy/imap-core/lib/imap-connection.js +2 -2
- package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
- package/lib/imapproxy/imap-server.js +13 -3
- package/lib/license-beacon.js +1 -1
- package/lib/llm-pre-process.js +1 -1
- package/lib/msgpack.js +62 -0
- package/lib/oauth/decode-jwt-payload.js +39 -0
- package/lib/oauth/outlook-identity.js +61 -0
- package/lib/oauth/retry-setup.js +38 -0
- package/lib/oauth2-apps.js +1 -1
- package/lib/outbox.js +66 -3
- package/lib/pre-process.js +1 -1
- package/lib/read-env-value.js +37 -0
- package/lib/schemas.js +12 -0
- package/lib/templates.js +1 -1
- package/lib/tokens.js +1 -1
- package/lib/tools.js +117 -48
- package/lib/totp.js +67 -0
- package/lib/ui-routes/account-routes.js +91 -15
- package/lib/ui-routes/admin-config-routes.js +2 -7
- package/lib/ui-routes/auth-routes.js +6 -24
- package/lib/ui-routes/reference-routes.js +8 -5
- package/lib/ui-routes/route-helpers.js +28 -0
- package/lib/utils/is-email.js +34 -0
- package/lib/utils/to-camel-case.js +17 -0
- package/lib/webhook-egress.js +37 -0
- package/lib/webhooks.js +1 -1
- package/package.json +22 -24
- package/sbom.json +1 -0
- package/server.js +1 -1
- package/static/css/flyonui.css +1 -1
- package/static/css/public.css +3 -0
- package/static/css/src/app.tailwind.css +23 -0
- package/static/js/app.js +69 -0
- package/static/js/reference.js +286 -1
- package/static/licenses.html +656 -1558
- package/translations/README.md +64 -0
- package/translations/de.mo +0 -0
- package/translations/de.po +164 -120
- package/translations/en.po +200 -161
- package/translations/et.mo +0 -0
- package/translations/et.po +163 -120
- package/translations/fr.mo +0 -0
- package/translations/fr.po +163 -120
- package/translations/ja.mo +0 -0
- package/translations/ja.po +163 -120
- package/translations/messages.pot +76 -46
- package/translations/nl.mo +0 -0
- package/translations/nl.po +164 -120
- package/translations/pl.mo +0 -0
- package/translations/pl.po +163 -120
- package/views/account-identity-error.hbs +34 -0
- package/views/accounts/edit.hbs +1 -0
- package/views/accounts/register/imap.hbs +12 -2
- package/views/layout/app.hbs +29 -5
- package/views/oauth-scope-error.hbs +1 -1
- package/views/partials/reference/nav.hbs +36 -9
- package/views/partials/reference/operation.hbs +1 -1
- package/views/partials/reference/schema-node.hbs +1 -1
- package/views/partials/reference/token-alert.hbs +35 -10
- package/views/reference/index.hbs +1 -1
- package/workers/api.js +157 -87
- package/workers/imap.js +1 -1
- package/workers/submit.js +1 -1
- package/workers/webhooks.js +2 -13
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Builds the pending-setup record for a retry after an OAuth2 attempt the user can correct themselves -
|
|
4
|
+
// a consent screen with permissions unchecked, or signing in as an account the setup link is not pinned
|
|
5
|
+
// to. The retry is a fresh single-use setup, so it needs a record of its own.
|
|
6
|
+
//
|
|
7
|
+
// The subtlety is which parts of the rejected attempt to carry over. By the time either failure is
|
|
8
|
+
// detected, the provider branches have already rewritten accountData from whoever actually signed in:
|
|
9
|
+
// `email` holds the authenticated address, `name` may hold their display name, and `oauth2` holds their
|
|
10
|
+
// tokens. Copying that wholesale would let a rejected identity leak into the account the retry creates,
|
|
11
|
+
// while rebuilding from scratch would drop what the caller actually asked for.
|
|
12
|
+
//
|
|
13
|
+
// So the tokens go, and the caller's own intent comes back:
|
|
14
|
+
//
|
|
15
|
+
// oauth2.auth.delegatedUser - names the MAILBOX TO BIND, not a credential. Dropping it silently turns a
|
|
16
|
+
// shared-mailbox setup into a personal one, so the retry would bind the
|
|
17
|
+
// principal's own mailbox while reporting success.
|
|
18
|
+
// email - for a delegated setup this is the shared mailbox, and both delegation
|
|
19
|
+
// paths in the Outlook branch key on it. Overwriting it with the address
|
|
20
|
+
// the user is being steered towards breaks them.
|
|
21
|
+
// name - filled in from the signed-in profile when the caller supplied none, and
|
|
22
|
+
// kept by `name || profile.name` on the retry, so the rejected user's
|
|
23
|
+
// display name would stick to the account and become its From name.
|
|
24
|
+
//
|
|
25
|
+
// `_meta` rides along unchanged: it carries the redirect URL, the expected identity and the single-use
|
|
26
|
+
// form nonce, which is claimed only on success and so is still unspent here.
|
|
27
|
+
function buildRetrySetup(accountData, requestedSetup, provider, accountMeta) {
|
|
28
|
+
const { email, name, delegatedUser } = requestedSetup || {};
|
|
29
|
+
|
|
30
|
+
return Object.assign({}, accountData, {
|
|
31
|
+
oauth2: delegatedUser ? { provider, auth: { delegatedUser } } : { provider },
|
|
32
|
+
email,
|
|
33
|
+
name,
|
|
34
|
+
_meta: accountMeta
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = { buildRetrySetup };
|
package/lib/oauth2-apps.js
CHANGED
package/lib/outbox.js
CHANGED
|
@@ -3,6 +3,15 @@
|
|
|
3
3
|
const { submitQueue, redis } = require('./db');
|
|
4
4
|
const { REDIS_PREFIX } = require('../lib/consts');
|
|
5
5
|
|
|
6
|
+
// Job removals are issued in bounded batches. ioredis writes each command as it is issued, so a
|
|
7
|
+
// batch costs one round trip rather than one per job, while the bound keeps an account with a huge
|
|
8
|
+
// outbox from putting an unlimited number of Lua scripts in flight at once.
|
|
9
|
+
const REMOVE_BATCH_SIZE = 100;
|
|
10
|
+
|
|
11
|
+
function outboxKey(account) {
|
|
12
|
+
return `${REDIS_PREFIX}iaq:${account}`;
|
|
13
|
+
}
|
|
14
|
+
|
|
6
15
|
function formatQueueEntry(job) {
|
|
7
16
|
let scheduled = job.timestamp + (Number(job.opts.delay) || 0);
|
|
8
17
|
|
|
@@ -76,7 +85,7 @@ async function del(options) {
|
|
|
76
85
|
|
|
77
86
|
// Delete message content
|
|
78
87
|
try {
|
|
79
|
-
let res = await redis.hdel(
|
|
88
|
+
let res = await redis.hdel(outboxKey(job.data.account), job.data.queueId);
|
|
80
89
|
logger.info({ msg: 'Removed queued message', res, account: job.data.account, queueId: job.data.queueId, messageId: job.data.messageId });
|
|
81
90
|
} catch (err) {
|
|
82
91
|
logger.error({ msg: 'Failed to remove queued message', account: job.data.account, queueId: job.data.queueId, messageId: job.data.messageId, err });
|
|
@@ -109,7 +118,7 @@ async function get(options) {
|
|
|
109
118
|
}
|
|
110
119
|
|
|
111
120
|
try {
|
|
112
|
-
let queueEntryBuf = await redis.hgetBuffer(
|
|
121
|
+
let queueEntryBuf = await redis.hgetBuffer(outboxKey(job.data.account), job.data.queueId);
|
|
113
122
|
if (!queueEntryBuf) {
|
|
114
123
|
return false;
|
|
115
124
|
}
|
|
@@ -121,4 +130,58 @@ async function get(options) {
|
|
|
121
130
|
return formatQueueEntry(job);
|
|
122
131
|
}
|
|
123
132
|
|
|
124
|
-
|
|
133
|
+
/**
|
|
134
|
+
* Removes the submit queue jobs of messages that were queued for an account that no longer exists.
|
|
135
|
+
*
|
|
136
|
+
* Deleting an account removes the message content, but the queue job pointing at it is a separate
|
|
137
|
+
* structure that the deletion does not touch, and its job data still carries the envelope, the
|
|
138
|
+
* subject and the message ID. A job that is merely waiting cleans itself up the moment it runs,
|
|
139
|
+
* because the worker finds no content and returns, but a *delayed* job does not run until its
|
|
140
|
+
* `sendAt`, which the API caller chooses and which can be arbitrarily far in the future. Without
|
|
141
|
+
* this, a message scheduled for next year would keep its recipient addresses and subject line in
|
|
142
|
+
* Redis for that long after the account was erased.
|
|
143
|
+
*
|
|
144
|
+
* The `notify` queue is deliberately not handled the same way. Webhook entries for a deleted
|
|
145
|
+
* account are never delivered, as the notify worker checks that the account still exists before
|
|
146
|
+
* doing anything, and the entries that do not clean themselves up - deliveries that already failed
|
|
147
|
+
* permanently - are bounded by EENGINE_QUEUE_KEEP_FAILED_AGE. They are inert and self-expiring,
|
|
148
|
+
* whereas finding them would mean matching on job payloads that BullMQ reads inside a blocking Lua
|
|
149
|
+
* script. Submit jobs that already reached the failed set are bounded the same way, and are left
|
|
150
|
+
* alone for the same reason.
|
|
151
|
+
*
|
|
152
|
+
* @param {String[]} queueIds - Queue IDs, which are also the submit queue job IDs
|
|
153
|
+
* @param {Object} options - Options
|
|
154
|
+
* @param {String} options.account - Account ID, for logging
|
|
155
|
+
* @param {Object} options.logger - Logger instance
|
|
156
|
+
* @returns {Promise<Number>} Number of jobs removed. A job a worker holds the lock on is left
|
|
157
|
+
* behind, which is harmless: the worker finds no content for it and completes without sending.
|
|
158
|
+
*/
|
|
159
|
+
async function removeJobs(queueIds, options) {
|
|
160
|
+
const { account, logger } = options;
|
|
161
|
+
|
|
162
|
+
let removed = 0;
|
|
163
|
+
|
|
164
|
+
for (let i = 0; i < queueIds.length; i += REMOVE_BATCH_SIZE) {
|
|
165
|
+
let batch = queueIds.slice(i, i + REMOVE_BATCH_SIZE);
|
|
166
|
+
|
|
167
|
+
let results = await Promise.all(
|
|
168
|
+
batch.map(async queueId => {
|
|
169
|
+
try {
|
|
170
|
+
// Removes by ID without loading the job payload, and returns 0 instead of
|
|
171
|
+
// throwing when a worker holds the job lock. Submit jobs are never flow nodes,
|
|
172
|
+
// so skipping the child lookups saves five Redis calls per job.
|
|
173
|
+
return await submitQueue.remove(queueId, { removeChildren: false });
|
|
174
|
+
} catch (err) {
|
|
175
|
+
logger.error({ msg: 'Failed to remove queued message job', account, queueId, err });
|
|
176
|
+
return 0;
|
|
177
|
+
}
|
|
178
|
+
})
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
removed += results.filter(code => code === 1).length;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return removed;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
module.exports = { list, del, get, removeJobs };
|
package/lib/pre-process.js
CHANGED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Split out of lib/tools.js so modules that resolve configuration during their own initialization
|
|
4
|
+
// can read it without pulling in the whole utility surface (and without the import cycle that
|
|
5
|
+
// would create). Still re-exported from lib/tools.js, which is where most callers reach it.
|
|
6
|
+
|
|
7
|
+
const Fs = require('fs');
|
|
8
|
+
const logger = require('./logger');
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Reads an environment value, falling back to the contents of the `<KEY>_FILE` variable.
|
|
12
|
+
*
|
|
13
|
+
* 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.
|
|
15
|
+
*
|
|
16
|
+
* @param {string} key - Environment variable name
|
|
17
|
+
* @returns {string|undefined} The value, or undefined when neither form is set
|
|
18
|
+
*/
|
|
19
|
+
function readEnvValue(key) {
|
|
20
|
+
if (key in process.env) {
|
|
21
|
+
return process.env[key];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (typeof process.env[`${key}_FILE`] === 'string' && process.env[`${key}_FILE`]) {
|
|
25
|
+
try {
|
|
26
|
+
// try to load from file
|
|
27
|
+
process.env[key] = Fs.readFileSync(process.env[`${key}_FILE`], 'utf-8').replace(/\r?\n/g, '\n').trim();
|
|
28
|
+
logger.trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
|
|
29
|
+
} catch (err) {
|
|
30
|
+
logger.fatal({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
|
|
31
|
+
process.env[key] = '';
|
|
32
|
+
}
|
|
33
|
+
return process.env[key];
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
module.exports = { readEnvValue };
|
package/lib/schemas.js
CHANGED
|
@@ -1563,6 +1563,13 @@ const messageUpdateSchema = Joi.object({
|
|
|
1563
1563
|
}
|
|
1564
1564
|
});
|
|
1565
1565
|
|
|
1566
|
+
// The update variant below is derived from this one, so the two cannot drift apart in the published API
|
|
1567
|
+
// document - only the "how to clear it" sentence differs.
|
|
1568
|
+
const EXPECTED_EMAIL_DESCRIPTION =
|
|
1569
|
+
'Pins the account to an email address. A hosted authentication form setup is rejected unless the identity it authenticates matches this address. For OAuth2 the address is compared against what the provider returns, never against caller-supplied hints, so for a shared or delegated mailbox this must be the authenticating principal rather than the mailbox address. For IMAP it is compared against the address entered on the form, which the credentials do not prove ownership of. Once set, the constraint stays on the account and applies to later reauthentication as well.';
|
|
1570
|
+
|
|
1571
|
+
const expectedEmailSchema = Joi.string().empty('').email().example('user@example.com').description(EXPECTED_EMAIL_DESCRIPTION);
|
|
1572
|
+
|
|
1566
1573
|
const accountSchemas = {
|
|
1567
1574
|
syncFrom: Joi.date()
|
|
1568
1575
|
.iso()
|
|
@@ -1586,6 +1593,11 @@ const accountSchemas = {
|
|
|
1586
1593
|
)
|
|
1587
1594
|
.label('SubconnectionPaths'),
|
|
1588
1595
|
|
|
1596
|
+
expectedEmail: expectedEmailSchema,
|
|
1597
|
+
|
|
1598
|
+
// Same field on the update endpoint, where null clears the constraint.
|
|
1599
|
+
expectedEmailUpdate: expectedEmailSchema.allow(null).description(`${EXPECTED_EMAIL_DESCRIPTION} Set to \`null\` to remove the constraint.`),
|
|
1600
|
+
|
|
1589
1601
|
imapIndexer: Joi.string()
|
|
1590
1602
|
.empty('')
|
|
1591
1603
|
.trim()
|
package/lib/templates.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
const { redis } = require('./db');
|
|
4
|
-
const msgpack = require('
|
|
4
|
+
const msgpack = require('./msgpack');
|
|
5
5
|
const logger = require('./logger');
|
|
6
6
|
const { REDIS_PREFIX } = require('./consts');
|
|
7
7
|
const { filterListPage } = require('./tools');
|
package/lib/tokens.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
const { redis } = require('./db');
|
|
4
4
|
const crypto = require('crypto');
|
|
5
|
-
const msgpack = require('
|
|
5
|
+
const msgpack = require('./msgpack');
|
|
6
6
|
const logger = require('./logger');
|
|
7
7
|
const { REDIS_PREFIX } = require('./consts');
|
|
8
8
|
const { constantTimeEqual, filterListPage } = require('./tools');
|
package/lib/tools.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
'use strict';
|
|
4
4
|
|
|
5
|
-
const msgpack = require('
|
|
5
|
+
const msgpack = require('./msgpack');
|
|
6
6
|
const enumMessageFlags = require('./enum-message-flags');
|
|
7
7
|
const Joi = require('joi');
|
|
8
8
|
const he = require('he');
|
|
@@ -27,6 +27,8 @@ const pathlib = require('path');
|
|
|
27
27
|
const { randomUUID: uuid } = require('crypto');
|
|
28
28
|
const mimeTypes = require('nodemailer/lib/mime-funcs/mime-types');
|
|
29
29
|
const { v3: murmurhash } = require('murmurhash');
|
|
30
|
+
const { isEmail } = require('./utils/is-email');
|
|
31
|
+
const { toCamelCase } = require('./utils/to-camel-case');
|
|
30
32
|
const { compare: compareVersions, validate: validateVersion } = require('compare-versions');
|
|
31
33
|
const {
|
|
32
34
|
REDIS_PREFIX,
|
|
@@ -49,6 +51,8 @@ const { getLocalAddress } = require('./utils/network');
|
|
|
49
51
|
const { fetch: fetchCmd, Agent, RetryAgent, ProxyAgent } = require('undici');
|
|
50
52
|
const tls = require('tls');
|
|
51
53
|
const { SocksClient } = require('socks');
|
|
54
|
+
const { createWebhookLookup, WEBHOOK_EGRESS_POLICY } = require('./webhook-egress');
|
|
55
|
+
const { readEnvValue } = require('./read-env-value');
|
|
52
56
|
|
|
53
57
|
const AGENT_OPTS = {
|
|
54
58
|
strictContentLength: false,
|
|
@@ -82,19 +86,46 @@ const RETRY_OPTS = {
|
|
|
82
86
|
]
|
|
83
87
|
};
|
|
84
88
|
|
|
89
|
+
// Webhook deliveries are the one outbound path whose destination the operator supplies, so they
|
|
90
|
+
// get a dispatcher that resolves through the egress policy (lib/webhook-egress.js) rather than the
|
|
91
|
+
// shared resolver. It is built here because its lifetime is tied to the other agents': a proxy
|
|
92
|
+
// setting change swaps them all out together.
|
|
93
|
+
function buildWebhookDispatcher(proxied, existing) {
|
|
94
|
+
const lookup = createWebhookLookup();
|
|
95
|
+
|
|
96
|
+
// Behind a proxy the target hostname is resolved by the proxy, not here, so a local lookup can
|
|
97
|
+
// only vet the route to the proxy itself. There is nothing to bind; fall back to the shared
|
|
98
|
+
// dispatcher and leave assertAllowedUrl() as the advisory check it can only be in that setup.
|
|
99
|
+
if (proxied || !lookup) {
|
|
100
|
+
return httpAgent.retry;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Nothing a reload changes can affect a dedicated dispatcher - the policy is fixed at startup
|
|
104
|
+
// and the Agent never references httpAgent.fetch - so reuse it rather than discarding warm
|
|
105
|
+
// sockets. Saving the network settings form reloads on any field, not just a proxy one.
|
|
106
|
+
return existing || new RetryAgent(new Agent(Object.assign({}, AGENT_OPTS, { connect: { lookup } })), RETRY_OPTS);
|
|
107
|
+
}
|
|
108
|
+
|
|
85
109
|
// Shared mutable object -- consumers import the object reference and access
|
|
86
|
-
// .fetch / .retry at call time, so replacing properties here is visible everywhere.
|
|
110
|
+
// .fetch / .retry / .webhook at call time, so replacing properties here is visible everywhere.
|
|
87
111
|
const httpAgent = {
|
|
88
112
|
fetch: new Agent(AGENT_OPTS),
|
|
89
|
-
retry: null
|
|
113
|
+
retry: null,
|
|
114
|
+
webhook: null
|
|
90
115
|
};
|
|
91
116
|
httpAgent.retry = new RetryAgent(httpAgent.fetch, RETRY_OPTS);
|
|
117
|
+
httpAgent.webhook = buildWebhookDispatcher(false, null);
|
|
92
118
|
|
|
93
119
|
// Backward-compat aliases (read from httpAgent at call time via getter)
|
|
94
120
|
// backward-compat aliases are defined as getters on module.exports below
|
|
95
121
|
|
|
96
122
|
const SOCKS4_PROTOCOLS = new Set(['socks4:', 'socks4a:']);
|
|
97
123
|
|
|
124
|
+
// Accounts a stale-useAuthServer warning was already logged for, keyed by account:target.
|
|
125
|
+
// getActiveAccessTokenData() runs once per API request, so an unconditional warn would repeat
|
|
126
|
+
// the same line for the lifetime of the stale flag.
|
|
127
|
+
const AUTH_SERVER_FALLBACK_WARNED = new Set();
|
|
128
|
+
|
|
98
129
|
function createSocksAgent(proxyUrl, agentOpts) {
|
|
99
130
|
let parsed = new URL(proxyUrl);
|
|
100
131
|
let proxyType = SOCKS4_PROTOCOLS.has(parsed.protocol) ? 4 : 5;
|
|
@@ -194,6 +225,9 @@ async function _doReloadHttpProxyAgent() {
|
|
|
194
225
|
}
|
|
195
226
|
|
|
196
227
|
let oldFetch = httpAgent.fetch;
|
|
228
|
+
// Only a dedicated dispatcher is ours to close; when webhooks share the general one it is
|
|
229
|
+
// closed via oldFetch. Read before anything is swapped, while the comparison still holds.
|
|
230
|
+
let oldWebhook = httpAgent.webhook !== httpAgent.retry ? httpAgent.webhook : null;
|
|
197
231
|
|
|
198
232
|
try {
|
|
199
233
|
if (enabled && proxyUrl) {
|
|
@@ -217,20 +251,27 @@ async function _doReloadHttpProxyAgent() {
|
|
|
217
251
|
}
|
|
218
252
|
|
|
219
253
|
httpAgent.retry = new RetryAgent(httpAgent.fetch, RETRY_OPTS);
|
|
254
|
+
httpAgent.webhook = buildWebhookDispatcher(!!(enabled && proxyUrl), oldWebhook);
|
|
220
255
|
|
|
221
256
|
logger.info({
|
|
222
257
|
msg: 'HTTP proxy agent reloaded',
|
|
223
258
|
httpProxyEnabled: !!enabled,
|
|
224
|
-
httpProxyUrl: enabled && proxyUrl ? proxyUrl : null
|
|
259
|
+
httpProxyUrl: enabled && proxyUrl ? proxyUrl : null,
|
|
260
|
+
webhookEgressPolicy: WEBHOOK_EGRESS_POLICY,
|
|
261
|
+
webhookEgressPinned: httpAgent.webhook !== httpAgent.retry
|
|
225
262
|
});
|
|
226
263
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
264
|
+
// Closing is graceful, so it waits for whatever is still in flight to drain. Overlap the
|
|
265
|
+
// two rather than making one agent's slow request hold the other's sockets open.
|
|
266
|
+
// Closing a RetryAgent closes the Agent it wraps.
|
|
267
|
+
await Promise.all(
|
|
268
|
+
[
|
|
269
|
+
[oldFetch, httpAgent.fetch],
|
|
270
|
+
[oldWebhook, httpAgent.webhook]
|
|
271
|
+
]
|
|
272
|
+
.filter(([stale, current]) => stale && stale !== current)
|
|
273
|
+
.map(([stale]) => stale.close().catch(() => false))
|
|
274
|
+
);
|
|
234
275
|
} catch (err) {
|
|
235
276
|
logger.error({ msg: 'Failed to create HTTP proxy agent, keeping existing agent', err });
|
|
236
277
|
}
|
|
@@ -278,6 +319,9 @@ function resolveOAuthErrorStatus(responseError, err) {
|
|
|
278
319
|
}
|
|
279
320
|
|
|
280
321
|
module.exports = {
|
|
322
|
+
// keep the re-export, lib/utils/to-camel-case.js holds it so pure modules can use it too
|
|
323
|
+
toCamelCase,
|
|
324
|
+
|
|
281
325
|
/**
|
|
282
326
|
* Establish an admin session: every full session write goes through here
|
|
283
327
|
* so the session always carries a random sid. The message browser binds
|
|
@@ -614,6 +658,63 @@ module.exports = {
|
|
|
614
658
|
return value;
|
|
615
659
|
},
|
|
616
660
|
|
|
661
|
+
// Whether a `useAuthServer` flag should be honored. The flag was accepted and stored but
|
|
662
|
+
// silently ignored on several code paths for years, so long-lived instances carry it on
|
|
663
|
+
// accounts that were never auth-server backed and sync fine on their stored credentials.
|
|
664
|
+
// Honoring such a stale flag on an instance with no auth server configured can only fail,
|
|
665
|
+
// so when the caller has stored credentials to fall back to, the flag is ignored with a
|
|
666
|
+
// warning instead of parking the account. Call sites use the useAuthServerForOAuth2() /
|
|
667
|
+
// useAuthServerForConnection() wrappers below, which pair the config shape with the right
|
|
668
|
+
// credential predicate.
|
|
669
|
+
async shouldUseAuthServer(hasStoredCredentials, logger, meta) {
|
|
670
|
+
if (!hasStoredCredentials) {
|
|
671
|
+
// Nothing to fall back to - consult the auth server and let resolveCredentials()
|
|
672
|
+
// report the missing configuration.
|
|
673
|
+
return true;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
if (await settings.get('authServer')) {
|
|
677
|
+
return true;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
const warnKey = `${meta && meta.account}:${meta && meta.target}`;
|
|
681
|
+
if (!AUTH_SERVER_FALLBACK_WARNED.has(warnKey)) {
|
|
682
|
+
AUTH_SERVER_FALLBACK_WARNED.add(warnKey);
|
|
683
|
+
logger.warn({
|
|
684
|
+
msg: 'Ignoring the useAuthServer flag: no authentication server is configured, using stored credentials instead',
|
|
685
|
+
...meta
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
return false;
|
|
690
|
+
},
|
|
691
|
+
|
|
692
|
+
// Whether an oauth2 block holds tokens EmailEngine can use on its own: a refresh token to
|
|
693
|
+
// renew from, or an access token that may still be valid. Only the top-level fields count -
|
|
694
|
+
// the renew and cached-token paths never read tokens nested under `auth`.
|
|
695
|
+
hasStoredOAuth2Tokens(oauth2Data) {
|
|
696
|
+
return Boolean(oauth2Data.refreshToken || oauth2Data.accessToken);
|
|
697
|
+
},
|
|
698
|
+
|
|
699
|
+
// Whether an imap/smtp connection config carries complete stored credentials.
|
|
700
|
+
hasStoredServerCredentials(connectionConfig) {
|
|
701
|
+
const auth = connectionConfig.auth;
|
|
702
|
+
return Boolean(auth && auth.user && (auth.pass || auth.accessToken));
|
|
703
|
+
},
|
|
704
|
+
|
|
705
|
+
// Should this oauth2 block be resolved through the external auth server?
|
|
706
|
+
async useAuthServerForOAuth2(oauth2Data, logger, meta) {
|
|
707
|
+
return Boolean(oauth2Data.useAuthServer) && (await module.exports.shouldUseAuthServer(module.exports.hasStoredOAuth2Tokens(oauth2Data), logger, meta));
|
|
708
|
+
},
|
|
709
|
+
|
|
710
|
+
// Should this imap/smtp connection config be resolved through the external auth server?
|
|
711
|
+
async useAuthServerForConnection(connectionConfig, logger, meta) {
|
|
712
|
+
return (
|
|
713
|
+
Boolean(connectionConfig.useAuthServer) &&
|
|
714
|
+
(await module.exports.shouldUseAuthServer(module.exports.hasStoredServerCredentials(connectionConfig), logger, meta))
|
|
715
|
+
);
|
|
716
|
+
},
|
|
717
|
+
|
|
617
718
|
getWorkerCount(processCount) {
|
|
618
719
|
if (/^\s*cpus\s*$/i.test(processCount)) {
|
|
619
720
|
processCount = os.cpus().length;
|
|
@@ -1320,26 +1421,9 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
1320
1421
|
}
|
|
1321
1422
|
},
|
|
1322
1423
|
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
});
|
|
1327
|
-
|
|
1328
|
-
const { error, value } = schema.validate(
|
|
1329
|
-
{ email: str },
|
|
1330
|
-
{
|
|
1331
|
-
abortEarly: false,
|
|
1332
|
-
stripUnknown: true,
|
|
1333
|
-
convert: true
|
|
1334
|
-
}
|
|
1335
|
-
);
|
|
1336
|
-
|
|
1337
|
-
if (error) {
|
|
1338
|
-
return false;
|
|
1339
|
-
}
|
|
1340
|
-
|
|
1341
|
-
return value.email;
|
|
1342
|
-
},
|
|
1424
|
+
// Re-exported from lib/utils/is-email.js so pure modules can use the same check without requiring
|
|
1425
|
+
// this file (and with it settings and Redis). Keep the re-export - callers import it from here.
|
|
1426
|
+
isEmail,
|
|
1343
1427
|
|
|
1344
1428
|
async emitChangeEvent(logger, account, type, key, payload) {
|
|
1345
1429
|
try {
|
|
@@ -1813,6 +1897,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
1813
1897
|
account: opts.account,
|
|
1814
1898
|
name: opts.name,
|
|
1815
1899
|
email: opts.email,
|
|
1900
|
+
expectedEmail: opts.expectedEmail,
|
|
1816
1901
|
syncFrom: (opts.syncFrom && opts.syncFrom.toISOString()) || null,
|
|
1817
1902
|
notifyFrom: (opts.notifyFrom && opts.notifyFrom.toISOString()) || null,
|
|
1818
1903
|
subconnections: opts.subconnections && opts.subconnections.length ? opts.subconnections : null,
|
|
@@ -2060,23 +2145,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2060
2145
|
.filter(v => v);
|
|
2061
2146
|
},
|
|
2062
2147
|
|
|
2063
|
-
readEnvValue
|
|
2064
|
-
if (key in process.env) {
|
|
2065
|
-
return process.env[key];
|
|
2066
|
-
}
|
|
2067
|
-
|
|
2068
|
-
if (typeof process.env[`${key}_FILE`] === 'string' && process.env[`${key}_FILE`]) {
|
|
2069
|
-
try {
|
|
2070
|
-
// try to load from file
|
|
2071
|
-
process.env[key] = Fs.readFileSync(process.env[`${key}_FILE`], 'utf-8').replace(/\r?\n/g, '\n').trim();
|
|
2072
|
-
logger.trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
|
|
2073
|
-
} catch (err) {
|
|
2074
|
-
logger.fatal({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
|
|
2075
|
-
process.env[key] = '';
|
|
2076
|
-
}
|
|
2077
|
-
return process.env[key];
|
|
2078
|
-
}
|
|
2079
|
-
},
|
|
2148
|
+
readEnvValue,
|
|
2080
2149
|
|
|
2081
2150
|
convertDataUrisToAttachments(data) {
|
|
2082
2151
|
if (data.html) {
|
package/lib/totp.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const { base32Encode } = require('./base32');
|
|
5
|
+
|
|
6
|
+
// In-house RFC 4226 / RFC 6238 TOTP implementation (SHA-1, 6 digits, 30-second period).
|
|
7
|
+
// Replaces the unmaintained speakeasy package while staying byte-compatible with seeds it
|
|
8
|
+
// generated: `totpSeed` is stored as an ASCII string and its raw bytes are the shared secret.
|
|
9
|
+
|
|
10
|
+
const TOTP_STEP_SECONDS = 30;
|
|
11
|
+
const TOTP_DIGITS = 6;
|
|
12
|
+
const TOTP_TOKEN_RE = new RegExp(`^[0-9]{${TOTP_DIGITS}}$`);
|
|
13
|
+
|
|
14
|
+
const SEED_LENGTH = 20;
|
|
15
|
+
const SEED_CHARSET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
|
16
|
+
|
|
17
|
+
function hotp(secret, counter) {
|
|
18
|
+
let counterBuf = Buffer.alloc(8);
|
|
19
|
+
counterBuf.writeBigUInt64BE(BigInt(counter));
|
|
20
|
+
|
|
21
|
+
let digest = crypto.createHmac('sha1', secret).update(counterBuf).digest();
|
|
22
|
+
|
|
23
|
+
let offset = digest[digest.length - 1] & 0x0f;
|
|
24
|
+
let code = (digest.readUInt32BE(offset) & 0x7fffffff) % 10 ** TOTP_DIGITS;
|
|
25
|
+
|
|
26
|
+
return code.toString().padStart(TOTP_DIGITS, '0');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function generateTotpSeed() {
|
|
30
|
+
let seed = '';
|
|
31
|
+
for (let i = 0; i < SEED_LENGTH; i++) {
|
|
32
|
+
seed += SEED_CHARSET[crypto.randomInt(SEED_CHARSET.length)];
|
|
33
|
+
}
|
|
34
|
+
return seed;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function verifyTotp(seed, token, options) {
|
|
38
|
+
let { window = 0, now = Date.now() } = options || {};
|
|
39
|
+
|
|
40
|
+
token = (token || '').toString().trim();
|
|
41
|
+
if (!TOTP_TOKEN_RE.test(token)) {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
let secret = Buffer.from(seed);
|
|
46
|
+
let tokenBuf = Buffer.from(token);
|
|
47
|
+
let counter = Math.floor(now / 1000 / TOTP_STEP_SECONDS);
|
|
48
|
+
|
|
49
|
+
let verified = false;
|
|
50
|
+
for (let delta = -window; delta <= window; delta++) {
|
|
51
|
+
if (counter + delta < 0) {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
// no early break - every offset is checked so response timing does not depend on which one matched
|
|
55
|
+
if (crypto.timingSafeEqual(Buffer.from(hotp(secret, counter + delta)), tokenBuf)) {
|
|
56
|
+
verified = true;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return verified;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function generateTotpUrl(seed, { label, issuer }) {
|
|
64
|
+
return `otpauth://totp/${encodeURIComponent(label)}?secret=${base32Encode(Buffer.from(seed))}&issuer=${encodeURIComponent(issuer)}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
module.exports = { generateTotpSeed, verifyTotp, generateTotpUrl };
|