emailengine-app 2.84.1 → 2.85.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/.dockerignore +6 -0
- package/.ncurc.js +5 -3
- package/.prettierignore +5 -1
- package/.prettierrc.js +2 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +61 -0
- package/Dockerfile +8 -2
- package/README.md +1 -1
- package/bin/emailengine.js +444 -403
- package/copy-static-files.sh +39 -14
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +16562 -0
- package/docker-compose.yml +1 -1
- package/eslint.config.js +81 -99
- package/lib/account/own-account-key.js +42 -0
- package/lib/account-assignment.js +1 -33
- package/lib/account.js +68 -24
- package/lib/add-trackers.js +11 -4
- package/lib/api-reference/format.js +4 -3
- package/lib/api-routes/account-routes.js +244 -26
- package/lib/api-routes/blocklist-routes.js +23 -2
- package/lib/api-routes/delivery-test-routes.js +26 -3
- package/lib/api-routes/export-routes.js +28 -2
- package/lib/api-routes/gateway-routes.js +37 -5
- package/lib/api-routes/mailbox-routes.js +41 -2
- package/lib/api-routes/message-routes.js +104 -4
- package/lib/api-routes/mint-bounds.js +11 -0
- package/lib/api-routes/oauth2-app-routes.js +48 -15
- package/lib/api-routes/outbox-routes.js +45 -11
- package/lib/api-routes/permission-map.js +12 -1
- package/lib/api-routes/route-helpers.js +125 -3
- package/lib/api-routes/settings-routes.js +23 -2
- package/lib/api-routes/submit-routes.js +338 -309
- package/lib/api-routes/template-routes.js +38 -2
- package/lib/api-routes/token-routes.js +142 -96
- package/lib/api-routes/webhook-route-routes.js +13 -2
- package/lib/auth-token.js +23 -10
- package/lib/bounce-detect.js +414 -210
- package/lib/consts.js +39 -4
- package/lib/create-imap-client.js +41 -2
- package/lib/email-client/base-client.js +30 -41
- package/lib/email-client/gmail-client.js +30 -18
- package/lib/email-client/imap/mailbox.js +13 -23
- package/lib/email-client/imap/response-metrics.js +75 -0
- package/lib/email-client/imap/subconnection.js +1 -1
- package/lib/email-client/imap-client.js +6 -3
- package/lib/email-client/message-builder.js +7 -2
- package/lib/email-client/notification-handler.js +1 -2
- package/lib/email-client/outlook/graph-api.js +17 -2
- package/lib/email-client/outlook-client.js +6 -3
- package/lib/email-client/smtp-pool-manager.js +6 -0
- package/lib/encrypt.js +9 -0
- package/lib/export.js +3 -1
- package/lib/gateway.js +2 -3
- package/lib/get-raw-email.js +4 -2
- package/lib/hapi-request-logger.js +107 -0
- package/lib/imap-proxy-auth.js +14 -1
- package/lib/imapproxy/imap-core/README.md +6 -5
- package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
- package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
- package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
- package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
- package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
- package/lib/mcp/listen.js +10 -1
- package/lib/mcp/tools.js +37 -8
- package/lib/notify-attachments.js +17 -0
- package/lib/oauth/external-account-config.js +3 -1
- package/lib/oauth/gmail.js +21 -48
- package/lib/oauth/mail-ru.js +5 -38
- package/lib/oauth/outlook-mailbox.js +35 -0
- package/lib/oauth/outlook.js +26 -44
- package/lib/oauth/state.js +24 -0
- package/lib/oauth2-apps.js +1 -1
- package/lib/pbkdf2-phc.js +19 -2
- package/lib/privileged-settings.js +6 -3
- package/lib/redis-scan-delete.js +15 -1
- package/lib/schemas.js +79 -33
- package/lib/settings.js +13 -1
- package/lib/smtp-auth.js +23 -0
- package/lib/sso.js +1 -1
- package/lib/swagger-options.js +1 -1
- package/lib/thread-diagnostics.js +46 -0
- package/lib/timezones.js +109 -0
- package/lib/token-permission-view.js +3 -3
- package/lib/tools.js +285 -66
- package/lib/totp.js +2 -5
- package/lib/translations.js +1 -2
- package/lib/ui-routes/account-routes.js +491 -491
- package/lib/ui-routes/account-setup.js +99 -0
- package/lib/ui-routes/admin-config-routes.js +98 -48
- package/lib/ui-routes/admin-entities-routes.js +113 -31
- package/lib/ui-routes/auth-routes.js +137 -62
- package/lib/ui-routes/connection-security-form.js +74 -0
- package/lib/ui-routes/form-lists.js +46 -0
- package/lib/ui-routes/internals-routes.js +5 -0
- package/lib/ui-routes/mcp-consent-routes.js +5 -1
- package/lib/ui-routes/oauth-config-routes.js +133 -100
- package/lib/ui-routes/route-helpers.js +19 -3
- package/lib/ui-routes/sign-in-helpers.js +59 -0
- package/lib/ui-routes/tls-config-routes.js +58 -15
- package/lib/ui-routes/unsubscribe-routes.js +6 -3
- package/lib/utils/back-off.js +82 -0
- package/lib/utils/map-concurrent.js +36 -0
- package/lib/utils/murmurhash3.js +66 -0
- package/lib/utils/network.js +28 -0
- package/lib/utils/provider-id.js +27 -0
- package/lib/utils/public-suffix.js +122 -0
- package/lib/utils/random-id.js +26 -0
- package/lib/utils/require-tls.js +33 -0
- package/lib/utils/version.js +74 -0
- package/lib/web-safe-html.js +5 -6
- package/lib/webhook-penalty.js +75 -0
- package/lib/webhook-routing.js +49 -2
- package/lib/webhooks.js +41 -6
- package/package.json +37 -39
- package/sbom.json +7980 -1
- package/server.js +659 -455
- package/static/js/ace/ace.js +1 -1
- package/static/js/ace/mode-handlebars.js +1 -1
- package/static/js/ace/mode-html.js +1 -1
- package/static/js/ace/mode-javascript.js +1 -1
- package/static/js/ace/mode-markdown.js +1 -1
- package/static/js/ace/worker-html.js +1 -1
- package/static/js/ace/worker-javascript.js +1 -1
- package/static/js/ace/worker-json.js +1 -1
- package/static/js/ee-client.js +5 -0
- package/static/licenses.html +191 -1016
- package/translations/messages.pot +70 -71
- package/views/account/security.hbs +10 -0
- package/views/accounts/account.hbs +11 -11
- package/views/accounts/edit.hbs +6 -2
- package/views/config/ai.hbs +1 -1
- package/views/config/security.hbs +2 -2
- package/views/config/service.hbs +3 -0
- package/views/internals/index.hbs +8 -0
- package/views/partials/gateway_form.hbs +3 -1
- package/views/partials/webhook_form.hbs +1 -1
- package/views/suppression-lists/index.hbs +1 -1
- package/workers/api.js +780 -585
- package/workers/export.js +1 -1
- package/workers/submit.js +1 -1
- package/workers/webhooks.js +54 -34
- package/config/test.toml +0 -46
- package/install.sh +0 -428
- package/setup-production.sh +0 -215
- package/systemd/emailengine.service +0 -97
- package/systemd/nginx-proxy.conf +0 -77
package/lib/tools.js
CHANGED
|
@@ -27,18 +27,27 @@ const punycode = require('punycode.js');
|
|
|
27
27
|
const { PassThrough } = require('stream');
|
|
28
28
|
const socks = require('socks');
|
|
29
29
|
const os = require('os');
|
|
30
|
+
const { monitorEventLoopDelay } = require('perf_hooks');
|
|
30
31
|
const Fs = require('fs');
|
|
31
32
|
const fs = Fs.promises;
|
|
32
33
|
const pathlib = require('path');
|
|
33
34
|
const { randomUUID: uuid } = require('crypto');
|
|
34
35
|
const mimeTypes = require('nodemailer/lib/mime-funcs/mime-types');
|
|
35
|
-
const {
|
|
36
|
+
const { murmurhash3 } = require('./utils/murmurhash3');
|
|
36
37
|
const { isEmail } = require('./utils/is-email');
|
|
37
38
|
const { toCamelCase } = require('./utils/to-camel-case');
|
|
38
39
|
const { normalizePath } = require('./utils/mailbox-path');
|
|
39
|
-
const {
|
|
40
|
+
const { applyRequireTls } = require('./utils/require-tls');
|
|
41
|
+
const { compareVersions, parseVersion } = require('./utils/version');
|
|
42
|
+
|
|
43
|
+
// Largest decompressed license blob accepted, well above any real license
|
|
44
|
+
const MAX_LICENSE_SIZE = 1024 * 1024;
|
|
45
|
+
|
|
46
|
+
// deriveSigningKey() results, by purpose
|
|
47
|
+
const derivedSigningKeys = new Map();
|
|
40
48
|
const {
|
|
41
49
|
REDIS_PREFIX,
|
|
50
|
+
ADMIN_SESSION_MAX_AGE,
|
|
42
51
|
TLS_DEFAULTS,
|
|
43
52
|
URL_FETCH_TIMEOUT,
|
|
44
53
|
MAX_FORM_TTL,
|
|
@@ -204,7 +213,9 @@ function createSocksAgent(proxyUrl, agentOpts) {
|
|
|
204
213
|
|
|
205
214
|
if (useTls) {
|
|
206
215
|
let rawSocket = socket;
|
|
207
|
-
|
|
216
|
+
// Node's own TLS defaults, not TLS_DEFAULTS: those (TLSv1, SECLEVEL=0) exist for old
|
|
217
|
+
// mail servers, and this is an HTTPS request to an API or a webhook target
|
|
218
|
+
socket = tls.connect({ socket: rawSocket, servername: servername || hostname });
|
|
208
219
|
// The SOCKS timeout above only covers the proxy negotiation. A proxy (or a target
|
|
209
220
|
// behind it) that accepts the tunnel and then never answers the ClientHello would
|
|
210
221
|
// otherwise hold the request, and whatever awaits it (a token refresh, a Gmail or
|
|
@@ -326,7 +337,8 @@ httpAgent.forRoute = dispatchersForRoute;
|
|
|
326
337
|
try {
|
|
327
338
|
installDispatchers((workerData && workerData.httpProxyUrl) || null, null);
|
|
328
339
|
} catch (err) {
|
|
329
|
-
|
|
340
|
+
// the URL error carries the proxy URL, credentials included, as its input
|
|
341
|
+
logger.error({ msg: 'Failed to create HTTP proxy agent, using direct connections', err: module.exports.sanitizeUrlError(err) });
|
|
330
342
|
installDispatchers(null, null);
|
|
331
343
|
}
|
|
332
344
|
|
|
@@ -454,7 +466,11 @@ async function _doReloadHttpProxyAgent() {
|
|
|
454
466
|
.map(([stale]) => stale.close().catch(() => false))
|
|
455
467
|
);
|
|
456
468
|
} catch (err) {
|
|
457
|
-
logger.error({
|
|
469
|
+
logger.error({
|
|
470
|
+
msg: 'Failed to create HTTP proxy agent, keeping existing agent',
|
|
471
|
+
httpProxyUrl: module.exports.redactUrlCredentials(proxyUrl),
|
|
472
|
+
err: module.exports.sanitizeUrlError(err)
|
|
473
|
+
});
|
|
458
474
|
}
|
|
459
475
|
}
|
|
460
476
|
|
|
@@ -580,10 +596,11 @@ function redactValidationError(err) {
|
|
|
580
596
|
}
|
|
581
597
|
|
|
582
598
|
// Shared token grammar for cid: references in HTML. Collection
|
|
583
|
-
// (collectCidReferences) and
|
|
584
|
-
// identically,
|
|
585
|
-
//
|
|
586
|
-
// than one regex instance so no lastIndex state can leak
|
|
599
|
+
// (collectCidReferences) and the data URI replace step (embedCidImages) tokenize
|
|
600
|
+
// a reference identically, so everything the replace step rewrites was collected
|
|
601
|
+
// and fetched first, otherwise inline images would silently disappear. Exposed as
|
|
602
|
+
// a factory rather than one regex instance so no lastIndex state can leak
|
|
603
|
+
// between callers.
|
|
587
604
|
const CID_REFERENCE_SOURCE = String.raw`\bcid:([^"'\s>]+)`;
|
|
588
605
|
|
|
589
606
|
function cidReferenceRegex() {
|
|
@@ -595,13 +612,6 @@ function cidReferenceRegex() {
|
|
|
595
612
|
// break out of the src attribute of HTML that is served as web safe
|
|
596
613
|
const DATA_URL_CONTENT_TYPE = /^[\w.+-]+\/[\w.+-]+$/;
|
|
597
614
|
|
|
598
|
-
/**
|
|
599
|
-
* Replaces cid: references in HTML with data: URLs for the attachments that have content
|
|
600
|
-
*
|
|
601
|
-
* @param {String} html
|
|
602
|
-
* @param {Function} lookup - called with the content id, returns { contentType, content } (content as base64) or a falsy value
|
|
603
|
-
* @returns {String}
|
|
604
|
-
*/
|
|
605
615
|
/**
|
|
606
616
|
* Reads a Retry-After header as seconds. Accepts a fetch Headers object (or anything with get())
|
|
607
617
|
* and a plain header object with keys in any casing, which is how the items of a Graph $batch
|
|
@@ -643,17 +653,51 @@ function parseRetryAfter(headers) {
|
|
|
643
653
|
return Math.max(0, Math.ceil((date - Date.now()) / 1000));
|
|
644
654
|
}
|
|
645
655
|
|
|
656
|
+
/**
|
|
657
|
+
* Builds a regex for the named HTML attributes with their value in any of the three syntaxes:
|
|
658
|
+
* group 1 is everything up to the value, group 2 the value as written, quotes included. The HTML
|
|
659
|
+
* parser treats '/' between attributes like whitespace, hence [\s/] rather than \s, and a new
|
|
660
|
+
* attribute name may start right after a quoted value (`open=""class="..."`), so a quote counts as
|
|
661
|
+
* a boundary too
|
|
662
|
+
*
|
|
663
|
+
* @param {String[]} names - attribute names
|
|
664
|
+
* @returns {RegExp} global, case-insensitive
|
|
665
|
+
*/
|
|
666
|
+
function attributeValueRegex(names) {
|
|
667
|
+
return new RegExp(`([\\s/"'](?:${names.join('|')})\\s*=\\s*)("[^"]*"|'[^']*'|[^\\s"'>]+)`, 'gi');
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// The attributes a cid: reference is embedded in. A reference anywhere else (an href, the text
|
|
671
|
+
// of the message) is left as it is: this runs after the sanitizer, which refuses a data: URL on a
|
|
672
|
+
// link, and rewriting a cid: link into one would hand the sender exactly what was refused
|
|
673
|
+
const CID_EMBED_ATTRIBUTE = attributeValueRegex(['src', 'srcset', 'background']);
|
|
674
|
+
|
|
675
|
+
/**
|
|
676
|
+
* Replaces the cid: references in the image attributes of an HTML string with data: URLs for the
|
|
677
|
+
* attachments that have content
|
|
678
|
+
*
|
|
679
|
+
* @param {String} html
|
|
680
|
+
* @param {Function} lookup - called with the content id, returns { contentType, content } (content as base64) or a falsy value
|
|
681
|
+
* @returns {String}
|
|
682
|
+
*/
|
|
646
683
|
function embedCidImages(html, lookup) {
|
|
647
|
-
if (!html) {
|
|
684
|
+
if (!html || !html.includes('cid:')) {
|
|
648
685
|
return html;
|
|
649
686
|
}
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
if (!
|
|
653
|
-
return
|
|
654
|
-
}
|
|
655
|
-
let
|
|
656
|
-
|
|
687
|
+
let references = cidReferenceRegex();
|
|
688
|
+
return html.replace(CID_EMBED_ATTRIBUTE, (attribute, prefix, value) => {
|
|
689
|
+
if (!value.includes('cid:')) {
|
|
690
|
+
return attribute;
|
|
691
|
+
}
|
|
692
|
+
let embedded = value.replace(references, (reference, cid) => {
|
|
693
|
+
let attachment = lookup(cid);
|
|
694
|
+
if (!attachment || !attachment.content) {
|
|
695
|
+
return reference;
|
|
696
|
+
}
|
|
697
|
+
let contentType = DATA_URL_CONTENT_TYPE.test(attachment.contentType || '') ? attachment.contentType : 'application/octet-stream';
|
|
698
|
+
return `data:${contentType};base64,${attachment.content}`;
|
|
699
|
+
});
|
|
700
|
+
return prefix + embedded;
|
|
657
701
|
});
|
|
658
702
|
}
|
|
659
703
|
|
|
@@ -718,6 +762,7 @@ module.exports = {
|
|
|
718
762
|
TLS_MATERIAL_SETTINGS,
|
|
719
763
|
|
|
720
764
|
cidReferenceRegex,
|
|
765
|
+
attributeValueRegex,
|
|
721
766
|
embedCidImages,
|
|
722
767
|
parseRetryAfter,
|
|
723
768
|
|
|
@@ -734,7 +779,9 @@ module.exports = {
|
|
|
734
779
|
* @param {Object} sessionData Session payload (user/profile/etc, no sid)
|
|
735
780
|
*/
|
|
736
781
|
setAdminSession(request, sessionData) {
|
|
737
|
-
|
|
782
|
+
// issuedAt is what isEndedSession() ages the session by; a caller re-stamping a session
|
|
783
|
+
// it means to keep may carry the old value over
|
|
784
|
+
request.cookieAuth.set(Object.assign({ issuedAt: Date.now() }, sessionData, { sid: randomBytes(32).toString('hex') }));
|
|
738
785
|
},
|
|
739
786
|
|
|
740
787
|
/**
|
|
@@ -754,12 +801,28 @@ module.exports = {
|
|
|
754
801
|
* password exists (an unsecured instance), or nobody has ever bumped it,
|
|
755
802
|
* and a session stamped before the field existed must not be force-expired.
|
|
756
803
|
*
|
|
804
|
+
* A session is also over once it is older than ADMIN_SESSION_MAX_AGE, by
|
|
805
|
+
* the issuedAt setAdminSession() stamps. The sealed cookie has no expiry of
|
|
806
|
+
* its own, so a cookie captured once used to stay valid until the next
|
|
807
|
+
* password change, however long ago it was issued. A session carrying no
|
|
808
|
+
* issuedAt was issued before the stamp existed and is over too: that is one
|
|
809
|
+
* sign-in at upgrade time for whoever is logged in, against never ageing
|
|
810
|
+
* out a cookie whose age nobody can tell.
|
|
811
|
+
*
|
|
757
812
|
* @param {Number} currentPasswordVersion authData.passwordVersion, or 0
|
|
758
813
|
* @param {Object} session decoded session cookie
|
|
814
|
+
* @param {Number} [now] the current time, for tests
|
|
759
815
|
* @returns {Boolean} true when the session is over
|
|
760
816
|
*/
|
|
761
|
-
isEndedSession(currentPasswordVersion, session) {
|
|
762
|
-
|
|
817
|
+
isEndedSession(currentPasswordVersion, session, now) {
|
|
818
|
+
if (!currentPasswordVersion) {
|
|
819
|
+
return false;
|
|
820
|
+
}
|
|
821
|
+
if (currentPasswordVersion !== (session && session.passwordVersion)) {
|
|
822
|
+
return true;
|
|
823
|
+
}
|
|
824
|
+
let issuedAt = Number(session.issuedAt);
|
|
825
|
+
return !issuedAt || (now || Date.now()) - issuedAt > ADMIN_SESSION_MAX_AGE;
|
|
763
826
|
},
|
|
764
827
|
|
|
765
828
|
/**
|
|
@@ -796,12 +859,14 @@ module.exports = {
|
|
|
796
859
|
* lookup per attachment instead of scanning the full HTML once per attachment:
|
|
797
860
|
* the repeated synchronous scans cost attachment count times body size, which
|
|
798
861
|
* on a crafted message blocks the worker event loop past the heartbeat
|
|
799
|
-
* restart timeout. Tokenizes with the same grammar as the
|
|
862
|
+
* restart timeout. Tokenizes with the same grammar as the replace step
|
|
800
863
|
* (cidReferenceRegex), so a content id that is only a prefix of a referenced
|
|
801
|
-
* id, or that appears outside a cid: link, does not match.
|
|
802
|
-
*
|
|
803
|
-
*
|
|
804
|
-
*
|
|
864
|
+
* id, or that appears outside a cid: link, does not match. The set answers
|
|
865
|
+
* which attachments the HTML refers to at all, which is also what decides
|
|
866
|
+
* whether an attachment is inline, so it looks at every reference, while
|
|
867
|
+
* embedCidImages() rewrites only the image attributes among them. Each token
|
|
868
|
+
* is additionally added truncated at a closing parenthesis, so that a CSS
|
|
869
|
+
* url(cid:...) reference counts as a reference to its attachment.
|
|
805
870
|
* @param {String} html HTML content to scan
|
|
806
871
|
* @returns {Set<String>} Content ids referenced in the HTML
|
|
807
872
|
*/
|
|
@@ -1240,6 +1305,13 @@ module.exports = {
|
|
|
1240
1305
|
return processCount;
|
|
1241
1306
|
},
|
|
1242
1307
|
|
|
1308
|
+
// A worker pool size: the environment value if it gives one, else the configuration file's, else
|
|
1309
|
+
// the pool's default. Both accept "cpus", and a fraction is rounded down so a pool never gets
|
|
1310
|
+
// more threads than asked for.
|
|
1311
|
+
workerPoolSize(envValue, configValue, defaultCount = 1) {
|
|
1312
|
+
return Math.floor(module.exports.getWorkerCount(envValue)) || Math.floor(module.exports.getWorkerCount(configValue)) || defaultCount;
|
|
1313
|
+
},
|
|
1314
|
+
|
|
1243
1315
|
getDuration(val, opts = {}) {
|
|
1244
1316
|
val = (val || '').toString().replace(/^([\d.]+)\s*([smhdy][a-z]*)$/i, (o, num, m) => {
|
|
1245
1317
|
if (!num || isNaN(num)) {
|
|
@@ -1500,7 +1572,7 @@ module.exports = {
|
|
|
1500
1572
|
},
|
|
1501
1573
|
|
|
1502
1574
|
getRendezvousScore(key, shardId) {
|
|
1503
|
-
return
|
|
1575
|
+
return murmurhash3(`${(shardId || '').toString()}\x00${key}`);
|
|
1504
1576
|
},
|
|
1505
1577
|
|
|
1506
1578
|
selectRendezvousNode(key, workers) {
|
|
@@ -1568,7 +1640,9 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
1568
1640
|
);
|
|
1569
1641
|
}
|
|
1570
1642
|
|
|
1571
|
-
|
|
1643
|
+
// bounded: the blob is caller-supplied and brotli expands a few hundred bytes into
|
|
1644
|
+
// hundreds of megabytes; a license is a few kilobytes
|
|
1645
|
+
let signedLicense = await brotliDecompressAsync(encodedLicense, { maxOutputLength: MAX_LICENSE_SIZE });
|
|
1572
1646
|
|
|
1573
1647
|
let { l: licenseRaw, s: signature } = msgpack.decode(signedLicense);
|
|
1574
1648
|
|
|
@@ -1829,6 +1903,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
1829
1903
|
smtpConfig.tls[key] = TLS_DEFAULTS[key];
|
|
1830
1904
|
}
|
|
1831
1905
|
}
|
|
1906
|
+
applyRequireTls(smtpConfig);
|
|
1832
1907
|
|
|
1833
1908
|
for (let level of ['trace', 'debug', 'info', 'warn', 'error', 'fatal']) {
|
|
1834
1909
|
smtpLogger[level] = (data, message, ...args) => {
|
|
@@ -1923,7 +1998,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
1923
1998
|
);
|
|
1924
1999
|
}
|
|
1925
2000
|
|
|
1926
|
-
let signedContent = await brotliDecompressAsync(encodedContent);
|
|
2001
|
+
let signedContent = await brotliDecompressAsync(encodedContent, { maxOutputLength: MAX_LICENSE_SIZE });
|
|
1927
2002
|
let { l: contentRaw, s: signature } = msgpack.decode(signedContent);
|
|
1928
2003
|
for (let rootItem of rootList) {
|
|
1929
2004
|
try {
|
|
@@ -2316,11 +2391,11 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2316
2391
|
}
|
|
2317
2392
|
|
|
2318
2393
|
let releaseVersion = (releaseData.tag_name || '').toString().replace(/^v/, '');
|
|
2319
|
-
if (!
|
|
2394
|
+
if (!parseVersion(releaseVersion)) {
|
|
2320
2395
|
return { current: packageData.version, available: false, canUpgrade: false };
|
|
2321
2396
|
}
|
|
2322
2397
|
|
|
2323
|
-
if (compareVersions(releaseVersion, packageData.version
|
|
2398
|
+
if (compareVersions(releaseVersion, packageData.version) > 0) {
|
|
2324
2399
|
return { current: packageData.version, available: releaseVersion, canUpgrade: true };
|
|
2325
2400
|
}
|
|
2326
2401
|
|
|
@@ -2331,6 +2406,65 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2331
2406
|
return secretKey.replace(/^(.{8}).*$/, `$1... (${secretKey.length}B)`);
|
|
2332
2407
|
},
|
|
2333
2408
|
|
|
2409
|
+
// What an operator needs to tell which client secret the instance holds when the provider says
|
|
2410
|
+
// it is wrong: the length and the first few characters. Carried on the token error as
|
|
2411
|
+
// `clientSecretHint`, where the log serializer picks it up and nothing that builds an API
|
|
2412
|
+
// payload or a webhook out of `err.tokenRequest` does. Shorter than formatPartialSecretKey()
|
|
2413
|
+
// all the same, since eight characters of a thirty-character secret is a quarter of it
|
|
2414
|
+
formatSecretHint(secretKey) {
|
|
2415
|
+
secretKey = (secretKey || '').toString();
|
|
2416
|
+
return `${secretKey.slice(0, 3)}... (${secretKey.length}B)`;
|
|
2417
|
+
},
|
|
2418
|
+
|
|
2419
|
+
// The body of a token request and the token response as they may go to the log. The secrets
|
|
2420
|
+
// in them are masked whether or not raw logging is on: EENGINE_LOG_RAW is for the protocol
|
|
2421
|
+
// traffic, and the application's client secret and the refresh tokens of every account are
|
|
2422
|
+
// not something a debug switch should put in the log in full
|
|
2423
|
+
formatOAuthRequestBody(searchParams) {
|
|
2424
|
+
let entries = typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
|
|
2425
|
+
let data = Object.fromEntries(entries);
|
|
2426
|
+
|
|
2427
|
+
for (let key of ['refresh_token', 'client_secret', 'code']) {
|
|
2428
|
+
if (data[key]) {
|
|
2429
|
+
data[key] = module.exports.formatPartialSecretKey(data[key]);
|
|
2430
|
+
}
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2433
|
+
if (data.assertion) {
|
|
2434
|
+
// a signed JWT
|
|
2435
|
+
let [payload, signature] = data.assertion.toString().split('.');
|
|
2436
|
+
data.assertion = [payload, module.exports.formatPartialSecretKey(signature)].join('.');
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
return data;
|
|
2440
|
+
},
|
|
2441
|
+
|
|
2442
|
+
formatOAuthResponse(responseObj) {
|
|
2443
|
+
if (!responseObj || typeof responseObj !== 'object') {
|
|
2444
|
+
return responseObj;
|
|
2445
|
+
}
|
|
2446
|
+
|
|
2447
|
+
let data = module.exports.structuredClone(responseObj);
|
|
2448
|
+
for (let key of ['access_token', 'refresh_token', 'id_token']) {
|
|
2449
|
+
if (data[key]) {
|
|
2450
|
+
data[key] = module.exports.formatPartialSecretKey(data[key]);
|
|
2451
|
+
}
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
return data;
|
|
2455
|
+
},
|
|
2456
|
+
|
|
2457
|
+
// An error from `new URL()` carries the string it failed on as `err.input`, and when that
|
|
2458
|
+
// string is a proxy URL it carries the proxy credentials. The logger redacts that field on its
|
|
2459
|
+
// own (REDACTED_LOG_KEYS), but the error object also reaches Sentry whole, so the string itself
|
|
2460
|
+
// is rewritten. Returns the same error with the credentials redacted
|
|
2461
|
+
sanitizeUrlError(err) {
|
|
2462
|
+
if (err && typeof err === 'object' && typeof err.input === 'string') {
|
|
2463
|
+
err.input = module.exports.redactUrlCredentials(err.input);
|
|
2464
|
+
}
|
|
2465
|
+
return err;
|
|
2466
|
+
},
|
|
2467
|
+
|
|
2334
2468
|
// Returns the URL with any embedded basic auth credentials removed, safe for logging. Never
|
|
2335
2469
|
// throws: an unparseable value is replaced with a static placeholder rather than echoed back,
|
|
2336
2470
|
// because the raw string could itself carry the credentials that made it unparseable.
|
|
@@ -2406,9 +2540,21 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2406
2540
|
if (stored) {
|
|
2407
2541
|
serviceSecret = stored;
|
|
2408
2542
|
} else {
|
|
2409
|
-
// The field exists but reads back empty
|
|
2410
|
-
//
|
|
2411
|
-
//
|
|
2543
|
+
// The field exists but reads back empty. Two cases, and they must not be
|
|
2544
|
+
// treated the same. A legacy blank (the settings API used to allow it) is
|
|
2545
|
+
// healed by overwriting, which HSETNX cannot do. A value that is present but
|
|
2546
|
+
// does not decrypt is the instance running with the wrong EENGINE_SECRET, and
|
|
2547
|
+
// overwriting it would destroy a secret the rotation CLI can still recover
|
|
2548
|
+
// once the right one is back, so that one is an error here: links stop
|
|
2549
|
+
// verifying until the operator fixes the secret, the same as every stored
|
|
2550
|
+
// credential already does.
|
|
2551
|
+
let raw = await settings.getRaw('serviceSecret');
|
|
2552
|
+
if (raw) {
|
|
2553
|
+
let error = new Error('The stored service secret can not be decrypted; check EENGINE_SECRET');
|
|
2554
|
+
error.code = 'EServiceSecretUnreadable';
|
|
2555
|
+
error.statusCode = 500;
|
|
2556
|
+
throw error;
|
|
2557
|
+
}
|
|
2412
2558
|
await settings.set('serviceSecret', serviceSecret);
|
|
2413
2559
|
}
|
|
2414
2560
|
}
|
|
@@ -2416,6 +2562,40 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2416
2562
|
return serviceSecret;
|
|
2417
2563
|
},
|
|
2418
2564
|
|
|
2565
|
+
// One service secret signs several unrelated things: webhook bodies, hosted setup-form blobs,
|
|
2566
|
+
// tracking links and unsubscribe links. Each is HMAC-SHA256 of some bytes, so without a purpose
|
|
2567
|
+
// in the key a signature made for one is a valid signature for the others - a webhook body and
|
|
2568
|
+
// its X-EE-Wh-Signature header was a valid setup blob for the account the delivery named. The
|
|
2569
|
+
// key for each purpose is derived from the service secret, so a signature only verifies where
|
|
2570
|
+
// it was minted. The webhook signature itself keeps the raw secret: its format is documented
|
|
2571
|
+
// and verified by customer code.
|
|
2572
|
+
SIGNING_PURPOSE: {
|
|
2573
|
+
FORM: 'form',
|
|
2574
|
+
TRACKING: 'tracking',
|
|
2575
|
+
UNSUBSCRIBE: 'unsubscribe'
|
|
2576
|
+
},
|
|
2577
|
+
|
|
2578
|
+
// Derived once per purpose and kept while the secret is the one it was derived from: a
|
|
2579
|
+
// tracked message signs one blob per link, and the key is the same for all of them
|
|
2580
|
+
deriveSigningKey(serviceSecret, purpose) {
|
|
2581
|
+
if (!Object.values(module.exports.SIGNING_PURPOSE).includes(purpose)) {
|
|
2582
|
+
throw new Error(`Unknown signing purpose ${JSON.stringify(purpose)}`);
|
|
2583
|
+
}
|
|
2584
|
+
let cached = derivedSigningKeys.get(purpose);
|
|
2585
|
+
if (cached && cached.serviceSecret === serviceSecret) {
|
|
2586
|
+
return cached.key;
|
|
2587
|
+
}
|
|
2588
|
+
let key = createHmac('sha256', serviceSecret).update(`emailengine:signing:${purpose}:v1`).digest();
|
|
2589
|
+
derivedSigningKeys.set(purpose, { serviceSecret, key });
|
|
2590
|
+
return key;
|
|
2591
|
+
},
|
|
2592
|
+
|
|
2593
|
+
signServiceData(serviceSecret, data, purpose) {
|
|
2594
|
+
let hmac = createHmac('sha256', module.exports.deriveSigningKey(serviceSecret, purpose));
|
|
2595
|
+
hmac.update(data);
|
|
2596
|
+
return hmac.digest('base64url');
|
|
2597
|
+
},
|
|
2598
|
+
|
|
2419
2599
|
async getSignedFormData(opts) {
|
|
2420
2600
|
const serviceSecret = await module.exports.getServiceSecret();
|
|
2421
2601
|
return module.exports.getSignedFormDataSync(serviceSecret, opts);
|
|
@@ -2431,8 +2611,11 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2431
2611
|
return res;
|
|
2432
2612
|
},
|
|
2433
2613
|
|
|
2434
|
-
|
|
2614
|
+
// Signs a hosted setup-form blob (the default purpose), a tracking blob or an unsubscribe
|
|
2615
|
+
// blob; the purpose picks the derived key the matching verifier checks against
|
|
2616
|
+
getSignedFormDataSync(serviceSecret, opts, asIs, purpose) {
|
|
2435
2617
|
opts = opts || {};
|
|
2618
|
+
purpose = purpose || module.exports.SIGNING_PURPOSE.FORM;
|
|
2436
2619
|
|
|
2437
2620
|
let data = Buffer.from(
|
|
2438
2621
|
JSON.stringify(
|
|
@@ -2455,11 +2638,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2455
2638
|
)
|
|
2456
2639
|
);
|
|
2457
2640
|
|
|
2458
|
-
let signature;
|
|
2459
|
-
|
|
2460
|
-
let hmac = createHmac('sha256', serviceSecret);
|
|
2461
|
-
hmac.update(data);
|
|
2462
|
-
signature = hmac.digest('base64url');
|
|
2641
|
+
let signature = module.exports.signServiceData(serviceSecret, data, purpose);
|
|
2463
2642
|
|
|
2464
2643
|
return { data: data.toString('base64url'), signature };
|
|
2465
2644
|
},
|
|
@@ -2483,7 +2662,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2483
2662
|
payload.msg = opts.messageId;
|
|
2484
2663
|
}
|
|
2485
2664
|
|
|
2486
|
-
let { data: signedData, signature } = module.exports.getSignedFormDataSync(serviceSecret, payload, true);
|
|
2665
|
+
let { data: signedData, signature } = module.exports.getSignedFormDataSync(serviceSecret, payload, true, module.exports.SIGNING_PURPOSE.UNSUBSCRIBE);
|
|
2487
2666
|
|
|
2488
2667
|
let unsubscribeUrlObj = new URL('/unsubscribe', baseUrl || 'http://localhost');
|
|
2489
2668
|
unsubscribeUrlObj.searchParams.append('data', signedData);
|
|
@@ -2499,24 +2678,36 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2499
2678
|
// silently skipped (an empty secret would otherwise accept forged, unsigned data). Returns true
|
|
2500
2679
|
// only when `sig` matches `data`.
|
|
2501
2680
|
//
|
|
2502
|
-
//
|
|
2503
|
-
//
|
|
2504
|
-
//
|
|
2505
|
-
//
|
|
2506
|
-
//
|
|
2507
|
-
//
|
|
2508
|
-
//
|
|
2509
|
-
//
|
|
2510
|
-
|
|
2681
|
+
// Fail-closed on purpose: an install whose stored serviceSecret is blank answers 403 to the
|
|
2682
|
+
// tracking and unsubscribe links in already-delivered mail (skipping the check resolved them,
|
|
2683
|
+
// and accepted forged blobs with them). An operator can restore the previous secret through
|
|
2684
|
+
// the settings API to revive old links.
|
|
2685
|
+
//
|
|
2686
|
+
// `purpose` names the derived key (SIGNING_PURPOSE; the setup form when omitted). Tracking and
|
|
2687
|
+
// unsubscribe links live in mail that was sent before the keys were derived, so for those two
|
|
2688
|
+
// purposes a signature made with the raw secret is still accepted; a setup blob is not, since
|
|
2689
|
+
// a nonce-less one is exactly what a replayed webhook body or tracking blob used to pass as.
|
|
2690
|
+
async verifyServiceSignature(data, sig, purpose) {
|
|
2691
|
+
purpose = purpose || module.exports.SIGNING_PURPOSE.FORM;
|
|
2511
2692
|
const serviceSecret = await module.exports.getServiceSecret();
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2693
|
+
|
|
2694
|
+
if (module.exports.constantTimeEqual(module.exports.signServiceData(serviceSecret, data, purpose), sig)) {
|
|
2695
|
+
return true;
|
|
2696
|
+
}
|
|
2697
|
+
|
|
2698
|
+
if (purpose === module.exports.SIGNING_PURPOSE.TRACKING || purpose === module.exports.SIGNING_PURPOSE.UNSUBSCRIBE) {
|
|
2699
|
+
// a link minted before the keys were derived
|
|
2700
|
+
const legacy = createHmac('sha256', serviceSecret);
|
|
2701
|
+
legacy.update(data);
|
|
2702
|
+
return module.exports.constantTimeEqual(legacy.digest('base64url'), sig);
|
|
2703
|
+
}
|
|
2704
|
+
|
|
2705
|
+
return false;
|
|
2515
2706
|
},
|
|
2516
2707
|
|
|
2517
2708
|
// Redis key for a hosted-form single-use nonce (`n` inside the signed blob). Built in one place so
|
|
2518
|
-
// the sites that must agree on it - the consumed-nonce check below
|
|
2519
|
-
//
|
|
2709
|
+
// the sites that must agree on it - the consumed-nonce check below and the claim both setup arms
|
|
2710
|
+
// make through lib/ui-routes/account-setup.js - cannot drift.
|
|
2520
2711
|
formNonceKey(n) {
|
|
2521
2712
|
return `${REDIS_PREFIX}account:form:${n}`;
|
|
2522
2713
|
},
|
|
@@ -2524,8 +2715,8 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2524
2715
|
// Atomically claim a hosted-form single-use nonce (SET NX). Returns true when THIS caller won the
|
|
2525
2716
|
// claim, false when the key already existed (the signed URL was already used). Throws on a Redis error
|
|
2526
2717
|
// - a Redis failure is NOT a consumed nonce, so callers must map it to a retryable 5xx, not a 403.
|
|
2527
|
-
//
|
|
2528
|
-
//
|
|
2718
|
+
// Called from lib/ui-routes/account-setup.js, which both setup arms complete through, and which maps
|
|
2719
|
+
// the outcome to its 403/500 refusals.
|
|
2529
2720
|
async claimFormNonce(redis, n, t) {
|
|
2530
2721
|
const claimed = await redis.set(module.exports.formNonceKey(n), (t || '0').toString(), 'EX', Math.floor(MAX_FORM_TTL / 1000), 'NX');
|
|
2531
2722
|
return !!claimed;
|
|
@@ -2545,11 +2736,13 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2545
2736
|
}
|
|
2546
2737
|
},
|
|
2547
2738
|
|
|
2739
|
+
// `opts.purpose` selects the signing key (SIGNING_PURPOSE; the setup form when omitted), see
|
|
2740
|
+
// verifyServiceSignature()
|
|
2548
2741
|
async parseSignedFormData(redis, payload, gt, opts) {
|
|
2549
2742
|
opts = opts || {};
|
|
2550
2743
|
|
|
2551
2744
|
let data = Buffer.from(payload.data, 'base64url').toString();
|
|
2552
|
-
if (!(await module.exports.verifyServiceSignature(data, payload.sig))) {
|
|
2745
|
+
if (!(await module.exports.verifyServiceSignature(data, payload.sig, opts.purpose))) {
|
|
2553
2746
|
let error = Boom.boomify(new Error(gt.gettext('Signature validation failed')), { statusCode: 403 });
|
|
2554
2747
|
throw error;
|
|
2555
2748
|
}
|
|
@@ -2695,7 +2888,11 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2695
2888
|
convertDataUrisToAttachments(data) {
|
|
2696
2889
|
if (data.html) {
|
|
2697
2890
|
let cidCounter = 0;
|
|
2698
|
-
|
|
2891
|
+
// `[^<>]*` before src and a bounded media type: an `<img` that is never closed used to
|
|
2892
|
+
// let the scan run to the end of the body from every image tag and backtrack over it
|
|
2893
|
+
// (80 KB of `<img ` took half a second, the 5 MB schema cap would have taken minutes).
|
|
2894
|
+
// A tag never contains `<`, so well-formed markup is unaffected
|
|
2895
|
+
let html = data.html.replace(/(<img\b[^<>]* src\s*=[\s"']*)(data:([^;"'>\s]{1,256});[^"'>\s]+)/gi, (match, prefix, dataUri, mimeType) => {
|
|
2699
2896
|
let cid = `${uuid()}@emailengine`;
|
|
2700
2897
|
if (!data.attachments) {
|
|
2701
2898
|
data.attachments = [];
|
|
@@ -2730,8 +2927,30 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2730
2927
|
heapTotal: memUsage.heapTotal,
|
|
2731
2928
|
external: memUsage.external,
|
|
2732
2929
|
rss: memUsage.rss,
|
|
2733
|
-
arrayBuffers: memUsage.arrayBuffers || 0
|
|
2930
|
+
arrayBuffers: memUsage.arrayBuffers || 0,
|
|
2931
|
+
eventLoopDelay: this.readEventLoopDelay()
|
|
2734
2932
|
};
|
|
2933
|
+
},
|
|
2934
|
+
|
|
2935
|
+
// How late this thread's event loop ran since the previous reading, in milliseconds. The
|
|
2936
|
+
// main thread's metrics collector reads every thread every 15 seconds, so a reading covers
|
|
2937
|
+
// that window. The histogram starts with the first reading, which therefore has nothing
|
|
2938
|
+
// to report.
|
|
2939
|
+
readEventLoopDelay() {
|
|
2940
|
+
if (!this.delayHistogram) {
|
|
2941
|
+
this.delayHistogram = monitorEventLoopDelay({ resolution: 20 });
|
|
2942
|
+
this.delayHistogram.enable();
|
|
2943
|
+
return null;
|
|
2944
|
+
}
|
|
2945
|
+
let histogram = this.delayHistogram;
|
|
2946
|
+
let reading = histogram.count
|
|
2947
|
+
? {
|
|
2948
|
+
max: histogram.max / 1e6,
|
|
2949
|
+
p99: histogram.percentile(99) / 1e6
|
|
2950
|
+
}
|
|
2951
|
+
: null;
|
|
2952
|
+
histogram.reset();
|
|
2953
|
+
return reading;
|
|
2735
2954
|
}
|
|
2736
2955
|
},
|
|
2737
2956
|
|
package/lib/totp.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const crypto = require('crypto');
|
|
4
4
|
const { base32Encode } = require('./base32');
|
|
5
5
|
const qrcode = require('qrcode-generator');
|
|
6
|
+
const { randomId } = require('./utils/random-id');
|
|
6
7
|
|
|
7
8
|
// The otpauth URL is percent-encoded ASCII, but the encoder qrcode-generator selects by default
|
|
8
9
|
// keeps one byte per character, so it is switched to UTF-8 once here rather than relied on
|
|
@@ -32,11 +33,7 @@ function hotp(secret, counter) {
|
|
|
32
33
|
}
|
|
33
34
|
|
|
34
35
|
function generateTotpSeed() {
|
|
35
|
-
|
|
36
|
-
for (let i = 0; i < SEED_LENGTH; i++) {
|
|
37
|
-
seed += SEED_CHARSET[crypto.randomInt(SEED_CHARSET.length)];
|
|
38
|
-
}
|
|
39
|
-
return seed;
|
|
36
|
+
return randomId(SEED_CHARSET, SEED_LENGTH);
|
|
40
37
|
}
|
|
41
38
|
|
|
42
39
|
function verifyTotp(seed, token, options) {
|
package/lib/translations.js
CHANGED
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
const fs = require('fs').promises;
|
|
4
4
|
const Path = require('path');
|
|
5
5
|
const Gettext = require('@postalsys/gettext');
|
|
6
|
-
const { mo } = require('gettext-parser');
|
|
7
6
|
const locales = require('../translations/locales.json');
|
|
8
7
|
const joiMessages = require('@postalsys/joi-messages');
|
|
9
8
|
|
|
@@ -25,7 +24,7 @@ async function loadTranslations() {
|
|
|
25
24
|
// Gettext translations
|
|
26
25
|
for (let locale of locales) {
|
|
27
26
|
let fContent = await fs.readFile(Path.join(translationsDir, locale.file || `${locale.locale}.mo`));
|
|
28
|
-
let parsedTranslations =
|
|
27
|
+
let parsedTranslations = Gettext.parseMo(fContent);
|
|
29
28
|
gt.addTranslations(locale.locale, domain, parsedTranslations);
|
|
30
29
|
}
|
|
31
30
|
}
|