emailengine-app 2.85.0 → 2.86.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/.ncurc.js +24 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +74 -0
- package/Dockerfile +14 -1
- package/ENVIRONMENT.md +139 -0
- package/README.md +1 -1
- package/config/default.toml +2 -0
- package/copy-static-files.sh +4 -2
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +4 -3
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +194 -165
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +78 -26
- package/lib/api-routes/blocklist-routes.js +68 -2
- package/lib/api-routes/delivery-test-routes.js +1 -1
- package/lib/api-routes/gateway-routes.js +82 -10
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +3 -3
- package/lib/api-routes/message-routes.js +15 -7
- package/lib/api-routes/oauth2-app-routes.js +15 -8
- package/lib/api-routes/outbox-routes.js +77 -66
- package/lib/api-routes/permission-map.js +55 -6
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +11 -4
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +4 -3
- package/lib/api-routes/template-routes.js +7 -6
- package/lib/api-routes/token-routes.js +11 -5
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +119 -4
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -46
- package/lib/db.js +14 -6
- package/lib/delivery-error.js +6 -0
- package/lib/deprecations.js +270 -0
- package/lib/email-client/base-client.js +130 -156
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +51 -11
- package/lib/email-client/imap/adaptive-idle-store.js +73 -0
- package/lib/email-client/imap/adaptive-idle.js +278 -0
- package/lib/email-client/imap/connection-errors.js +14 -1
- package/lib/email-client/imap/idle-settings.js +31 -5
- package/lib/email-client/imap/listing-diff.js +37 -0
- package/lib/email-client/imap/mailbox.js +372 -226
- package/lib/email-client/imap/subconnection.js +7 -29
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +227 -163
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/outlook-client.js +372 -338
- package/lib/email-client/smtp-pool-manager.js +16 -13
- package/lib/email-client/sync-state-fields.js +19 -0
- package/lib/encrypt.js +157 -41
- package/lib/enum-descriptions.js +3 -1
- package/lib/env-setting-overrides.js +288 -0
- package/lib/export-worker.js +751 -0
- package/lib/export.js +64 -15
- package/lib/gateway.js +17 -1
- package/lib/get-raw-email.js +25 -107
- package/lib/health.js +75 -0
- package/lib/lock-run.js +119 -0
- package/lib/logger-consts.js +48 -0
- package/lib/logger.js +1 -1
- package/lib/lua/z-head-scores.lua +28 -0
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +20 -1
- package/lib/oauth2-apps.js +630 -655
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/privileged-settings.js +2 -2
- package/lib/queue-browser/definitions.js +11 -0
- package/lib/queue-browser/index.js +68 -19
- package/lib/queue-job-actions.js +18 -1
- package/lib/queue-retention.js +48 -12
- package/lib/queue-stats.js +11 -2
- package/lib/read-env-value.js +3 -0
- package/lib/redis-memory-warnings.js +99 -0
- package/lib/redis-reconnect.js +29 -0
- package/lib/request-timing.js +23 -0
- package/lib/respawn-backoff.js +35 -0
- package/lib/rewrite-text-nodes.js +19 -59
- package/lib/schemas.js +163 -39
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/thread-diagnostics.js +18 -1
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +4 -3
- package/lib/tools.js +8 -41
- package/lib/ui-routes/admin-config-routes.js +64 -90
- package/lib/ui-routes/admin-entities-routes.js +2 -14
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/outlook-subscription-view.js +1 -1
- package/lib/ui-routes/overridable-fields.js +84 -0
- package/lib/ui-routes/queue-routes.js +8 -5
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/utils/decode-headers.js +3 -12
- package/lib/utils/filter-empty.js +20 -0
- package/lib/utils/int-setting.js +48 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/web-safe-html.js +18 -105
- package/lib/webhook-delivery.js +461 -0
- package/lib/webhook-failures.js +132 -0
- package/lib/webhook-request.js +29 -1
- package/lib/webhook-routing.js +30 -1
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +54 -41
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +21 -20
- package/sbom.json +304 -382
- package/server.js +149 -76
- package/static/js/ace/ace.js +1 -1
- package/static/licenses.html +21 -31
- package/translations/messages.pot +26 -26
- package/views/config/security.hbs +22 -0
- package/views/config/service.hbs +44 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/workers/api.js +102 -28
- package/workers/export.js +16 -631
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/webhooks.js +18 -432
- package/lib/email-client/outlook-fallback-poll.js +0 -30
package/lib/export.js
CHANGED
|
@@ -631,25 +631,51 @@ class Export {
|
|
|
631
631
|
}
|
|
632
632
|
|
|
633
633
|
static async queueMessage(account, exportId, messageInfo) {
|
|
634
|
+
return (await Export.queueMessages(account, exportId, [messageInfo])) === 1;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* Queues messages of an export: per message the ZADD, the count of a new member and the queue's
|
|
639
|
+
* expiry (copied from the record's), all of them sent as one pipeline. Indexing used to send one
|
|
640
|
+
* call per message. A retried folder queues the messages its failed attempt already queued, and
|
|
641
|
+
* only a new member counts, see the script
|
|
642
|
+
* @param {string} account
|
|
643
|
+
* @param {string} exportId
|
|
644
|
+
* @param {Object[]} messages - { folder, messageId, uid, size, date }
|
|
645
|
+
* @returns {Promise<number>} How many were new
|
|
646
|
+
*/
|
|
647
|
+
static async queueMessages(account, exportId, messages) {
|
|
648
|
+
if (!messages.length) {
|
|
649
|
+
return 0;
|
|
650
|
+
}
|
|
651
|
+
|
|
634
652
|
const queueKey = getExportQueueKey(account, exportId);
|
|
635
653
|
const exportKey = getExportKey(account, exportId);
|
|
636
654
|
|
|
637
|
-
const
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
655
|
+
const pipeline = redis.pipeline();
|
|
656
|
+
for (const messageInfo of messages) {
|
|
657
|
+
const score = calculateScore(messageInfo.date, messageInfo.folder, messageInfo.messageId, messageInfo.uid);
|
|
658
|
+
const value = msgpack
|
|
659
|
+
.encode({
|
|
660
|
+
folder: messageInfo.folder,
|
|
661
|
+
messageId: messageInfo.messageId,
|
|
662
|
+
uid: messageInfo.uid,
|
|
663
|
+
size: messageInfo.size || 0
|
|
664
|
+
})
|
|
665
|
+
.toString('base64url');
|
|
666
|
+
pipeline.eeExportQueueAdd(exportKey, queueKey, score, value, 'messagesQueued');
|
|
667
|
+
}
|
|
647
668
|
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
669
|
+
let added = 0;
|
|
670
|
+
for (const [err, result] of await pipeline.exec()) {
|
|
671
|
+
if (err) {
|
|
672
|
+
throw err;
|
|
673
|
+
}
|
|
674
|
+
if (result) {
|
|
675
|
+
added++;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
return added;
|
|
653
679
|
}
|
|
654
680
|
|
|
655
681
|
static async getNextBatch(account, exportId, limit) {
|
|
@@ -684,6 +710,29 @@ class Export {
|
|
|
684
710
|
await redis.hincrby(getExportKey(account, exportId), 'messagesSkipped', 1);
|
|
685
711
|
}
|
|
686
712
|
|
|
713
|
+
/**
|
|
714
|
+
* Adds a batch worth of progress to the export record in one round trip
|
|
715
|
+
* @param {string} account
|
|
716
|
+
* @param {string} exportId
|
|
717
|
+
* @param {{exported?: number, bytesWritten?: number, skipped?: number}} counts
|
|
718
|
+
*/
|
|
719
|
+
static async incrementCounters(account, exportId, counts) {
|
|
720
|
+
const exportKey = getExportKey(account, exportId);
|
|
721
|
+
const fields = [
|
|
722
|
+
['messagesExported', counts.exported],
|
|
723
|
+
['bytesWritten', counts.bytesWritten],
|
|
724
|
+
['messagesSkipped', counts.skipped]
|
|
725
|
+
].filter(([, value]) => value);
|
|
726
|
+
if (!fields.length) {
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
const multi = redis.multi();
|
|
730
|
+
for (const [field, value] of fields) {
|
|
731
|
+
multi.hincrby(exportKey, field, value);
|
|
732
|
+
}
|
|
733
|
+
await multi.exec();
|
|
734
|
+
}
|
|
735
|
+
|
|
687
736
|
static async complete(account, exportId) {
|
|
688
737
|
const exportKey = getExportKey(account, exportId);
|
|
689
738
|
const queueKey = getExportQueueKey(account, exportId);
|
package/lib/gateway.js
CHANGED
|
@@ -292,4 +292,20 @@ class Gateway {
|
|
|
292
292
|
}
|
|
293
293
|
}
|
|
294
294
|
|
|
295
|
-
|
|
295
|
+
/**
|
|
296
|
+
* The SMTP connection config of a gateway: what a message sent through it connects with, and what
|
|
297
|
+
* verifyAccountInfo() checks it with, from its stored settings or from the same fields on the admin
|
|
298
|
+
* form
|
|
299
|
+
* @param {Object} data - `{ host, port, secure, requireTLS, user, pass }`
|
|
300
|
+
* @returns {Object} SMTP configuration
|
|
301
|
+
*/
|
|
302
|
+
function gatewaySmtpConfig(data) {
|
|
303
|
+
const { host, port, secure, requireTLS, user, pass } = data;
|
|
304
|
+
const config = { host, port, secure, requireTLS };
|
|
305
|
+
if (user || pass) {
|
|
306
|
+
config.auth = { user: user || '', pass: pass || '' };
|
|
307
|
+
}
|
|
308
|
+
return config;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
module.exports = { Gateway, gatewaySmtpConfig };
|
package/lib/get-raw-email.js
CHANGED
|
@@ -7,10 +7,9 @@ const { HeadersRewriter } = require('./headers-rewriter');
|
|
|
7
7
|
const { markParseFailure } = require('./smtp-message-processor');
|
|
8
8
|
const mimeFuncs = require('nodemailer/lib/mime-funcs');
|
|
9
9
|
const MimeNode = require('nodemailer/lib/mime-node');
|
|
10
|
-
const
|
|
10
|
+
const { parseAddressHeader } = require('mailparser');
|
|
11
11
|
const { randomUUID: uuid } = require('crypto');
|
|
12
12
|
const os = require('os');
|
|
13
|
-
const libmime = require('libmime');
|
|
14
13
|
const { getBoolean, genBaseBoundary, download } = require('./tools');
|
|
15
14
|
const msgpack = require('./msgpack');
|
|
16
15
|
const crypto = require('crypto');
|
|
@@ -58,8 +57,6 @@ async function processMessage(data, licenseInfo) {
|
|
|
58
57
|
const splitter = new Splitter();
|
|
59
58
|
const joiner = new Joiner();
|
|
60
59
|
const headersRewriter = new HeadersRewriter(async headers => {
|
|
61
|
-
let mn = new MimeNode();
|
|
62
|
-
|
|
63
60
|
let sendAtVal = headers.getFirst('x-ee-send-at');
|
|
64
61
|
headers.remove('x-ee-send-at');
|
|
65
62
|
|
|
@@ -120,7 +117,7 @@ async function processMessage(data, licenseInfo) {
|
|
|
120
117
|
}
|
|
121
118
|
|
|
122
119
|
// update or add new
|
|
123
|
-
let headerLine =
|
|
120
|
+
let headerLine = MimeNode.encodeHeaderValue(addrKey, addrValue);
|
|
124
121
|
if (headers.hasHeader(addrKey)) {
|
|
125
122
|
let addressEntries = addrValue.filter(entry => !entry._default);
|
|
126
123
|
if (!addressEntries.length) {
|
|
@@ -143,77 +140,21 @@ async function processMessage(data, licenseInfo) {
|
|
|
143
140
|
|
|
144
141
|
hasBcc = headers.hasHeader('bcc');
|
|
145
142
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
return addr;
|
|
160
|
-
})
|
|
161
|
-
.find(addr => addr && addr.address),
|
|
162
|
-
to: headers
|
|
163
|
-
.get('to')
|
|
164
|
-
.flatMap(line => addressparser(line, { flatten: true }))
|
|
165
|
-
.filter(a => a)
|
|
166
|
-
.map(addr => {
|
|
167
|
-
if (addr.name) {
|
|
168
|
-
try {
|
|
169
|
-
addr.name = libmime.decodeWords(addr.name);
|
|
170
|
-
} catch (err) {
|
|
171
|
-
// ignore
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
return addr;
|
|
175
|
-
}),
|
|
176
|
-
cc: headers
|
|
177
|
-
.get('cc')
|
|
178
|
-
.flatMap(line => addressparser(line, { flatten: true }))
|
|
179
|
-
.filter(a => a)
|
|
180
|
-
.map(addr => {
|
|
181
|
-
if (addr.name) {
|
|
182
|
-
try {
|
|
183
|
-
addr.name = libmime.decodeWords(addr.name);
|
|
184
|
-
} catch (err) {
|
|
185
|
-
// ignore
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
return addr;
|
|
189
|
-
}),
|
|
190
|
-
bcc: headers
|
|
191
|
-
.get('bcc')
|
|
192
|
-
.flatMap(line => addressparser(line, { flatten: true }))
|
|
193
|
-
.filter(a => a)
|
|
194
|
-
.map(addr => {
|
|
195
|
-
if (addr.name) {
|
|
196
|
-
try {
|
|
197
|
-
addr.name = libmime.decodeWords(addr.name);
|
|
198
|
-
} catch (err) {
|
|
199
|
-
// ignore
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
return addr;
|
|
203
|
-
})
|
|
204
|
-
};
|
|
143
|
+
// The addresses an envelope is built from: a punycode domain stays in the ASCII form every
|
|
144
|
+
// server accepts, and an entry left without an address (an encoded word hiding one is
|
|
145
|
+
// dropped by the parser) is no recipient. getDecoded() unfolds the value and drops the
|
|
146
|
+
// header name, and leaves encoded words for the parser to judge
|
|
147
|
+
const envelopeAddresses = key =>
|
|
148
|
+
parseAddressHeader(
|
|
149
|
+
headers.getDecoded(key).map(header => header.value),
|
|
150
|
+
{ flatten: true, decodePunycode: false }
|
|
151
|
+
)
|
|
152
|
+
.value.map(addr => addr.address)
|
|
153
|
+
.filter(address => address);
|
|
205
154
|
|
|
206
155
|
envelope = data.envelope || {
|
|
207
|
-
from: (
|
|
208
|
-
to: Array.from(
|
|
209
|
-
new Set(
|
|
210
|
-
[]
|
|
211
|
-
.concat(addresses.to)
|
|
212
|
-
.concat(addresses.cc)
|
|
213
|
-
.concat(addresses.bcc)
|
|
214
|
-
.map(addr => addr.address)
|
|
215
|
-
)
|
|
216
|
-
)
|
|
156
|
+
from: envelopeAddresses('from')[0] || '',
|
|
157
|
+
to: Array.from(new Set([...envelopeAddresses('to'), ...envelopeAddresses('cc'), ...envelopeAddresses('bcc')]))
|
|
217
158
|
};
|
|
218
159
|
|
|
219
160
|
envelope.from = [].concat(envelope.from || []).shift() || '';
|
|
@@ -259,7 +200,11 @@ async function processMessage(data, licenseInfo) {
|
|
|
259
200
|
headers.update(casedKey, data.headers[key]);
|
|
260
201
|
break;
|
|
261
202
|
default:
|
|
262
|
-
|
|
203
|
+
// Encoded like any other header: a non-ASCII value used to go out as raw 8-bit
|
|
204
|
+
headers.add(
|
|
205
|
+
casedKey,
|
|
206
|
+
typeof data.headers[key] === 'string' ? MimeNode.encodeHeaderValue(casedKey, data.headers[key]) : data.headers[key]
|
|
207
|
+
);
|
|
263
208
|
break;
|
|
264
209
|
}
|
|
265
210
|
}
|
|
@@ -444,40 +389,13 @@ async function getRawEmail(data, licenseInfo, options) {
|
|
|
444
389
|
|
|
445
390
|
if (!options.returnObject) {
|
|
446
391
|
for (let attachment of mailComposerOptions.attachments || []) {
|
|
447
|
-
// Insert message/rfc822 attachments "as is" without any encoding
|
|
392
|
+
// Insert message/rfc822 attachments "as is" without any encoding. Handed over decoded,
|
|
393
|
+
// nodemailer (10.2.0) labels the part 7bit when it is plain ASCII and 8bit otherwise,
|
|
394
|
+
// which this used to work out itself by building the part's headers by hand
|
|
448
395
|
if (/^message\/rfc822\b/i.test(attachment.contentType) && typeof attachment.content === 'string' && attachment.encoding) {
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
delete attachment.content;
|
|
396
|
+
attachment.content = Buffer.from(attachment.content, attachment.encoding);
|
|
452
397
|
delete attachment.encoding;
|
|
453
|
-
|
|
454
|
-
let isAscii = true;
|
|
455
|
-
for (let i = 0, len = raw.length; i < len; i++) {
|
|
456
|
-
if (raw[i] > 0x7f) {
|
|
457
|
-
// 8bit byte encountered, so the contents are not purely ascii (7bit)
|
|
458
|
-
isAscii = false;
|
|
459
|
-
break;
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
// we need to generate a valid message header with correct filename encoding (if needed)
|
|
464
|
-
const mimeNode = new MimeNode('message/rfc822', {
|
|
465
|
-
filename: attachment.filename,
|
|
466
|
-
// Use empty root node, otherwise MimeNode will set default Date and Message-ID headers which we do not need
|
|
467
|
-
rootNode: new MimeNode()
|
|
468
|
-
});
|
|
469
|
-
mimeNode.setHeader('Content-Disposition', attachment.contentDisposition || 'attachment');
|
|
470
|
-
mimeNode.setHeader('Content-Transfer-Encoding', isAscii ? '7bit' : '8bit');
|
|
471
|
-
const nodeHeaders = mimeNode.buildHeaders();
|
|
472
|
-
|
|
473
|
-
attachment.raw = Buffer.concat([
|
|
474
|
-
// Generated message/rfc822 headers
|
|
475
|
-
Buffer.from(nodeHeaders),
|
|
476
|
-
// Linebreak between headers and content
|
|
477
|
-
Buffer.from('\r\n\r\n'),
|
|
478
|
-
// Unencoded message/rfc822 contents
|
|
479
|
-
raw
|
|
480
|
-
]);
|
|
398
|
+
attachment.contentDisposition = attachment.contentDisposition || 'attachment';
|
|
481
399
|
}
|
|
482
400
|
}
|
|
483
401
|
|
package/lib/health.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The checks behind the health endpoints, kept free of Hapi and of the worker's own globals so each
|
|
4
|
+
// failure branch can be tested without booting the API.
|
|
5
|
+
//
|
|
6
|
+
// Two questions with different consequences. Liveness asks whether this process should be
|
|
7
|
+
// restarted, so it only depends on the process itself: answering it with a Redis check would make
|
|
8
|
+
// an orchestrator restart every pod whenever Redis has a hiccup. Readiness asks whether this process
|
|
9
|
+
// should get traffic, and that needs the IMAP workers and Redis, and is false while the API worker is
|
|
10
|
+
// draining on shutdown.
|
|
11
|
+
|
|
12
|
+
const crypto = require('crypto');
|
|
13
|
+
const { statusError } = require('./utils/status-error');
|
|
14
|
+
|
|
15
|
+
const notReady = (message, code) => statusError(message, code, 503);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {Object} deps
|
|
19
|
+
* @param {Function} deps.call - RPC to the main thread, resolves with the command's answer
|
|
20
|
+
* @param {Object} deps.redis - ioredis client
|
|
21
|
+
* @param {string} deps.prefix - Redis key prefix
|
|
22
|
+
* @param {number} deps.expectedImapWorkers - IMAP worker threads the instance is configured for
|
|
23
|
+
* @param {Function} deps.isDraining - True once the worker has started shutting down
|
|
24
|
+
* @returns {{ live: Function, ready: Function }}
|
|
25
|
+
*/
|
|
26
|
+
function createHealthChecks(deps) {
|
|
27
|
+
const { call, redis, prefix, expectedImapWorkers, isDraining } = deps;
|
|
28
|
+
|
|
29
|
+
function live() {
|
|
30
|
+
if (isDraining()) {
|
|
31
|
+
// Still alive while it drains; reporting otherwise would get it killed mid-request
|
|
32
|
+
return { success: true, draining: true };
|
|
33
|
+
}
|
|
34
|
+
return { success: true };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param {number} [timeout] - RPC timeout, already validated by the caller
|
|
39
|
+
*/
|
|
40
|
+
async function ready(timeout) {
|
|
41
|
+
if (isDraining()) {
|
|
42
|
+
throw notReady('Shutting down', 'ShuttingDown');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
let workers;
|
|
46
|
+
try {
|
|
47
|
+
({ workers } = (await call({ cmd: 'imapWorkerCount', timeout })) || {});
|
|
48
|
+
} catch (err) {
|
|
49
|
+
throw notReady(`Worker check failed: ${err.message}`, 'WorkerCheckFailed');
|
|
50
|
+
}
|
|
51
|
+
// The answer used to be compared as a whole object, which is never less than a number, so
|
|
52
|
+
// missing workers were never reported
|
|
53
|
+
if (!(workers >= expectedImapWorkers)) {
|
|
54
|
+
throw notReady('Not all IMAP workers available', 'WorkersUnavailable');
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const checkKey = `${prefix}test:${Date.now()}:${crypto.randomBytes(4).toString('hex')}`;
|
|
58
|
+
const expected = crypto.randomBytes(8).toString('hex');
|
|
59
|
+
let res;
|
|
60
|
+
try {
|
|
61
|
+
res = await redis.multi().set(checkKey, expected).get(checkKey).del(checkKey).exec();
|
|
62
|
+
} catch (err) {
|
|
63
|
+
throw notReady(`Database check failed: ${err.message}`, 'DatabaseCheckFailed');
|
|
64
|
+
}
|
|
65
|
+
if (!(res?.[1]?.[1] === expected && res?.[2]?.[1] === 1)) {
|
|
66
|
+
throw notReady('Database check failed', 'DatabaseCheckFailed');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return { success: true };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return { live, ready };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
module.exports = { createHealthChecks };
|
package/lib/lock-run.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const Boom = require('@hapi/boom');
|
|
4
|
+
|
|
5
|
+
// Runs a critical section under an ioredfour lock through its withLock(), which owns the acquire,
|
|
6
|
+
// the release in every case, and a failed release (the lock expires on its own). What a caller
|
|
7
|
+
// does when the lock is not there to take differs per site: refuse with an error of its own, or go
|
|
8
|
+
// ahead unserialized, so that is the one thing left to it.
|
|
9
|
+
|
|
10
|
+
let sharedLock = null;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The lock instance every EmailEngine lock is taken from: one namespace, one subscriber connection
|
|
14
|
+
* per worker, and the one place a failed release (which withLock() reports as an 'error' event and
|
|
15
|
+
* never as the result) is logged. Built on first use, so requiring this module opens nothing
|
|
16
|
+
* @returns {Object} ioredfour Lock
|
|
17
|
+
*/
|
|
18
|
+
function getSharedLock() {
|
|
19
|
+
if (!sharedLock) {
|
|
20
|
+
const Lock = require('ioredfour');
|
|
21
|
+
const { redis } = require('./db');
|
|
22
|
+
const logger = require('./logger');
|
|
23
|
+
sharedLock = new Lock({ redis, namespace: 'ee' });
|
|
24
|
+
sharedLock.on('error', err => logger.warn({ msg: 'Lock operation failed, the lock expires on its own', err }));
|
|
25
|
+
}
|
|
26
|
+
return sharedLock;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @param {Object} lock - ioredfour Lock instance
|
|
31
|
+
* @param {string} id - Lock id
|
|
32
|
+
* @param {Object} opts
|
|
33
|
+
* @param {number} opts.ttl - Lock TTL in ms
|
|
34
|
+
* @param {number|false} opts.wait - How long to wait for the lock in ms, false for one try
|
|
35
|
+
* @param {boolean} [opts.extend] - Keep extending the lock while fn runs, so ttl only has to cover a
|
|
36
|
+
* stalled process rather than the whole job
|
|
37
|
+
* @param {Function} fn - The critical section
|
|
38
|
+
* @param {Function} onUnavailable - (err) => value or throw, when the lock was not obtained (err is
|
|
39
|
+
* ioredfour's ELOCKNOTACQUIRED LockError, or the Redis error that kept it from being taken)
|
|
40
|
+
* @returns {Promise<*>} What fn resolves with, or what onUnavailable returns
|
|
41
|
+
*/
|
|
42
|
+
async function runLocked(lock, id, { ttl, wait, extend }, fn, onUnavailable) {
|
|
43
|
+
// withLock() rejects the same way whether the lock was not taken or fn failed; only the first
|
|
44
|
+
// goes to onUnavailable
|
|
45
|
+
let entered = false;
|
|
46
|
+
try {
|
|
47
|
+
return await lock.withLock(
|
|
48
|
+
id,
|
|
49
|
+
ttl,
|
|
50
|
+
wait === false ? 0 : wait,
|
|
51
|
+
async (...args) => {
|
|
52
|
+
entered = true;
|
|
53
|
+
return await fn(...args);
|
|
54
|
+
},
|
|
55
|
+
{ wait: wait !== false, extend: !!extend }
|
|
56
|
+
);
|
|
57
|
+
} catch (err) {
|
|
58
|
+
if (entered) {
|
|
59
|
+
throw err;
|
|
60
|
+
}
|
|
61
|
+
return await onUnavailable(err);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const isContention = err => !!err && err.code === 'ELOCKNOTACQUIRED';
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* An onUnavailable for runLocked() that refuses with a Boom error: contention (someone else held the
|
|
69
|
+
* lock for the whole wait) is logged as a warning and answered with `contention` (a 500 with no code
|
|
70
|
+
* of its own by default), a lock that could not be taken at all as an error and a 500 carrying the
|
|
71
|
+
* Redis error's code
|
|
72
|
+
* @param {Object} logger
|
|
73
|
+
* @param {string} message - What failed, e.g. 'Failed to get renewal lock'
|
|
74
|
+
* @param {Object} fields - Fields for the log entry
|
|
75
|
+
* @param {Object} [contention] - `{ statusCode, code, message, logMessage }` for the contention answer
|
|
76
|
+
* @returns {Function}
|
|
77
|
+
*/
|
|
78
|
+
function refuseUnavailableLock(logger, message, fields, contention = {}) {
|
|
79
|
+
return err => {
|
|
80
|
+
let error;
|
|
81
|
+
if (isContention(err)) {
|
|
82
|
+
logger.warn(Object.assign({ msg: contention.logMessage || `${message}, timed out waiting for the current holder` }, fields));
|
|
83
|
+
error = Boom.boomify(new Error(contention.message || message), { statusCode: contention.statusCode || 500 });
|
|
84
|
+
if (contention.code) {
|
|
85
|
+
error.output.payload.code = contention.code;
|
|
86
|
+
}
|
|
87
|
+
} else {
|
|
88
|
+
logger.error(Object.assign({ msg: message }, fields, { err }));
|
|
89
|
+
error = Boom.boomify(new Error(contention.failureMessage || message), { statusCode: 500 });
|
|
90
|
+
if (err && err.code) {
|
|
91
|
+
error.output.payload.code = err.code;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
throw error;
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* An onUnavailable for runLocked() outside the API: contention becomes an Error of its own (code
|
|
100
|
+
* LockNotAcquired) after a warning, any other failure is logged and rethrown as it is
|
|
101
|
+
* @param {Object} logger
|
|
102
|
+
* @param {string} message - What failed, e.g. 'Failed to get connection lock'
|
|
103
|
+
* @param {Object} fields - Fields for the log entry
|
|
104
|
+
* @returns {Function}
|
|
105
|
+
*/
|
|
106
|
+
function rethrowUnavailableLock(logger, message, fields) {
|
|
107
|
+
return err => {
|
|
108
|
+
if (isContention(err)) {
|
|
109
|
+
logger.warn(Object.assign({ msg: `${message}, timed out waiting for the current holder` }, fields));
|
|
110
|
+
const error = new Error(message);
|
|
111
|
+
error.code = 'LockNotAcquired';
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
logger.error(Object.assign({ msg: message }, fields, { err }));
|
|
115
|
+
throw err;
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
module.exports = { runLocked, refuseUnavailableLock, rethrowUnavailableLock, getSharedLock, isContention };
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The constants lib/logger.js needs, in a module that requires nothing. lib/consts.js reads its
|
|
4
|
+
// own environment variables through lib/read-env-value.js, which logs through lib/logger.js, so a
|
|
5
|
+
// logger that required lib/consts.js was a require cycle, and read-env-value had to defer every
|
|
6
|
+
// log line by a tick to get around it. lib/consts.js re-exports both, so other callers are unchanged.
|
|
7
|
+
|
|
8
|
+
// Transient network error codes that indicate a retry-worthy connection failure
|
|
9
|
+
const TRANSIENT_NETWORK_CODES = new Set([
|
|
10
|
+
'ENOTFOUND',
|
|
11
|
+
'EAI_AGAIN',
|
|
12
|
+
'ETIMEDOUT',
|
|
13
|
+
'ECONNRESET',
|
|
14
|
+
'ECONNREFUSED',
|
|
15
|
+
// no route to the host, such as an IPv6 address on a host without IPv6 connectivity
|
|
16
|
+
'ENETUNREACH',
|
|
17
|
+
'EHOSTUNREACH',
|
|
18
|
+
'UND_ERR_SOCKET',
|
|
19
|
+
'UND_ERR_CONNECT_TIMEOUT',
|
|
20
|
+
'UND_ERR_HEADERS_TIMEOUT',
|
|
21
|
+
// a response body that stalled mid-transfer
|
|
22
|
+
'UND_ERR_BODY_TIMEOUT'
|
|
23
|
+
]);
|
|
24
|
+
|
|
25
|
+
// Applied by lib/logger.js to the root logger, so every worker inherits it. A logged joi
|
|
26
|
+
// ValidationError carries the full submitted payload in `_original` and the offending value in
|
|
27
|
+
// each detail context, and `rawPacket` is a TLS-error field that can carry an unparsed
|
|
28
|
+
// credential frame - without these a failed validation writes plaintext passwords, OAuth2
|
|
29
|
+
// client secrets and access tokens into the log, the per-account log store and Sentry.
|
|
30
|
+
// `req.query.access_token` is here because the api-token scheme accepts the credential as a
|
|
31
|
+
// query argument, and the request logger (lib/hapi-request-logger.js) logs the parsed query
|
|
32
|
+
// object with every request - so a client using that form wrote a live token into this
|
|
33
|
+
// instance's own request log. The serialized `req.url` is the pathname only
|
|
34
|
+
// (pino-std-serializers reports `req.path`), so the credential reaches the log through the
|
|
35
|
+
// query object and nowhere else.
|
|
36
|
+
const REDACTED_LOG_KEYS = [
|
|
37
|
+
'req.headers.authorization',
|
|
38
|
+
'req.headers.cookie',
|
|
39
|
+
'req.query.access_token',
|
|
40
|
+
'err.rawPacket',
|
|
41
|
+
'err._original',
|
|
42
|
+
'err.details[*].context.value',
|
|
43
|
+
// the WHATWG URL parser attaches the string it rejected, and a stored proxy or webhook URL
|
|
44
|
+
// carries its credentials inline
|
|
45
|
+
'err.input'
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
module.exports = { REDACTED_LOG_KEYS, TRANSIENT_NETWORK_CODES };
|
package/lib/logger.js
CHANGED
|
@@ -7,7 +7,7 @@ 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 { REDACTED_LOG_KEYS } = require('./consts');
|
|
10
|
+
const { REDACTED_LOG_KEYS } = require('./logger-consts');
|
|
11
11
|
const { isTransientNetworkError } = require('./network-errors');
|
|
12
12
|
|
|
13
13
|
config.log = config.log || {
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
--[[
|
|
2
|
+
Script: z-head-scores.lua
|
|
3
|
+
Purpose: Returns the scores of the lowest-scored entries of a sorted set, without the members.
|
|
4
|
+
For a queue scored by UID whose members are full JSON payloads, the UIDs are all a caller wants,
|
|
5
|
+
and ZRANGE WITHSCORES would send every payload along with them
|
|
6
|
+
|
|
7
|
+
KEYS:
|
|
8
|
+
[1] key - Sorted set key
|
|
9
|
+
|
|
10
|
+
ARGV:
|
|
11
|
+
[1] count - How many entries to read from the head of the set
|
|
12
|
+
|
|
13
|
+
Returns:
|
|
14
|
+
Array of scores (as strings), lowest first; empty when the set does not exist
|
|
15
|
+
--]]
|
|
16
|
+
|
|
17
|
+
local count = tonumber(ARGV[1]) or 0;
|
|
18
|
+
if count < 1 then
|
|
19
|
+
return {};
|
|
20
|
+
end;
|
|
21
|
+
|
|
22
|
+
local list = redis.call("ZRANGE", KEYS[1], 0, count - 1, "WITHSCORES");
|
|
23
|
+
local scores = {};
|
|
24
|
+
for i = 2, #list, 2 do
|
|
25
|
+
scores[#scores + 1] = list[i];
|
|
26
|
+
end;
|
|
27
|
+
|
|
28
|
+
return scores;
|
package/lib/network-errors.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
//
|
|
7
7
|
// Dependency-free apart from consts, so lib/logger.js can use it without a require cycle.
|
|
8
8
|
|
|
9
|
-
const { TRANSIENT_NETWORK_CODES } = require('./consts');
|
|
9
|
+
const { TRANSIENT_NETWORK_CODES } = require('./logger-consts');
|
|
10
10
|
|
|
11
11
|
// How far down a cause chain the transient check looks. A chain is not guaranteed to be finite - an
|
|
12
12
|
// error may cite itself - so the walk is bounded rather than trusting it to end.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The oldest Node.js release the dependency tree supports, matching `engines.node` in package.json
|
|
4
|
+
// (test/node-version-test.js keeps the two in step). Requires nothing but the dependency-free
|
|
5
|
+
// lib/utils/version.js, because server.js checks it before it requires anything else.
|
|
6
|
+
|
|
7
|
+
const MIN_SUPPORTED_NODE = '20.19.0';
|
|
8
|
+
|
|
9
|
+
const { compareVersions } = require('./utils/version');
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Whether a Node.js version is older than MIN_SUPPORTED_NODE
|
|
13
|
+
* @param {string} version - A version such as process.versions.node ("20.18.1")
|
|
14
|
+
* @returns {boolean} True when the version is older, false for one that can not be read
|
|
15
|
+
*/
|
|
16
|
+
function isBelowSupportedNode(version) {
|
|
17
|
+
try {
|
|
18
|
+
return compareVersions(String(version || '').replace(/^v/, ''), MIN_SUPPORTED_NODE) < 0;
|
|
19
|
+
} catch (err) {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
module.exports = { MIN_SUPPORTED_NODE, isBelowSupportedNode };
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const { mapConcurrent } = require('./utils/map-concurrent');
|
|
4
|
+
|
|
5
|
+
// Attachment downloads a Gmail API or Graph client runs at once for one message
|
|
6
|
+
const API_ATTACHMENT_CONCURRENCY = 4;
|
|
7
|
+
|
|
3
8
|
// Whether an attachment's content belongs in a messageNew payload under the notifyAttachmentSize
|
|
4
9
|
// setting. Both processNew() implementations ask it before downloading an attachment and
|
|
5
10
|
// formatPayload() asks it again for content loaded on other paths, such as inline images the
|
|
@@ -14,4 +19,18 @@ function withinNotifyAttachmentSize(attachment, notifyAttachmentSize) {
|
|
|
14
19
|
return size <= notifyAttachmentSize;
|
|
15
20
|
}
|
|
16
21
|
|
|
17
|
-
|
|
22
|
+
/**
|
|
23
|
+
* Loads the content of every attachment the messageNew webhook carries (`notifyAttachments`), the
|
|
24
|
+
* ones over `notifyAttachmentSize` excepted. Shared by the IMAP mailbox and the API clients
|
|
25
|
+
* @param {Object[]} attachments - The message's attachments
|
|
26
|
+
* @param {number} sizeLimit - The notifyAttachmentSize setting
|
|
27
|
+
* @param {Function} load - async (attachment) => void, sets attachment.content (base64) when it can
|
|
28
|
+
* @param {number} [concurrency=1] - Downloads at a time: one for IMAP, where they share the
|
|
29
|
+
* connection, a few for the API clients, where each is an HTTP request of its own
|
|
30
|
+
*/
|
|
31
|
+
async function loadNotifyAttachments(attachments, sizeLimit, load, concurrency = 1) {
|
|
32
|
+
const pending = (attachments || []).filter(attachment => withinNotifyAttachmentSize(attachment, sizeLimit) && !attachment.content);
|
|
33
|
+
await mapConcurrent(pending, concurrency, load);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
module.exports = { withinNotifyAttachmentSize, loadNotifyAttachments, API_ATTACHMENT_CONCURRENCY };
|