emailengine-app 2.79.8 → 2.80.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/.github/dependabot.yml +22 -0
- package/.github/workflows/test.yml +39 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +69 -0
- package/DOCKER_DEPLOYMENT.md +6 -7
- package/Dockerfile +35 -11
- package/config/default.toml +7 -2
- package/copy-static-files.sh +23 -5
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +43 -0
- package/lib/account/account-state.js +62 -0
- package/lib/account.js +60 -3
- package/lib/api-routes/account-routes.js +20 -0
- package/lib/api-routes/bull-board-routes.js +3 -2
- package/lib/api-routes/index.js +1 -1
- package/lib/api-routes/route-helpers.js +8 -0
- package/lib/api-routes/settings-routes.js +17 -2
- package/lib/auth-token.js +73 -2
- package/lib/autodetect-imap-settings.js +379 -69
- package/lib/cert-handler.js +62 -0
- package/lib/consts.js +58 -7
- package/lib/db.js +12 -0
- package/lib/egress-fetch.js +145 -0
- package/lib/email-client/base-client.js +234 -66
- package/lib/email-client/credential-errors.js +118 -0
- package/lib/email-client/gmail/gmail-api.js +2 -1
- package/lib/email-client/gmail-client.js +70 -64
- package/lib/email-client/imap/connection-errors.js +52 -0
- package/lib/email-client/imap/listing-diff.js +47 -6
- package/lib/email-client/imap/mailbox.js +457 -379
- package/lib/email-client/imap/subconnection.js +15 -11
- package/lib/email-client/imap/sync-operations.js +46 -59
- package/lib/email-client/imap-client.js +136 -95
- package/lib/email-client/message-builder.js +11 -11
- package/lib/email-client/outlook/graph-api.js +2 -1
- package/lib/email-client/outlook-client.js +219 -106
- package/lib/export.js +35 -2
- package/lib/handlebars-helpers.js +129 -0
- package/lib/imap-proxy-auth.js +96 -21
- package/lib/imapproxy/imap-core/README.md +1 -0
- package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
- package/lib/imapproxy/imap-server.js +56 -66
- package/lib/lua/h-del-if-equals.lua +39 -0
- package/lib/lua/h-set-if-equals.lua +39 -0
- package/lib/openapi/index.js +3 -0
- package/lib/outbox.js +28 -3
- package/lib/rate-limit.js +23 -4
- package/lib/routes-ui.js +4 -34
- package/lib/schemas.js +42 -3
- package/lib/security-headers.js +411 -0
- package/lib/sentry.js +36 -4
- package/lib/smtp-auth.js +86 -7
- package/lib/tls/context.js +376 -0
- package/lib/tls/der.js +223 -0
- package/lib/tls/provision.js +555 -0
- package/lib/tls/self-signed.js +282 -0
- package/lib/tls/status.js +431 -0
- package/lib/tls/store.js +666 -0
- package/lib/tools.js +337 -147
- package/lib/ui-routes/account-routes.js +47 -33
- package/lib/ui-routes/admin-config-routes.js +22 -1
- package/lib/ui-routes/auth-routes.js +16 -1
- package/lib/ui-routes/export-routes.js +4 -0
- package/lib/ui-routes/internals-routes.js +3 -5
- package/lib/ui-routes/mcp-consent-routes.js +7 -0
- package/lib/ui-routes/network-config-routes.js +58 -48
- package/lib/ui-routes/route-helpers.js +24 -8
- package/lib/ui-routes/smtp-test-routes.js +7 -0
- package/lib/ui-routes/tls-config-routes.js +581 -0
- package/lib/utils/mailbox-path.js +51 -0
- package/lib/utils/severity.js +31 -0
- package/lib/webhook-egress.js +5 -0
- package/package.json +21 -24
- package/sbom.json +1 -1
- package/server.js +53 -36
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +11 -0
- package/static/js/ace/css/ace.css +1462 -0
- package/static/js/ace/css/kuroir-1.png +0 -0
- package/static/js/ace/css/kuroir-2.png +0 -0
- package/static/js/ace/css/main-1.png +0 -0
- package/static/js/ace/css/main-10.svg +4 -0
- package/static/js/ace/css/main-11.svg +5 -0
- package/static/js/ace/css/main-12.svg +4 -0
- package/static/js/ace/css/main-13.png +0 -0
- package/static/js/ace/css/main-14.png +0 -0
- package/static/js/ace/css/main-15.png +0 -0
- package/static/js/ace/css/main-16.png +0 -0
- package/static/js/ace/css/main-17.png +0 -0
- package/static/js/ace/css/main-18.png +0 -0
- package/static/js/ace/css/main-19.png +0 -0
- package/static/js/ace/css/main-2.png +0 -0
- package/static/js/ace/css/main-20.png +0 -0
- package/static/js/ace/css/main-21.png +0 -0
- package/static/js/ace/css/main-22.png +0 -0
- package/static/js/ace/css/main-23.png +0 -0
- package/static/js/ace/css/main-24.png +0 -0
- package/static/js/ace/css/main-25.svg +1 -0
- package/static/js/ace/css/main-26.png +0 -0
- package/static/js/ace/css/main-3.png +0 -0
- package/static/js/ace/css/main-4.png +0 -0
- package/static/js/ace/css/main-5.svg +7 -0
- package/static/js/ace/css/main-6.svg +9 -0
- package/static/js/ace/css/main-7.svg +7 -0
- package/static/js/ace/css/main-8.svg +9 -0
- package/static/js/ace/css/main-9.svg +6 -0
- package/static/js/ace/css/theme/kuroir.css +78 -0
- package/static/js/ace/css/theme/tomorrow_night.css +128 -0
- package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
- package/static/js/ace/css/theme/xcode.css +106 -0
- package/static/js/ace/css/tomorrow_night-1.png +0 -0
- package/static/js/ace/css/tomorrow_night-2.png +0 -0
- package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
- package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
- package/static/js/ace/css/xcode-1.png +0 -0
- package/static/js/ace/css/xcode-2.png +0 -0
- package/static/js/app.js +34 -0
- package/static/js/ee-client.js +256 -102
- package/static/js/public.js +13 -2
- package/static/js/ui.js +40 -25
- package/static/licenses.html +393 -1282
- package/static/vendor/simplewebauthn/browser.min.js +2 -2
- package/translations/messages.pot +203 -157
- package/views/account/login-redirect.hbs +22 -0
- package/views/accounts/account.hbs +15 -37
- package/views/accounts/browse.hbs +3 -1
- package/views/accounts/edit.hbs +1 -1
- package/views/accounts/register/imap-server.hbs +1 -1
- package/views/config/ai.hbs +1 -1
- package/views/config/branding.hbs +2 -2
- package/views/config/document-store/chat.hbs +1 -1
- package/views/config/document-store/index.hbs +1 -1
- package/views/config/imap-proxy.hbs +1 -4
- package/views/config/license.hbs +1 -1
- package/views/config/mcp.hbs +1 -1
- package/views/config/network.hbs +14 -16
- package/views/config/oauth/app.hbs +2 -2
- package/views/config/service.hbs +1 -1
- package/views/config/smtp.hbs +1 -4
- package/views/config/tls-upload.hbs +81 -0
- package/views/config/tls.hbs +492 -0
- package/views/config/webhooks.hbs +2 -2
- package/views/error.hbs +4 -2
- package/views/internals/index.hbs +1 -1
- package/views/layout/app.hbs +3 -11
- package/views/mcp/authorize.hbs +1 -1
- package/views/partials/ace_assets.hbs +13 -0
- package/views/partials/add_account_modal.hbs +1 -1
- package/views/partials/address_list.hbs +4 -4
- package/views/partials/filter_editor_js.hbs +2 -2
- package/views/partials/gateway_js.hbs +1 -1
- package/views/partials/oauth_form.hbs +1 -1
- package/views/partials/public_theme_init.hbs +1 -1
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/template_form.hbs +2 -2
- package/views/partials/test_send.hbs +7 -4
- package/views/partials/theme_init.hbs +1 -1
- package/views/partials/tls_security_card.hbs +25 -53
- package/views/partials/ui/alert-banner.hbs +3 -2
- package/views/partials/ui/badge.hbs +6 -2
- package/views/partials/ui/btn.hbs +5 -2
- package/views/partials/ui/details.hbs +2 -2
- package/views/partials/webhooks_editor_functions.hbs +1 -1
- package/views/reference/redirect.hbs +1 -1
- package/views/templates/template.hbs +2 -2
- package/views/tokens/new.hbs +1 -1
- package/views/unsubscribe.hbs +1 -1
- package/views/webhooks/webhook.hbs +2 -2
- package/workers/api.js +131 -242
- package/workers/export.js +1 -5
- package/workers/imap-proxy.js +4 -1
- package/workers/imap.js +1 -3
- package/workers/smtp.js +59 -83
- package/workers/submit.js +6 -12
- package/workers/webhooks.js +6 -17
- package/static/front/EmailEngine_logo_horiz.png +0 -0
- package/static/front/EmailEngine_logo_vert.png +0 -0
- package/static/front/index.html +0 -57
- package/static/front/logo.png +0 -0
- package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
- package/views/partials/tls_security_js.hbs +0 -64
- package/views/partials/tls_security_modal.hbs +0 -22
package/workers/api.js
CHANGED
|
@@ -35,15 +35,13 @@ const {
|
|
|
35
35
|
hasEnvValue,
|
|
36
36
|
getBoolean,
|
|
37
37
|
loadTlsConfig,
|
|
38
|
-
maybeReloadHttpProxyAgent,
|
|
39
38
|
resolveOAuthErrorStatus,
|
|
40
39
|
constantTimeEqual,
|
|
41
40
|
verifyServiceSignature,
|
|
42
41
|
claimFormNonce,
|
|
43
42
|
releaseFormNonce,
|
|
44
43
|
setAdminSession,
|
|
45
|
-
isEndedSession
|
|
46
|
-
reloadTlsServers
|
|
44
|
+
isEndedSession
|
|
47
45
|
} = require('../lib/tools');
|
|
48
46
|
const { matchIp, resolveClientIp, detectAutomatedRequest } = require('../lib/utils/network');
|
|
49
47
|
|
|
@@ -94,16 +92,16 @@ const specOptions = require('../lib/swagger-options');
|
|
|
94
92
|
const { registerOpenApiRoute } = require('../lib/openapi');
|
|
95
93
|
const { getModel: getApiReferenceModel, clearServiceUrlCache } = require('../lib/api-reference');
|
|
96
94
|
|
|
97
|
-
const {
|
|
98
|
-
const {
|
|
99
|
-
const
|
|
95
|
+
const { createCertHandler } = require('../lib/cert-handler');
|
|
96
|
+
const { createTlsContext, applyTlsContext, apiTlsConfig } = require('../lib/tls/context');
|
|
97
|
+
const { reconcileCertificates, requestProvisioning } = require('../lib/tls/provision');
|
|
98
|
+
const { buildCertificateStatus } = require('../lib/tls/status');
|
|
100
99
|
|
|
101
100
|
const consts = require('../lib/consts');
|
|
102
101
|
const {
|
|
103
102
|
TRACK_OPEN_NOTIFY,
|
|
104
103
|
TRACK_CLICK_NOTIFY,
|
|
105
104
|
REDIS_PREFIX,
|
|
106
|
-
BLOCK_TLS_RENEW,
|
|
107
105
|
TLS_RENEW_CHECK_INTERVAL,
|
|
108
106
|
DEFAULT_CORS_MAX_AGE,
|
|
109
107
|
LIST_UNSUBSCRIBE_NOTIFY,
|
|
@@ -117,6 +115,8 @@ const {
|
|
|
117
115
|
|
|
118
116
|
const registerApiRoutes = require('../lib/api-routes');
|
|
119
117
|
const bullBoardRoutes = require('../lib/api-routes/bull-board-routes');
|
|
118
|
+
const { securityHeadersExt, attachSecurityContext, isAdminPath, isMachineRoute, isSecureOrigin, CSP_MODES } = require('../lib/security-headers');
|
|
119
|
+
const { registerHandlebarsHelpers } = require('../lib/handlebars-helpers');
|
|
120
120
|
|
|
121
121
|
const {
|
|
122
122
|
imapSchema,
|
|
@@ -198,11 +198,21 @@ const API_PORT =
|
|
|
198
198
|
const API_HOST = readEnvValue('EENGINE_HOST') || config.api.host;
|
|
199
199
|
|
|
200
200
|
// Either an object (TLS enabled) or `false` (TLS disabled)
|
|
201
|
-
const API_TLS =
|
|
201
|
+
const API_TLS = apiTlsConfig();
|
|
202
202
|
|
|
203
203
|
// Merge TLS settings from config params and environment
|
|
204
204
|
loadTlsConfig(API_TLS, 'EENGINE_API_TLS_');
|
|
205
205
|
|
|
206
|
+
// How the Content-Security-Policy is delivered: enforce (default), report-only, or off.
|
|
207
|
+
// An unknown value falls back to enforce, and says so once
|
|
208
|
+
const CSP_MODE_CONFIGURED = String(hasEnvValue('EENGINE_CSP_MODE') ? readEnvValue('EENGINE_CSP_MODE') : config.api.cspMode || '')
|
|
209
|
+
.trim()
|
|
210
|
+
.toLowerCase();
|
|
211
|
+
const CSP_MODE = CSP_MODES.includes(CSP_MODE_CONFIGURED) ? CSP_MODE_CONFIGURED : 'enforce';
|
|
212
|
+
if (CSP_MODE_CONFIGURED && CSP_MODE_CONFIGURED !== CSP_MODE) {
|
|
213
|
+
logger.warn({ msg: 'Unknown Content-Security-Policy mode, enforcing the policy', configured: CSP_MODE_CONFIGURED, cspMode: CSP_MODE });
|
|
214
|
+
}
|
|
215
|
+
|
|
206
216
|
// Per-worker thread metadata. With multiple API workers (EENGINE_WORKERS_API > 1) the
|
|
207
217
|
// main thread assigns each one an index and whether to bind with SO_REUSEPORT. Only
|
|
208
218
|
// worker 0 runs singleton maintenance tasks (e.g. TLS certificate renewal).
|
|
@@ -366,6 +376,12 @@ async function onCommand(command) {
|
|
|
366
376
|
switch (command.cmd) {
|
|
367
377
|
case 'resource-usage':
|
|
368
378
|
return threadStats.usage();
|
|
379
|
+
|
|
380
|
+
case 'apiReloadCertificates':
|
|
381
|
+
// Every API worker gets this, not just the one that ordered the certificate: the
|
|
382
|
+
// reconciler is a singleton but the HTTPS listeners are not, and a sibling worker that
|
|
383
|
+
// kept its old context would go on serving the certificate that was just replaced.
|
|
384
|
+
return refreshApiTls ? await refreshApiTls() : { updated: false };
|
|
369
385
|
default:
|
|
370
386
|
logger.debug({ msg: 'Unhandled command', command });
|
|
371
387
|
return 999;
|
|
@@ -408,6 +424,10 @@ function publishChangeEvent(data) {
|
|
|
408
424
|
// strategy that does not exist yet or race the boot-time server.auth.default() call
|
|
409
425
|
let sessionAuthServer = null;
|
|
410
426
|
|
|
427
|
+
// Installs a renewed certificate on this worker's own HTTPS listener. Published by init() when the
|
|
428
|
+
// API is serving TLS, and called through the apiReloadCertificates command.
|
|
429
|
+
let refreshApiTls = null;
|
|
430
|
+
|
|
411
431
|
parentPort.on('message', message => {
|
|
412
432
|
if (message && message.cmd === 'resp' && message.mid && callQueue.has(message.mid)) {
|
|
413
433
|
let { resolve, reject, timer } = callQueue.get(message.mid);
|
|
@@ -460,9 +480,7 @@ parentPort.on('message', message => {
|
|
|
460
480
|
}
|
|
461
481
|
|
|
462
482
|
if (message && message.cmd === 'settings') {
|
|
463
|
-
//
|
|
464
|
-
maybeReloadHttpProxyAgent(message.data);
|
|
465
|
-
// ...and the API reference's memoized serviceUrl, which its code samples embed
|
|
483
|
+
// the API reference memoizes serviceUrl, which its code samples embed
|
|
466
484
|
clearServiceUrlCache();
|
|
467
485
|
|
|
468
486
|
// The first admin password is saved by whichever API worker served the form, and only
|
|
@@ -483,98 +501,7 @@ const init = async () => {
|
|
|
483
501
|
|
|
484
502
|
gt.setLocale((await settings.get('locale')) || 'en');
|
|
485
503
|
|
|
486
|
-
handlebars
|
|
487
|
-
let params = args.slice(1, args.length - 1);
|
|
488
|
-
|
|
489
|
-
let locale = params.shift();
|
|
490
|
-
|
|
491
|
-
let localGt = locale ? gt.useLocale(locale) : gt;
|
|
492
|
-
|
|
493
|
-
let translated = localGt.gettext(args[0]);
|
|
494
|
-
if (params.length) {
|
|
495
|
-
translated = util.format(translated, ...params);
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
return new handlebars.SafeString(translated);
|
|
499
|
-
});
|
|
500
|
-
|
|
501
|
-
// HTML-escape a value for safe interpolation into an otherwise-unescaped context - e.g. a
|
|
502
|
-
// dynamic `%s` argument to the SafeString-returning `_` helper. Returns a plain string so
|
|
503
|
-
// the surrounding markup stays live while the value itself is entity-escaped.
|
|
504
|
-
handlebars.registerHelper('escapeHtml', value => handlebars.escapeExpression(value));
|
|
505
|
-
|
|
506
|
-
// Translate Bootstrap-era color names emitted by server code (flash types,
|
|
507
|
-
// systemAlerts levels) into the FlyonUI color vocabulary used by the admin
|
|
508
|
-
// theme, so templates interpolate a single closed set of class suffixes
|
|
509
|
-
// (which the stylesheet safelists). Single translation point - producers
|
|
510
|
-
// keep using "danger" etc.
|
|
511
|
-
handlebars.registerHelper('eeColor', value => (value === 'danger' ? 'error' : value || 'neutral'));
|
|
512
|
-
|
|
513
|
-
// Percent-encode a value for interpolation into a URL path segment. Handlebars escapes for
|
|
514
|
-
// HTML, which leaves "#", "/", "?" and "%" untouched - and an account ID is free text, so
|
|
515
|
-
// href="/admin/accounts/{{account}}" resolves somewhere else entirely for an ID carrying one.
|
|
516
|
-
handlebars.registerHelper('urlpart', value => encodeURIComponent(value === null || value === undefined ? '' : value));
|
|
517
|
-
|
|
518
|
-
// Join string fragments in subexpressions, e.g. building composed partial
|
|
519
|
-
// hash values: text=(concat "Up to " (formatInteger n locale) " lines")
|
|
520
|
-
handlebars.registerHelper('concat', (...args) => args.slice(0, -1).join(''));
|
|
521
|
-
|
|
522
|
-
// Ternary for subexpressions: placeholder=(when hasPass "set..." "")
|
|
523
|
-
handlebars.registerHelper('when', (cond, truthyValue, falsyValue) => (cond ? truthyValue : typeof falsyValue === 'string' ? falsyValue : ''));
|
|
524
|
-
|
|
525
|
-
handlebars.registerHelper('isodate', time => new Date(Number(time)).toISOString());
|
|
526
|
-
|
|
527
|
-
handlebars.registerHelper('ngettext', (msgid, plural, count) => util.format(gt.ngettext(msgid, plural, count), count));
|
|
528
|
-
|
|
529
|
-
handlebars.registerHelper('equals', function (compareVal, baseVal, options) {
|
|
530
|
-
if (baseVal === compareVal) {
|
|
531
|
-
return options.fn(this);
|
|
532
|
-
}
|
|
533
|
-
return options.inverse(this);
|
|
534
|
-
});
|
|
535
|
-
|
|
536
|
-
handlebars.registerHelper('inc', (nr, inc) => Number(nr) + Number(inc));
|
|
537
|
-
|
|
538
|
-
handlebars.registerHelper('json', payload => {
|
|
539
|
-
let res;
|
|
540
|
-
try {
|
|
541
|
-
res = typeof payload === 'undefined' ? 'undefined' : JSON.stringify(payload, false, 2);
|
|
542
|
-
} catch (err) {
|
|
543
|
-
res = util.inspect(payload, false, 4, false);
|
|
544
|
-
}
|
|
545
|
-
// SECURITY: return a plain string (NOT a SafeString) so Handlebars HTML-escapes the
|
|
546
|
-
// output. `payload` can carry attacker-controlled data (e.g. inbound email fields in
|
|
547
|
-
// webhook / pre-processing error logs); wrapping it in a SafeString allowed a stored
|
|
548
|
-
// XSS via a </textarea> breakout in the error-log views (security review H1). In the
|
|
549
|
-
// <textarea> render contexts this is display-identical (the browser decodes entities).
|
|
550
|
-
return res;
|
|
551
|
-
});
|
|
552
|
-
|
|
553
|
-
handlebars.registerHelper('lastVal', (value, separator) => {
|
|
554
|
-
separator = separator || '/';
|
|
555
|
-
|
|
556
|
-
let res = (value || '').toString().split(separator).pop();
|
|
557
|
-
|
|
558
|
-
return new handlebars.SafeString(res);
|
|
559
|
-
});
|
|
560
|
-
|
|
561
|
-
handlebars.registerHelper('formatInteger', (intVal, locale) => {
|
|
562
|
-
if (isNaN(intVal)) {
|
|
563
|
-
// ignore non-numbers
|
|
564
|
-
return intVal;
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
locale = (locale || 'en_US').replace(/_/g, '-');
|
|
568
|
-
|
|
569
|
-
let formatter;
|
|
570
|
-
try {
|
|
571
|
-
formatter = new Intl.NumberFormat(locale, {});
|
|
572
|
-
} catch (err) {
|
|
573
|
-
formatter = new Intl.NumberFormat('en-US', {});
|
|
574
|
-
}
|
|
575
|
-
|
|
576
|
-
return formatter.format(intVal);
|
|
577
|
-
});
|
|
504
|
+
registerHandlebarsHelpers(handlebars, { gt });
|
|
578
505
|
|
|
579
506
|
// Base Hapi options shared by both the default and SO_REUSEPORT binding paths
|
|
580
507
|
const serverOptions = {
|
|
@@ -604,6 +531,24 @@ const init = async () => {
|
|
|
604
531
|
}
|
|
605
532
|
};
|
|
606
533
|
|
|
534
|
+
let certHandler = createCertHandler(logger);
|
|
535
|
+
|
|
536
|
+
// The admin UI and REST API over HTTPS. EENGINE_API_TLS_* and [api.tls] supply the certificate
|
|
537
|
+
// when the operator has one; everything they leave out comes from the same sources every other
|
|
538
|
+
// listener uses, so an instance that already holds a Let's Encrypt certificate for its own
|
|
539
|
+
// service domain no longer needs a second, external pipeline to serve it here.
|
|
540
|
+
let apiTlsContext = null;
|
|
541
|
+
if (API_TLS) {
|
|
542
|
+
apiTlsContext = await createTlsContext({
|
|
543
|
+
certs: certHandler,
|
|
544
|
+
logger,
|
|
545
|
+
// The operator's material and handshake settings are snapshotted inside, at entry,
|
|
546
|
+
// before the resolved options are merged back into this same object below
|
|
547
|
+
listenerOptions: API_TLS
|
|
548
|
+
});
|
|
549
|
+
Object.assign(API_TLS, apiTlsContext.options);
|
|
550
|
+
}
|
|
551
|
+
|
|
607
552
|
// With multiple API workers we provide our own listener and bind it ourselves with
|
|
608
553
|
// SO_REUSEPORT so the kernel load-balances connections. Hapi forbids port/host when
|
|
609
554
|
// autoListen is false and needs a truthy `tls` flag to treat a provided HTTPS
|
|
@@ -624,105 +569,58 @@ const init = async () => {
|
|
|
624
569
|
|
|
625
570
|
const server = Hapi.server(serverOptions);
|
|
626
571
|
|
|
572
|
+
if (apiTlsContext && typeof server.listener.setSecureContext === 'function') {
|
|
573
|
+
// Connections already established keep the context they negotiated with; the next handshake
|
|
574
|
+
// gets the new one, which is why this does not restart anything.
|
|
575
|
+
refreshApiTls = async () =>
|
|
576
|
+
await applyTlsContext({
|
|
577
|
+
context: apiTlsContext,
|
|
578
|
+
// setSecureContext() replaces the context rather than merging into it: anything
|
|
579
|
+
// left out reverts to Node's default, so a reload that sent only the certificate
|
|
580
|
+
// and key dropped the operator's ca, ciphers and version bounds at the first
|
|
581
|
+
// renewal. SNICallback is a listener option and is not one of them.
|
|
582
|
+
apply: options => {
|
|
583
|
+
const secureContext = Object.assign({}, options);
|
|
584
|
+
delete secureContext.SNICallback;
|
|
585
|
+
server.listener.setSecureContext(secureContext);
|
|
586
|
+
},
|
|
587
|
+
logger
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
|
|
627
591
|
let assertPreconditionResult;
|
|
628
592
|
server.decorate('toolkit', 'getESClient', async (...args) => await getESClient(...args));
|
|
629
593
|
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
let hostname = (parsedUrl.hostname || '').toString().toLowerCase().trim();
|
|
641
|
-
if (!hostname || net.isIP(hostname) || ['localhost'].includes(hostname) || /(\.local|\.lan)$/i.test(hostname)) {
|
|
642
|
-
// empty string, not false: the value is interpolated into
|
|
643
|
-
// templates, where a boolean would render as the text "false"
|
|
644
|
-
return '';
|
|
645
|
-
}
|
|
646
|
-
return hostname;
|
|
594
|
+
// A read-only view of the certificate store for routes. Ordering a certificate is the
|
|
595
|
+
// reconciler's job - it owns the state a page follows, the retry pacing and the listener
|
|
596
|
+
// reload - and the difference between reading and ordering is one argument
|
|
597
|
+
// (`getCertificate(host, false)`), which is not a difference a route should be able to make by
|
|
598
|
+
// accident. Routes that need one ask through requestCertificates() below.
|
|
599
|
+
const readOnlyCerts = {
|
|
600
|
+
getCertificate: async hostname => await certHandler.getCertificate(hostname, true),
|
|
601
|
+
deleteCertificateData: async hostname => await certHandler.deleteCertificateData(hostname),
|
|
602
|
+
routeHandler: async (...args) => await certHandler.routeHandler(...args)
|
|
647
603
|
};
|
|
648
604
|
|
|
649
|
-
|
|
650
|
-
redis,
|
|
651
|
-
namespace: `${REDIS_PREFIX}`,
|
|
652
|
-
|
|
653
|
-
acme: {
|
|
654
|
-
environment: 'emailengine',
|
|
655
|
-
directoryUrl: 'https://acme-v02.api.letsencrypt.org/directory'
|
|
656
|
-
//directoryUrl: 'https://acme-staging-v02.api.letsencrypt.org/directory',
|
|
657
|
-
},
|
|
658
|
-
|
|
659
|
-
logger: logger.child({ sub: 'acme' }),
|
|
660
|
-
|
|
661
|
-
encryptFn: async value => {
|
|
662
|
-
const encryptSecret = await getSecret();
|
|
663
|
-
return encrypt(value, encryptSecret);
|
|
664
|
-
},
|
|
665
|
-
|
|
666
|
-
decryptFn: async value => {
|
|
667
|
-
const encryptSecret = await getSecret();
|
|
668
|
-
return decrypt(value, encryptSecret);
|
|
669
|
-
}
|
|
670
|
-
});
|
|
605
|
+
server.decorate('toolkit', 'certs', readOnlyCerts);
|
|
671
606
|
|
|
672
|
-
server.decorate(
|
|
673
|
-
|
|
607
|
+
server.decorate(
|
|
608
|
+
'toolkit',
|
|
609
|
+
'requestCertificates',
|
|
610
|
+
async (hostnames, requestLogger) => await requestProvisioning({ certs: certHandler, logger: requestLogger || logger, call, hostnames })
|
|
611
|
+
);
|
|
674
612
|
|
|
675
613
|
server.decorate('toolkit', 'checkRateLimit', checkRateLimit);
|
|
676
614
|
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
615
|
+
// The certificate model the admin UI renders. Reading it never provisions anything: ordering a
|
|
616
|
+
// certificate is the reconciler's job, and a page render that could start an ACME order was
|
|
617
|
+
// exactly how a checkbox came to hold an HTTP request open for the length of one.
|
|
618
|
+
server.decorate('toolkit', 'tlsStatus', async () => await buildCertificateStatus({ certs: readOnlyCerts }));
|
|
680
619
|
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
if (!certificateData) {
|
|
686
|
-
certificateData = {
|
|
687
|
-
domain: hostname,
|
|
688
|
-
status: 'self_signed',
|
|
689
|
-
label: { type: 'warning', text: 'Self-signed', title: 'Using a self-signed certificate' }
|
|
690
|
-
};
|
|
691
|
-
} else if (certificateData.status !== 'valid') {
|
|
692
|
-
switch (certificateData.status) {
|
|
693
|
-
case 'pending':
|
|
694
|
-
certificateData.label = { type: 'info', text: 'Provisioning...', title: 'Currently provisioning a certificate' };
|
|
695
|
-
break;
|
|
696
|
-
case 'failed':
|
|
697
|
-
certificateData.label = {
|
|
698
|
-
type: 'error',
|
|
699
|
-
text: 'Failed',
|
|
700
|
-
title: (certificateData.lastError && certificateData.lastError.err) || 'Failed to generate a certificate'
|
|
701
|
-
};
|
|
702
|
-
break;
|
|
703
|
-
}
|
|
704
|
-
} else if (certificateData.validFrom > new Date()) {
|
|
705
|
-
certificateData.label = {
|
|
706
|
-
type: 'warning',
|
|
707
|
-
text: 'Future certificate',
|
|
708
|
-
title: 'Certificate is not yet valid'
|
|
709
|
-
};
|
|
710
|
-
} else if (certificateData.validTo < new Date()) {
|
|
711
|
-
certificateData.label = {
|
|
712
|
-
type: 'warning',
|
|
713
|
-
text: 'Expired certificate',
|
|
714
|
-
title: (certificateData.lastError && certificateData.lastError.err) || 'Certificate has been expired'
|
|
715
|
-
};
|
|
716
|
-
} else {
|
|
717
|
-
certificateData.label = {
|
|
718
|
-
type: 'success',
|
|
719
|
-
text: 'Valid certificate',
|
|
720
|
-
title: certificateData.fingerprint
|
|
721
|
-
};
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
return certificateData;
|
|
725
|
-
});
|
|
620
|
+
server.decorate('toolkit', 'apiTlsInfo', () => ({
|
|
621
|
+
enabled: !!API_TLS,
|
|
622
|
+
active: apiTlsContext ? apiTlsContext.active : null
|
|
623
|
+
}));
|
|
726
624
|
|
|
727
625
|
server.ext('onPreAuth', async (request, h) => {
|
|
728
626
|
const tags = (request.route && request.route.settings && request.route.settings.tags) || [];
|
|
@@ -805,7 +703,11 @@ const init = async () => {
|
|
|
805
703
|
|
|
806
704
|
// Both settings are needed on every request and neither depends on the other, so they are
|
|
807
705
|
// read in a single HMGET rather than two serialized round trips
|
|
808
|
-
let { enableApiProxy, disableTokens } = await settings.getMulti('enableApiProxy', 'disableTokens');
|
|
706
|
+
let { enableApiProxy, disableTokens, serviceUrl } = await settings.getMulti('enableApiProxy', 'disableTokens', 'serviceUrl');
|
|
707
|
+
|
|
708
|
+
// Before anything can render a view (the allowlist refusal below does), so the nonce
|
|
709
|
+
// the template stamps on its scripts is the one the response header carries
|
|
710
|
+
attachSecurityContext(request, { secureOrigin: isSecureOrigin(serviceUrl) });
|
|
809
711
|
|
|
810
712
|
// check if client IP is resolved from X-Forwarded-For or not
|
|
811
713
|
request.app.ip = resolveClientIp({
|
|
@@ -839,7 +741,7 @@ const init = async () => {
|
|
|
839
741
|
request.flash = async message => await flash(redis, request, message);
|
|
840
742
|
|
|
841
743
|
if (ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length) {
|
|
842
|
-
if (request.path
|
|
744
|
+
if (isAdminPath(request.path) && !matchIp(request.app.ip, ADMIN_ACCESS_ADDRESSES)) {
|
|
843
745
|
logger.info({
|
|
844
746
|
msg: 'Blocked access from unlisted IP address',
|
|
845
747
|
remoteAddress: request.app.ip,
|
|
@@ -1258,22 +1160,17 @@ const init = async () => {
|
|
|
1258
1160
|
await server.register(Cookie);
|
|
1259
1161
|
await server.register(Bell);
|
|
1260
1162
|
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
let serviceUrl = await settings.get('serviceUrl');
|
|
1264
|
-
if (serviceUrl) {
|
|
1265
|
-
let parsedUrl = new URL(serviceUrl);
|
|
1266
|
-
secureCookie = parsedUrl.protocol === 'https:';
|
|
1267
|
-
}
|
|
1268
|
-
} catch (err) {
|
|
1269
|
-
// skip
|
|
1270
|
-
}
|
|
1163
|
+
// the signal HSTS keys on too, so the cookies and the header agree on what "https" means
|
|
1164
|
+
let secureCookie = isSecureOrigin(await settings.get('serviceUrl'));
|
|
1271
1165
|
|
|
1272
1166
|
server.state('locale', {
|
|
1273
1167
|
ttl: null,
|
|
1274
1168
|
encoding: 'base64json',
|
|
1275
1169
|
clearInvalid: true,
|
|
1276
|
-
path: '/'
|
|
1170
|
+
path: '/',
|
|
1171
|
+
// Same signal as the session and CSRF cookies. hapi's default is Secure, which a browser
|
|
1172
|
+
// drops on a plain-http instance, so the chosen locale never stuck there
|
|
1173
|
+
isSecure: secureCookie
|
|
1277
1174
|
});
|
|
1278
1175
|
|
|
1279
1176
|
// The version an SSO login stamps into its session, so the checks that end a session later can
|
|
@@ -2940,7 +2837,7 @@ const init = async () => {
|
|
|
2940
2837
|
skip: (request /*, h*/) => {
|
|
2941
2838
|
let tags = (request.route && request.route.settings && request.route.settings.tags) || [];
|
|
2942
2839
|
|
|
2943
|
-
if (
|
|
2840
|
+
if (isMachineRoute(tags)) {
|
|
2944
2841
|
return true;
|
|
2945
2842
|
}
|
|
2946
2843
|
|
|
@@ -3164,6 +3061,8 @@ const init = async () => {
|
|
|
3164
3061
|
const isAuthenticated = !!(request.auth && request.auth.isAuthenticated);
|
|
3165
3062
|
|
|
3166
3063
|
return {
|
|
3064
|
+
// the per-request CSP nonce every inline <script> carries (lib/security-headers.js)
|
|
3065
|
+
cspNonce: request.app.cspNonce,
|
|
3167
3066
|
pageBrandName: pageBrandName || 'EmailEngine',
|
|
3168
3067
|
values: request.payload || {},
|
|
3169
3068
|
errors: (request.error && request.error.details) || {},
|
|
@@ -3249,7 +3148,9 @@ const init = async () => {
|
|
|
3249
3148
|
const routeTags = (request.route && request.route.settings && request.route.settings.tags) || [];
|
|
3250
3149
|
|
|
3251
3150
|
// `external` covers the MCP endpoint and its OAuth routes: machine-facing surfaces whose
|
|
3252
|
-
// clients expect JSON errors, never the admin HTML error page
|
|
3151
|
+
// clients expect JSON errors, never the admin HTML error page. Narrower than
|
|
3152
|
+
// isMachineRoute() on purpose: that one also covers `static`, and a browser following a
|
|
3153
|
+
// link to a missing asset is better served the themed error page than a JSON body
|
|
3253
3154
|
const wantsJsonError = routeTags.includes('api') || routeTags.includes('external');
|
|
3254
3155
|
|
|
3255
3156
|
if (request.errorInfo && wantsJsonError) {
|
|
@@ -3281,6 +3182,10 @@ const init = async () => {
|
|
|
3281
3182
|
|
|
3282
3183
|
server.ext('onPreResponse', preResponse);
|
|
3283
3184
|
|
|
3185
|
+
// After preResponse on purpose: it replaces an error response with the rendered error page
|
|
3186
|
+
// or a JSON body, and the headers have to land on whatever is actually sent
|
|
3187
|
+
server.ext('onPreResponse', securityHeadersExt({ cspMode: CSP_MODE }));
|
|
3188
|
+
|
|
3284
3189
|
server.ext('onPostAuth', async (request, h) => {
|
|
3285
3190
|
if (request.requireTotp) {
|
|
3286
3191
|
// The password step is done and only the second factor is missing, so the session
|
|
@@ -3322,7 +3227,8 @@ const init = async () => {
|
|
|
3322
3227
|
return h.response(renderedMetrics).type('text/plain');
|
|
3323
3228
|
},
|
|
3324
3229
|
options: {
|
|
3325
|
-
|
|
3230
|
+
// external: a Prometheus scraper wants JSON errors and no CSRF or page policy
|
|
3231
|
+
tags: ['scope:metrics', 'external'],
|
|
3326
3232
|
auth: {
|
|
3327
3233
|
strategy: 'api-token',
|
|
3328
3234
|
mode: 'required'
|
|
@@ -3406,12 +3312,21 @@ const init = async () => {
|
|
|
3406
3312
|
});
|
|
3407
3313
|
});
|
|
3408
3314
|
|
|
3409
|
-
//
|
|
3315
|
+
// Keep the configured hostnames supplied with certificates.
|
|
3316
|
+
//
|
|
3317
|
+
// This used to be a renewal timer and nothing else: it read the certificate for the service
|
|
3318
|
+
// domain and, if one existed, asked whether it was due for replacement. A hostname with no
|
|
3319
|
+
// certificate at all was therefore never provisioned by it - not on a fresh install, not after
|
|
3320
|
+
// a flushed Redis, not after a restored backup - and the only way to get a first certificate
|
|
3321
|
+
// was a checkbox in the admin UI that ordered one in the foreground. An instance whose record
|
|
3322
|
+
// was lost stayed down until somebody noticed and clicked it twice.
|
|
3323
|
+
//
|
|
3324
|
+
// The reconciler in lib/tls/provision.js owns the whole decision now, including the renewal
|
|
3325
|
+
// one, and it is the only thing that orders certificates. The admin UI's button asks it to run
|
|
3326
|
+
// immediately rather than doing the work itself. A first order still needs a listener with TLS
|
|
3327
|
+
// switched on, which is what the checkbox used to be; see listenersServeTls() there.
|
|
3410
3328
|
setInterval(() => {
|
|
3411
3329
|
async function handler() {
|
|
3412
|
-
let serviceDomain = await getServiceDomain();
|
|
3413
|
-
let currentCert = await certHandler.getCertificate(serviceDomain, true);
|
|
3414
|
-
|
|
3415
3330
|
try {
|
|
3416
3331
|
await runPrechecks(redis);
|
|
3417
3332
|
assertPreconditionResult = false;
|
|
@@ -3419,37 +3334,11 @@ const init = async () => {
|
|
|
3419
3334
|
assertPreconditionResult = Boom.boomify(err);
|
|
3420
3335
|
}
|
|
3421
3336
|
|
|
3422
|
-
|
|
3423
|
-
|
|
3424
|
-
// Date.now() - RENEW_TLS_AFTER, which is the expiry date thirty days in the past: it
|
|
3425
|
-
// read as "renew with thirty days left" but meant "renew thirty days after it died",
|
|
3426
|
-
// so the automatic path only ever ran once the certificate had been broken for a
|
|
3427
|
-
// month. Let's Encrypt is on the way from 90 day certificates to 45, which would have
|
|
3428
|
-
// left a service unreachable for two thirds of every certificate's life.
|
|
3429
|
-
if (
|
|
3430
|
-
IS_PRIMARY_API_WORKER &&
|
|
3431
|
-
currentCert &&
|
|
3432
|
-
isRenewalDue(currentCert) &&
|
|
3433
|
-
(!currentCert.lastCheck || currentCert.lastCheck < new Date(Date.now() - BLOCK_TLS_RENEW))
|
|
3434
|
-
) {
|
|
3435
|
-
try {
|
|
3436
|
-
let renewedCert = await certHandler.acquireCert(serviceDomain);
|
|
3437
|
-
|
|
3438
|
-
// Only when the certificate actually changed, so a renewal that was skipped
|
|
3439
|
-
// or failed does not restart both servers for nothing.
|
|
3440
|
-
if (renewedCert && renewedCert.fingerprint && renewedCert.fingerprint !== currentCert.fingerprint) {
|
|
3441
|
-
await reloadTlsServers(call, logger, { serviceDomain });
|
|
3442
|
-
}
|
|
3443
|
-
} catch (err) {
|
|
3444
|
-
logger.error({ msg: 'Failed to acquire TLS certificate', serviceDomain, err });
|
|
3445
|
-
} finally {
|
|
3446
|
-
try {
|
|
3447
|
-
await certHandler.setCertificateData(serviceDomain, { lastCheck: new Date() });
|
|
3448
|
-
} catch (err) {
|
|
3449
|
-
logger.error({ msg: 'Failed to set certificate data', serviceDomain, err });
|
|
3450
|
-
}
|
|
3451
|
-
}
|
|
3337
|
+
if (!IS_PRIMARY_API_WORKER) {
|
|
3338
|
+
return;
|
|
3452
3339
|
}
|
|
3340
|
+
|
|
3341
|
+
await reconcileCertificates({ certs: certHandler, logger, call });
|
|
3453
3342
|
}
|
|
3454
3343
|
|
|
3455
3344
|
handler().catch(err => logger.error({ msg: 'Failed to run certificate handler', err }));
|
package/workers/export.js
CHANGED
|
@@ -17,7 +17,7 @@ const {
|
|
|
17
17
|
DEFAULT_EXPORT_MAX_MESSAGES,
|
|
18
18
|
DEFAULT_EXPORT_MAX_SIZE
|
|
19
19
|
} = require('../lib/consts');
|
|
20
|
-
const { getDuration, readEnvValue, threadStats
|
|
20
|
+
const { getDuration, readEnvValue, threadStats } = require('../lib/tools');
|
|
21
21
|
const { webhooks: Webhooks } = require('../lib/webhooks');
|
|
22
22
|
const settings = require('../lib/settings');
|
|
23
23
|
const {
|
|
@@ -975,10 +975,6 @@ parentPort.on('message', message => {
|
|
|
975
975
|
.then(response => parentPort.postMessage({ cmd: 'resp', mid: message.mid, response }))
|
|
976
976
|
.catch(err => parentPort.postMessage({ cmd: 'resp', mid: message.mid, error: err.message, code: err.code, statusCode: err.statusCode }));
|
|
977
977
|
}
|
|
978
|
-
|
|
979
|
-
if (message && message.cmd === 'settings') {
|
|
980
|
-
maybeReloadHttpProxyAgent(message.data);
|
|
981
|
-
}
|
|
982
978
|
});
|
|
983
979
|
|
|
984
980
|
logger.info({ msg: 'Started Export worker thread', version: packageData.version });
|
package/workers/imap-proxy.js
CHANGED
|
@@ -7,7 +7,7 @@ const logger = require('../lib/logger');
|
|
|
7
7
|
|
|
8
8
|
const { threadStats } = require('../lib/tools');
|
|
9
9
|
|
|
10
|
-
const { run } = require('../lib/imapproxy/imap-server');
|
|
10
|
+
const { run, reloadCertificates } = require('../lib/imapproxy/imap-server');
|
|
11
11
|
|
|
12
12
|
const { initSentry } = require('../lib/sentry');
|
|
13
13
|
initSentry('imapProxy');
|
|
@@ -16,6 +16,9 @@ async function onCommand(command) {
|
|
|
16
16
|
switch (command.cmd) {
|
|
17
17
|
case 'resource-usage':
|
|
18
18
|
return threadStats.usage();
|
|
19
|
+
|
|
20
|
+
case 'imapProxyReloadCertificates':
|
|
21
|
+
return await reloadCertificates();
|
|
19
22
|
default:
|
|
20
23
|
logger.debug({ msg: 'Unhandled command', command });
|
|
21
24
|
return 999;
|
package/workers/imap.js
CHANGED
|
@@ -7,7 +7,7 @@ const logger = require('../lib/logger');
|
|
|
7
7
|
|
|
8
8
|
const { REDIS_PREFIX } = require('../lib/consts');
|
|
9
9
|
|
|
10
|
-
const { getDuration, getBoolean, emitChangeEvent, readEnvValue, hasEnvValue, threadStats
|
|
10
|
+
const { getDuration, getBoolean, emitChangeEvent, readEnvValue, hasEnvValue, threadStats } = require('../lib/tools');
|
|
11
11
|
|
|
12
12
|
const { initSentry } = require('../lib/sentry');
|
|
13
13
|
initSentry('imap');
|
|
@@ -874,8 +874,6 @@ class ConnectionHandler {
|
|
|
874
874
|
|
|
875
875
|
switch (message.cmd) {
|
|
876
876
|
case 'settings':
|
|
877
|
-
maybeReloadHttpProxyAgent(message.data);
|
|
878
|
-
|
|
879
877
|
if (message.data && message.data.logs) {
|
|
880
878
|
for (let [account, accountObject] of this.accounts) {
|
|
881
879
|
// update log handling
|