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.
Files changed (182) hide show
  1. package/.github/dependabot.yml +22 -0
  2. package/.github/workflows/test.yml +39 -0
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +69 -0
  5. package/DOCKER_DEPLOYMENT.md +6 -7
  6. package/Dockerfile +35 -11
  7. package/config/default.toml +7 -2
  8. package/copy-static-files.sh +23 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +43 -0
  11. package/lib/account/account-state.js +62 -0
  12. package/lib/account.js +60 -3
  13. package/lib/api-routes/account-routes.js +20 -0
  14. package/lib/api-routes/bull-board-routes.js +3 -2
  15. package/lib/api-routes/index.js +1 -1
  16. package/lib/api-routes/route-helpers.js +8 -0
  17. package/lib/api-routes/settings-routes.js +17 -2
  18. package/lib/auth-token.js +73 -2
  19. package/lib/autodetect-imap-settings.js +379 -69
  20. package/lib/cert-handler.js +62 -0
  21. package/lib/consts.js +58 -7
  22. package/lib/db.js +12 -0
  23. package/lib/egress-fetch.js +145 -0
  24. package/lib/email-client/base-client.js +234 -66
  25. package/lib/email-client/credential-errors.js +118 -0
  26. package/lib/email-client/gmail/gmail-api.js +2 -1
  27. package/lib/email-client/gmail-client.js +70 -64
  28. package/lib/email-client/imap/connection-errors.js +52 -0
  29. package/lib/email-client/imap/listing-diff.js +47 -6
  30. package/lib/email-client/imap/mailbox.js +457 -379
  31. package/lib/email-client/imap/subconnection.js +15 -11
  32. package/lib/email-client/imap/sync-operations.js +46 -59
  33. package/lib/email-client/imap-client.js +136 -95
  34. package/lib/email-client/message-builder.js +11 -11
  35. package/lib/email-client/outlook/graph-api.js +2 -1
  36. package/lib/email-client/outlook-client.js +219 -106
  37. package/lib/export.js +35 -2
  38. package/lib/handlebars-helpers.js +129 -0
  39. package/lib/imap-proxy-auth.js +96 -21
  40. package/lib/imapproxy/imap-core/README.md +1 -0
  41. package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
  42. package/lib/imapproxy/imap-server.js +56 -66
  43. package/lib/lua/h-del-if-equals.lua +39 -0
  44. package/lib/lua/h-set-if-equals.lua +39 -0
  45. package/lib/openapi/index.js +3 -0
  46. package/lib/outbox.js +28 -3
  47. package/lib/rate-limit.js +23 -4
  48. package/lib/routes-ui.js +4 -34
  49. package/lib/schemas.js +42 -3
  50. package/lib/security-headers.js +411 -0
  51. package/lib/sentry.js +36 -4
  52. package/lib/smtp-auth.js +86 -7
  53. package/lib/tls/context.js +376 -0
  54. package/lib/tls/der.js +223 -0
  55. package/lib/tls/provision.js +555 -0
  56. package/lib/tls/self-signed.js +282 -0
  57. package/lib/tls/status.js +431 -0
  58. package/lib/tls/store.js +666 -0
  59. package/lib/tools.js +337 -147
  60. package/lib/ui-routes/account-routes.js +47 -33
  61. package/lib/ui-routes/admin-config-routes.js +22 -1
  62. package/lib/ui-routes/auth-routes.js +16 -1
  63. package/lib/ui-routes/export-routes.js +4 -0
  64. package/lib/ui-routes/internals-routes.js +3 -5
  65. package/lib/ui-routes/mcp-consent-routes.js +7 -0
  66. package/lib/ui-routes/network-config-routes.js +58 -48
  67. package/lib/ui-routes/route-helpers.js +24 -8
  68. package/lib/ui-routes/smtp-test-routes.js +7 -0
  69. package/lib/ui-routes/tls-config-routes.js +581 -0
  70. package/lib/utils/mailbox-path.js +51 -0
  71. package/lib/utils/severity.js +31 -0
  72. package/lib/webhook-egress.js +5 -0
  73. package/package.json +21 -24
  74. package/sbom.json +1 -1
  75. package/server.js +53 -36
  76. package/static/css/flyonui.css +1 -1
  77. package/static/css/src/app.tailwind.css +11 -0
  78. package/static/js/ace/css/ace.css +1462 -0
  79. package/static/js/ace/css/kuroir-1.png +0 -0
  80. package/static/js/ace/css/kuroir-2.png +0 -0
  81. package/static/js/ace/css/main-1.png +0 -0
  82. package/static/js/ace/css/main-10.svg +4 -0
  83. package/static/js/ace/css/main-11.svg +5 -0
  84. package/static/js/ace/css/main-12.svg +4 -0
  85. package/static/js/ace/css/main-13.png +0 -0
  86. package/static/js/ace/css/main-14.png +0 -0
  87. package/static/js/ace/css/main-15.png +0 -0
  88. package/static/js/ace/css/main-16.png +0 -0
  89. package/static/js/ace/css/main-17.png +0 -0
  90. package/static/js/ace/css/main-18.png +0 -0
  91. package/static/js/ace/css/main-19.png +0 -0
  92. package/static/js/ace/css/main-2.png +0 -0
  93. package/static/js/ace/css/main-20.png +0 -0
  94. package/static/js/ace/css/main-21.png +0 -0
  95. package/static/js/ace/css/main-22.png +0 -0
  96. package/static/js/ace/css/main-23.png +0 -0
  97. package/static/js/ace/css/main-24.png +0 -0
  98. package/static/js/ace/css/main-25.svg +1 -0
  99. package/static/js/ace/css/main-26.png +0 -0
  100. package/static/js/ace/css/main-3.png +0 -0
  101. package/static/js/ace/css/main-4.png +0 -0
  102. package/static/js/ace/css/main-5.svg +7 -0
  103. package/static/js/ace/css/main-6.svg +9 -0
  104. package/static/js/ace/css/main-7.svg +7 -0
  105. package/static/js/ace/css/main-8.svg +9 -0
  106. package/static/js/ace/css/main-9.svg +6 -0
  107. package/static/js/ace/css/theme/kuroir.css +78 -0
  108. package/static/js/ace/css/theme/tomorrow_night.css +128 -0
  109. package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
  110. package/static/js/ace/css/theme/xcode.css +106 -0
  111. package/static/js/ace/css/tomorrow_night-1.png +0 -0
  112. package/static/js/ace/css/tomorrow_night-2.png +0 -0
  113. package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
  114. package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
  115. package/static/js/ace/css/xcode-1.png +0 -0
  116. package/static/js/ace/css/xcode-2.png +0 -0
  117. package/static/js/app.js +34 -0
  118. package/static/js/ee-client.js +256 -102
  119. package/static/js/public.js +13 -2
  120. package/static/js/ui.js +40 -25
  121. package/static/licenses.html +393 -1282
  122. package/static/vendor/simplewebauthn/browser.min.js +2 -2
  123. package/translations/messages.pot +203 -157
  124. package/views/account/login-redirect.hbs +22 -0
  125. package/views/accounts/account.hbs +15 -37
  126. package/views/accounts/browse.hbs +3 -1
  127. package/views/accounts/edit.hbs +1 -1
  128. package/views/accounts/register/imap-server.hbs +1 -1
  129. package/views/config/ai.hbs +1 -1
  130. package/views/config/branding.hbs +2 -2
  131. package/views/config/document-store/chat.hbs +1 -1
  132. package/views/config/document-store/index.hbs +1 -1
  133. package/views/config/imap-proxy.hbs +1 -4
  134. package/views/config/license.hbs +1 -1
  135. package/views/config/mcp.hbs +1 -1
  136. package/views/config/network.hbs +14 -16
  137. package/views/config/oauth/app.hbs +2 -2
  138. package/views/config/service.hbs +1 -1
  139. package/views/config/smtp.hbs +1 -4
  140. package/views/config/tls-upload.hbs +81 -0
  141. package/views/config/tls.hbs +492 -0
  142. package/views/config/webhooks.hbs +2 -2
  143. package/views/error.hbs +4 -2
  144. package/views/internals/index.hbs +1 -1
  145. package/views/layout/app.hbs +3 -11
  146. package/views/mcp/authorize.hbs +1 -1
  147. package/views/partials/ace_assets.hbs +13 -0
  148. package/views/partials/add_account_modal.hbs +1 -1
  149. package/views/partials/address_list.hbs +4 -4
  150. package/views/partials/filter_editor_js.hbs +2 -2
  151. package/views/partials/gateway_js.hbs +1 -1
  152. package/views/partials/oauth_form.hbs +1 -1
  153. package/views/partials/public_theme_init.hbs +1 -1
  154. package/views/partials/side_menu.hbs +1 -0
  155. package/views/partials/template_form.hbs +2 -2
  156. package/views/partials/test_send.hbs +7 -4
  157. package/views/partials/theme_init.hbs +1 -1
  158. package/views/partials/tls_security_card.hbs +25 -53
  159. package/views/partials/ui/alert-banner.hbs +3 -2
  160. package/views/partials/ui/badge.hbs +6 -2
  161. package/views/partials/ui/btn.hbs +5 -2
  162. package/views/partials/ui/details.hbs +2 -2
  163. package/views/partials/webhooks_editor_functions.hbs +1 -1
  164. package/views/reference/redirect.hbs +1 -1
  165. package/views/templates/template.hbs +2 -2
  166. package/views/tokens/new.hbs +1 -1
  167. package/views/unsubscribe.hbs +1 -1
  168. package/views/webhooks/webhook.hbs +2 -2
  169. package/workers/api.js +131 -242
  170. package/workers/export.js +1 -5
  171. package/workers/imap-proxy.js +4 -1
  172. package/workers/imap.js +1 -3
  173. package/workers/smtp.js +59 -83
  174. package/workers/submit.js +6 -12
  175. package/workers/webhooks.js +6 -17
  176. package/static/front/EmailEngine_logo_horiz.png +0 -0
  177. package/static/front/EmailEngine_logo_vert.png +0 -0
  178. package/static/front/index.html +0 -57
  179. package/static/front/logo.png +0 -0
  180. package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
  181. package/views/partials/tls_security_js.hbs +0 -64
  182. package/views/partials/tls_security_modal.hbs +0 -22
