emailengine-app 2.84.2 → 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 +29 -9
- package/.prettierignore +5 -1
- package/.prettierrc.js +2 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +107 -0
- package/Dockerfile +20 -1
- package/ENVIRONMENT.md +139 -0
- package/README.md +2 -2
- package/bin/emailengine.js +434 -408
- package/config/default.toml +2 -0
- package/copy-static-files.sh +41 -14
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +16563 -0
- package/eslint.config.js +81 -99
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +230 -170
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/format.js +4 -3
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +255 -38
- package/lib/api-routes/blocklist-routes.js +91 -4
- package/lib/api-routes/delivery-test-routes.js +27 -4
- package/lib/api-routes/export-routes.js +28 -2
- package/lib/api-routes/gateway-routes.js +110 -12
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +44 -5
- package/lib/api-routes/message-routes.js +112 -10
- package/lib/api-routes/oauth2-app-routes.js +63 -23
- package/lib/api-routes/outbox-routes.js +97 -52
- package/lib/api-routes/permission-map.js +67 -7
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +34 -6
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +337 -309
- package/lib/api-routes/template-routes.js +45 -8
- package/lib/api-routes/token-routes.js +152 -100
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +132 -6
- package/lib/bounce-detect.js +397 -205
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -45
- 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 +137 -184
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +60 -22
- 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 -242
- package/lib/email-client/imap/subconnection.js +8 -30
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +228 -164
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/notification-handler.js +1 -2
- 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 +19 -4
- package/lib/get-raw-email.js +25 -107
- package/lib/hapi-request-logger.js +107 -0
- package/lib/health.js +75 -0
- package/lib/imapproxy/imap-core/README.md +6 -5
- 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/mcp/tools.js +37 -8
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +36 -0
- package/lib/oauth/outlook-mailbox.js +35 -0
- package/lib/oauth/state.js +24 -0
- package/lib/oauth2-apps.js +631 -656
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/pbkdf2-phc.js +1 -1
- 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 +164 -40
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/sso.js +1 -1
- package/lib/swagger-options.js +1 -1
- package/lib/thread-diagnostics.js +63 -0
- package/lib/timezones.js +109 -0
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +7 -6
- package/lib/tools.js +48 -51
- package/lib/totp.js +2 -5
- package/lib/translations.js +1 -2
- package/lib/ui-routes/account-routes.js +475 -454
- package/lib/ui-routes/account-setup.js +99 -0
- package/lib/ui-routes/admin-config-routes.js +152 -100
- package/lib/ui-routes/admin-entities-routes.js +93 -21
- package/lib/ui-routes/auth-routes.js +90 -38
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/internals-routes.js +5 -0
- package/lib/ui-routes/oauth-config-routes.js +124 -82
- 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/route-helpers.js +19 -3
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/ui-routes/tls-config-routes.js +58 -15
- package/lib/utils/back-off.js +82 -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/murmurhash3.js +66 -0
- package/lib/utils/public-suffix.js +122 -0
- package/lib/utils/random-id.js +26 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/utils/version.js +74 -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 +56 -0
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +93 -45
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +37 -38
- package/sbom.json +7902 -1
- package/server.js +784 -518
- package/static/js/ace/ace.js +1 -1
- package/static/licenses.html +225 -1060
- package/translations/messages.pot +62 -63
- package/views/config/ai.hbs +1 -1
- package/views/config/security.hbs +24 -2
- package/views/config/service.hbs +47 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/internals/index.hbs +8 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/views/partials/webhook_form.hbs +1 -1
- package/views/suppression-lists/index.hbs +1 -1
- package/workers/api.js +840 -611
- package/workers/export.js +17 -632
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/submit.js +1 -1
- package/workers/webhooks.js +18 -448
- 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
|
@@ -5,8 +5,7 @@ const Boom = require('@hapi/boom');
|
|
|
5
5
|
const { REDIS_PREFIX } = require('./consts');
|
|
6
6
|
const logger = require('./logger');
|
|
7
7
|
const { encrypt, decrypt } = require('./encrypt');
|
|
8
|
-
const {
|
|
9
|
-
const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
|
|
8
|
+
const { randomId } = require('./utils/random-id');
|
|
10
9
|
const { mergeObjects, filterListPage } = require('./tools');
|
|
11
10
|
|
|
12
11
|
class Gateway {
|
|
@@ -87,7 +86,7 @@ class Gateway {
|
|
|
87
86
|
let id;
|
|
88
87
|
let retries = 0;
|
|
89
88
|
while (retries++ < 20) {
|
|
90
|
-
id =
|
|
89
|
+
id = randomId();
|
|
91
90
|
let alreadyExists = await this.redis.hexists(`${REDIS_PREFIX}gateway:${id}`, 'gateway');
|
|
92
91
|
if (alreadyExists) {
|
|
93
92
|
id = false;
|
|
@@ -293,4 +292,20 @@ class Gateway {
|
|
|
293
292
|
}
|
|
294
293
|
}
|
|
295
294
|
|
|
296
|
-
|
|
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
|
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Request logging for the API server, in place of the hapi-pino plugin (which pulled a second pino
|
|
4
|
+
// major into the tree). It writes the same records hapi-pino did, because operators parse them:
|
|
5
|
+
//
|
|
6
|
+
// - every request gets `request.logger`, a child bound to the serialized request (`req`)
|
|
7
|
+
// - "[response] <method> <path> <status> (<ms>ms)" at info with `res` and `responseTime` when a
|
|
8
|
+
// response is sent, "-" in place of the status when the client went away first
|
|
9
|
+
// - a request error event at error level with `err` and `tags`, its message as the line
|
|
10
|
+
// - server.log() and request.log() events with `tags` and `data`, at the most severe level named
|
|
11
|
+
// among the tags (info when none is)
|
|
12
|
+
// - "server started" / "server stopped" carrying server.info
|
|
13
|
+
//
|
|
14
|
+
// The server is decorated with `server.logger`.
|
|
15
|
+
|
|
16
|
+
const { stdSerializers } = require('pino');
|
|
17
|
+
|
|
18
|
+
const LEVEL_TAGS = new Set(['trace', 'debug', 'info', 'warn', 'error', 'fatal']);
|
|
19
|
+
|
|
20
|
+
const SERIALIZERS = {
|
|
21
|
+
req: stdSerializers.wrapRequestSerializer(stdSerializers.req),
|
|
22
|
+
res: stdSerializers.wrapResponseSerializer(stdSerializers.res),
|
|
23
|
+
err: stdSerializers.err
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
function logEvent(logger, event) {
|
|
27
|
+
const tags = event.tags || [];
|
|
28
|
+
|
|
29
|
+
let level = 'info';
|
|
30
|
+
let highest = 0;
|
|
31
|
+
for (const tag of tags) {
|
|
32
|
+
if (LEVEL_TAGS.has(tag) && logger.levels.values[tag] > highest) {
|
|
33
|
+
highest = logger.levels.values[tag];
|
|
34
|
+
level = tag;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
logger[level]({ tags, data: event.data });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function getRequestLogger(logger, request) {
|
|
42
|
+
if (!request.logger) {
|
|
43
|
+
request.logger = logger.child({ req: request });
|
|
44
|
+
}
|
|
45
|
+
return request.logger;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
module.exports = {
|
|
49
|
+
name: 'request-logger',
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @param {Object} server Hapi server
|
|
53
|
+
* @param {Object} options
|
|
54
|
+
* @param {Object} options.logger Pino logger to write through
|
|
55
|
+
*/
|
|
56
|
+
register(server, options) {
|
|
57
|
+
// Serializers the logger already carries win, the way hapi-pino merged them
|
|
58
|
+
const logger = options.logger.child({}, { serializers: SERIALIZERS });
|
|
59
|
+
|
|
60
|
+
server.decorate('server', 'logger', logger);
|
|
61
|
+
|
|
62
|
+
server.ext('onRequest', (request, h) => {
|
|
63
|
+
request.logger = logger.child({ req: request });
|
|
64
|
+
return h.continue;
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
server.events.on('log', event => {
|
|
68
|
+
if (event.error) {
|
|
69
|
+
logger.error({ err: event.error, tags: event.tags });
|
|
70
|
+
} else {
|
|
71
|
+
logEvent(logger, event);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
server.events.on('request', (request, event, tags) => {
|
|
76
|
+
// hapi's internal channel is noise apart from a malformed Accept-Encoding header
|
|
77
|
+
if (event.channel === 'internal' && !tags['accept-encoding']) {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (event.error) {
|
|
82
|
+
getRequestLogger(logger, request).error({ tags: event.tags, err: event.error }, event.error.message);
|
|
83
|
+
} else if (event.channel === 'app') {
|
|
84
|
+
logEvent(getRequestLogger(logger, request), event);
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
server.events.on('response', request => {
|
|
89
|
+
const { info, raw } = request;
|
|
90
|
+
const responseTime = (info.completed !== undefined ? info.completed : info.responded) - info.received;
|
|
91
|
+
const status = raw.res.headersSent ? raw.res.statusCode : '-';
|
|
92
|
+
|
|
93
|
+
getRequestLogger(logger, request).info(
|
|
94
|
+
{ res: raw.res, responseTime },
|
|
95
|
+
`[response] ${request.method} ${request.path} ${status} (${responseTime}ms)`
|
|
96
|
+
);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
server.ext('onPostStart', async () => {
|
|
100
|
+
logger.info(server.info, 'server started');
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
server.ext('onPostStop', async () => {
|
|
104
|
+
logger.info(server.info, 'server stopped');
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
};
|
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 };
|
|
@@ -47,8 +47,9 @@ The `test/` directory is upstream's mocha suite. It is written for mocha, which
|
|
|
47
47
|
dependency here, and had never been executed after the import.
|
|
48
48
|
|
|
49
49
|
The hermetic specs now run as part of the normal unit tier through
|
|
50
|
-
`test/imap-core-vendored-test.js`, which installs the mocha globals the specs expect
|
|
51
|
-
|
|
50
|
+
`test/imap-core-vendored-test.js`, which installs the mocha globals the specs expect, routes their
|
|
51
|
+
`require('chai')` to a node:assert-backed stand-in (`test/helpers/chai-stand-in.js`, covering only
|
|
52
|
+
the chains these files use; chai itself is not a dependency), and requires them. **Do not edit the files under `test/` to make them run** - keeping them byte-identical to
|
|
52
53
|
upstream is what makes the patch list above reviewable. Adapt them from the EmailEngine side
|
|
53
54
|
instead.
|
|
54
55
|
|
|
@@ -59,12 +60,12 @@ Wired up and running:
|
|
|
59
60
|
- `imap-compile-stream-test.js`
|
|
60
61
|
- `imap-indexer-test.js` (upstream has its `#rebuild` block commented out)
|
|
61
62
|
- `tools-test.js`
|
|
63
|
+
- `search-test.js` (unit tests for the SEARCH query parser and matcher)
|
|
62
64
|
|
|
63
|
-
Not wired up, because
|
|
64
|
-
|
|
65
|
+
Not wired up, because it drives a live WildDuck server and needs MongoDB plus a WildDuck REST API
|
|
66
|
+
(`prepare.sh` loads its fixtures through both) that do not exist in this repository:
|
|
65
67
|
|
|
66
68
|
- `protocol-test.js`
|
|
67
|
-
- `search-test.js`
|
|
68
69
|
|
|
69
70
|
That is a real coverage gap: `protocol-test.js` is the suite that exercises the connection and
|
|
70
71
|
command state machines, which is where most of the local patches above landed. The connection
|
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 };
|