emailengine-app 2.87.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 +19 -0
- package/Dockerfile +3 -4
- 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 +9 -8
- package/lib/api-listener.js +40 -0
- 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 +23 -107
- package/lib/email-client/gmail-client.js +7 -4
- package/lib/email-client/imap/mailbox.js +89 -96
- 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 +4 -2
- package/lib/env-setting-overrides.js +6 -2
- package/lib/export-worker.js +3 -2
- package/lib/export.js +43 -4
- package/lib/get-boolean.js +38 -0
- 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/oauth2-apps.js +2 -1
- package/lib/read-env-value.js +19 -7
- package/lib/redis-keys.js +19 -0
- package/lib/redis-operations.js +7 -3
- 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/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/worker-rpc-error.js +10 -5
- package/lib/worker-rpc.js +138 -0
- package/package.json +17 -19
- package/sbom.json +370 -1446
- package/server.js +6 -5
- package/static/css/flyonui.css +2 -2
- package/static/licenses.html +253 -1366
- package/translations/messages.pot +16 -16
- package/workers/api.js +41 -465
- 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
|
@@ -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');
|
|
@@ -2912,7 +2914,7 @@ class OutlookClient extends BaseClient {
|
|
|
2912
2914
|
* Get Redis key for account data
|
|
2913
2915
|
*/
|
|
2914
2916
|
getAccountKey() {
|
|
2915
|
-
return
|
|
2917
|
+
return accountDataKey(this.account);
|
|
2916
2918
|
}
|
|
2917
2919
|
|
|
2918
2920
|
/**
|
|
@@ -4637,7 +4639,7 @@ class OutlookClient extends BaseClient {
|
|
|
4637
4639
|
}
|
|
4638
4640
|
|
|
4639
4641
|
// check if we have seen this message before or not (approximate estimation using HyperLogLog)
|
|
4640
|
-
messageData.seemsLikeNew = messageData
|
|
4642
|
+
messageData.seemsLikeNew = !isOwnSent(messageData) && !!(await this.redis.pfadd(this.getSeenMessagesKey(), messageData.messageId));
|
|
4641
4643
|
|
|
4642
4644
|
return messageData;
|
|
4643
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');
|
|
@@ -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 };
|
|
@@ -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 {
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Keeps a failed type-of-service marking from ending the process.
|
|
4
|
+
//
|
|
5
|
+
// undici 7 (held there by the Node 20 floor, see .ncurc.js) calls socket.setTypeOfService() for
|
|
6
|
+
// every request on a Node that has it (24.x), unguarded, as it writes the request (client-h1.js). On macOS
|
|
7
|
+
// the underlying setsockopt() answers EINVAL once the peer has reset the connection, so a peer that
|
|
8
|
+
// went away right after accepting (a server shutting down or restarting) threw an uncaughtException
|
|
9
|
+
// in whichever thread made the request. undici 8 wraps the call itself; marking is best effort
|
|
10
|
+
// there too. EmailEngine never sets a type of service, so nothing is lost by ignoring the failure.
|
|
11
|
+
// Remove this together with the undici 8 upgrade.
|
|
12
|
+
|
|
13
|
+
const net = require('net');
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Wraps setTypeOfService() of a socket prototype so a failure of the call itself is ignored
|
|
17
|
+
* @param {Object} proto - net.Socket.prototype, or a stand-in in tests
|
|
18
|
+
* @returns {boolean} Whether the prototype was wrapped (false without the method, or done before)
|
|
19
|
+
*/
|
|
20
|
+
function guardTypeOfService(proto) {
|
|
21
|
+
const original = proto.setTypeOfService;
|
|
22
|
+
if (typeof original !== 'function' || original.tosGuarded) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
const guarded = function setTypeOfService(...args) {
|
|
26
|
+
try {
|
|
27
|
+
return original.apply(this, args);
|
|
28
|
+
} catch (err) {
|
|
29
|
+
if (err && err.syscall === 'setTypeOfService') {
|
|
30
|
+
return this;
|
|
31
|
+
}
|
|
32
|
+
throw err;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
guarded.tosGuarded = true;
|
|
36
|
+
proto.setTypeOfService = guarded;
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
guardTypeOfService(net.Socket.prototype);
|
|
41
|
+
|
|
42
|
+
module.exports = { guardTypeOfService };
|
package/lib/oauth2-apps.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const { accountDataKey } = require('./redis-keys');
|
|
3
4
|
const { redis } = require('./db');
|
|
4
5
|
const msgpack = require('./msgpack');
|
|
5
6
|
const logger = require('./logger');
|
|
@@ -643,7 +644,7 @@ class OAuth2AppsHandler {
|
|
|
643
644
|
let chunk = accounts.slice(i, i + CHUNK_SIZE);
|
|
644
645
|
let readReq = this.redis.pipeline();
|
|
645
646
|
for (let account of chunk) {
|
|
646
|
-
readReq = readReq.hget(
|
|
647
|
+
readReq = readReq.hget(accountDataKey(account), 'oauth2');
|
|
647
648
|
}
|
|
648
649
|
let rows = await readReq.exec();
|
|
649
650
|
|
package/lib/read-env-value.js
CHANGED
|
@@ -6,9 +6,11 @@
|
|
|
6
6
|
|
|
7
7
|
const Fs = require('fs');
|
|
8
8
|
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
|
|
9
|
+
// Loaded on first use: only the <KEY>_FILE branch logs, and a short-lived process that reads plain
|
|
10
|
+
// variables (the Docker health check) should not pay for pino and dotenv. lib/logger.js takes its
|
|
11
|
+
// constants from lib/logger-consts.js rather than lib/consts.js, so there is no cycle either way.
|
|
12
|
+
let logger;
|
|
13
|
+
const getLogger = () => (logger = logger || require('./logger'));
|
|
12
14
|
|
|
13
15
|
// The keys that lib/db.js and lib/get-secret.js used to resolve through private copies of this
|
|
14
16
|
// function. Those copies stripped a single trailing newline and nothing else, so for a file carrying
|
|
@@ -52,20 +54,30 @@ function readEnvValue(key) {
|
|
|
52
54
|
// the operator needs to find it, and the value is what the warning exists to protect.
|
|
53
55
|
const legacyValue = contents.replace(/\r?\n$/, '');
|
|
54
56
|
if (LEGACY_UNTRIMMED_KEYS.has(key) && value !== legacyValue) {
|
|
55
|
-
|
|
57
|
+
getLogger().warn({
|
|
56
58
|
msg: 'Environment value read from file carries whitespace that is now trimmed, so it resolves differently than in earlier releases. Set the variable itself rather than the file to keep the old value, as one given in the environment is used verbatim.',
|
|
57
59
|
key,
|
|
58
60
|
file: process.env[`${key}_FILE`]
|
|
59
61
|
});
|
|
60
62
|
}
|
|
61
63
|
|
|
62
|
-
|
|
64
|
+
getLogger().trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
|
|
63
65
|
} catch (err) {
|
|
64
|
-
|
|
66
|
+
getLogger().error({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
|
|
65
67
|
process.env[key] = '';
|
|
66
68
|
}
|
|
67
69
|
return process.env[key];
|
|
68
70
|
}
|
|
69
71
|
}
|
|
70
72
|
|
|
71
|
-
|
|
73
|
+
/**
|
|
74
|
+
* Whether an environment value is set, in either its plain or its `<KEY>_FILE` form.
|
|
75
|
+
*
|
|
76
|
+
* @param {string} key - Environment variable name
|
|
77
|
+
* @returns {boolean}
|
|
78
|
+
*/
|
|
79
|
+
function hasEnvValue(key) {
|
|
80
|
+
return key in process.env || `${key}_FILE` in process.env;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
module.exports = { readEnvValue, hasEnvValue };
|