@@ -0,0 +1,581 @@
1
+ 'use strict';
2
+
3
+ // Admin UI routes for TLS certificates (/admin/config/tls).
4
+ //
5
+ // Certificates used to be configured from a checkbox on two other pages. Ticking it ordered one in
6
+ // the foreground, before the setting it belonged to had been saved, and a failure silently unticked
7
+ // it. There was nowhere to see what was installed, no way to upload a certificate, and no way to
8
+ // find out why an order had failed.
9
+ //
10
+ // This page separates the three things that checkbox conflated: which names EmailEngine serves,
11
+ // where the certificate for them comes from, and which listeners use TLS. The last of those stays
12
+ // on the SMTP and IMAP proxy pages, because it is part of what those servers are; this page shows
13
+ // it read-only alongside the certificate each listener is actually serving.
14
+ //
15
+ // The page is status first: what each listener serves, then one row per hostname. Hostnames are
16
+ // added and removed from that table and post immediately, the way every other list on the admin
17
+ // surface is edited; the settings form left over holds one radio group. Uploading a certificate
18
+ // has a page of its own, because three PEM fields do not fit a card on a page that is mostly
19
+ // about reading.
20
+
21
+ const Joi = require('joi');
22
+
23
+ const settings = require('../settings');
24
+ const { failAction, reloadTlsCertificates, maybeReloadTlsCertificates, redactValidationError } = require('../tools');
25
+ const { settingsSchema } = require('../schemas');
26
+ const { getServerStatus } = require('./route-helpers');
27
+ const { registerSettingsPage } = require('./settings-page');
28
+ const {
29
+ getCertificateHostnames,
30
+ hostnamesFrom,
31
+ extraHostnamesFrom,
32
+ tlsSettingChanged,
33
+ peekManualCertificate,
34
+ setManualCertificate,
35
+ deleteManualCertificate,
36
+ deleteSelfSignedCertificate,
37
+ getSelfSignedCertificate,
38
+ normalizeHostname,
39
+ LISTENER_TLS_SETTINGS,
40
+ listenerTlsFrom
41
+ } = require('../tls/store');
42
+ const { buildCertificateStatus, listenerCertificateSummary, summarizeLabels, publicView, reportedListenerTls } = require('../tls/status');
43
+ const { runPreflight, resolvePreflightProbe, clearProvisioningStatus } = require('../tls/provision');
44
+
45
+ // Certificates and keys are pasted into a textarea. A generous ceiling that still refuses a file
46
+ // upload dressed as a certificate: a full chain with a 4096 bit leaf is a few kilobytes.
47
+ const MAX_PEM_SIZE = 128 * 1024;
48
+
49
+ const TLS_PAGE = '/admin/config/tls';
50
+ const UPLOAD_PAGE = '/admin/config/tls/upload';
51
+
52
+ const configTlsSchema = {
53
+ tlsProvisioning: settingsSchema.tlsProvisioning.default('acme')
54
+ };
55
+
56
+ const EMPTY_HOSTNAME_MESSAGE = 'Enter a hostname to add';
57
+
58
+ /**
59
+ * Folds one typed hostname the way the certificate stores spell it.
60
+ *
61
+ * @param {string} value Raw form input
62
+ * @returns {string} Hostname, empty when there was none
63
+ */
64
+ function parseHostname(value) {
65
+ // A name copied out of a URL keeps the brackets an IPv6 literal wears there; a certificate
66
+ // name has none. Everything else about the fold is the one the certificate stores use.
67
+ return normalizeHostname(value).replace(/^\[|\]$/g, '');
68
+ }
69
+
70
+ /**
71
+ * Validates one hostname against the schema the REST API applies to the list, so the form is not
72
+ * the one way to store a "hostname" that no certificate could ever be issued for.
73
+ *
74
+ * @param {string} value Raw form input
75
+ * @returns {string} The folded hostname
76
+ * @throws {Error} When the name is empty or the schema refuses it
77
+ */
78
+ function validateHostname(value) {
79
+ const hostname = parseHostname(value);
80
+ const parsed = settingsSchema.tlsHostnames.validate(hostname ? [hostname] : []);
81
+
82
+ if (!hostname || parsed.error) {
83
+ throw new Error(hostname ? `Not a valid hostname: ${parsed.error.message}` : EMPTY_HOSTNAME_MESSAGE);
84
+ }
85
+
86
+ return hostname;
87
+ }
88
+
89
+ /**
90
+ * Refuses a hostname this instance has not been configured to serve.
91
+ *
92
+ * Both the preflight and the provisioning request take a hostname from the browser, and both then
93
+ * act on it: one makes an HTTP request to it, the other asks a CA to validate it. Neither is a
94
+ * reason to accept an arbitrary name from a form post, even an admin-authenticated one.
95
+ *
96
+ * @param {string} hostname Name from the request
97
+ * @returns {Promise<string>} The same name, once it is known
98
+ */
99
+ async function assertConfiguredHostname(hostname) {
100
+ const configured = await getCertificateHostnames();
101
+ const name = normalizeHostname(hostname);
102
+
103
+ if (!configured.includes(name)) {
104
+ let err = new Error('This hostname is not configured for this instance');
105
+ err.code = 'UnknownHostname';
106
+ throw err;
107
+ }
108
+
109
+ return name;
110
+ }
111
+
112
+ function init(args) {
113
+ const { server, call } = args;
114
+
115
+ // The path Let's Encrypt fetches to validate a domain, and the only unauthenticated route on
116
+ // this module. It lives here rather than in the routes-ui monolith because it is part of the
117
+ // certificate story, and because the preflight probe below shares its token store.
118
+ server.route({
119
+ method: 'GET',
120
+ path: '/.well-known/acme-challenge/{token}',
121
+ async handler(request, h) {
122
+ let domain = (request.headers.host || '').toString().replace(/:.*$/g, '').trim().toLowerCase();
123
+
124
+ // A preflight probe: the admin UI asked this instance to fetch its own challenge path
125
+ // over the public name, to find out whether Let's Encrypt will be able to. The token
126
+ // is random, lives for two minutes, and is answered before anything else, so a probe
127
+ // never reaches the certificate library and cannot be confused with a real challenge.
128
+ let probe = await resolvePreflightProbe(request.params.token);
129
+ if (probe) {
130
+ return h.response(probe).type('application/octet-stream');
131
+ }
132
+
133
+ let challenge;
134
+ try {
135
+ // Resolves to the key authorization or throws with a responseCode; it has no third
136
+ // answer, so there is nothing to check the result for.
137
+ challenge = await h.certs.routeHandler(domain, request.params.token);
138
+ } catch (err) {
139
+ // routeHandler() reports the status as responseCode, so reading statusCode turned
140
+ // an unknown token into a 500 rather than the 404 it is
141
+ return h
142
+ .response(
143
+ `Request failed: ${err.message}
144
+ Domain: ${JSON.stringify(domain)}
145
+ Token: ${JSON.stringify(request.params.token)}`
146
+ )
147
+ .type('text/plain')
148
+ .code(err.responseCode || 500);
149
+ }
150
+
151
+ // RFC 8555 section 8.3: the key authorization is the whole body, compared byte for byte
152
+ return h.response(challenge).type('application/octet-stream');
153
+ },
154
+
155
+ options: {
156
+ auth: false
157
+ }
158
+ });
159
+
160
+ registerSettingsPage(server, {
161
+ path: TLS_PAGE,
162
+ view: 'config/tls',
163
+ pageTitle: 'TLS Certificates',
164
+ menuKey: 'menuConfigTls',
165
+ schema: configTlsSchema,
166
+
167
+ async loadValues() {
168
+ return {
169
+ tlsProvisioning: (await settings.get('tlsProvisioning')) || 'acme'
170
+ };
171
+ },
172
+
173
+ viewContext: async (request, values, h) => await tlsPageContext(h),
174
+
175
+ async applySettings(request) {
176
+ const mode = request.payload.tlsProvisioning;
177
+ const changed = tlsSettingChanged('tlsProvisioning', await settings.get('tlsProvisioning'), mode);
178
+
179
+ await settings.set('tlsProvisioning', mode);
180
+
181
+ // The listeners resolve their material against the source mode, so a change here is
182
+ // what they should be offering from now on. Left alone when nothing changed: a reload
183
+ // for a save that wrote the same value would only churn the secure contexts.
184
+ await maybeReloadTlsCertificates(call, request.logger, changed ? ['tlsProvisioning'] : [], { action: 'settings' });
185
+ }
186
+ });
187
+
188
+ // Hostnames are rows of the certificate table, added and removed one at a time. Each write
189
+ // reloads the listeners: they resolve their material against the hostname list, and the
190
+ // self-signed fallback is regenerated when that list no longer matches what it covers. Without
191
+ // the reload a name added here is served the previous certificate until something else restarts
192
+ // the worker, and the page would report a certificate the listener is not using.
193
+ server.route({
194
+ method: 'POST',
195
+ path: '/admin/config/tls/hostnames',
196
+ async handler(request, h) {
197
+ try {
198
+ const hostname = validateHostname(request.payload.hostname);
199
+
200
+ // One read serves both the duplicate check (against every configured name, the
201
+ // Service URL's included) and the list the name is appended to
202
+ const values = await settings.getMulti('serviceUrl', 'tlsHostnames');
203
+
204
+ if (hostnamesFrom(values).includes(hostname)) {
205
+ await request.flash({ type: 'info', message: `${hostname} is already listed` });
206
+ return h.redirect(TLS_PAGE);
207
+ }
208
+
209
+ await settings.set('tlsHostnames', extraHostnamesFrom(values).concat(hostname));
210
+ await reloadTlsCertificates(call, request.logger, { action: 'settings' });
211
+
212
+ await request.flash({ type: 'info', message: `Added ${hostname}` });
213
+ } catch (err) {
214
+ request.logger.error({ msg: 'Failed to add a certificate hostname', err });
215
+ await request.flash({ type: 'danger', message: err.message });
216
+ }
217
+
218
+ return h.redirect(TLS_PAGE);
219
+ },
220
+ options: {
221
+ validate: {
222
+ options: { stripUnknown: true, abortEarly: false, convert: true },
223
+
224
+ async failAction(request, h, err) {
225
+ request.logger.error({ msg: 'Failed to validate a certificate hostname', err });
226
+ await request.flash({ type: 'danger', message: EMPTY_HOSTNAME_MESSAGE });
227
+ return h.redirect(TLS_PAGE).takeover();
228
+ },
229
+
230
+ payload: Joi.object({
231
+ crumb: Joi.string().max(1024),
232
+ hostname: Joi.string().max(255).required()
233
+ })
234
+ }
235
+ }
236
+ });
237
+
238
+ server.route({
239
+ method: 'POST',
240
+ path: '/admin/config/tls/hostnames/delete',
241
+ async handler(request, h) {
242
+ try {
243
+ const hostname = parseHostname(request.payload.hostname);
244
+ const values = await settings.getMulti('serviceUrl', 'tlsHostnames');
245
+ const extra = extraHostnamesFrom(values);
246
+
247
+ if (!extra.includes(hostname)) {
248
+ throw new Error(
249
+ hostnamesFrom(values).includes(hostname)
250
+ ? 'The Service URL hostname is set on the General page and is always served'
251
+ : `${hostname} is not listed`
252
+ );
253
+ }
254
+
255
+ // The recorded order state would otherwise describe a name the table no longer has
256
+ // a row for. The issued certificate itself is kept: a name that comes back gets it
257
+ // again instead of a second order against the rate limit. Two independent keys, so
258
+ // the writes go out together; only the reload has to follow both.
259
+ await Promise.all([
260
+ settings.set(
261
+ 'tlsHostnames',
262
+ extra.filter(entry => entry !== hostname)
263
+ ),
264
+ clearProvisioningStatus(hostname)
265
+ ]);
266
+ await reloadTlsCertificates(call, request.logger, { action: 'settings' });
267
+
268
+ await request.flash({ type: 'info', message: `Removed ${hostname}` });
269
+ } catch (err) {
270
+ request.logger.error({ msg: 'Failed to remove a certificate hostname', err });
271
+ await request.flash({ type: 'danger', message: err.message });
272
+ }
273
+
274
+ return h.redirect(TLS_PAGE);
275
+ },
276
+ options: {
277
+ validate: {
278
+ options: { stripUnknown: true, abortEarly: false, convert: true },
279
+
280
+ async failAction(request, h, err) {
281
+ request.logger.error({ msg: 'Failed to validate a certificate hostname removal', err });
282
+ return h.redirect(TLS_PAGE).takeover();
283
+ },
284
+
285
+ payload: Joi.object({
286
+ crumb: Joi.string().max(1024),
287
+ hostname: Joi.string().max(255).required()
288
+ })
289
+ }
290
+ }
291
+ });
292
+
293
+ server.route({
294
+ method: 'GET',
295
+ path: UPLOAD_PAGE,
296
+ async handler(request, h) {
297
+ return h.view(
298
+ 'config/tls-upload',
299
+ {
300
+ pageTitle: 'Upload a certificate',
301
+ menuConfig: true,
302
+ menuConfigTls: true,
303
+ manual: publicView(await peekManualCertificate())
304
+ },
305
+ { layout: 'app' }
306
+ );
307
+ }
308
+ });
309
+
310
+ server.route({
311
+ method: 'POST',
312
+ path: '/admin/config/tls/request',
313
+ async handler(request, h) {
314
+ try {
315
+ const hostnames = request.payload.hostname ? [await assertConfiguredHostname(request.payload.hostname)] : await getCertificateHostnames();
316
+
317
+ // Through the toolkit, because ordering needs the provisioning-capable handle and
318
+ // routes are only given the read-only one.
319
+ const { accepted, declined } = await h.requestCertificates(hostnames, request.logger);
320
+
321
+ // A decline is an answer, not a failure: it is why nothing will happen, and the
322
+ // page has to say so rather than leaving a badge reading "Requesting" forever.
323
+ if (!accepted.length && declined.length) {
324
+ return { success: false, error: declined[0].reason };
325
+ }
326
+
327
+ return { success: true, hostnames: accepted };
328
+ } catch (err) {
329
+ request.logger.error({ msg: 'Failed to request a certificate', err });
330
+ return { success: false, error: err.message };
331
+ }
332
+ },
333
+ options: {
334
+ validate: {
335
+ options: { stripUnknown: true, abortEarly: false, convert: true },
336
+ failAction,
337
+ payload: Joi.object({
338
+ crumb: Joi.string().max(1024),
339
+ hostname: Joi.string().empty('').max(255)
340
+ })
341
+ }
342
+ }
343
+ });
344
+
345
+ server.route({
346
+ method: 'POST',
347
+ path: '/admin/config/tls/preflight',
348
+ async handler(request) {
349
+ try {
350
+ const hostname = await assertConfiguredHostname(request.payload.hostname);
351
+ return Object.assign({ success: true }, await runPreflight({ hostname, logger: request.logger }));
352
+ } catch (err) {
353
+ request.logger.error({ msg: 'Certificate preflight failed', err });
354
+ return { success: false, error: err.message };
355
+ }
356
+ },
357
+ options: {
358
+ validate: {
359
+ options: { stripUnknown: true, abortEarly: false, convert: true },
360
+ failAction,
361
+ payload: Joi.object({
362
+ crumb: Joi.string().max(1024),
363
+ hostname: Joi.string().max(255).required()
364
+ })
365
+ }
366
+ }
367
+ });
368
+
369
+ server.route({
370
+ method: 'POST',
371
+ path: '/admin/config/tls/upload',
372
+ async handler(request, h) {
373
+ try {
374
+ const stored = await setManualCertificate({
375
+ cert: request.payload.cert,
376
+ ca: request.payload.ca,
377
+ privateKey: request.payload.privateKey,
378
+ passphrase: request.payload.passphrase
379
+ });
380
+
381
+ // An uploaded certificate is only useful once the listeners serve it, and they do
382
+ // not poll for one.
383
+ await reloadTlsCertificates(call, request.logger, { source: 'manual' });
384
+
385
+ await request.flash({
386
+ type: 'info',
387
+ message: `Installed the certificate for ${(stored.altNames || []).join(', ') || stored.subject}`
388
+ });
389
+ } catch (err) {
390
+ request.logger.error({ msg: 'Failed to store an uploaded certificate', err });
391
+ await request.flash({ type: 'danger', message: err.message });
392
+ // Back to the form, so the operator can fix the one field that was refused
393
+ return h.redirect(UPLOAD_PAGE);
394
+ }
395
+
396
+ return h.redirect(TLS_PAGE);
397
+ },
398
+ options: {
399
+ validate: {
400
+ options: { stripUnknown: true, abortEarly: false, convert: true },
401
+
402
+ async failAction(request, h, err) {
403
+ // The rejected payload is a private key and its passphrase, and a joi error
404
+ // carries the submitted values in four places. The global redaction list covers
405
+ // them, but this is the one place in the codebase where the value being logged
406
+ // is definitely a private key, so it does not lean on that alone.
407
+ request.logger.error({ msg: 'Failed to validate an uploaded certificate', err: redactValidationError(err) });
408
+ await request.flash({ type: 'danger', message: 'The certificate or key was not accepted. Check that both are PEM encoded.' });
409
+ return h.redirect(UPLOAD_PAGE).takeover();
410
+ },
411
+
412
+ payload: Joi.object({
413
+ crumb: Joi.string().max(1024),
414
+ cert: Joi.string().max(MAX_PEM_SIZE).required(),
415
+ ca: Joi.string().empty('').max(MAX_PEM_SIZE).default(''),
416
+ privateKey: Joi.string().max(MAX_PEM_SIZE).required(),
417
+ passphrase: Joi.string().empty('').max(1024).default('')
418
+ })
419
+ }
420
+ }
421
+ });
422
+
423
+ server.route({
424
+ method: 'POST',
425
+ path: '/admin/config/tls/delete',
426
+ async handler(request, h) {
427
+ try {
428
+ switch (request.payload.certificate) {
429
+ case 'manual':
430
+ await deleteManualCertificate();
431
+ await request.flash({ type: 'info', message: 'Removed the uploaded certificate' });
432
+ break;
433
+
434
+ case 'self-signed':
435
+ await deleteSelfSignedCertificate();
436
+ // Regenerated immediately rather than on the next handshake, so the
437
+ // fingerprint the page shows after this is the one clients will see.
438
+ await getSelfSignedCertificate(await getCertificateHostnames(), request.logger);
439
+ await request.flash({ type: 'info', message: 'Generated a new self-signed certificate' });
440
+ break;
441
+
442
+ default: {
443
+ const hostname = await assertConfiguredHostname(request.payload.certificate);
444
+ await h.certs.deleteCertificateData(hostname);
445
+ await clearProvisioningStatus(hostname);
446
+ await request.flash({ type: 'info', message: `Removed the certificate for ${hostname}` });
447
+ break;
448
+ }
449
+ }
450
+
451
+ await reloadTlsCertificates(call, request.logger, { action: 'delete' });
452
+ } catch (err) {
453
+ request.logger.error({ msg: 'Failed to remove a certificate', err });
454
+ await request.flash({ type: 'danger', message: err.message });
455
+ }
456
+
457
+ return h.redirect(TLS_PAGE);
458
+ },
459
+ options: {
460
+ validate: {
461
+ options: { stripUnknown: true, abortEarly: false, convert: true },
462
+
463
+ async failAction(request, h, err) {
464
+ request.logger.error({ msg: 'Failed to validate a certificate removal', err });
465
+ return h.redirect(TLS_PAGE).takeover();
466
+ },
467
+
468
+ payload: Joi.object({
469
+ crumb: Joi.string().max(1024),
470
+ // Not "target": a form control named `target` shadows HTMLFormElement.target,
471
+ // and the shared busy-button handler reads that property on every submit.
472
+ certificate: Joi.string().max(255).required()
473
+ })
474
+ }
475
+ }
476
+ });
477
+ }
478
+
479
+ /**
480
+ * The whole page model: the certificate for every configured name, the stored sources, and the
481
+ * listeners with what each of them is serving right now.
482
+ *
483
+ * A listener reports its own certificate in its state payload rather than having it inferred here.
484
+ * Inferring it would describe what the listener would load if it started now, which is not the same
485
+ * thing as what it is serving, and the difference is exactly the case an operator is looking at
486
+ * this page to understand.
487
+ *
488
+ * @param {Object} h Hapi response toolkit
489
+ * @returns {Promise<Object>} View context
490
+ */
491
+ async function tlsPageContext(h) {
492
+ const apiTls = h.apiTlsInfo();
493
+
494
+ // Independent reads, so the page costs one round of latency rather than three.
495
+ const listenerReads = Promise.all([getServerStatus('smtp'), getServerStatus('imapProxy'), settings.getMulti(...LISTENER_TLS_SETTINGS)]);
496
+
497
+ // What each listener says it is serving, in the order the listener list below is built in.
498
+ const reports = listenerReads.then(([smtp, imapProxy]) => [apiTls.active || null, reportedListenerTls(smtp), reportedListenerTls(imapProxy)]);
499
+
500
+ // The model needs those reports: material supplied through the TLS environment variables is per
501
+ // listener and per process, so a name served only that way has nothing stored for it and would
502
+ // otherwise be described as having no certificate. It is built alongside the listener reads
503
+ // rather than after them, so the page still costs one round of latency and not two.
504
+ const [[smtpState, imapProxyState, serverSettings], reported, status] = await Promise.all([
505
+ listenerReads,
506
+ reports,
507
+ buildCertificateStatus({ certs: h.certs, reported: reports })
508
+ ]);
509
+
510
+ // The one statement of "enabled, and TLS on" - the reconciler reads the same derivation
511
+ const switches = listenerTlsFrom(serverSettings);
512
+
513
+ // The name clients connect to, and the order state recorded for it. A listener serves every
514
+ // configured name, but the one it reports on is the default context, which is the first name.
515
+ const primary = status.certificates[0] || null;
516
+ const primaryHostname = primary ? primary.hostname : null;
517
+
518
+ // Described the way the certificate table on this same page describes one, so a listener's
519
+ // certificate cannot read differently depending on where it is shown.
520
+ const serving = report => listenerCertificateSummary({ reported: report, hostname: primaryHostname, status: primary ? primary.status : null });
521
+
522
+ // A server listener that reports no certificate gets one sentence saying why. The template
523
+ // adds the link to the listener's own page when switching something on there is the next step.
524
+ const serverListener = (listener, report) =>
525
+ Object.assign(listener, {
526
+ serving: serving(report),
527
+ hint: !listener.enabled
528
+ ? 'The server is disabled.'
529
+ : listener.tlsEnabled
530
+ ? 'TLS is on, but the listener has not reported a certificate yet.'
531
+ : 'TLS is off.',
532
+ needsSetup: !listener.enabled || !listener.tlsEnabled
533
+ });
534
+
535
+ const listeners = [
536
+ {
537
+ key: 'api',
538
+ name: 'Admin UI and API',
539
+ configuredAt: null,
540
+ enabled: true,
541
+ tlsEnabled: apiTls.enabled,
542
+ serving: serving(reported[0])
543
+ },
544
+ serverListener(
545
+ {
546
+ key: 'smtp',
547
+ name: 'SMTP server',
548
+ configuredAt: '/admin/config/smtp',
549
+ enabled: switches.smtp.enabled,
550
+ tlsEnabled: switches.smtp.tlsEnabled,
551
+ state: smtpState.label
552
+ },
553
+ reported[1]
554
+ ),
555
+ serverListener(
556
+ {
557
+ key: 'imapProxy',
558
+ name: 'IMAP proxy',
559
+ configuredAt: '/admin/config/imap-proxy',
560
+ enabled: switches.imapProxy.enabled,
561
+ tlsEnabled: switches.imapProxy.tlsEnabled,
562
+ state: imapProxyState.label
563
+ },
564
+ reported[2]
565
+ )
566
+ ];
567
+
568
+ // The header badge: the worst of what the listeners serve and, once something is served, of
569
+ // the rows too, so a failed order for one name is not hidden behind a green tile
570
+ const labels = listeners.map(listener => listener.serving.label);
571
+ if (status.served) {
572
+ labels.push(...status.certificates.map(entry => entry.label));
573
+ }
574
+
575
+ return Object.assign({}, status, { listeners, pageLabel: summarizeLabels(labels) });
576
+ }
577
+
578
+ module.exports = init;
579
+ module.exports.parseHostname = parseHostname;
580
+ module.exports.validateHostname = validateHostname;
581
+ module.exports.tlsPageContext = tlsPageContext;
@@ -0,0 +1,51 @@
1
+ 'use strict';
2
+
3
+ // Lives here rather than in lib/tools.js so that pure modules can use it: tools.js opens Redis,
4
+ // which hangs a unit test that only wants to compare two folder names. tools.js re-exports
5
+ // normalizePath, so the existing `require('../tools')` consumers are unaffected.
6
+
7
+ /**
8
+ * Folds a folder path to the spelling the sync keys everything by. IMAP makes the name "INBOX"
9
+ * case-insensitive, so a server is free to answer "Inbox" in one response and "INBOX" in the
10
+ * next; without this the two would read as different folders. Only that one name is folded -
11
+ * every other folder name is case-sensitive on IMAP and must be left alone.
12
+ *
13
+ * With a separator the fold also covers the hierarchy below the inbox ("inbox/Sub" into
14
+ * "INBOX/Sub"), which needs the server's delimiter and so is only available to callers that
15
+ * have listed the account.
16
+ *
17
+ * @param {String} path - Folder path
18
+ * @param {String} [separator] - The server's hierarchy delimiter, when known
19
+ * @returns {String} Normalized path
20
+ */
21
+ function normalizePath(path, separator) {
22
+ if (separator) {
23
+ return path.replace(new RegExp(`^INBOX($|${separator.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'i'), n => n.toUpperCase());
24
+ }
25
+
26
+ if (/^INBOX$/i.test(path)) {
27
+ return 'INBOX';
28
+ }
29
+
30
+ return path;
31
+ }
32
+
33
+ /**
34
+ * Do two paths name the same folder? Both sides are normalized, so the "INBOX" an operator typed
35
+ * into the account configuration matches the "Inbox" a server chose to report. Anything that is
36
+ * not a string matches nothing, so two missing paths can never compare equal - normalizePath()
37
+ * hands back what it was given, and `undefined === undefined` would otherwise be a match.
38
+ *
39
+ * Only the top-level inbox name is folded, because the separator is not available at every call
40
+ * site: a configured "Inbox/Archive" still has to match the server's spelling below the root,
41
+ * the same gap the mailbox map and the stored listing keys have.
42
+ *
43
+ * @param {String} a - Folder path
44
+ * @param {String} b - Folder path
45
+ * @returns {Boolean} True when both name the same folder
46
+ */
47
+ function samePath(a, b) {
48
+ return typeof a === 'string' && typeof b === 'string' && normalizePath(a) === normalizePath(b);
49
+ }
50
+
51
+ module.exports = { normalizePath, samePath };
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+
3
+ // One severity order for every "worst of" roll-up in the admin UI: a group of workers, the
4
+ // listeners on the TLS page. Kept in one place so two badges cannot rank the same states
5
+ // differently. Neutral sits above success on purpose - an unknown member is worth showing over
6
+ // a healthy one - and informational sits below anything that asks for attention.
7
+ const SEVERITY_ORDER = ['success', 'neutral', 'info', 'warning', 'error'];
8
+
9
+ /**
10
+ * Where a badge type sits in the order; an unknown type ranks with success.
11
+ *
12
+ * @param {string} type Badge variant: success|neutral|info|warning|error
13
+ * @returns {number} Higher means worse
14
+ */
15
+ function severityRank(type) {
16
+ const rank = SEVERITY_ORDER.indexOf(type);
17
+ return rank < 0 ? 0 : rank;
18
+ }
19
+
20
+ /**
21
+ * The worst item by badge type.
22
+ *
23
+ * @param {Array} items Non-empty list
24
+ * @param {Function} typeOf Reads the badge type off an item
25
+ * @returns {*} The item that ranks worst; the first of equals
26
+ */
27
+ function worstBy(items, typeOf) {
28
+ return items.reduce((worst, item) => (severityRank(typeOf(item)) > severityRank(typeOf(worst)) ? item : worst));
29
+ }
30
+
31
+ module.exports = { SEVERITY_ORDER, severityRank, worstBy };
@@ -13,6 +13,11 @@ const { assertAllowedUrl, createEgressLookup, normalizePolicy, POLICY_OFF } = re
13
13
  // system can aim EmailEngine at anything its host can route to. Defaults to blocking the
14
14
  // link-local range (cloud instance metadata); `private` also blocks RFC1918 and friends, `off`
15
15
  // disables the check and restores redirect following. See lib/egress-filter.js
16
+ //
17
+ // The autodiscovery lookups (lib/autodetect-imap-settings.js) apply the same policy: their
18
+ // destinations are derived from the domain of a caller-supplied email address, which a DNS record
19
+ // can point anywhere. One policy rather than two because they guard the same thing, the host's
20
+ // network position, and an operator who tuned it for webhooks meant the tuning for all egress.
16
21
  const WEBHOOK_EGRESS_POLICY = normalizePolicy(readEnvValue('EENGINE_WEBHOOK_EGRESS_POLICY'));
17
22
 
18
23
  const policyEnabled = WEBHOOK_EGRESS_POLICY !== POLICY_OFF;