emailengine-app 2.84.1 → 2.84.2
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/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +28 -0
- package/Dockerfile +2 -2
- package/bin/emailengine.js +15 -0
- package/data/google-crawlers.json +1 -1
- package/docker-compose.yml +1 -1
- package/lib/account/own-account-key.js +42 -0
- package/lib/account-assignment.js +1 -33
- package/lib/account.js +32 -19
- package/lib/add-trackers.js +11 -4
- package/lib/api-routes/account-routes.js +67 -14
- package/lib/api-routes/gateway-routes.js +9 -3
- package/lib/api-routes/message-routes.js +7 -1
- package/lib/api-routes/mint-bounds.js +11 -0
- package/lib/api-routes/route-helpers.js +125 -3
- package/lib/api-routes/submit-routes.js +4 -2
- package/lib/auth-token.js +23 -10
- package/lib/bounce-detect.js +17 -5
- package/lib/consts.js +34 -0
- package/lib/create-imap-client.js +41 -2
- package/lib/email-client/base-client.js +20 -10
- package/lib/email-client/gmail-client.js +21 -7
- package/lib/email-client/imap/mailbox.js +10 -4
- package/lib/email-client/imap/response-metrics.js +75 -0
- package/lib/email-client/imap-client.js +5 -2
- package/lib/email-client/message-builder.js +7 -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/get-raw-email.js +4 -2
- package/lib/imap-proxy-auth.js +14 -1
- 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/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.js +26 -44
- package/lib/pbkdf2-phc.js +18 -1
- package/lib/privileged-settings.js +6 -3
- package/lib/redis-scan-delete.js +15 -1
- package/lib/schemas.js +78 -32
- package/lib/settings.js +13 -1
- package/lib/smtp-auth.js +23 -0
- package/lib/tools.js +245 -56
- package/lib/ui-routes/account-routes.js +16 -37
- package/lib/ui-routes/admin-config-routes.js +10 -38
- package/lib/ui-routes/admin-entities-routes.js +22 -24
- package/lib/ui-routes/auth-routes.js +47 -24
- package/lib/ui-routes/connection-security-form.js +74 -0
- package/lib/ui-routes/form-lists.js +46 -0
- package/lib/ui-routes/mcp-consent-routes.js +5 -1
- package/lib/ui-routes/oauth-config-routes.js +9 -18
- package/lib/ui-routes/sign-in-helpers.js +59 -0
- package/lib/ui-routes/unsubscribe-routes.js +6 -3
- package/lib/utils/map-concurrent.js +36 -0
- package/lib/utils/network.js +28 -0
- package/lib/utils/provider-id.js +27 -0
- package/lib/utils/require-tls.js +33 -0
- package/lib/web-safe-html.js +5 -6
- package/lib/webhook-penalty.js +75 -0
- package/lib/webhook-routing.js +22 -2
- package/package.json +21 -21
- package/sbom.json +1 -1
- package/server.js +25 -14
- 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 +23 -23
- package/translations/messages.pot +66 -66
- package/views/account/security.hbs +10 -0
- package/views/accounts/account.hbs +11 -11
- package/views/accounts/edit.hbs +6 -2
- package/views/partials/gateway_form.hbs +3 -1
- package/workers/api.js +43 -3
- package/workers/webhooks.js +39 -3
- 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
|
@@ -36,9 +36,17 @@ const { v3: murmurhash } = require('murmurhash');
|
|
|
36
36
|
const { isEmail } = require('./utils/is-email');
|
|
37
37
|
const { toCamelCase } = require('./utils/to-camel-case');
|
|
38
38
|
const { normalizePath } = require('./utils/mailbox-path');
|
|
39
|
+
const { applyRequireTls } = require('./utils/require-tls');
|
|
39
40
|
const { compare: compareVersions, validate: validateVersion } = require('compare-versions');
|
|
41
|
+
|
|
42
|
+
// Largest decompressed license blob accepted, well above any real license
|
|
43
|
+
const MAX_LICENSE_SIZE = 1024 * 1024;
|
|
44
|
+
|
|
45
|
+
// deriveSigningKey() results, by purpose
|
|
46
|
+
const derivedSigningKeys = new Map();
|
|
40
47
|
const {
|
|
41
48
|
REDIS_PREFIX,
|
|
49
|
+
ADMIN_SESSION_MAX_AGE,
|
|
42
50
|
TLS_DEFAULTS,
|
|
43
51
|
URL_FETCH_TIMEOUT,
|
|
44
52
|
MAX_FORM_TTL,
|
|
@@ -204,7 +212,9 @@ function createSocksAgent(proxyUrl, agentOpts) {
|
|
|
204
212
|
|
|
205
213
|
if (useTls) {
|
|
206
214
|
let rawSocket = socket;
|
|
207
|
-
|
|
215
|
+
// Node's own TLS defaults, not TLS_DEFAULTS: those (TLSv1, SECLEVEL=0) exist for old
|
|
216
|
+
// mail servers, and this is an HTTPS request to an API or a webhook target
|
|
217
|
+
socket = tls.connect({ socket: rawSocket, servername: servername || hostname });
|
|
208
218
|
// The SOCKS timeout above only covers the proxy negotiation. A proxy (or a target
|
|
209
219
|
// behind it) that accepts the tunnel and then never answers the ClientHello would
|
|
210
220
|
// otherwise hold the request, and whatever awaits it (a token refresh, a Gmail or
|
|
@@ -326,7 +336,8 @@ httpAgent.forRoute = dispatchersForRoute;
|
|
|
326
336
|
try {
|
|
327
337
|
installDispatchers((workerData && workerData.httpProxyUrl) || null, null);
|
|
328
338
|
} catch (err) {
|
|
329
|
-
|
|
339
|
+
// the URL error carries the proxy URL, credentials included, as its input
|
|
340
|
+
logger.error({ msg: 'Failed to create HTTP proxy agent, using direct connections', err: module.exports.sanitizeUrlError(err) });
|
|
330
341
|
installDispatchers(null, null);
|
|
331
342
|
}
|
|
332
343
|
|
|
@@ -454,7 +465,11 @@ async function _doReloadHttpProxyAgent() {
|
|
|
454
465
|
.map(([stale]) => stale.close().catch(() => false))
|
|
455
466
|
);
|
|
456
467
|
} catch (err) {
|
|
457
|
-
logger.error({
|
|
468
|
+
logger.error({
|
|
469
|
+
msg: 'Failed to create HTTP proxy agent, keeping existing agent',
|
|
470
|
+
httpProxyUrl: module.exports.redactUrlCredentials(proxyUrl),
|
|
471
|
+
err: module.exports.sanitizeUrlError(err)
|
|
472
|
+
});
|
|
458
473
|
}
|
|
459
474
|
}
|
|
460
475
|
|
|
@@ -580,10 +595,11 @@ function redactValidationError(err) {
|
|
|
580
595
|
}
|
|
581
596
|
|
|
582
597
|
// 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
|
|
598
|
+
// (collectCidReferences) and the data URI replace step (embedCidImages) tokenize
|
|
599
|
+
// a reference identically, so everything the replace step rewrites was collected
|
|
600
|
+
// and fetched first, otherwise inline images would silently disappear. Exposed as
|
|
601
|
+
// a factory rather than one regex instance so no lastIndex state can leak
|
|
602
|
+
// between callers.
|
|
587
603
|
const CID_REFERENCE_SOURCE = String.raw`\bcid:([^"'\s>]+)`;
|
|
588
604
|
|
|
589
605
|
function cidReferenceRegex() {
|
|
@@ -595,13 +611,6 @@ function cidReferenceRegex() {
|
|
|
595
611
|
// break out of the src attribute of HTML that is served as web safe
|
|
596
612
|
const DATA_URL_CONTENT_TYPE = /^[\w.+-]+\/[\w.+-]+$/;
|
|
597
613
|
|
|
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
614
|
/**
|
|
606
615
|
* Reads a Retry-After header as seconds. Accepts a fetch Headers object (or anything with get())
|
|
607
616
|
* and a plain header object with keys in any casing, which is how the items of a Graph $batch
|
|
@@ -643,17 +652,51 @@ function parseRetryAfter(headers) {
|
|
|
643
652
|
return Math.max(0, Math.ceil((date - Date.now()) / 1000));
|
|
644
653
|
}
|
|
645
654
|
|
|
655
|
+
/**
|
|
656
|
+
* Builds a regex for the named HTML attributes with their value in any of the three syntaxes:
|
|
657
|
+
* group 1 is everything up to the value, group 2 the value as written, quotes included. The HTML
|
|
658
|
+
* parser treats '/' between attributes like whitespace, hence [\s/] rather than \s, and a new
|
|
659
|
+
* attribute name may start right after a quoted value (`open=""class="..."`), so a quote counts as
|
|
660
|
+
* a boundary too
|
|
661
|
+
*
|
|
662
|
+
* @param {String[]} names - attribute names
|
|
663
|
+
* @returns {RegExp} global, case-insensitive
|
|
664
|
+
*/
|
|
665
|
+
function attributeValueRegex(names) {
|
|
666
|
+
return new RegExp(`([\\s/"'](?:${names.join('|')})\\s*=\\s*)("[^"]*"|'[^']*'|[^\\s"'>]+)`, 'gi');
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// The attributes a cid: reference is embedded in. A reference anywhere else (an href, the text
|
|
670
|
+
// of the message) is left as it is: this runs after the sanitizer, which refuses a data: URL on a
|
|
671
|
+
// link, and rewriting a cid: link into one would hand the sender exactly what was refused
|
|
672
|
+
const CID_EMBED_ATTRIBUTE = attributeValueRegex(['src', 'srcset', 'background']);
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* Replaces the cid: references in the image attributes of an HTML string with data: URLs for the
|
|
676
|
+
* attachments that have content
|
|
677
|
+
*
|
|
678
|
+
* @param {String} html
|
|
679
|
+
* @param {Function} lookup - called with the content id, returns { contentType, content } (content as base64) or a falsy value
|
|
680
|
+
* @returns {String}
|
|
681
|
+
*/
|
|
646
682
|
function embedCidImages(html, lookup) {
|
|
647
|
-
if (!html) {
|
|
683
|
+
if (!html || !html.includes('cid:')) {
|
|
648
684
|
return html;
|
|
649
685
|
}
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
if (!
|
|
653
|
-
return
|
|
654
|
-
}
|
|
655
|
-
let
|
|
656
|
-
|
|
686
|
+
let references = cidReferenceRegex();
|
|
687
|
+
return html.replace(CID_EMBED_ATTRIBUTE, (attribute, prefix, value) => {
|
|
688
|
+
if (!value.includes('cid:')) {
|
|
689
|
+
return attribute;
|
|
690
|
+
}
|
|
691
|
+
let embedded = value.replace(references, (reference, cid) => {
|
|
692
|
+
let attachment = lookup(cid);
|
|
693
|
+
if (!attachment || !attachment.content) {
|
|
694
|
+
return reference;
|
|
695
|
+
}
|
|
696
|
+
let contentType = DATA_URL_CONTENT_TYPE.test(attachment.contentType || '') ? attachment.contentType : 'application/octet-stream';
|
|
697
|
+
return `data:${contentType};base64,${attachment.content}`;
|
|
698
|
+
});
|
|
699
|
+
return prefix + embedded;
|
|
657
700
|
});
|
|
658
701
|
}
|
|
659
702
|
|
|
@@ -718,6 +761,7 @@ module.exports = {
|
|
|
718
761
|
TLS_MATERIAL_SETTINGS,
|
|
719
762
|
|
|
720
763
|
cidReferenceRegex,
|
|
764
|
+
attributeValueRegex,
|
|
721
765
|
embedCidImages,
|
|
722
766
|
parseRetryAfter,
|
|
723
767
|
|
|
@@ -734,7 +778,9 @@ module.exports = {
|
|
|
734
778
|
* @param {Object} sessionData Session payload (user/profile/etc, no sid)
|
|
735
779
|
*/
|
|
736
780
|
setAdminSession(request, sessionData) {
|
|
737
|
-
|
|
781
|
+
// issuedAt is what isEndedSession() ages the session by; a caller re-stamping a session
|
|
782
|
+
// it means to keep may carry the old value over
|
|
783
|
+
request.cookieAuth.set(Object.assign({ issuedAt: Date.now() }, sessionData, { sid: randomBytes(32).toString('hex') }));
|
|
738
784
|
},
|
|
739
785
|
|
|
740
786
|
/**
|
|
@@ -754,12 +800,28 @@ module.exports = {
|
|
|
754
800
|
* password exists (an unsecured instance), or nobody has ever bumped it,
|
|
755
801
|
* and a session stamped before the field existed must not be force-expired.
|
|
756
802
|
*
|
|
803
|
+
* A session is also over once it is older than ADMIN_SESSION_MAX_AGE, by
|
|
804
|
+
* the issuedAt setAdminSession() stamps. The sealed cookie has no expiry of
|
|
805
|
+
* its own, so a cookie captured once used to stay valid until the next
|
|
806
|
+
* password change, however long ago it was issued. A session carrying no
|
|
807
|
+
* issuedAt was issued before the stamp existed and is over too: that is one
|
|
808
|
+
* sign-in at upgrade time for whoever is logged in, against never ageing
|
|
809
|
+
* out a cookie whose age nobody can tell.
|
|
810
|
+
*
|
|
757
811
|
* @param {Number} currentPasswordVersion authData.passwordVersion, or 0
|
|
758
812
|
* @param {Object} session decoded session cookie
|
|
813
|
+
* @param {Number} [now] the current time, for tests
|
|
759
814
|
* @returns {Boolean} true when the session is over
|
|
760
815
|
*/
|
|
761
|
-
isEndedSession(currentPasswordVersion, session) {
|
|
762
|
-
|
|
816
|
+
isEndedSession(currentPasswordVersion, session, now) {
|
|
817
|
+
if (!currentPasswordVersion) {
|
|
818
|
+
return false;
|
|
819
|
+
}
|
|
820
|
+
if (currentPasswordVersion !== (session && session.passwordVersion)) {
|
|
821
|
+
return true;
|
|
822
|
+
}
|
|
823
|
+
let issuedAt = Number(session.issuedAt);
|
|
824
|
+
return !issuedAt || (now || Date.now()) - issuedAt > ADMIN_SESSION_MAX_AGE;
|
|
763
825
|
},
|
|
764
826
|
|
|
765
827
|
/**
|
|
@@ -796,12 +858,14 @@ module.exports = {
|
|
|
796
858
|
* lookup per attachment instead of scanning the full HTML once per attachment:
|
|
797
859
|
* the repeated synchronous scans cost attachment count times body size, which
|
|
798
860
|
* on a crafted message blocks the worker event loop past the heartbeat
|
|
799
|
-
* restart timeout. Tokenizes with the same grammar as the
|
|
861
|
+
* restart timeout. Tokenizes with the same grammar as the replace step
|
|
800
862
|
* (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
|
-
*
|
|
863
|
+
* id, or that appears outside a cid: link, does not match. The set answers
|
|
864
|
+
* which attachments the HTML refers to at all, which is also what decides
|
|
865
|
+
* whether an attachment is inline, so it looks at every reference, while
|
|
866
|
+
* embedCidImages() rewrites only the image attributes among them. Each token
|
|
867
|
+
* is additionally added truncated at a closing parenthesis, so that a CSS
|
|
868
|
+
* url(cid:...) reference counts as a reference to its attachment.
|
|
805
869
|
* @param {String} html HTML content to scan
|
|
806
870
|
* @returns {Set<String>} Content ids referenced in the HTML
|
|
807
871
|
*/
|
|
@@ -1568,7 +1632,9 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
1568
1632
|
);
|
|
1569
1633
|
}
|
|
1570
1634
|
|
|
1571
|
-
|
|
1635
|
+
// bounded: the blob is caller-supplied and brotli expands a few hundred bytes into
|
|
1636
|
+
// hundreds of megabytes; a license is a few kilobytes
|
|
1637
|
+
let signedLicense = await brotliDecompressAsync(encodedLicense, { maxOutputLength: MAX_LICENSE_SIZE });
|
|
1572
1638
|
|
|
1573
1639
|
let { l: licenseRaw, s: signature } = msgpack.decode(signedLicense);
|
|
1574
1640
|
|
|
@@ -1829,6 +1895,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
1829
1895
|
smtpConfig.tls[key] = TLS_DEFAULTS[key];
|
|
1830
1896
|
}
|
|
1831
1897
|
}
|
|
1898
|
+
applyRequireTls(smtpConfig);
|
|
1832
1899
|
|
|
1833
1900
|
for (let level of ['trace', 'debug', 'info', 'warn', 'error', 'fatal']) {
|
|
1834
1901
|
smtpLogger[level] = (data, message, ...args) => {
|
|
@@ -1923,7 +1990,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
1923
1990
|
);
|
|
1924
1991
|
}
|
|
1925
1992
|
|
|
1926
|
-
let signedContent = await brotliDecompressAsync(encodedContent);
|
|
1993
|
+
let signedContent = await brotliDecompressAsync(encodedContent, { maxOutputLength: MAX_LICENSE_SIZE });
|
|
1927
1994
|
let { l: contentRaw, s: signature } = msgpack.decode(signedContent);
|
|
1928
1995
|
for (let rootItem of rootList) {
|
|
1929
1996
|
try {
|
|
@@ -2331,6 +2398,65 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2331
2398
|
return secretKey.replace(/^(.{8}).*$/, `$1... (${secretKey.length}B)`);
|
|
2332
2399
|
},
|
|
2333
2400
|
|
|
2401
|
+
// What an operator needs to tell which client secret the instance holds when the provider says
|
|
2402
|
+
// it is wrong: the length and the first few characters. Carried on the token error as
|
|
2403
|
+
// `clientSecretHint`, where the log serializer picks it up and nothing that builds an API
|
|
2404
|
+
// payload or a webhook out of `err.tokenRequest` does. Shorter than formatPartialSecretKey()
|
|
2405
|
+
// all the same, since eight characters of a thirty-character secret is a quarter of it
|
|
2406
|
+
formatSecretHint(secretKey) {
|
|
2407
|
+
secretKey = (secretKey || '').toString();
|
|
2408
|
+
return `${secretKey.slice(0, 3)}... (${secretKey.length}B)`;
|
|
2409
|
+
},
|
|
2410
|
+
|
|
2411
|
+
// The body of a token request and the token response as they may go to the log. The secrets
|
|
2412
|
+
// in them are masked whether or not raw logging is on: EENGINE_LOG_RAW is for the protocol
|
|
2413
|
+
// traffic, and the application's client secret and the refresh tokens of every account are
|
|
2414
|
+
// not something a debug switch should put in the log in full
|
|
2415
|
+
formatOAuthRequestBody(searchParams) {
|
|
2416
|
+
let entries = typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
|
|
2417
|
+
let data = Object.fromEntries(entries);
|
|
2418
|
+
|
|
2419
|
+
for (let key of ['refresh_token', 'client_secret', 'code']) {
|
|
2420
|
+
if (data[key]) {
|
|
2421
|
+
data[key] = module.exports.formatPartialSecretKey(data[key]);
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
|
|
2425
|
+
if (data.assertion) {
|
|
2426
|
+
// a signed JWT
|
|
2427
|
+
let [payload, signature] = data.assertion.toString().split('.');
|
|
2428
|
+
data.assertion = [payload, module.exports.formatPartialSecretKey(signature)].join('.');
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
return data;
|
|
2432
|
+
},
|
|
2433
|
+
|
|
2434
|
+
formatOAuthResponse(responseObj) {
|
|
2435
|
+
if (!responseObj || typeof responseObj !== 'object') {
|
|
2436
|
+
return responseObj;
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
let data = module.exports.structuredClone(responseObj);
|
|
2440
|
+
for (let key of ['access_token', 'refresh_token', 'id_token']) {
|
|
2441
|
+
if (data[key]) {
|
|
2442
|
+
data[key] = module.exports.formatPartialSecretKey(data[key]);
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
|
|
2446
|
+
return data;
|
|
2447
|
+
},
|
|
2448
|
+
|
|
2449
|
+
// An error from `new URL()` carries the string it failed on as `err.input`, and when that
|
|
2450
|
+
// string is a proxy URL it carries the proxy credentials. The logger redacts that field on its
|
|
2451
|
+
// own (REDACTED_LOG_KEYS), but the error object also reaches Sentry whole, so the string itself
|
|
2452
|
+
// is rewritten. Returns the same error with the credentials redacted
|
|
2453
|
+
sanitizeUrlError(err) {
|
|
2454
|
+
if (err && typeof err === 'object' && typeof err.input === 'string') {
|
|
2455
|
+
err.input = module.exports.redactUrlCredentials(err.input);
|
|
2456
|
+
}
|
|
2457
|
+
return err;
|
|
2458
|
+
},
|
|
2459
|
+
|
|
2334
2460
|
// Returns the URL with any embedded basic auth credentials removed, safe for logging. Never
|
|
2335
2461
|
// throws: an unparseable value is replaced with a static placeholder rather than echoed back,
|
|
2336
2462
|
// because the raw string could itself carry the credentials that made it unparseable.
|
|
@@ -2406,9 +2532,21 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2406
2532
|
if (stored) {
|
|
2407
2533
|
serviceSecret = stored;
|
|
2408
2534
|
} else {
|
|
2409
|
-
// The field exists but reads back empty
|
|
2410
|
-
//
|
|
2411
|
-
//
|
|
2535
|
+
// The field exists but reads back empty. Two cases, and they must not be
|
|
2536
|
+
// treated the same. A legacy blank (the settings API used to allow it) is
|
|
2537
|
+
// healed by overwriting, which HSETNX cannot do. A value that is present but
|
|
2538
|
+
// does not decrypt is the instance running with the wrong EENGINE_SECRET, and
|
|
2539
|
+
// overwriting it would destroy a secret the rotation CLI can still recover
|
|
2540
|
+
// once the right one is back, so that one is an error here: links stop
|
|
2541
|
+
// verifying until the operator fixes the secret, the same as every stored
|
|
2542
|
+
// credential already does.
|
|
2543
|
+
let raw = await settings.getRaw('serviceSecret');
|
|
2544
|
+
if (raw) {
|
|
2545
|
+
let error = new Error('The stored service secret can not be decrypted; check EENGINE_SECRET');
|
|
2546
|
+
error.code = 'EServiceSecretUnreadable';
|
|
2547
|
+
error.statusCode = 500;
|
|
2548
|
+
throw error;
|
|
2549
|
+
}
|
|
2412
2550
|
await settings.set('serviceSecret', serviceSecret);
|
|
2413
2551
|
}
|
|
2414
2552
|
}
|
|
@@ -2416,6 +2554,40 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2416
2554
|
return serviceSecret;
|
|
2417
2555
|
},
|
|
2418
2556
|
|
|
2557
|
+
// One service secret signs several unrelated things: webhook bodies, hosted setup-form blobs,
|
|
2558
|
+
// tracking links and unsubscribe links. Each is HMAC-SHA256 of some bytes, so without a purpose
|
|
2559
|
+
// in the key a signature made for one is a valid signature for the others - a webhook body and
|
|
2560
|
+
// its X-EE-Wh-Signature header was a valid setup blob for the account the delivery named. The
|
|
2561
|
+
// key for each purpose is derived from the service secret, so a signature only verifies where
|
|
2562
|
+
// it was minted. The webhook signature itself keeps the raw secret: its format is documented
|
|
2563
|
+
// and verified by customer code.
|
|
2564
|
+
SIGNING_PURPOSE: {
|
|
2565
|
+
FORM: 'form',
|
|
2566
|
+
TRACKING: 'tracking',
|
|
2567
|
+
UNSUBSCRIBE: 'unsubscribe'
|
|
2568
|
+
},
|
|
2569
|
+
|
|
2570
|
+
// Derived once per purpose and kept while the secret is the one it was derived from: a
|
|
2571
|
+
// tracked message signs one blob per link, and the key is the same for all of them
|
|
2572
|
+
deriveSigningKey(serviceSecret, purpose) {
|
|
2573
|
+
if (!Object.values(module.exports.SIGNING_PURPOSE).includes(purpose)) {
|
|
2574
|
+
throw new Error(`Unknown signing purpose ${JSON.stringify(purpose)}`);
|
|
2575
|
+
}
|
|
2576
|
+
let cached = derivedSigningKeys.get(purpose);
|
|
2577
|
+
if (cached && cached.serviceSecret === serviceSecret) {
|
|
2578
|
+
return cached.key;
|
|
2579
|
+
}
|
|
2580
|
+
let key = createHmac('sha256', serviceSecret).update(`emailengine:signing:${purpose}:v1`).digest();
|
|
2581
|
+
derivedSigningKeys.set(purpose, { serviceSecret, key });
|
|
2582
|
+
return key;
|
|
2583
|
+
},
|
|
2584
|
+
|
|
2585
|
+
signServiceData(serviceSecret, data, purpose) {
|
|
2586
|
+
let hmac = createHmac('sha256', module.exports.deriveSigningKey(serviceSecret, purpose));
|
|
2587
|
+
hmac.update(data);
|
|
2588
|
+
return hmac.digest('base64url');
|
|
2589
|
+
},
|
|
2590
|
+
|
|
2419
2591
|
async getSignedFormData(opts) {
|
|
2420
2592
|
const serviceSecret = await module.exports.getServiceSecret();
|
|
2421
2593
|
return module.exports.getSignedFormDataSync(serviceSecret, opts);
|
|
@@ -2431,8 +2603,11 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2431
2603
|
return res;
|
|
2432
2604
|
},
|
|
2433
2605
|
|
|
2434
|
-
|
|
2606
|
+
// Signs a hosted setup-form blob (the default purpose), a tracking blob or an unsubscribe
|
|
2607
|
+
// blob; the purpose picks the derived key the matching verifier checks against
|
|
2608
|
+
getSignedFormDataSync(serviceSecret, opts, asIs, purpose) {
|
|
2435
2609
|
opts = opts || {};
|
|
2610
|
+
purpose = purpose || module.exports.SIGNING_PURPOSE.FORM;
|
|
2436
2611
|
|
|
2437
2612
|
let data = Buffer.from(
|
|
2438
2613
|
JSON.stringify(
|
|
@@ -2455,11 +2630,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2455
2630
|
)
|
|
2456
2631
|
);
|
|
2457
2632
|
|
|
2458
|
-
let signature;
|
|
2459
|
-
|
|
2460
|
-
let hmac = createHmac('sha256', serviceSecret);
|
|
2461
|
-
hmac.update(data);
|
|
2462
|
-
signature = hmac.digest('base64url');
|
|
2633
|
+
let signature = module.exports.signServiceData(serviceSecret, data, purpose);
|
|
2463
2634
|
|
|
2464
2635
|
return { data: data.toString('base64url'), signature };
|
|
2465
2636
|
},
|
|
@@ -2483,7 +2654,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2483
2654
|
payload.msg = opts.messageId;
|
|
2484
2655
|
}
|
|
2485
2656
|
|
|
2486
|
-
let { data: signedData, signature } = module.exports.getSignedFormDataSync(serviceSecret, payload, true);
|
|
2657
|
+
let { data: signedData, signature } = module.exports.getSignedFormDataSync(serviceSecret, payload, true, module.exports.SIGNING_PURPOSE.UNSUBSCRIBE);
|
|
2487
2658
|
|
|
2488
2659
|
let unsubscribeUrlObj = new URL('/unsubscribe', baseUrl || 'http://localhost');
|
|
2489
2660
|
unsubscribeUrlObj.searchParams.append('data', signedData);
|
|
@@ -2499,19 +2670,31 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2499
2670
|
// silently skipped (an empty secret would otherwise accept forged, unsigned data). Returns true
|
|
2500
2671
|
// only when `sig` matches `data`.
|
|
2501
2672
|
//
|
|
2502
|
-
//
|
|
2503
|
-
//
|
|
2504
|
-
//
|
|
2505
|
-
//
|
|
2506
|
-
//
|
|
2507
|
-
//
|
|
2508
|
-
//
|
|
2509
|
-
//
|
|
2510
|
-
|
|
2673
|
+
// Fail-closed on purpose: an install whose stored serviceSecret is blank answers 403 to the
|
|
2674
|
+
// tracking and unsubscribe links in already-delivered mail (skipping the check resolved them,
|
|
2675
|
+
// and accepted forged blobs with them). An operator can restore the previous secret through
|
|
2676
|
+
// the settings API to revive old links.
|
|
2677
|
+
//
|
|
2678
|
+
// `purpose` names the derived key (SIGNING_PURPOSE; the setup form when omitted). Tracking and
|
|
2679
|
+
// unsubscribe links live in mail that was sent before the keys were derived, so for those two
|
|
2680
|
+
// purposes a signature made with the raw secret is still accepted; a setup blob is not, since
|
|
2681
|
+
// a nonce-less one is exactly what a replayed webhook body or tracking blob used to pass as.
|
|
2682
|
+
async verifyServiceSignature(data, sig, purpose) {
|
|
2683
|
+
purpose = purpose || module.exports.SIGNING_PURPOSE.FORM;
|
|
2511
2684
|
const serviceSecret = await module.exports.getServiceSecret();
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2685
|
+
|
|
2686
|
+
if (module.exports.constantTimeEqual(module.exports.signServiceData(serviceSecret, data, purpose), sig)) {
|
|
2687
|
+
return true;
|
|
2688
|
+
}
|
|
2689
|
+
|
|
2690
|
+
if (purpose === module.exports.SIGNING_PURPOSE.TRACKING || purpose === module.exports.SIGNING_PURPOSE.UNSUBSCRIBE) {
|
|
2691
|
+
// a link minted before the keys were derived
|
|
2692
|
+
const legacy = createHmac('sha256', serviceSecret);
|
|
2693
|
+
legacy.update(data);
|
|
2694
|
+
return module.exports.constantTimeEqual(legacy.digest('base64url'), sig);
|
|
2695
|
+
}
|
|
2696
|
+
|
|
2697
|
+
return false;
|
|
2515
2698
|
},
|
|
2516
2699
|
|
|
2517
2700
|
// Redis key for a hosted-form single-use nonce (`n` inside the signed blob). Built in one place so
|
|
@@ -2545,11 +2728,13 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2545
2728
|
}
|
|
2546
2729
|
},
|
|
2547
2730
|
|
|
2731
|
+
// `opts.purpose` selects the signing key (SIGNING_PURPOSE; the setup form when omitted), see
|
|
2732
|
+
// verifyServiceSignature()
|
|
2548
2733
|
async parseSignedFormData(redis, payload, gt, opts) {
|
|
2549
2734
|
opts = opts || {};
|
|
2550
2735
|
|
|
2551
2736
|
let data = Buffer.from(payload.data, 'base64url').toString();
|
|
2552
|
-
if (!(await module.exports.verifyServiceSignature(data, payload.sig))) {
|
|
2737
|
+
if (!(await module.exports.verifyServiceSignature(data, payload.sig, opts.purpose))) {
|
|
2553
2738
|
let error = Boom.boomify(new Error(gt.gettext('Signature validation failed')), { statusCode: 403 });
|
|
2554
2739
|
throw error;
|
|
2555
2740
|
}
|
|
@@ -2695,7 +2880,11 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2695
2880
|
convertDataUrisToAttachments(data) {
|
|
2696
2881
|
if (data.html) {
|
|
2697
2882
|
let cidCounter = 0;
|
|
2698
|
-
|
|
2883
|
+
// `[^<>]*` before src and a bounded media type: an `<img` that is never closed used to
|
|
2884
|
+
// let the scan run to the end of the body from every image tag and backtrack over it
|
|
2885
|
+
// (80 KB of `<img ` took half a second, the 5 MB schema cap would have taken minutes).
|
|
2886
|
+
// A tag never contains `<`, so well-formed markup is unaffected
|
|
2887
|
+
let html = data.html.replace(/(<img\b[^<>]* src\s*=[\s"']*)(data:([^;"'>\s]{1,256});[^"'>\s]+)/gi, (match, prefix, dataUri, mimeType) => {
|
|
2699
2888
|
let cid = `${uuid()}@emailengine`;
|
|
2700
2889
|
if (!data.attachments) {
|
|
2701
2890
|
data.attachments = [];
|
|
@@ -20,6 +20,7 @@ const { Account, authFailureDisabledAt, isOperatorDisabled } = require('../accou
|
|
|
20
20
|
const { formatGmailWatch } = require('../account/account-state');
|
|
21
21
|
const { SPECIAL_USE_PATH_FIELDS } = require('./special-use-paths');
|
|
22
22
|
const { imapMaxIdleTimeFormSchema, imapMaxIdleTimeFormValue, applyImapMaxIdleTimeForm } = require('./imap-idle-field');
|
|
23
|
+
const { securityFormFields, securityFormValues, applySecurityForm } = require('./connection-security-form');
|
|
23
24
|
|
|
24
25
|
const { Gateway } = require('../gateway');
|
|
25
26
|
const { autodetectImapSettings, resolveAppPassword, getAppPassword } = require('../autodetect-imap-settings');
|
|
@@ -58,6 +59,7 @@ const {
|
|
|
58
59
|
closedAfterConnectMessage,
|
|
59
60
|
windowedPageLinks
|
|
60
61
|
} = require('./route-helpers');
|
|
62
|
+
const { parseCustomHeaders } = require('./form-lists');
|
|
61
63
|
const { webhooks: Webhooks } = require('../webhooks');
|
|
62
64
|
const { accountQueueSummary } = require('../queue-browser');
|
|
63
65
|
const { describeEffectiveRouting, isDeliverableRoute } = require('../webhook-routing');
|
|
@@ -2124,10 +2126,10 @@ function init(args) {
|
|
|
2124
2126
|
// explicit request to keep the account off. Unchecked, the connection fields are
|
|
2125
2127
|
// shown and the save writes `disabled: false`, which lifts the park.
|
|
2126
2128
|
imap_disabled: (!accountData.imap && !accountData.oauth2) || isOperatorDisabled(accountData),
|
|
2127
|
-
|
|
2129
|
+
...securityFormValues('imap', accountData.imap),
|
|
2128
2130
|
imap_maxIdleTime: imapMaxIdleTimeFormValue(accountData.imap),
|
|
2129
2131
|
smtp: !!accountData.smtp,
|
|
2130
|
-
|
|
2132
|
+
...securityFormValues('smtp', accountData.smtp),
|
|
2131
2133
|
oauth2: !!accountData.oauth2,
|
|
2132
2134
|
|
|
2133
2135
|
imap_auth_pass: '',
|
|
@@ -2205,23 +2207,10 @@ function init(args) {
|
|
|
2205
2207
|
webhooks: request.payload.webhooks
|
|
2206
2208
|
};
|
|
2207
2209
|
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
.
|
|
2211
|
-
|
|
2212
|
-
.map(line => {
|
|
2213
|
-
let sep = line.indexOf(':');
|
|
2214
|
-
if (sep >= 0) {
|
|
2215
|
-
return {
|
|
2216
|
-
key: line.substring(0, sep).trim(),
|
|
2217
|
-
value: line.substring(sep + 1).trim()
|
|
2218
|
-
};
|
|
2219
|
-
}
|
|
2220
|
-
return {
|
|
2221
|
-
key: line,
|
|
2222
|
-
value: ''
|
|
2223
|
-
};
|
|
2224
|
-
});
|
|
2210
|
+
// Absent only from a request that did not render the field, keep the stored headers then
|
|
2211
|
+
if (typeof request.payload.customHeaders === 'string') {
|
|
2212
|
+
updates.webhooksCustomHeaders = parseCustomHeaders(request.payload.customHeaders);
|
|
2213
|
+
}
|
|
2225
2214
|
|
|
2226
2215
|
if (request.payload.imap) {
|
|
2227
2216
|
let imapTls = (oldData.imap && oldData.imap.tls) || {};
|
|
@@ -2267,9 +2256,7 @@ function init(args) {
|
|
|
2267
2256
|
// accounts, so like `secure` these only apply when it was submitted.
|
|
2268
2257
|
// Written only when the effective state changes - an untouched form
|
|
2269
2258
|
// save must not add new keys, as any imap diff forces a reconnect
|
|
2270
|
-
|
|
2271
|
-
imapTls.rejectUnauthorized = !request.payload.imap_tls_ignoreCertErrors;
|
|
2272
|
-
}
|
|
2259
|
+
applySecurityForm(request.payload, 'imap', oldData.imap, updateKeys, imapTls);
|
|
2273
2260
|
if (request.payload.imap_disableIMAP4rev2 !== !!(oldData.imap && oldData.imap.disableIMAP4rev2)) {
|
|
2274
2261
|
updateKeys.disableIMAP4rev2 = request.payload.imap_disableIMAP4rev2;
|
|
2275
2262
|
}
|
|
@@ -2296,13 +2283,6 @@ function init(args) {
|
|
|
2296
2283
|
smtpAuth.pass = request.payload.smtp_auth_pass;
|
|
2297
2284
|
}
|
|
2298
2285
|
|
|
2299
|
-
// written only when the effective state changes, and the tls object is
|
|
2300
|
-
// skipped while empty - same as the IMAP flags, a no-op save must not
|
|
2301
|
-
// modify the stored account
|
|
2302
|
-
if (request.payload.smtp_tls_ignoreCertErrors !== (smtpTls.rejectUnauthorized === false)) {
|
|
2303
|
-
smtpTls.rejectUnauthorized = !request.payload.smtp_tls_ignoreCertErrors;
|
|
2304
|
-
}
|
|
2305
|
-
|
|
2306
2286
|
updates.smtp = Object.assign(oldData.smtp || {}, {
|
|
2307
2287
|
host: request.payload.smtp_host,
|
|
2308
2288
|
port: request.payload.smtp_port,
|
|
@@ -2310,6 +2290,11 @@ function init(args) {
|
|
|
2310
2290
|
auth: smtpAuth
|
|
2311
2291
|
});
|
|
2312
2292
|
|
|
2293
|
+
// written only when the effective state changes, and the tls object is
|
|
2294
|
+
// skipped while empty - same as the IMAP flags, a no-op save must not
|
|
2295
|
+
// modify the stored account
|
|
2296
|
+
applySecurityForm(request.payload, 'smtp', oldData.smtp, updates.smtp, smtpTls);
|
|
2297
|
+
|
|
2313
2298
|
if (Object.keys(smtpTls).length) {
|
|
2314
2299
|
updates.smtp.tls = smtpTls;
|
|
2315
2300
|
}
|
|
@@ -2442,10 +2427,7 @@ function init(args) {
|
|
|
2442
2427
|
.example(993)
|
|
2443
2428
|
.description('Service port number'),
|
|
2444
2429
|
imap_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 993'),
|
|
2445
|
-
|
|
2446
|
-
.default(false)
|
|
2447
|
-
.example(false)
|
|
2448
|
-
.description('Allow connections to servers with invalid TLS certificates for this account'),
|
|
2430
|
+
...securityFormFields('imap'),
|
|
2449
2431
|
imap_disableIMAP4rev2: formBoolean().default(false).example(false).description('Do not use IMAP4rev2 even if the server supports it'),
|
|
2450
2432
|
imap_disabled: formBoolean()
|
|
2451
2433
|
.default(false)
|
|
@@ -2490,10 +2472,7 @@ function init(args) {
|
|
|
2490
2472
|
.example(465)
|
|
2491
2473
|
.description('Service port number'),
|
|
2492
2474
|
smtp_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465'),
|
|
2493
|
-
|
|
2494
|
-
.default(false)
|
|
2495
|
-
.example(false)
|
|
2496
|
-
.description('Allow connections to servers with invalid TLS certificates for this account'),
|
|
2475
|
+
...securityFormFields('smtp'),
|
|
2497
2476
|
|
|
2498
2477
|
customHeaders: Joi.string()
|
|
2499
2478
|
.allow('')
|