emailengine-app 2.83.1 → 2.84.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/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +30 -0
- package/README.md +1 -1
- package/SECURITY.md +126 -47
- package/data/google-crawlers.json +1 -1
- package/gettext-extract.js +95 -15
- package/lib/api-routes/outbox-routes.js +132 -9
- package/lib/api-routes/permission-map.js +11 -1
- package/lib/consts.js +3 -5
- package/lib/email-client/base-client.js +44 -20
- package/lib/email-client/credential-errors.js +3 -31
- package/lib/email-client/imap/idle-settings.js +44 -0
- package/lib/email-client/imap/mailbox.js +19 -7
- package/lib/email-client/imap-client.js +3 -21
- package/lib/email-client/smtp-pool-manager.js +25 -6
- package/lib/enum-descriptions.js +7 -0
- package/lib/export.js +46 -42
- package/lib/field-usage.js +4 -0
- package/lib/handlebars-helpers.js +4 -0
- package/lib/imapproxy/imap-core/lib/commands/starttls.js +4 -2
- package/lib/imapproxy/imap-core/lib/imap-server.js +44 -11
- package/lib/imapproxy/proxy-handoff.js +10 -1
- package/lib/logger.js +3 -2
- package/lib/message-port-stream.js +23 -0
- package/lib/network-errors.js +50 -0
- package/lib/oauth/gmail.js +5 -1
- package/lib/oauth/mail-ru.js +5 -1
- package/lib/oauth/outlook.js +5 -1
- package/lib/oauth/pubsub/google.js +3 -2
- package/lib/oauth/token-fetch.js +2 -3
- package/lib/outbox.js +338 -10
- package/lib/queue-browser/definitions.js +132 -0
- package/lib/queue-browser/format.js +387 -0
- package/lib/queue-browser/index.js +568 -0
- package/lib/queue-job-actions.js +75 -0
- package/lib/queue-retention.js +53 -1
- package/lib/routes-ui.js +5 -0
- package/lib/schemas.js +42 -2
- package/lib/security-headers.js +2 -24
- package/lib/sub-script.js +10 -3
- package/lib/token-permission-view.js +1 -1
- package/lib/tools.js +16 -2
- package/lib/ui-routes/account-routes.js +6 -0
- package/lib/ui-routes/imap-idle-field.js +42 -0
- package/lib/ui-routes/queue-routes.js +371 -0
- package/lib/utils/status-error.js +21 -0
- package/package.json +18 -20
- package/prepare-bundle-deps.sh +1 -1
- package/sbom.json +1 -1
- package/server.js +10 -0
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +2 -0
- package/static/js/queues.js +117 -0
- package/static/licenses.html +127 -251
- package/translations/README.md +3 -2
- package/translations/messages.pot +280 -265
- package/views/accounts/account.hbs +31 -0
- package/views/accounts/edit.hbs +2 -0
- package/views/config/service.hbs +1 -2
- package/views/dashboard.hbs +2 -2
- package/views/partials/queue_cell_account.hbs +20 -0
- package/views/partials/queue_cell_failure.hbs +6 -0
- package/views/partials/queue_clean_items.hbs +9 -0
- package/views/partials/queue_clean_modal.hbs +9 -0
- package/views/partials/queue_entry_actions.hbs +41 -0
- package/views/partials/queue_job_actions.hbs +15 -0
- package/views/partials/queue_pause_controls.hbs +18 -0
- package/views/partials/queue_retention_note.hbs +49 -0
- package/views/partials/queue_rows_export.hbs +58 -0
- package/views/partials/queue_rows_notify.hbs +73 -0
- package/views/partials/queue_rows_submit.hbs +70 -0
- package/views/partials/side_menu.hbs +1 -1
- package/views/partials/ui/tooltip.hbs +5 -3
- package/views/queues/index.hbs +104 -0
- package/views/queues/job.hbs +224 -0
- package/views/queues/queue.hbs +93 -0
- package/views/webhooks/webhook.hbs +3 -0
- package/workers/api.js +0 -4
- package/workers/imap.js +10 -3
- package/workers/smtp.js +16 -1
- package/workers/submit.js +19 -5
- package/workers/webhooks.js +13 -0
- package/lib/api-routes/bull-board-routes.js +0 -56
|
@@ -3853,6 +3853,29 @@ class BaseClient {
|
|
|
3853
3853
|
* @param {Object} context - Error handling context
|
|
3854
3854
|
*/
|
|
3855
3855
|
async handleSubmitError(err, context) {
|
|
3856
|
+
// Every caller rethrows err once this returns, so nothing in here may throw instead of it:
|
|
3857
|
+
// a Redis failure replacing a permanent 550 was classified and retried as the Redis error
|
|
3858
|
+
try {
|
|
3859
|
+
await this.recordSubmitError(err, context);
|
|
3860
|
+
} catch (recordErr) {
|
|
3861
|
+
this.logger.error({ msg: 'Failed to record the delivery error', queueId: context.queueId, err: recordErr });
|
|
3862
|
+
}
|
|
3863
|
+
|
|
3864
|
+
// Enhance error with additional context. The API clients report their send failures
|
|
3865
|
+
// through here as well, and those arrive with a statusCode and info of their own that
|
|
3866
|
+
// must survive - only an SMTP reply code overrides the status
|
|
3867
|
+
err.code = err.code || 'SubmitFail';
|
|
3868
|
+
err.statusCode = Number(err.responseCode) || err.statusCode || null;
|
|
3869
|
+
err.info = Object.assign({}, err.info, { networkRouting: context.networkRouting });
|
|
3870
|
+
}
|
|
3871
|
+
|
|
3872
|
+
/**
|
|
3873
|
+
* Records a send failure: the account and gateway SMTP status, the feedback key and the
|
|
3874
|
+
* delivery error webhook. Each step is attempted even when an earlier one failed
|
|
3875
|
+
* @param {Error} err - The error that occurred
|
|
3876
|
+
* @param {Object} context - Error handling context
|
|
3877
|
+
*/
|
|
3878
|
+
async recordSubmitError(err, context) {
|
|
3856
3879
|
const { smtpSettings, networkRouting, gatewayData, gatewayObject, data, jobData, queueId, envelope } = context;
|
|
3857
3880
|
|
|
3858
3881
|
// Build SMTP status from error. Only an SMTP attempt has one to report: a provider API send
|
|
@@ -3881,29 +3904,30 @@ class BaseClient {
|
|
|
3881
3904
|
// Update feedback key with failure status
|
|
3882
3905
|
if (data.feedbackKey && !jobData.nextAttempt) {
|
|
3883
3906
|
const errorMessage = (smtpStatus && smtpStatus.description) || 'Failed to send email';
|
|
3884
|
-
|
|
3907
|
+
try {
|
|
3908
|
+
await this.updateFeedbackKey(data.feedbackKey, false, errorMessage);
|
|
3909
|
+
} catch (feedbackErr) {
|
|
3910
|
+
this.logger.error({ msg: 'Failed to update the submission feedback key', queueId, messageId: data.messageId, err: feedbackErr });
|
|
3911
|
+
}
|
|
3885
3912
|
}
|
|
3886
3913
|
|
|
3887
3914
|
// Send delivery error notification
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3894
|
-
|
|
3895
|
-
|
|
3896
|
-
|
|
3897
|
-
|
|
3898
|
-
|
|
3899
|
-
|
|
3900
|
-
|
|
3901
|
-
|
|
3902
|
-
|
|
3903
|
-
|
|
3904
|
-
err.code = err.code || 'SubmitFail';
|
|
3905
|
-
err.statusCode = Number(err.responseCode) || err.statusCode || null;
|
|
3906
|
-
err.info = Object.assign({}, err.info, { networkRouting });
|
|
3915
|
+
try {
|
|
3916
|
+
await this.notify(
|
|
3917
|
+
false,
|
|
3918
|
+
EMAIL_DELIVERY_ERROR_NOTIFY,
|
|
3919
|
+
NotificationBuilder.buildErrorPayload({
|
|
3920
|
+
error: err,
|
|
3921
|
+
queueId,
|
|
3922
|
+
envelope,
|
|
3923
|
+
messageId: data.messageId,
|
|
3924
|
+
networkRouting,
|
|
3925
|
+
jobData
|
|
3926
|
+
})
|
|
3927
|
+
);
|
|
3928
|
+
} catch (notifyErr) {
|
|
3929
|
+
this.logger.error({ msg: 'Failed to queue the delivery error notification', queueId, messageId: data.messageId, err: notifyErr });
|
|
3930
|
+
}
|
|
3907
3931
|
}
|
|
3908
3932
|
|
|
3909
3933
|
// stub - to be implemented by subclasses
|
|
@@ -18,39 +18,11 @@
|
|
|
18
18
|
// pure subconnection tests do not inherit the Redis connections this module's imports open.
|
|
19
19
|
|
|
20
20
|
const { resolveCredentials } = require('../tools');
|
|
21
|
-
const { AUTH_ERROR_NOTIFY
|
|
21
|
+
const { AUTH_ERROR_NOTIFY } = require('../consts');
|
|
22
|
+
// Re-exported: the credential and API retry paths have always imported it from here
|
|
23
|
+
const { isTransientNetworkError } = require('../network-errors');
|
|
22
24
|
const { ACCOUNT_STATES } = require('../account/account-state');
|
|
23
25
|
|
|
24
|
-
// How far down a cause chain the transient check looks. A chain is not guaranteed to be finite - an
|
|
25
|
-
// error may cite itself - so the walk is bounded rather than trusting it to end.
|
|
26
|
-
const MAX_CAUSE_DEPTH = 5;
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* Failing to reach a remote endpoint is a connection problem, not a rejected credential. Both
|
|
30
|
-
* OAuth2 credential sources (EmailEngine's own token refresh and an external authentication
|
|
31
|
-
* server) use this to avoid reporting an unreachable host as an authentication error, and the API
|
|
32
|
-
* transports use it to decide which failed requests to repeat.
|
|
33
|
-
*
|
|
34
|
-
* The whole cause chain is searched, not one level. undici reports a connection failure as a generic
|
|
35
|
-
* TypeError ("fetch failed") with the real DNS/socket error on err.cause, and a caller that wraps THAT
|
|
36
|
-
* failure in an error of its own pushes it one level deeper: lib/oauth/external-account-signer.js does
|
|
37
|
-
* exactly that for its three Workload Identity Federation requests, so an unreachable Google STS
|
|
38
|
-
* endpoint used to be classified as a refused credential and park the account - the one outcome this
|
|
39
|
-
* check exists to prevent.
|
|
40
|
-
*
|
|
41
|
-
* @param {Error} err - The error to check
|
|
42
|
-
* @returns {boolean} True if the error, or anything it was caused by, is a transient network failure
|
|
43
|
-
*/
|
|
44
|
-
function isTransientNetworkError(err) {
|
|
45
|
-
for (let cause = err, depth = 0; cause && typeof cause === 'object' && depth < MAX_CAUSE_DEPTH; cause = cause.cause, depth++) {
|
|
46
|
-
if (TRANSIENT_NETWORK_CODES.has(cause.code)) {
|
|
47
|
-
return true;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
return false;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
26
|
/**
|
|
55
27
|
* Reads the HTTP status a failed credential request came back with. The OAuth2 clients put it on
|
|
56
28
|
* the error itself and repeat it in the request record they attach; the Graph and Gmail transports
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* How often an IMAP connection restarts IDLE (ImapFlow's `maxIdleTime`) and which command keeps it
|
|
5
|
+
* alive on a server without IDLE (`missingIdleCommand`).
|
|
6
|
+
*
|
|
7
|
+
* A few providers get a built-in value, and an account can set its own `imap.maxIdleTime` for a
|
|
8
|
+
* server, or something in front of it, that drops a connection left idle for a few minutes without
|
|
9
|
+
* sending BYE. The account value wins over the built-in one.
|
|
10
|
+
*
|
|
11
|
+
* Kept free of connection and Redis code so the rules can be tested on their own.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const PROVIDER_IDLE_SETTINGS = [
|
|
15
|
+
// Rambler supports IDLE but needs it restarted frequently
|
|
16
|
+
{ host: /\.rambler\.ru$/i, maxIdleTime: 55 * 1000 },
|
|
17
|
+
// 163.com (Coremail) does not support IDLE and ignores NOOP for idle timer reset.
|
|
18
|
+
// Use STATUS as the keepalive command - it counts as real activity for the server.
|
|
19
|
+
{ host: /\.163\.com$/i, maxIdleTime: 55 * 1000, missingIdleCommand: 'STATUS' },
|
|
20
|
+
// Break IDLE at least once every three minutes
|
|
21
|
+
{ host: /\.yahoo\.com$/i, maxIdleTime: 3 * 60 * 1000 }
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Sets the IDLE options on a connection config that is about to be handed to ImapFlow
|
|
26
|
+
* @param {Object} imapConfig - The ImapFlow config, modified in place
|
|
27
|
+
* @param {Object} [accountImap] - The account's stored `imap` object. Read on its own because an
|
|
28
|
+
* OAuth2 account builds its connection config without it
|
|
29
|
+
*/
|
|
30
|
+
function applyIdleSettings(imapConfig, accountImap) {
|
|
31
|
+
const provider = PROVIDER_IDLE_SETTINGS.find(entry => entry.host.test(imapConfig.host || ''));
|
|
32
|
+
if (provider) {
|
|
33
|
+
imapConfig.maxIdleTime = provider.maxIdleTime;
|
|
34
|
+
if (provider.missingIdleCommand) {
|
|
35
|
+
imapConfig.missingIdleCommand = provider.missingIdleCommand;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (accountImap?.maxIdleTime) {
|
|
40
|
+
imapConfig.maxIdleTime = accountImap.maxIdleTime;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
module.exports = { applyIdleSettings };
|
|
@@ -1277,6 +1277,8 @@ class Mailbox {
|
|
|
1277
1277
|
let bounceNotifyInfo;
|
|
1278
1278
|
let complaintNotifyInfo;
|
|
1279
1279
|
let content;
|
|
1280
|
+
// Set once a download found the message already expunged
|
|
1281
|
+
let messageGone = false;
|
|
1280
1282
|
|
|
1281
1283
|
// Check if this might be an ARF (Abuse Reporting Format) complaint
|
|
1282
1284
|
if (this.connection.mightBeAComplaint(messageInfo)) {
|
|
@@ -1336,19 +1338,29 @@ class Mailbox {
|
|
|
1336
1338
|
|
|
1337
1339
|
// Check if this might be a DSN (Delivery Status Notification)
|
|
1338
1340
|
if (this.connection.mightBeDSNResponse(messageInfo)) {
|
|
1341
|
+
let sourceStream;
|
|
1339
1342
|
try {
|
|
1340
|
-
|
|
1343
|
+
({ content: sourceStream } = await this.requireImapClient().download(messageInfo.uid, false, {
|
|
1341
1344
|
uid: true,
|
|
1342
1345
|
chunkSize: options.chunkSize,
|
|
1343
1346
|
maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
|
|
1344
|
-
});
|
|
1347
|
+
}));
|
|
1345
1348
|
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1349
|
+
// No content means the message was expunged after it was detected (a server-side
|
|
1350
|
+
// filter moving it to Junk, for instance), which is a normal race and not a failure.
|
|
1351
|
+
// The bounce check below does not ask for it again
|
|
1352
|
+
if (!sourceStream) {
|
|
1353
|
+
messageGone = true;
|
|
1354
|
+
} else {
|
|
1355
|
+
let parsed = await parseMessage(sourceStream, DSN_PARSER_OPTIONS);
|
|
1356
|
+
if (parsed) {
|
|
1357
|
+
content = { parsed };
|
|
1358
|
+
applyDeliveryReport(parsed, messageInfo, this.logger);
|
|
1359
|
+
}
|
|
1350
1360
|
}
|
|
1351
1361
|
} catch (err) {
|
|
1362
|
+
// A parser failure leaves the IMAP download unconsumed
|
|
1363
|
+
sourceStream?.destroy?.();
|
|
1352
1364
|
if (isConnectionGone(err)) {
|
|
1353
1365
|
throw err;
|
|
1354
1366
|
}
|
|
@@ -1366,7 +1378,7 @@ class Mailbox {
|
|
|
1366
1378
|
if (this.connection.mightBeABounce(messageInfo)) {
|
|
1367
1379
|
// Parse for bounce information
|
|
1368
1380
|
try {
|
|
1369
|
-
if (!content) {
|
|
1381
|
+
if (!content && !messageGone) {
|
|
1370
1382
|
let result = await this.requireImapClient().download(messageInfo.uid, false, {
|
|
1371
1383
|
uid: true,
|
|
1372
1384
|
chunkSize: options.chunkSize,
|
|
@@ -20,6 +20,7 @@ const { connectionNotAvailableError, connectionUnavailableError } = require('./i
|
|
|
20
20
|
const { ReconnectBackoff } = require('./reconnect-backoff');
|
|
21
21
|
const { isRefusedImapLogin, imapResponseText } = require('./imap/login-failure');
|
|
22
22
|
const { knownUidNext, planStaleViewProbe, evaluateStaleViewProbe } = require('./imap/stale-view');
|
|
23
|
+
const { applyIdleSettings } = require('./imap/idle-settings');
|
|
23
24
|
|
|
24
25
|
const {
|
|
25
26
|
normalizePath,
|
|
@@ -1692,27 +1693,8 @@ class IMAPClient extends BaseClient {
|
|
|
1692
1693
|
}
|
|
1693
1694
|
}
|
|
1694
1695
|
|
|
1695
|
-
// Provider
|
|
1696
|
-
|
|
1697
|
-
// Rambler supports IDLE but needs it restarted frequently
|
|
1698
|
-
imapConfig.maxIdleTime = 55 * 1000;
|
|
1699
|
-
} else if (/\.163\.com$/i.test(imapConfig.host)) {
|
|
1700
|
-
// 163.com (Coremail) does not support IDLE and ignores NOOP for idle timer reset.
|
|
1701
|
-
// Use STATUS as the keepalive command - it counts as real activity for the server.
|
|
1702
|
-
imapConfig.maxIdleTime = 55 * 1000;
|
|
1703
|
-
imapConfig.missingIdleCommand = 'STATUS';
|
|
1704
|
-
} else if (/\.yahoo\.com$/i.test(imapConfig.host)) {
|
|
1705
|
-
// Special case for Yahoo. Break IDLE at least once every three minutes
|
|
1706
|
-
imapConfig.maxIdleTime = 3 * 60 * 1000;
|
|
1707
|
-
}
|
|
1708
|
-
|
|
1709
|
-
/*
|
|
1710
|
-
else if (/(\.naver\.com)$/i.test(imapConfig.host)) {
|
|
1711
|
-
// NOOP does nothing in Naver, must run SELECT for changes in the folder to apply
|
|
1712
|
-
imapConfig.maxIdleTime = 55 * 1000;
|
|
1713
|
-
imapConfig.missingIdleCommand = 'SELECT';
|
|
1714
|
-
}
|
|
1715
|
-
*/
|
|
1696
|
+
// Provider IDLE workarounds, and the account's own IDLE restart interval
|
|
1697
|
+
applyIdleSettings(imapConfig, accountData.imap);
|
|
1716
1698
|
|
|
1717
1699
|
// Apply global settings
|
|
1718
1700
|
if (DISABLE_IMAP_COMPRESSION) {
|
|
@@ -133,11 +133,29 @@ function closePooledConnection(poolKey) {
|
|
|
133
133
|
}
|
|
134
134
|
}
|
|
135
135
|
|
|
136
|
+
/**
|
|
137
|
+
* Whether a pooled transport still has a message queued or being transmitted. Reads nodemailer's
|
|
138
|
+
* pool internals: isIdle() turns true while a message is still on the wire
|
|
139
|
+
* @param {Object} transporter - Nodemailer transport instance
|
|
140
|
+
* @returns {boolean}
|
|
141
|
+
*/
|
|
142
|
+
function hasPendingDeliveries(transporter) {
|
|
143
|
+
const pool = transporter && transporter.transporter;
|
|
144
|
+
if (!pool) {
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
return (
|
|
148
|
+
(Array.isArray(pool._queue) && pool._queue.length > 0) ||
|
|
149
|
+
(Array.isArray(pool._connections) && pool._connections.some(connection => connection.queueEntry))
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
|
|
136
153
|
/**
|
|
137
154
|
* Performs cleanup of idle SMTP pool connections
|
|
155
|
+
* @param {number} [now] - Current time, for tests
|
|
138
156
|
*/
|
|
139
|
-
function cleanupIdlePools() {
|
|
140
|
-
|
|
157
|
+
function cleanupIdlePools(now) {
|
|
158
|
+
now = now || Date.now();
|
|
141
159
|
const idleKeys = [];
|
|
142
160
|
|
|
143
161
|
for (const [poolKey, lastUsed] of SMTP_POOL_LAST_USED.entries()) {
|
|
@@ -149,11 +167,11 @@ function cleanupIdlePools() {
|
|
|
149
167
|
for (const poolKey of idleKeys) {
|
|
150
168
|
const transporter = SMTP_POOLS.get(poolKey);
|
|
151
169
|
if (transporter) {
|
|
152
|
-
//
|
|
153
|
-
|
|
154
|
-
|
|
170
|
+
// "Idle" is measured from the last time a message was handed to the pool, so a single
|
|
171
|
+
// transmission that outlasts the idle window would otherwise be cut off
|
|
172
|
+
if (hasPendingDeliveries(transporter)) {
|
|
155
173
|
SMTP_POOL_LAST_USED.set(poolKey, now);
|
|
156
|
-
logger.trace({ msg: 'SMTP pool still has
|
|
174
|
+
logger.trace({ msg: 'SMTP pool still has deliveries in progress, skipping cleanup', poolKey });
|
|
157
175
|
continue;
|
|
158
176
|
}
|
|
159
177
|
|
|
@@ -193,6 +211,7 @@ module.exports = {
|
|
|
193
211
|
getPoolSize,
|
|
194
212
|
// Exported for testing
|
|
195
213
|
generatePoolKey,
|
|
214
|
+
cleanupIdlePools,
|
|
196
215
|
SMTP_POOL_MAX_IDLE,
|
|
197
216
|
SMTP_POOL_CLEANUP_INTERVAL
|
|
198
217
|
};
|
package/lib/enum-descriptions.js
CHANGED
|
@@ -44,6 +44,13 @@ const ENUM_DESCRIPTIONS = {
|
|
|
44
44
|
error: 'Delivery failed. See the error field for the reason and whether it will be retried'
|
|
45
45
|
},
|
|
46
46
|
|
|
47
|
+
outboxState: {
|
|
48
|
+
delayed: 'Waiting for its scheduled time, or for the backoff before its next delivery attempt',
|
|
49
|
+
waiting: 'Ready to be delivered as soon as a submit worker is free',
|
|
50
|
+
active: 'A delivery attempt is running right now',
|
|
51
|
+
failed: 'Every delivery attempt failed, or the receiving server rejected the message for good. Listed while the job record is retained, and retryable while its content is'
|
|
52
|
+
},
|
|
53
|
+
|
|
47
54
|
outboxSource: {
|
|
48
55
|
smtp: 'Submitted through the built-in SMTP server',
|
|
49
56
|
api: 'Submitted through the REST API',
|
package/lib/export.js
CHANGED
|
@@ -7,6 +7,7 @@ const pathlib = require('path');
|
|
|
7
7
|
const zlib = require('zlib');
|
|
8
8
|
const { pipeline } = require('stream');
|
|
9
9
|
const msgpack = require('./msgpack');
|
|
10
|
+
const { statusError } = require('./utils/status-error');
|
|
10
11
|
const { redis, exportQueue } = require('./db');
|
|
11
12
|
const settings = require('./settings');
|
|
12
13
|
const logger = require('./logger');
|
|
@@ -208,12 +209,7 @@ function generateExportId() {
|
|
|
208
209
|
return EXPORT_ID_PREFIX + crypto.randomBytes(12).toString('hex');
|
|
209
210
|
}
|
|
210
211
|
|
|
211
|
-
|
|
212
|
-
const err = new Error(message);
|
|
213
|
-
err.code = code;
|
|
214
|
-
err.statusCode = statusCode;
|
|
215
|
-
return err;
|
|
216
|
-
}
|
|
212
|
+
const createError = statusError;
|
|
217
213
|
|
|
218
214
|
// Error classifiers used by the export worker to decide between retrying, skipping a single
|
|
219
215
|
// message, or failing the whole export job.
|
|
@@ -400,50 +396,58 @@ class Export {
|
|
|
400
396
|
const now = Date.now();
|
|
401
397
|
const expiresAt = now + maxAge;
|
|
402
398
|
|
|
403
|
-
const activeEntry = await tryAddToActiveSet(account, exportId);
|
|
404
|
-
|
|
405
|
-
await fs.promises.mkdir(exportPath, { recursive: true });
|
|
406
|
-
|
|
407
|
-
const secret = await getSecret();
|
|
408
|
-
const isEncrypted = !!secret;
|
|
409
|
-
const fileExtension = isEncrypted ? EXPORT_FILE_EXTENSION_ENCRYPTED : EXPORT_FILE_EXTENSION;
|
|
410
|
-
const filePath = pathlib.join(exportPath, `${exportId}${fileExtension}`);
|
|
411
399
|
const startDate = toTimestamp(options.startDate);
|
|
412
400
|
const endDate = toTimestamp(options.endDate);
|
|
413
401
|
|
|
414
|
-
const
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
402
|
+
const activeEntry = await tryAddToActiveSet(account, exportId);
|
|
403
|
+
|
|
404
|
+
// Anything that fails after taking the slot has to give it back, or the account reads as
|
|
405
|
+
// busy (429) until the sweeper notices
|
|
406
|
+
try {
|
|
407
|
+
await fs.promises.mkdir(exportPath, { recursive: true });
|
|
408
|
+
|
|
409
|
+
const secret = await getSecret();
|
|
410
|
+
const isEncrypted = !!secret;
|
|
411
|
+
const fileExtension = isEncrypted ? EXPORT_FILE_EXTENSION_ENCRYPTED : EXPORT_FILE_EXTENSION;
|
|
412
|
+
const filePath = pathlib.join(exportPath, `${exportId}${fileExtension}`);
|
|
413
|
+
|
|
414
|
+
const exportData = {
|
|
415
|
+
exportId,
|
|
416
|
+
account,
|
|
417
|
+
status: 'queued',
|
|
418
|
+
phase: 'pending',
|
|
419
|
+
folders: JSON.stringify(options.folders || []),
|
|
420
|
+
startDate,
|
|
421
|
+
endDate,
|
|
422
|
+
textType: options.textType || '*',
|
|
423
|
+
// Preserve an explicit 0 ("unlimited" per the API contract); only fall back when unset.
|
|
424
|
+
maxBytes: Number.isInteger(options.maxBytes) ? options.maxBytes : 5 * 1024 * 1024,
|
|
425
|
+
includeAttachments: options.includeAttachments ? '1' : '0',
|
|
426
|
+
isEncrypted: isEncrypted ? '1' : '0',
|
|
427
|
+
foldersScanned: 0,
|
|
428
|
+
foldersTotal: 0,
|
|
429
|
+
messagesQueued: 0,
|
|
430
|
+
messagesExported: 0,
|
|
431
|
+
messagesSkipped: 0,
|
|
432
|
+
bytesWritten: 0,
|
|
433
|
+
filePath,
|
|
434
|
+
created: now,
|
|
435
|
+
expiresAt,
|
|
436
|
+
error: ''
|
|
437
|
+
};
|
|
438
438
|
|
|
439
|
-
|
|
439
|
+
const ttl = Math.ceil(maxAge / 1000);
|
|
440
440
|
|
|
441
|
-
|
|
441
|
+
await redis.multi().hmset(exportKey, exportData).expire(exportKey, ttl).exec();
|
|
442
442
|
|
|
443
|
-
try {
|
|
444
443
|
await exportQueue.add('export', { account, exportId }, { jobId: exportId, removeOnComplete: true, removeOnFail: true });
|
|
445
444
|
} catch (err) {
|
|
446
|
-
|
|
445
|
+
try {
|
|
446
|
+
await redis.multi().srem(ACTIVE_EXPORTS_KEY, activeEntry).del(exportKey).exec();
|
|
447
|
+
} catch (cleanupErr) {
|
|
448
|
+
// the sweeper releases the slot eventually; the caller needs the original error
|
|
449
|
+
logger.error({ msg: 'Failed to release the export slot', account, exportId, err: cleanupErr });
|
|
450
|
+
}
|
|
447
451
|
throw err;
|
|
448
452
|
}
|
|
449
453
|
|
package/lib/field-usage.js
CHANGED
|
@@ -74,6 +74,10 @@ const FIELD_USAGE = {
|
|
|
74
74
|
'Set this only after a server has actually misbehaved. A handful of IMAP servers advertise IMAP4rev2 support and then answer incorrectly, and this forces EmailEngine back to IMAP4rev1 for that account.\n\n' +
|
|
75
75
|
'It has no effect on accounts that authenticate with OAuth2.',
|
|
76
76
|
|
|
77
|
+
maxIdleTime:
|
|
78
|
+
'Leave this unset unless the server, or something between it and EmailEngine, drops idle connections. Some providers close an IDLE session after a few minutes without saying BYE, which shows up as a reconnect every few minutes. Set a value below that limit, for instance 120000 for a connection that drops after about four and a half minutes, and EmailEngine ends and restarts IDLE that often, so the connection never looks idle.\n\n' +
|
|
79
|
+
'A handful of providers (Yahoo, Rambler, 163.com) already get a built-in value; one set here takes precedence over it. Unlike `disableIMAP4rev2` it also applies to accounts that authenticate with OAuth2. Changing it reconnects the account.',
|
|
80
|
+
|
|
77
81
|
// No description of what `full` and `fast` do: the row lists both values with their own
|
|
78
82
|
// descriptions from lib/enum-descriptions.js a few lines under this note, and saying it
|
|
79
83
|
// twice on one row is what that split exists to avoid.
|
|
@@ -62,6 +62,10 @@ function registerHandlebarsHelpers(handlebars, { gt }) {
|
|
|
62
62
|
// hash values: text=(concat "Up to " (formatInteger n locale) " lines")
|
|
63
63
|
handlebars.registerHelper('concat', (...args) => args.slice(0, -1).join(''));
|
|
64
64
|
|
|
65
|
+
// a line break inside a composed string, for a ui/tooltip body rendered multiline:
|
|
66
|
+
// (concat "first line" (newline) "second line")
|
|
67
|
+
handlebars.registerHelper('newline', () => '\n');
|
|
68
|
+
|
|
65
69
|
// Ternary for subexpressions: placeholder=(when hasPass "set..." "")
|
|
66
70
|
handlebars.registerHelper('when', (cond, truthyValue, falsyValue) => (cond ? truthyValue : typeof falsyValue === 'string' ? falsyValue : ''));
|
|
67
71
|
|
|
@@ -70,8 +70,10 @@ function upgrade(connection) {
|
|
|
70
70
|
}
|
|
71
71
|
};
|
|
72
72
|
|
|
73
|
-
// Apply additional socket options if these are set in the server options
|
|
74
|
-
|
|
73
|
+
// Apply additional socket options if these are set in the server options. SNICallback is not
|
|
74
|
+
// copied: the wrapper above already defers to it, and copying it over discarded the wrapper's
|
|
75
|
+
// error logging and its fallback to the default context
|
|
76
|
+
['requestCert', 'rejectUnauthorized', 'NPNProtocols', 'session', 'requestOCSP'].forEach(key => {
|
|
75
77
|
if (key in connection._server.options) {
|
|
76
78
|
socketOptions[key] = connection._server.options[key];
|
|
77
79
|
}
|
|
@@ -20,6 +20,9 @@ const MAX_PROXY_HEADER_SIZE = 256;
|
|
|
20
20
|
// has not produced it by then is not a proxy we are waiting on, and it must not hold an fd forever.
|
|
21
21
|
const PROXY_HEADER_TIMEOUT = 10 * 1000;
|
|
22
22
|
|
|
23
|
+
// How long an implicit TLS client has to complete its handshake
|
|
24
|
+
const TLS_HANDSHAKE_TIMEOUT = 30 * 1000;
|
|
25
|
+
|
|
23
26
|
/**
|
|
24
27
|
* Creates a IMAP server instance.
|
|
25
28
|
*
|
|
@@ -258,6 +261,20 @@ class IMAPServer extends EventEmitter {
|
|
|
258
261
|
socket.once('close', () => {
|
|
259
262
|
this._socketCount--;
|
|
260
263
|
});
|
|
264
|
+
|
|
265
|
+
// The non-PROXY path hands the socket over a tick later, with no error listener on it until
|
|
266
|
+
// then; a reset in that window would be uncaught and take down the whole worker
|
|
267
|
+
socket.on('error', err => {
|
|
268
|
+
this.logger.debug(
|
|
269
|
+
{
|
|
270
|
+
tnx: 'connect',
|
|
271
|
+
remoteAddress: socket.remoteAddress,
|
|
272
|
+
err
|
|
273
|
+
},
|
|
274
|
+
'Socket error on accepted connection: %s',
|
|
275
|
+
err && err.message
|
|
276
|
+
);
|
|
277
|
+
});
|
|
261
278
|
return true;
|
|
262
279
|
}
|
|
263
280
|
|
|
@@ -414,10 +431,24 @@ class IMAPServer extends EventEmitter {
|
|
|
414
431
|
|
|
415
432
|
let remoteAddress = socket.remoteAddress;
|
|
416
433
|
|
|
417
|
-
|
|
434
|
+
// A client-side failure to establish the session, logged quietly
|
|
435
|
+
let socketError = message => {
|
|
436
|
+
let err = new Error(message);
|
|
437
|
+
err.responseCode = 500;
|
|
438
|
+
err.code = 'SocketError';
|
|
439
|
+
err.report = false;
|
|
440
|
+
err.meta = {
|
|
441
|
+
protocol: 'imap',
|
|
442
|
+
stage: 'connect',
|
|
443
|
+
remoteAddress
|
|
444
|
+
};
|
|
445
|
+
return err;
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
let handshakeTimer = false;
|
|
418
449
|
let returned = false;
|
|
419
450
|
let onError = err => {
|
|
420
|
-
clearTimeout(
|
|
451
|
+
clearTimeout(handshakeTimer);
|
|
421
452
|
if (returned) {
|
|
422
453
|
return;
|
|
423
454
|
}
|
|
@@ -435,15 +466,7 @@ class IMAPServer extends EventEmitter {
|
|
|
435
466
|
};
|
|
436
467
|
}
|
|
437
468
|
if (!err || !err.message) {
|
|
438
|
-
err =
|
|
439
|
-
err.responseCode = 500;
|
|
440
|
-
err.code = 'SocketError';
|
|
441
|
-
err.report = false;
|
|
442
|
-
err.meta = {
|
|
443
|
-
protocol: 'imap',
|
|
444
|
-
stage: 'connect',
|
|
445
|
-
remoteAddress
|
|
446
|
-
};
|
|
469
|
+
err = socketError('Socket closed while initiating TLS');
|
|
447
470
|
}
|
|
448
471
|
callback(err);
|
|
449
472
|
};
|
|
@@ -466,7 +489,17 @@ class IMAPServer extends EventEmitter {
|
|
|
466
489
|
tlsSocket.once('clientError', onError);
|
|
467
490
|
tlsSocket.once('tlsClientError', onError);
|
|
468
491
|
|
|
492
|
+
// Without this a client that never completes the handshake holds its socket and its
|
|
493
|
+
// maxConnections slot for good: the PROXY header timeout is already cleared, and the
|
|
494
|
+
// session's own socket timeout only starts after the handshake
|
|
495
|
+
handshakeTimer = setTimeout(() => {
|
|
496
|
+
onError(socketError('TLS handshake timed out'));
|
|
497
|
+
tlsSocket.destroy();
|
|
498
|
+
socket.destroy();
|
|
499
|
+
}, Number(this.options.tlsHandshakeTimeout) || TLS_HANDSHAKE_TIMEOUT);
|
|
500
|
+
|
|
469
501
|
tlsSocket.on('secure', () => {
|
|
502
|
+
clearTimeout(handshakeTimer);
|
|
470
503
|
socket.removeListener('error', onError);
|
|
471
504
|
tlsSocket.removeListener('close', onCloseError);
|
|
472
505
|
tlsSocket.removeListener('error', onError);
|
|
@@ -200,8 +200,9 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
|
|
|
200
200
|
// stored account data (the login name is the same id, kept as a fallback).
|
|
201
201
|
const account = (accountData && accountData.account) || login.username;
|
|
202
202
|
|
|
203
|
+
let downstream;
|
|
203
204
|
try {
|
|
204
|
-
|
|
205
|
+
downstream = await createProxy({ imapConfig, id: session.id, logger: logger.child({ property: 'upstream', account }) });
|
|
205
206
|
|
|
206
207
|
session.onProxy = upstream => attachProxy({ session, account, downstream, upstream });
|
|
207
208
|
|
|
@@ -215,6 +216,14 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
|
|
|
215
216
|
);
|
|
216
217
|
}
|
|
217
218
|
} catch (err) {
|
|
219
|
+
// The client is refused, so an upstream session already opened has no one to serve
|
|
220
|
+
if (downstream && downstream.imapClient) {
|
|
221
|
+
try {
|
|
222
|
+
downstream.imapClient.close();
|
|
223
|
+
} catch (closeErr) {
|
|
224
|
+
logger.warn({ msg: 'Failed to close upstream connection', account, cid: session.id, err: closeErr });
|
|
225
|
+
}
|
|
226
|
+
}
|
|
218
227
|
throw loginFailure(err, { account, cid: session.id }, { response: 'Upstream authentication failed', fault: 'Failed to create proxy' });
|
|
219
228
|
}
|
|
220
229
|
|
package/lib/logger.js
CHANGED
|
@@ -7,7 +7,8 @@ if (!process.env.EE_ENV_LOADED) {
|
|
|
7
7
|
|
|
8
8
|
const config = require('@zone-eu/wild-config');
|
|
9
9
|
const pino = require('pino');
|
|
10
|
-
const {
|
|
10
|
+
const { REDACTED_LOG_KEYS } = require('./consts');
|
|
11
|
+
const { isTransientNetworkError } = require('./network-errors');
|
|
11
12
|
|
|
12
13
|
config.log = config.log || {
|
|
13
14
|
level: 'trace'
|
|
@@ -21,7 +22,7 @@ config.log.level = config.log.level || 'trace';
|
|
|
21
22
|
// error tracking, where they pile up as useless "fetch failed" reports. Genuine
|
|
22
23
|
// TypeError/RangeError bugs have no network errno cause and still get reported.
|
|
23
24
|
function isTransientFetchError(err) {
|
|
24
|
-
return err && err.name === 'TypeError' &&
|
|
25
|
+
return err && err.name === 'TypeError' && isTransientNetworkError(err);
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
let logger = pino({
|