emailengine-app 2.79.9 → 2.80.1

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