emailengine-app 2.86.0 → 2.87.1
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 +2 -4
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +42 -0
- package/DOCKER_DEPLOYMENT.md +2 -1
- package/Dockerfile +5 -6
- package/README.md +4 -0
- package/bin/emailengine.js +2 -4
- package/bin/healthcheck.js +20 -0
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +3 -7
- package/lib/account/auth-failure-backfill.js +3 -2
- package/lib/account/expected-identity.js +2 -2
- package/lib/account.js +101 -39
- package/lib/api-listener.js +40 -0
- package/lib/api-routes/account-routes.js +14 -7
- package/lib/api-routes/submit-routes.js +21 -2
- package/lib/api-token-auth.js +406 -0
- package/lib/autodetect-imap-settings.js +36 -3
- package/lib/consts.js +5 -0
- package/lib/email-client/base-client.js +27 -109
- package/lib/email-client/gmail-client.js +15 -4
- package/lib/email-client/imap/mailbox.js +97 -97
- package/lib/email-client/imap/sync-operations.js +13 -6
- package/lib/email-client/imap-client.js +28 -7
- package/lib/email-client/new-message-steps.js +162 -0
- package/lib/email-client/outlook-client.js +10 -2
- package/lib/env-setting-overrides.js +6 -2
- package/lib/export-worker.js +3 -2
- package/lib/export.js +43 -4
- package/lib/field-usage.js +1 -1
- package/lib/get-boolean.js +38 -0
- package/lib/get-raw-email.js +10 -1
- package/lib/health-probe.js +71 -0
- package/lib/imapproxy/imap-server.js +4 -55
- package/lib/net-tos-guard.js +42 -0
- package/lib/oauth/gmail.js +54 -29
- package/lib/oauth2-apps.js +2 -1
- package/lib/otp.js +66 -0
- package/lib/read-env-value.js +19 -7
- package/lib/redis-keys.js +19 -0
- package/lib/redis-operations.js +7 -3
- package/lib/schemas.js +62 -2
- package/lib/security-headers.js +18 -0
- package/lib/session-default.js +50 -0
- package/lib/settings.js +2 -1
- package/lib/stream-encrypt.js +71 -20
- package/lib/sub-script.js +8 -2
- package/lib/submit-lock.js +84 -0
- package/lib/submit-processor.js +283 -0
- package/lib/swagger-options.js +2 -2
- package/lib/templates.js +6 -3
- package/lib/tls/context.js +2 -16
- package/lib/tools.js +8 -30
- package/lib/utils/redis-errors.js +44 -0
- package/lib/webhook-delivery.js +3 -4
- package/lib/webhooks.js +5 -0
- package/lib/worker-rpc-error.js +10 -5
- package/lib/worker-rpc.js +138 -0
- package/package.json +25 -26
- package/sbom.json +660 -1736
- package/server.js +6 -5
- package/static/css/flyonui.css +2 -2
- package/static/js/ee-client.js +650 -196
- package/static/licenses.html +280 -1393
- package/translations/messages.pot +16 -16
- package/views/layout/app.hbs +9 -6
- package/views/legal.hbs +8 -0
- package/workers/api.js +51 -474
- package/workers/export.js +14 -55
- package/workers/imap-proxy.js +5 -18
- package/workers/imap.js +27 -49
- package/workers/smtp.js +7 -69
- package/workers/submit.js +21 -279
- package/workers/webhooks.js +7 -72
|
@@ -4,6 +4,7 @@ const { samePath } = require('../../utils/mailbox-path');
|
|
|
4
4
|
const { connectionClosedError, connectionNotAvailableError, syncInterrupted } = require('./connection-errors');
|
|
5
5
|
const crypto = require('crypto');
|
|
6
6
|
const { createTransaction } = require('../../redis-operations');
|
|
7
|
+
const { isTransientRedisError } = require('../../utils/redis-errors');
|
|
7
8
|
const { compareExisting, calculateFetchBackoff, readEnvValue, validUidValidity } = require('../../tools');
|
|
8
9
|
const config = require('@zone-eu/wild-config');
|
|
9
10
|
const { DEFAULT_FETCH_BATCH_SIZE, FETCH_RETRY_MAX_TIME, FETCH_RETRY_MIN_ATTEMPTS, MAILBOX_RESET_NOTIFY } = require('../../consts');
|
|
@@ -692,12 +693,11 @@ class SyncOperations {
|
|
|
692
693
|
|
|
693
694
|
let changes;
|
|
694
695
|
if (!storedMessage) {
|
|
695
|
-
// New message
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
}
|
|
696
|
+
// New message: indexed and queued for processing in one transaction.
|
|
697
|
+
// Written apart, a queue write Redis refused after the index write
|
|
698
|
+
// went through left a message the retried FETCH found indexed, so
|
|
699
|
+
// it was never announced
|
|
700
|
+
await this.writeChunk([messageData], []);
|
|
701
701
|
} else if ((changes = compareExisting(storedMessage.entry, messageData))) {
|
|
702
702
|
// Existing message with changes
|
|
703
703
|
let seq = await this.mailbox.entryListSet(messageData);
|
|
@@ -714,6 +714,13 @@ class SyncOperations {
|
|
|
714
714
|
}
|
|
715
715
|
fetchCompleted = true;
|
|
716
716
|
} catch (err) {
|
|
717
|
+
if (isTransientRedisError(err)) {
|
|
718
|
+
// Redis refused to store what the FETCH returned, which fetching it
|
|
719
|
+
// again from the server cannot change; the pass ends and gives the
|
|
720
|
+
// mailbox lock back, and the caller runs it again once Redis recovers
|
|
721
|
+
// (Mailbox.schedulePartialSync())
|
|
722
|
+
throw err;
|
|
723
|
+
}
|
|
717
724
|
try {
|
|
718
725
|
// set failure flag
|
|
719
726
|
await this.connection.redis.hSetExists(
|
|
@@ -538,9 +538,11 @@ class IMAPClient extends BaseClient {
|
|
|
538
538
|
* @param {number} uid - Message UID
|
|
539
539
|
* @param {Map} [statusCache] - Stored status by mailbox path, for a caller packing many UIDs
|
|
540
540
|
* of the same folder (a listing): the status is read once instead of one HGETALL per message
|
|
541
|
+
* @param {bigint|number} [knownUidValidity] - The UIDVALIDITY the server just reported for the
|
|
542
|
+
* folder (COPYUID, APPENDUID); used instead of the stored one, which is then not read at all
|
|
541
543
|
* @returns {string|false} Base64url encoded ID or false on error
|
|
542
544
|
*/
|
|
543
|
-
async packUid(mailbox, uid, statusCache) {
|
|
545
|
+
async packUid(mailbox, uid, statusCache, knownUidValidity) {
|
|
544
546
|
if (isNaN(uid) || !mailbox) {
|
|
545
547
|
return false;
|
|
546
548
|
}
|
|
@@ -551,13 +553,21 @@ class IMAPClient extends BaseClient {
|
|
|
551
553
|
|
|
552
554
|
// Convert mailbox path to mailbox object if needed
|
|
553
555
|
if (typeof mailbox === 'string') {
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
556
|
+
const registered = this.mailboxes.get(normalizePath(mailbox));
|
|
557
|
+
if (registered) {
|
|
558
|
+
mailbox = registered;
|
|
559
|
+
} else if (!validUidValidity(knownUidValidity)) {
|
|
557
560
|
return false;
|
|
558
561
|
}
|
|
559
562
|
}
|
|
560
563
|
|
|
564
|
+
// The UIDVALIDITY the server just reported (COPYUID of a MOVE or COPY, APPENDUID of an
|
|
565
|
+
// APPEND) is current, where a stored one can be missing (a folder created moments ago and
|
|
566
|
+
// not registered or synced yet) or stale (a folder recreated since), so nothing is read
|
|
567
|
+
if (validUidValidity(knownUidValidity)) {
|
|
568
|
+
return await this.packMailboxUid(typeof mailbox === 'string' ? mailbox : mailbox.path, knownUidValidity, uid);
|
|
569
|
+
}
|
|
570
|
+
|
|
561
571
|
// Get stored mailbox status including UID validity
|
|
562
572
|
let storedStatus = statusCache?.get(mailbox.path);
|
|
563
573
|
if (!storedStatus) {
|
|
@@ -609,10 +619,21 @@ class IMAPClient extends BaseClient {
|
|
|
609
619
|
// Only a usable status is reused, so a folder whose status is missing is looked at again
|
|
610
620
|
statusCache?.set(mailbox.path, storedStatus);
|
|
611
621
|
|
|
622
|
+
return await this.packMailboxUid(storedStatus.path, storedStatus.uidValidity, uid);
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* The message id of a UID in a folder whose path and UIDVALIDITY are known
|
|
627
|
+
* @param {string} path - Folder path as the server spells it
|
|
628
|
+
* @param {bigint|number} uidValidity
|
|
629
|
+
* @param {number} uid
|
|
630
|
+
* @returns {Promise<string|false>}
|
|
631
|
+
*/
|
|
632
|
+
async packMailboxUid(path, uidValidity, uid) {
|
|
612
633
|
// Pack UID validity and mailbox path into a buffer
|
|
613
634
|
let uidValBuf = Buffer.alloc(8);
|
|
614
|
-
uidValBuf.writeBigUInt64BE(
|
|
615
|
-
let mailboxBuf = Buffer.concat([uidValBuf, Buffer.from(
|
|
635
|
+
uidValBuf.writeBigUInt64BE(BigInt(uidValidity), 0);
|
|
636
|
+
let mailboxBuf = Buffer.concat([uidValBuf, Buffer.from(path)]);
|
|
616
637
|
|
|
617
638
|
// Get or create a numeric mailbox ID for efficient storage
|
|
618
639
|
let mailboxId;
|
|
@@ -3028,7 +3049,7 @@ class IMAPClient extends BaseClient {
|
|
|
3028
3049
|
let destinationPath = uploadResponse.destination || uploadResponse.path || data.path;
|
|
3029
3050
|
|
|
3030
3051
|
if (uploadResponse.uid) {
|
|
3031
|
-
response.id = await this.packUid(destinationPath, uploadResponse.uid);
|
|
3052
|
+
response.id = await this.packUid(destinationPath, uploadResponse.uid, null, uploadResponse.uidValidity);
|
|
3032
3053
|
}
|
|
3033
3054
|
|
|
3034
3055
|
response.path = destinationPath;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The steps of new-message processing that are the same for every backend. Mailbox.processNew()
|
|
4
|
+
// (IMAP) and BaseClient.processNew() (Gmail API, MS Graph) differ in how they fetch content - IMAP
|
|
5
|
+
// streams parts with size caps and rethrows a lost connection, the API clients ask for attachments
|
|
6
|
+
// by id - but what they do with that content has to agree, and two hand-kept copies had already
|
|
7
|
+
// drifted (the web-safe flag was set even when no web-safe copy came out, a classification failure
|
|
8
|
+
// was an error on one path and a warning on the other). Those shared decisions live here.
|
|
9
|
+
|
|
10
|
+
const { camelCaseComplaint } = require('../arf-detect');
|
|
11
|
+
const { embedCidImages } = require('../tools');
|
|
12
|
+
const { MESSAGE_NEW_NOTIFY, EMAIL_BOUNCE_NOTIFY, EMAIL_COMPLAINT_NOTIFY } = require('../consts');
|
|
13
|
+
|
|
14
|
+
const BOUNCE_CLASSIFY_TIMEOUT = 2 * 60 * 1000;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Whether a parsed bounce reports a failed delivery. A DSN also reports delivered, delayed,
|
|
18
|
+
* relayed and expanded recipients, and none of those is a bounce to store or to fire emailBounce
|
|
19
|
+
* for; a delayed DSN that landed in Junk used to reach the bounce path with its action set
|
|
20
|
+
* @param {Object} bounce - Result of bounceDetect()
|
|
21
|
+
* @returns {boolean}
|
|
22
|
+
*/
|
|
23
|
+
function isFailedDelivery(bounce) {
|
|
24
|
+
return !!bounce && typeof bounce.action === 'string' && bounce.action.trim().toLowerCase() === 'failed' && !!bounce.recipient && !!bounce.messageId;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Whether a new message is one the account sent itself, which is never reported as new: it is
|
|
29
|
+
* listed in a Sent folder, resolved to the Sent special use, or (Gmail) carries the \\Sent label,
|
|
30
|
+
* even next to \\Inbox
|
|
31
|
+
* @param {Object} messageData
|
|
32
|
+
* @param {String} [folderSpecialUse] - special use of the folder the message was found in
|
|
33
|
+
* @returns {Boolean}
|
|
34
|
+
*/
|
|
35
|
+
function isOwnSent(messageData, folderSpecialUse) {
|
|
36
|
+
return (
|
|
37
|
+
folderSpecialUse === '\\Sent' ||
|
|
38
|
+
messageData.messageSpecialUse === '\\Sent' ||
|
|
39
|
+
!!(Array.isArray(messageData.labels) && messageData.labels.includes('\\Sent'))
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Adds the classifier's verdict to a detected bounce's response. Best effort: a failed
|
|
45
|
+
* classification leaves the bounce as it was.
|
|
46
|
+
* @param {Object} bounce - bounceDetect() result, changed in place
|
|
47
|
+
* @param {Function} call - RPC to the main thread, where the classifier runs
|
|
48
|
+
* @param {Object} logger
|
|
49
|
+
*/
|
|
50
|
+
async function classifyBounce(bounce, call, logger) {
|
|
51
|
+
const message = bounce?.response?.message;
|
|
52
|
+
if (!message) {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
const bounceType = await call({ cmd: 'bounceClassify', data: { message }, timeout: BOUNCE_CLASSIFY_TIMEOUT });
|
|
57
|
+
if (bounceType?.label) {
|
|
58
|
+
bounce.response.category = bounceType.label;
|
|
59
|
+
}
|
|
60
|
+
if (bounceType?.action) {
|
|
61
|
+
bounce.response.recommendedAction = bounceType.action;
|
|
62
|
+
}
|
|
63
|
+
if (bounceType?.blocklist) {
|
|
64
|
+
bounce.response.blocklist = bounceType.blocklist;
|
|
65
|
+
}
|
|
66
|
+
if (bounceType?.retryAfter) {
|
|
67
|
+
bounce.response.retryAfter = bounceType.retryAfter;
|
|
68
|
+
}
|
|
69
|
+
} catch (err) {
|
|
70
|
+
// ignore, just do not include this information
|
|
71
|
+
logger.warn({ msg: 'Failed to classify bounce response', bounceResponse: message, err });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Marks a message that is a failed-delivery bounce and returns the payload of its bounce event
|
|
77
|
+
* @param {Object} bounce - bounceDetect() result
|
|
78
|
+
* @param {Object} messageData - the new message, changed in place
|
|
79
|
+
* @returns {Object|undefined} the emailBounce payload, or nothing when it is no bounce
|
|
80
|
+
*/
|
|
81
|
+
function bounceNotification(bounce, messageData) {
|
|
82
|
+
if (!isFailedDelivery(bounce)) {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
messageData.isBounce = true;
|
|
86
|
+
messageData.relatedMessageId = bounce.messageId;
|
|
87
|
+
return Object.assign({ bounceMessage: messageData.id }, bounce);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Marks a message that is an abuse report naming its recipient and returns the payload of its
|
|
92
|
+
* complaint event
|
|
93
|
+
* @param {Object} report - arfDetect() result
|
|
94
|
+
* @param {Object} messageData - the new message, changed in place
|
|
95
|
+
* @returns {Object|undefined} the emailComplained payload, or nothing when it is no usable report
|
|
96
|
+
*/
|
|
97
|
+
function complaintNotification(report, messageData) {
|
|
98
|
+
if (!report || !report.arf || !report.arf['original-rcpt-to'] || !report.arf['original-rcpt-to'].length) {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
const complaint = camelCaseComplaint(report);
|
|
102
|
+
messageData.isComplaint = true;
|
|
103
|
+
if (complaint.headers && complaint.headers.messageId) {
|
|
104
|
+
messageData.relatedMessageId = complaint.headers.messageId;
|
|
105
|
+
}
|
|
106
|
+
return Object.assign({ complaintMessage: messageData.id }, complaint);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Replaces the Content-ID references of the HTML and of its web-safe copy with data URIs. The
|
|
111
|
+
* web-safe copy is what webhooks deliver in place of the HTML, so it gets the same treatment.
|
|
112
|
+
* @param {Object} text - messageData.text, changed in place
|
|
113
|
+
* @param {Map} attachmentList - contentId -> { attachment, content } (content base64 or null)
|
|
114
|
+
*/
|
|
115
|
+
function embedInlineImages(text, attachmentList) {
|
|
116
|
+
if (!attachmentList.size) {
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const embedImages = html =>
|
|
120
|
+
embedCidImages(html, contentId => {
|
|
121
|
+
const { attachment, content } = attachmentList.get(contentId) || {};
|
|
122
|
+
return content && { contentType: attachment.contentType, content };
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
text.html = embedImages(text.html);
|
|
126
|
+
if (text._generatedHtml) {
|
|
127
|
+
text._generatedHtml = embedImages(text._generatedHtml);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Flags the text as web-safe only when a web-safe copy was produced: the webhook delivery swaps the
|
|
133
|
+
* HTML for that copy only when there is one, so a flag without it would mark the raw HTML safe
|
|
134
|
+
* @param {Object} text - messageData.text, changed in place
|
|
135
|
+
*/
|
|
136
|
+
function markWebSafe(text) {
|
|
137
|
+
if (text._generatedHtml) {
|
|
138
|
+
text.webSafe = true;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Sends messageNew, then the bounce and complaint events it carries, in that order: a receiver
|
|
144
|
+
* sees the message before the events that refer to it
|
|
145
|
+
* @param {Function} notify - (target, event, data) => Promise
|
|
146
|
+
* @param {Object} target - what messageNew is reported against (a mailbox, or a path and special use)
|
|
147
|
+
* @param {Object} messageData
|
|
148
|
+
* @param {Object} [related]
|
|
149
|
+
* @param {Object} [related.bounceNotifyInfo]
|
|
150
|
+
* @param {Object} [related.complaintNotifyInfo]
|
|
151
|
+
*/
|
|
152
|
+
async function notifyNewMessage(notify, target, messageData, { bounceNotifyInfo, complaintNotifyInfo } = {}) {
|
|
153
|
+
await notify(target, MESSAGE_NEW_NOTIFY, messageData);
|
|
154
|
+
if (bounceNotifyInfo) {
|
|
155
|
+
await notify(false, EMAIL_BOUNCE_NOTIFY, bounceNotifyInfo);
|
|
156
|
+
}
|
|
157
|
+
if (complaintNotifyInfo) {
|
|
158
|
+
await notify(false, EMAIL_COMPLAINT_NOTIFY, complaintNotifyInfo);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
module.exports = { isFailedDelivery, isOwnSent, classifyBounce, bounceNotification, complaintNotification, embedInlineImages, markWebSafe, notifyNewMessage };
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const { accountDataKey } = require('../redis-keys');
|
|
4
|
+
const { isOwnSent } = require('./new-message-steps');
|
|
3
5
|
const { BaseClient, metricsMeta } = require('./base-client');
|
|
4
6
|
const { isSafePathSegment } = require('../utils/provider-id');
|
|
5
7
|
const { isTransientCredentialError } = require('./credential-errors');
|
|
@@ -22,6 +24,7 @@ const { detectMimeType, detectExtension } = require('nodemailer/lib/mime-funcs/m
|
|
|
22
24
|
const graphApi = require('./outlook/graph-api');
|
|
23
25
|
const { buildRawSendMailRequest, buildStructuredSendMailRequest, buildDraftSendRequest } = require('./outlook/send-request');
|
|
24
26
|
const { pushHeaderValue } = require('../utils/header-map');
|
|
27
|
+
const { getMessageOtp } = require('../otp');
|
|
25
28
|
|
|
26
29
|
const {
|
|
27
30
|
REDIS_PREFIX,
|
|
@@ -2911,7 +2914,7 @@ class OutlookClient extends BaseClient {
|
|
|
2911
2914
|
* Get Redis key for account data
|
|
2912
2915
|
*/
|
|
2913
2916
|
getAccountKey() {
|
|
2914
|
-
return
|
|
2917
|
+
return accountDataKey(this.account);
|
|
2915
2918
|
}
|
|
2916
2919
|
|
|
2917
2920
|
/**
|
|
@@ -4119,6 +4122,11 @@ class OutlookClient extends BaseClient {
|
|
|
4119
4122
|
message.isAutoReply = true;
|
|
4120
4123
|
}
|
|
4121
4124
|
|
|
4125
|
+
const otp = getMessageOtp(message.headers, this.summaryProvider());
|
|
4126
|
+
if (otp) {
|
|
4127
|
+
message.otp = otp;
|
|
4128
|
+
}
|
|
4129
|
+
|
|
4122
4130
|
// Process attachments
|
|
4123
4131
|
if (messageData.attachments?.length) {
|
|
4124
4132
|
let cidReferences = collectCidReferences(message.text.html);
|
|
@@ -4631,7 +4639,7 @@ class OutlookClient extends BaseClient {
|
|
|
4631
4639
|
}
|
|
4632
4640
|
|
|
4633
4641
|
// check if we have seen this message before or not (approximate estimation using HyperLogLog)
|
|
4634
|
-
messageData.seemsLikeNew = messageData
|
|
4642
|
+
messageData.seemsLikeNew = !isOwnSent(messageData) && !!(await this.redis.pfadd(this.getSeenMessagesKey(), messageData.messageId));
|
|
4635
4643
|
|
|
4636
4644
|
return messageData;
|
|
4637
4645
|
}
|
|
@@ -202,9 +202,13 @@ async function getOverridableSettings(...keys) {
|
|
|
202
202
|
});
|
|
203
203
|
}
|
|
204
204
|
|
|
205
|
+
// Taken before awaiting any of them: a failed read deletes its entries once it settles, and
|
|
206
|
+
// reading the cache after the first await then found the next key gone (a TypeError that failed
|
|
207
|
+
// whatever asked, a webhook being queued for one)
|
|
208
|
+
const pending = keys.map(key => [key, cache.get(key).value]);
|
|
205
209
|
const result = {};
|
|
206
|
-
for (const key of
|
|
207
|
-
result[key] = await
|
|
210
|
+
for (const [key, value] of pending) {
|
|
211
|
+
result[key] = await value;
|
|
208
212
|
}
|
|
209
213
|
return result;
|
|
210
214
|
}
|
package/lib/export-worker.js
CHANGED
|
@@ -5,8 +5,9 @@
|
|
|
5
5
|
// tested without booting the BullMQ worker; the worker builds this with its own collaborators, a
|
|
6
6
|
// test with fakes.
|
|
7
7
|
|
|
8
|
+
const { accountDataKey } = require('./redis-keys');
|
|
8
9
|
const defaultLogger = require('./logger');
|
|
9
|
-
const {
|
|
10
|
+
const { DEFAULT_EXPORT_MAX_MESSAGE_SIZE, DEFAULT_EXPORT_MAX_MESSAGES, DEFAULT_EXPORT_MAX_SIZE } = require('./consts');
|
|
10
11
|
const {
|
|
11
12
|
Export: DefaultExport,
|
|
12
13
|
isTransientError,
|
|
@@ -134,7 +135,7 @@ function finalizeOutput(output) {
|
|
|
134
135
|
}
|
|
135
136
|
|
|
136
137
|
// One field is enough to tell whether the account still exists; reading the whole hash was not
|
|
137
|
-
const accountExists = async (redis, account) => (await redis.hexists(
|
|
138
|
+
const accountExists = async (redis, account) => (await redis.hexists(accountDataKey(account), 'account')) === 1;
|
|
138
139
|
|
|
139
140
|
/**
|
|
140
141
|
* @param {Object} deps
|
package/lib/export.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const { accountDataKey } = require('./redis-keys');
|
|
3
4
|
const os = require('os');
|
|
4
5
|
const crypto = require('crypto');
|
|
5
6
|
const fs = require('fs');
|
|
@@ -381,9 +382,45 @@ function calculateScore(timestamp, folder, messageId, uid) {
|
|
|
381
382
|
return baseSeconds * 1000000 + tiebreaker;
|
|
382
383
|
}
|
|
383
384
|
|
|
385
|
+
// BullMQ states of a job that is still going to run, or is running (markInterruptedAsFailed())
|
|
386
|
+
const LIVE_JOB_STATES = new Set(['waiting', 'delayed', 'prioritized', 'waiting-children', 'active']);
|
|
387
|
+
|
|
388
|
+
// Recovery runs in every export worker as it starts, so an export whose job is still live belongs
|
|
389
|
+
// to BullMQ rather than to recovery: a waiting job is picked up by a worker, an active one is
|
|
390
|
+
// either running in a sibling worker or held by the lock of a worker that died, which lapses after
|
|
391
|
+
// the export worker's lockDuration so BullMQ's stalled check runs it again. Export.startProcessing()
|
|
392
|
+
// rebuilds an export from the start on every run, so a crash ends the same way however long the
|
|
393
|
+
// restart took. Only an export whose job is gone or finished is failed here.
|
|
394
|
+
//
|
|
395
|
+
// The removal is still the last word before anything is deleted, because a job read as finished or
|
|
396
|
+
// gone a moment ago is the only thing standing between recovery and a live export: BullMQ refuses,
|
|
397
|
+
// in the same script that would remove it, a job whose lock is held, so a removal that succeeded
|
|
398
|
+
// means no worker can run the job any more. A refused removal, or any other failure, keeps the
|
|
399
|
+
// export rather than deleting it on a guess.
|
|
400
|
+
async function removeAbandonedJob(job, account, exportId) {
|
|
401
|
+
try {
|
|
402
|
+
await job.remove();
|
|
403
|
+
} catch (err) {
|
|
404
|
+
logger.info({ msg: 'Kept an interrupted export, its job could not be removed', account, exportId, err });
|
|
405
|
+
return false;
|
|
406
|
+
}
|
|
407
|
+
logger.info({ msg: 'Removed interrupted export job from queue', account, exportId });
|
|
408
|
+
return true;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// Whether startup recovery should leave an export to the queue. A cancelled export is never left:
|
|
412
|
+
// running its job would reset the status to processing and undo the cancellation, so its job is
|
|
413
|
+
// removed (unless a worker holds it, and that worker sees the cancellation itself)
|
|
414
|
+
async function isLeftToQueue(job, status) {
|
|
415
|
+
if (!job || status === 'cancelled') {
|
|
416
|
+
return false;
|
|
417
|
+
}
|
|
418
|
+
return LIVE_JOB_STATES.has(await job.getState().catch(() => null));
|
|
419
|
+
}
|
|
420
|
+
|
|
384
421
|
class Export {
|
|
385
422
|
static async create(account, options) {
|
|
386
|
-
const accountData = await redis.hgetall(
|
|
423
|
+
const accountData = await redis.hgetall(accountDataKey(account));
|
|
387
424
|
if (!accountData || !accountData.account) {
|
|
388
425
|
throw createError('Account not found', 'AccountNotFound', 404);
|
|
389
426
|
}
|
|
@@ -802,9 +839,11 @@ class Export {
|
|
|
802
839
|
|
|
803
840
|
if (data && (data.status === 'processing' || data.status === 'queued' || data.status === 'cancelled')) {
|
|
804
841
|
const job = await exportQueue.getJob(exportId).catch(() => null);
|
|
805
|
-
if (job) {
|
|
806
|
-
|
|
807
|
-
|
|
842
|
+
if (await isLeftToQueue(job, data.status)) {
|
|
843
|
+
continue;
|
|
844
|
+
}
|
|
845
|
+
if (job && !(await removeAbandonedJob(job, account, exportId))) {
|
|
846
|
+
continue;
|
|
808
847
|
}
|
|
809
848
|
|
|
810
849
|
await Export.fail(account, exportId, 'Export interrupted by application restart');
|
package/lib/field-usage.js
CHANGED
|
@@ -122,7 +122,7 @@ const FIELD_USAGE = {
|
|
|
122
122
|
|
|
123
123
|
revokeGrant:
|
|
124
124
|
'Set this when deleting an account should also cut EmailEngine off at the provider, for example because a user asked for their data to be disconnected rather than just removed here.\n\n' +
|
|
125
|
-
'It currently works for individual Gmail OAuth2 grants. Gmail Workspace service-account integrations, Outlook and non-OAuth2 accounts ignore it.
|
|
125
|
+
'It currently works for individual Gmail OAuth2 grants. Gmail Workspace service-account integrations, Outlook and non-OAuth2 accounts ignore it. The response reports the outcome under `revocation`. With `true` a failed revocation never blocks the deletion; use `required` when the account must stay until the grant is gone, so a failure can be retried without reading the token out of EmailEngine.',
|
|
126
126
|
|
|
127
127
|
webSafeHtml:
|
|
128
128
|
'Turn this on when you are rendering the message in your own UI and want EmailEngine to do the sanitising. It is a shorthand that overrides `textType`, `preProcessHtml` and `embedAttachedImages`.\n\n' +
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Split out of lib/tools.js so leaf modules (lib/api-listener.js) can read a switch without loading
|
|
4
|
+
// it. Still re-exported from lib/tools.js, which is where most callers reach it.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Reads a configuration switch the way every EmailEngine setting reads one.
|
|
8
|
+
*
|
|
9
|
+
* @param {*} value - A boolean, a number, or a string such as "true", "yes", "on", "enabled" or "1"
|
|
10
|
+
* @returns {boolean}
|
|
11
|
+
*/
|
|
12
|
+
function getBoolean(value) {
|
|
13
|
+
if (typeof value === 'boolean') {
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
if (typeof value === 'string') {
|
|
18
|
+
value = value.trim();
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (typeof value === 'string' && !isNaN(value) && /^[0-9]+$/.test(value)) {
|
|
22
|
+
value = Number(value);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (typeof value === 'number') {
|
|
26
|
+
return !!value;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (typeof value === 'string') {
|
|
30
|
+
// `on` and `enabled` are what several operators write in env files, and joi and
|
|
31
|
+
// resolveHttpProxy() already read `on` as true
|
|
32
|
+
return /^(y|true|on$|enabled$)/i.test(value);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = { getBoolean };
|
package/lib/get-raw-email.js
CHANGED
|
@@ -401,7 +401,16 @@ async function getRawEmail(data, licenseInfo, options) {
|
|
|
401
401
|
|
|
402
402
|
const mail = new MailComposer(mailComposerOptions);
|
|
403
403
|
|
|
404
|
-
|
|
404
|
+
let compiled;
|
|
405
|
+
try {
|
|
406
|
+
compiled = mail.compile();
|
|
407
|
+
} catch (err) {
|
|
408
|
+
// an otp value the schema let through but the OTP-Token header can not carry
|
|
409
|
+
if (err.code === 'EOTP') {
|
|
410
|
+
err.statusCode = 400;
|
|
411
|
+
}
|
|
412
|
+
throw err;
|
|
413
|
+
}
|
|
405
414
|
// do not strip Bcc header from the message (will be removed later)
|
|
406
415
|
compiled.keepBcc = true;
|
|
407
416
|
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The Docker image's HEALTHCHECK, run by bin/healthcheck.js. The image's first health check was a
|
|
4
|
+
// BusyBox wget against http://127.0.0.1:${EENGINE_PORT}, which failed every time on an instance
|
|
5
|
+
// serving the API over HTTPS: the probe reached a TLS socket with a plain request, Swarm marked
|
|
6
|
+
// the task unhealthy, sent it no traffic and replaced it every few minutes. The probe therefore
|
|
7
|
+
// asks lib/api-listener.js, the same resolver the API listener is built from.
|
|
8
|
+
|
|
9
|
+
const http = require('http');
|
|
10
|
+
const https = require('https');
|
|
11
|
+
const { apiPort, apiHost, apiTlsConfig } = require('./api-listener');
|
|
12
|
+
|
|
13
|
+
const PROBE_TIMEOUT = 5000;
|
|
14
|
+
const PROBE_PATH = '/health/live';
|
|
15
|
+
|
|
16
|
+
// A listener bound to every address answers on loopback; a specific address is probed directly
|
|
17
|
+
const WILDCARD_HOSTS = new Set(['', '0.0.0.0', '::']);
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Where the API listener of this instance can be reached from inside its own container.
|
|
21
|
+
*
|
|
22
|
+
* @param {Object} api - The `[api]` section of the configuration
|
|
23
|
+
* @returns {{ protocol: string, host: string, port: number }}
|
|
24
|
+
*/
|
|
25
|
+
function probeTarget(api) {
|
|
26
|
+
const host = (apiHost(api) || '')
|
|
27
|
+
.toString()
|
|
28
|
+
.trim()
|
|
29
|
+
.replace(/^\[(.*)\]$/, '$1');
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
protocol: apiTlsConfig(api) ? 'https' : 'http',
|
|
33
|
+
host: WILDCARD_HOSTS.has(host) ? '127.0.0.1' : host,
|
|
34
|
+
port: Number(apiPort(api))
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Asks the liveness endpoint once.
|
|
40
|
+
*
|
|
41
|
+
* @param {{ protocol: string, host: string, port: number }} target
|
|
42
|
+
* @param {Object} [opts]
|
|
43
|
+
* @param {number} [opts.timeout] - Milliseconds before the probe gives up
|
|
44
|
+
* @returns {Promise<{ ok: boolean, statusCode?: number, error?: string }>}
|
|
45
|
+
*/
|
|
46
|
+
function probe(target, { timeout = PROBE_TIMEOUT } = {}) {
|
|
47
|
+
const client = target.protocol === 'https' ? https : http;
|
|
48
|
+
|
|
49
|
+
return new Promise(resolve => {
|
|
50
|
+
const req = client.get(
|
|
51
|
+
{
|
|
52
|
+
host: target.host,
|
|
53
|
+
port: target.port,
|
|
54
|
+
path: PROBE_PATH,
|
|
55
|
+
timeout,
|
|
56
|
+
// The probe only asks whether this process answers. The certificate is whatever the
|
|
57
|
+
// operator serves for a public name (or the self-signed fallback), never one issued
|
|
58
|
+
// for the loopback address, and judging it is not the liveness check's business.
|
|
59
|
+
rejectUnauthorized: false
|
|
60
|
+
},
|
|
61
|
+
res => {
|
|
62
|
+
res.resume();
|
|
63
|
+
resolve({ ok: res.statusCode === 200, statusCode: res.statusCode });
|
|
64
|
+
}
|
|
65
|
+
);
|
|
66
|
+
req.on('timeout', () => req.destroy(new Error(`No response in ${timeout}ms`)));
|
|
67
|
+
req.on('error', err => resolve({ ok: false, error: err.message }));
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
module.exports = { probeTarget, probe, PROBE_PATH };
|
|
@@ -49,65 +49,14 @@ const IMAP_PROXY_MAX_CLIENTS = Number(readEnvValue('EENGINE_IMAPPROXY_MAX_CLIENT
|
|
|
49
49
|
|
|
50
50
|
const { TLS_DEFAULTS } = require('../consts');
|
|
51
51
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
async function call(message, transferList) {
|
|
56
|
-
return new Promise((resolve, reject) => {
|
|
57
|
-
let mid = `${Date.now()}:${++mids}`;
|
|
58
|
-
|
|
59
|
-
let ttl = Math.max(message.timeout || 0, EENGINE_TIMEOUT || 0);
|
|
60
|
-
let timer = setTimeout(() => {
|
|
61
|
-
let err = new Error('Timeout waiting for command response [T4]');
|
|
62
|
-
err.statusCode = 504;
|
|
63
|
-
err.code = 'Timeout';
|
|
64
|
-
err.ttl = ttl;
|
|
65
|
-
callQueue.delete(mid);
|
|
66
|
-
reject(err);
|
|
67
|
-
}, ttl);
|
|
68
|
-
|
|
69
|
-
callQueue.set(mid, { resolve, reject, timer });
|
|
70
|
-
|
|
71
|
-
try {
|
|
72
|
-
parentPort.postMessage(
|
|
73
|
-
{
|
|
74
|
-
cmd: 'call',
|
|
75
|
-
mid,
|
|
76
|
-
message
|
|
77
|
-
},
|
|
78
|
-
transferList
|
|
79
|
-
);
|
|
80
|
-
} catch (err) {
|
|
81
|
-
clearTimeout(timer);
|
|
82
|
-
callQueue.delete(mid);
|
|
83
|
-
return reject(err);
|
|
84
|
-
}
|
|
85
|
-
});
|
|
86
|
-
}
|
|
52
|
+
const { createRpcClient } = require('../worker-rpc');
|
|
53
|
+
const rpc = createRpcClient({ port: parentPort, defaultTimeout: EENGINE_TIMEOUT, timeoutTag: 'T4' });
|
|
54
|
+
const call = rpc.call;
|
|
87
55
|
|
|
88
56
|
// Resolve pending call() promises when the main thread answers. Without this any
|
|
89
57
|
// RPC issued from this worker (via the `call` passed into Account) would never settle
|
|
90
58
|
// and would reject on timeout. Mirrors the handlers in workers/imap.js and smtp.js.
|
|
91
|
-
parentPort.on('message',
|
|
92
|
-
if (message && message.cmd === 'resp' && message.mid && callQueue.has(message.mid)) {
|
|
93
|
-
let { resolve, reject, timer } = callQueue.get(message.mid);
|
|
94
|
-
clearTimeout(timer);
|
|
95
|
-
callQueue.delete(message.mid);
|
|
96
|
-
|
|
97
|
-
if (message.error) {
|
|
98
|
-
let err = new Error(message.error);
|
|
99
|
-
if (message.code) {
|
|
100
|
-
err.code = message.code;
|
|
101
|
-
}
|
|
102
|
-
if (message.statusCode) {
|
|
103
|
-
err.statusCode = message.statusCode;
|
|
104
|
-
}
|
|
105
|
-
return reject(err);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
return resolve(message.response);
|
|
109
|
-
}
|
|
110
|
-
});
|
|
59
|
+
parentPort.on('message', rpc.handleResponse);
|
|
111
60
|
|
|
112
61
|
async function metrics(logger, key, method, ...args) {
|
|
113
62
|
try {
|