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,667 @@
1
+ 'use strict';
2
+
3
+ // Where a TLS listener's certificate comes from, and in what order.
4
+ //
5
+ // EmailEngine has four possible sources and, until this module existed, no agreement between them.
6
+ // The SMTP server and the IMAP proxy each loaded their environment certificate and then overwrote
7
+ // it with whatever Let's Encrypt had provisioned, so an operator who pinned a certificate through
8
+ // the environment was silently overridden by an automatic one. The admin UI, meanwhile, described a
9
+ // self-signed fallback that did not exist.
10
+ //
11
+ // The order is now stated once, here, and every listener asks this module:
12
+ //
13
+ // 1. environment or config file, per listener (EENGINE_SMTP_TLS_*, [api.tls], ...). An explicit
14
+ // instruction from the operator outranks anything EmailEngine decided on its own.
15
+ // 2. a certificate uploaded through the admin UI, when it covers the name being served.
16
+ // 3. the Let's Encrypt certificate for that name.
17
+ // 4. a self-signed certificate covering every configured name.
18
+ //
19
+ // Only 2 and 4 are stored here, in EmailEngine's own `tls` hash. Let's Encrypt records stay in the
20
+ // @postalsys/certs store, which owns their lifecycle. Private keys in both places are encrypted
21
+ // with the instance secret and are re-encrypted by the rotation pass in encrypt.js.
22
+
23
+ const crypto = require('crypto');
24
+ const net = require('net');
25
+ const { isDeepStrictEqual } = require('node:util');
26
+
27
+ const { redis } = require('../db');
28
+ const settings = require('../settings');
29
+ const getSecret = require('../get-secret');
30
+ const { encrypt, decrypt } = require('../encrypt');
31
+ const { REDIS_PREFIX } = require('../consts');
32
+ const { createSelfSignedCertificate, toAsciiHostname } = require('./self-signed');
33
+
34
+ const TLS_KEY = `${REDIS_PREFIX}tls`;
35
+
36
+ const MANUAL_FIELD = 'manual';
37
+ const SELF_SIGNED_FIELD = 'selfSigned';
38
+
39
+ // A self-signed certificate is replaced this long before it expires. Generous, because replacing
40
+ // one invalidates whatever pinned its fingerprint and there is no reason to cut it fine.
41
+ const SELF_SIGNED_RENEW_BEFORE = 30 * 24 * 3600 * 1000;
42
+
43
+ // The name a self-signed certificate is issued to when nothing better is known. A listener with no
44
+ // service URL still has to start, and "localhost" is at least true for the loopback case that
45
+ // configuration usually means.
46
+ const FALLBACK_HOSTNAME = 'localhost';
47
+
48
+ const PEM_BLOCK = /-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g;
49
+
50
+ /**
51
+ * Splits a PEM bundle into its certificates. Operators paste leaf and chain into one field about as
52
+ * often as they use separate ones, so both have to work.
53
+ *
54
+ * @param {string} pem One or more concatenated PEM certificates
55
+ * @returns {string[]} Normalized PEM blocks
56
+ */
57
+ function splitPemChain(pem) {
58
+ return ((pem || '').toString().match(PEM_BLOCK) || []).map(block => `${block.replace(/\r\n/g, '\n').trim()}\n`);
59
+ }
60
+
61
+ /**
62
+ * Parses a PEM certificate, or reports that it does not parse.
63
+ *
64
+ * Callers that ask about a certificate more than once parse it here and keep the result: the SNI
65
+ * callback is on the accept path of three listeners, so a parse per handshake is a parse per
66
+ * client connection.
67
+ *
68
+ * @param {string} cert PEM certificate
69
+ * @returns {Object|false} An X509Certificate, or false
70
+ */
71
+ function parseCertificate(cert) {
72
+ if (!cert) {
73
+ return false;
74
+ }
75
+
76
+ try {
77
+ return new crypto.X509Certificate(cert);
78
+ } catch (err) {
79
+ return false;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Does this certificate cover this name? Wildcards and IP addresses included, which is why it asks
85
+ * Node rather than comparing the subjectAltName strings itself.
86
+ *
87
+ * @param {Object|false} x509 Parsed certificate
88
+ * @param {string} hostname Name to check
89
+ * @returns {boolean} True when the certificate may be served for that name
90
+ */
91
+ function coversHostname(x509, hostname) {
92
+ if (!x509 || !hostname) {
93
+ return false;
94
+ }
95
+
96
+ // Routed by what the name is, not tried in turn: checkIP() throws on anything that is not an
97
+ // address, and this runs inside the SNI callback, where a throw would fail the handshake of
98
+ // every client connecting by hostname.
99
+ return !!(net.isIP(hostname) ? x509.checkIP(hostname) : x509.checkHost(hostname));
100
+ }
101
+
102
+ /**
103
+ * Certificate metadata in the shape the admin UI and the listener status use.
104
+ *
105
+ * @param {string} cert PEM certificate
106
+ * @returns {Object|false} Parsed fields, or false when the PEM does not parse
107
+ */
108
+ function describeCertificate(cert) {
109
+ return describeX509(parseCertificate(cert));
110
+ }
111
+
112
+ /**
113
+ * The same metadata from a certificate that is already parsed. Split out for the callers that hold
114
+ * one: the SNI path parses every certificate it serves, and describing it from the PEM again means
115
+ * a second parse of the same bytes.
116
+ *
117
+ * @param {Object|false} x509 Parsed certificate
118
+ * @returns {Object|false} Parsed fields, or false when there was no certificate
119
+ */
120
+ function describeX509(x509) {
121
+ if (!x509) {
122
+ return false;
123
+ }
124
+
125
+ // subjectAltName is a display string. Node quotes an entry containing a comma or a quote, so
126
+ // the quotes come back off after the split - this list is what the admin UI shows as "Covers",
127
+ // and a crafted certificate should not be able to make it read as something else. Nothing
128
+ // decides coverage from this: that is coversHostname(), which asks OpenSSL.
129
+ const altNames = String(x509.subjectAltName || '')
130
+ .split(',')
131
+ .map(entry => entry.trim())
132
+ .filter(entry => /^(DNS|IP Address):/i.test(entry))
133
+ .map(entry =>
134
+ entry
135
+ .replace(/^(DNS|IP Address):/i, '')
136
+ .trim()
137
+ .replace(/^"|"$/g, '')
138
+ .toLowerCase()
139
+ );
140
+
141
+ return {
142
+ subject: x509.subject,
143
+ issuer: x509.issuer,
144
+ serialNumber: x509.serialNumber,
145
+ fingerprint: x509.fingerprint,
146
+ fingerprint256: x509.fingerprint256,
147
+ altNames,
148
+ validFrom: new Date(x509.validFrom),
149
+ validTo: new Date(x509.validTo),
150
+ selfSigned: x509.issuer === x509.subject
151
+ };
152
+ }
153
+
154
+ /**
155
+ * A stored record, with its private key decrypted - or without the key at all.
156
+ *
157
+ * A caller that only describes the certificate asks for `withPrivateKey: false`: the metadata a
158
+ * page paints needs the certificate alone, and a read that says "a certificate for X is installed"
159
+ * has no business pulling key material into memory.
160
+ *
161
+ * @param {string} value The stored JSON
162
+ * @param {Object} [opts]
163
+ * @param {boolean} [opts.withPrivateKey=true] False to drop the key instead of decrypting it
164
+ * @returns {Promise<Object|false>} The record, or false when there is none or it does not parse
165
+ */
166
+ async function decodeRecord(value, opts) {
167
+ if (!value) {
168
+ return false;
169
+ }
170
+
171
+ let record;
172
+ try {
173
+ record = JSON.parse(value);
174
+ } catch (err) {
175
+ return false;
176
+ }
177
+
178
+ if (!record) {
179
+ return false;
180
+ }
181
+
182
+ if (opts && opts.withPrivateKey === false) {
183
+ delete record.privateKey;
184
+ } else if (record.privateKey) {
185
+ const encryptSecret = await getSecret();
186
+ record.privateKey = await decrypt(record.privateKey, encryptSecret);
187
+ }
188
+
189
+ return record;
190
+ }
191
+
192
+ async function readRecord(field, opts) {
193
+ return await decodeRecord(await redis.hget(TLS_KEY, field), opts);
194
+ }
195
+
196
+ /**
197
+ * The material a stored record amounts to: its metadata, its source, and the record itself.
198
+ *
199
+ * A record whose certificate does not parse is no certificate, whatever source it came from.
200
+ * Answering it as one gave the page a "Valid" badge with no dates behind it while the listener,
201
+ * unable to build a context from it, quietly served the self-signed fallback for the name.
202
+ *
203
+ * @param {string} source `env`, `manual`, `acme` or `self-signed`
204
+ * @param {Object|false} record The stored record, or environment material in the same shape
205
+ * @returns {Object|false} `{ source, subject, altNames, validTo, ..., cert, ca, privateKey? }`
206
+ */
207
+ function materialFrom(source, record) {
208
+ const described = record && record.cert ? describeCertificate(record.cert) : false;
209
+ if (!described) {
210
+ return false;
211
+ }
212
+ return Object.assign({ source }, described, record);
213
+ }
214
+
215
+ async function serializeRecord(record) {
216
+ const stored = Object.assign({}, record);
217
+ if (stored.privateKey) {
218
+ const encryptSecret = await getSecret();
219
+ stored.privateKey = await encrypt(stored.privateKey, encryptSecret);
220
+ }
221
+ return JSON.stringify(stored);
222
+ }
223
+
224
+ /**
225
+ * The names EmailEngine serves TLS for: the service URL's hostname first, then whatever else the
226
+ * operator listed. The first one is the subject of a self-signed certificate and the name a
227
+ * Let's Encrypt certificate is ordered for; the rest are ordered separately and served over SNI.
228
+ *
229
+ * IP addresses and unqualified names are kept, unlike the ACME path which cannot use them: a
230
+ * self-signed certificate for an IP-only deployment is exactly the case this fallback exists for.
231
+ *
232
+ * @returns {Promise<string[]>} Lower-cased hostnames, deduplicated, in priority order
233
+ */
234
+ async function getCertificateHostnames() {
235
+ return hostnamesFrom(await settings.getMulti('serviceUrl', 'tlsHostnames'));
236
+ }
237
+
238
+ /**
239
+ * The one spelling of a hostname. Settings, certificate names and the server name a client sends
240
+ * are all compared folded, so every caller has to fold the same way.
241
+ *
242
+ * @param {string} hostname Name from a setting, a URL or a handshake
243
+ * @returns {string} Folded name, empty when there was none
244
+ */
245
+ function normalizeHostname(hostname) {
246
+ const name = (hostname || '').toString().toLowerCase().trim();
247
+
248
+ // Certificates and settings hold A-labels (`xn--...`), and so does the name the SMTP server
249
+ // and the API listener hand the SNI callback - but the IMAP proxy's server library decodes the
250
+ // ClientHello name to Unicode before asking for a context, and a Unicode name matches no SAN.
251
+ // Converted here, so the one spelling really is one. Gated on a non-ASCII byte because this
252
+ // runs once per client handshake and nearly every name is ASCII already.
253
+ // eslint-disable-next-line no-control-regex
254
+ return /[^\x00-\x7f]/.test(name) ? toAsciiHostname(name) : name;
255
+ }
256
+
257
+ /**
258
+ * The same derivation, from values the caller already has. Split out so a page that reads several
259
+ * settings at once does not issue a second round trip for the two this needs.
260
+ *
261
+ * @param {Object} values `{ serviceUrl, tlsHostnames }`
262
+ * @returns {string[]} Lower-cased hostnames, deduplicated, in priority order
263
+ */
264
+ function hostnamesFrom(values) {
265
+ const hostnames = [];
266
+
267
+ try {
268
+ const hostname = normalizeHostname(new URL(values && values.serviceUrl).hostname);
269
+ if (hostname) {
270
+ // A URL keeps an IPv6 literal in brackets; a certificate name does not.
271
+ hostnames.push(hostname.replace(/^\[|\]$/g, ''));
272
+ }
273
+ } catch (err) {
274
+ // no service URL, or not a URL at all
275
+ }
276
+
277
+ for (const entry of [].concat((values && values.tlsHostnames) || [])) {
278
+ const hostname = normalizeHostname(entry);
279
+ if (hostname && !hostnames.includes(hostname)) {
280
+ hostnames.push(hostname);
281
+ }
282
+ }
283
+
284
+ return hostnames;
285
+ }
286
+
287
+ /**
288
+ * The names the operator listed on top of the Service URL's own, folded the way every reader of
289
+ * the list compares them. Separate from hostnamesFrom() because the admin page treats the two
290
+ * differently: the Service URL's name is set on the General page, these are rows of its own.
291
+ *
292
+ * @param {Object} values `{ tlsHostnames }`
293
+ * @returns {string[]} Lower-cased hostnames, empty entries dropped
294
+ */
295
+ function extraHostnamesFrom(values) {
296
+ return []
297
+ .concat((values && values.tlsHostnames) || [])
298
+ .map(normalizeHostname)
299
+ .filter(name => name);
300
+ }
301
+
302
+ /**
303
+ * Whether writing `value` over the stored value actually changes what the TLS listeners serve.
304
+ *
305
+ * A write is not a change: settings.set() is an unconditional hset, and a read-modify-write API
306
+ * client posts the whole settings object back on every call. Reloading on the write alone handed
307
+ * three listeners a new certificate every time somebody changed the timezone. tlsHostnames is a
308
+ * set of names, so a reordered list is the same list.
309
+ *
310
+ * @param {string} key Settings key
311
+ * @param {*} storedValue What the store holds now
312
+ * @param {*} value What is about to be written
313
+ * @returns {boolean} True when the listeners should reload
314
+ */
315
+ function tlsSettingChanged(key, storedValue, value) {
316
+ if (key === 'tlsHostnames') {
317
+ const normalize = list => extraHostnamesFrom({ tlsHostnames: list }).sort();
318
+ return !isDeepStrictEqual(normalize(storedValue), normalize(value));
319
+ }
320
+
321
+ // Against what settings.set() will store rather than against what was posted: serviceUrl is
322
+ // reduced to its origin, so the stored value posted back with a trailing slash is the same value.
323
+ return (storedValue ?? '') !== (settings.formatSettingValue(key, value) ?? '');
324
+ }
325
+
326
+ /**
327
+ * The hostnames a Let's Encrypt certificate can be ordered for. The ACME http-01 challenge needs a
328
+ * name the CA can resolve and reach, so an address literal, a single label or a private-use suffix
329
+ * is not one of them.
330
+ *
331
+ * @param {string[]} hostnames Candidate names
332
+ * @returns {string[]} The subset that can be validated
333
+ */
334
+ function acmeEligibleHostnames(hostnames) {
335
+ return [].concat(hostnames || []).filter(hostname => {
336
+ if (!hostname || net.isIP(hostname)) {
337
+ return false;
338
+ }
339
+ if (!/\./.test(hostname) || /(\.local|\.lan|\.internal|\.home\.arpa|\.localhost)$/i.test(hostname)) {
340
+ return false;
341
+ }
342
+ return true;
343
+ });
344
+ }
345
+
346
+ /**
347
+ * The certificate an operator uploaded, if any.
348
+ *
349
+ * @returns {Promise<Object|false>} `{ cert, ca, privateKey, ...metadata }`
350
+ */
351
+ async function getManualCertificate() {
352
+ const record = await readRecord(MANUAL_FIELD);
353
+ return record && record.privateKey ? materialFrom('manual', record) : false;
354
+ }
355
+
356
+ /**
357
+ * The uploaded certificate's metadata, for a page that only names it. Unlike getManualCertificate()
358
+ * this never decrypts the private key; see decodeRecord().
359
+ *
360
+ * @returns {Promise<Object|false>} `{ source, cert, ca, subject, altNames, validTo, ... }`
361
+ */
362
+ async function peekManualCertificate() {
363
+ return materialFrom('manual', await readRecord(MANUAL_FIELD, { withPrivateKey: false }));
364
+ }
365
+
366
+ /**
367
+ * Validates and stores an uploaded certificate.
368
+ *
369
+ * Everything is checked before anything is written: a certificate that does not parse, a key that
370
+ * does not parse, or a pair that does not match is refused rather than stored and discovered at the
371
+ * next restart, when the listener would be down and the admin UI would still show it as installed.
372
+ *
373
+ * @param {Object} input
374
+ * @param {string} input.cert PEM certificate, optionally with the chain appended
375
+ * @param {string} [input.ca] PEM chain, when supplied separately
376
+ * @param {string} input.privateKey PEM private key
377
+ * @param {string} [input.passphrase] Passphrase, when the key is encrypted
378
+ * @returns {Promise<Object>} The stored record's metadata
379
+ */
380
+ async function setManualCertificate(input) {
381
+ const chain = splitPemChain(input && input.cert).concat(splitPemChain(input && input.ca));
382
+
383
+ if (!chain.length) {
384
+ throw certificateError('The certificate must be PEM encoded and start with "-----BEGIN CERTIFICATE-----"', 'cert');
385
+ }
386
+
387
+ let x509;
388
+ try {
389
+ x509 = new crypto.X509Certificate(chain[0]);
390
+ } catch (err) {
391
+ throw certificateError(`Could not read the certificate: ${err.message}`, 'cert');
392
+ }
393
+
394
+ const keyPem = (input.privateKey || '').toString().replace(/\r\n/g, '\n').trim();
395
+
396
+ // Read from the PEM, not from the error: OpenSSL reports a missing passphrase as "interrupted
397
+ // or cancelled" (it wanted to prompt for one), which tells the operator nothing at all.
398
+ const keyIsEncrypted = /BEGIN ENCRYPTED PRIVATE KEY|Proc-Type:\s*4,ENCRYPTED/i.test(keyPem);
399
+
400
+ if (keyIsEncrypted && !input.passphrase) {
401
+ throw certificateError('This private key is passphrase protected. Enter the passphrase to install it.', 'privateKey');
402
+ }
403
+
404
+ let privateKey;
405
+ try {
406
+ privateKey = crypto.createPrivateKey({ key: keyPem, passphrase: input.passphrase || undefined });
407
+ } catch (err) {
408
+ throw certificateError(
409
+ keyIsEncrypted ? 'Could not read the private key. Check the passphrase.' : `Could not read the private key: ${err.message}`,
410
+ 'privateKey'
411
+ );
412
+ }
413
+
414
+ if (!x509.checkPrivateKey(privateKey)) {
415
+ throw certificateError('The private key does not belong to this certificate', 'privateKey');
416
+ }
417
+
418
+ const record = {
419
+ cert: chain[0],
420
+ ca: chain.slice(1),
421
+ // Stored without its passphrase: the value is encrypted at rest with the instance secret,
422
+ // and keeping the passphrase would mean storing it next to what it protects.
423
+ privateKey: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(),
424
+ updated: new Date().toISOString()
425
+ };
426
+
427
+ await redis.hset(TLS_KEY, MANUAL_FIELD, await serializeRecord(record));
428
+
429
+ return Object.assign({ source: 'manual' }, describeCertificate(record.cert) || {});
430
+ }
431
+
432
+ function certificateError(message, field) {
433
+ const err = new Error(message);
434
+ err.code = 'InvalidCertificate';
435
+ if (field) {
436
+ err.details = { [field]: message };
437
+ }
438
+ return err;
439
+ }
440
+
441
+ async function deleteManualCertificate() {
442
+ return await redis.hdel(TLS_KEY, MANUAL_FIELD);
443
+ }
444
+
445
+ /**
446
+ * The instance's self-signed certificate, generated on first use and replaced when it no longer
447
+ * covers the configured names or is close to expiring.
448
+ *
449
+ * Written conditionally on the record that was read, so that two workers reaching this at the same
450
+ * moment agree on one certificate: whoever loses the race reads back the winner's rather than
451
+ * serving a second one that nobody pinned.
452
+ *
453
+ * @param {string[]} hostnames Names the certificate has to cover
454
+ * @param {Object} [logger] Logger for the generation notice
455
+ * @returns {Promise<Object>} `{ cert, privateKey, ...metadata }`
456
+ */
457
+ async function peekSelfSignedCertificate() {
458
+ return materialFrom('self-signed', await readRecord(SELF_SIGNED_FIELD, { withPrivateKey: false }));
459
+ }
460
+
461
+ // How many times a worker contends for the self-signed record before serving what it generated
462
+ // unstored. Each round is a read and one conditional write, and losing one takes another worker
463
+ // writing in the same instant; losing every round means Redis is being rewritten faster than it
464
+ // can be read, and a listener that has been switched on still has to start.
465
+ const SELF_SIGNED_WRITE_ATTEMPTS = 3;
466
+
467
+ async function getSelfSignedCertificate(hostnames, logger) {
468
+ const names = []
469
+ .concat(hostnames || [])
470
+ .map(normalizeHostname)
471
+ .filter(name => name);
472
+ if (!names.length) {
473
+ names.push(FALLBACK_HOSTNAME);
474
+ }
475
+
476
+ // The stored record as material this worker can serve, or false: no record, a certificate
477
+ // that does not parse, or one generated for other names or about to expire - both of which
478
+ // make a handshake fail, so it is replaced rather than kept.
479
+ const servable = record => (record && record.privateKey && !selfSignedIsStale(record, names) ? materialFrom('self-signed', record) : false);
480
+
481
+ let generated = null;
482
+
483
+ for (let attempt = 1; attempt <= SELF_SIGNED_WRITE_ATTEMPTS; attempt++) {
484
+ // The stored bytes are kept, not just the record: they are what the replacement below is
485
+ // made conditional on, and re-serializing cannot produce them again - the private key is
486
+ // encrypted with a fresh IV every time, so the same certificate serializes to a different
487
+ // string.
488
+ const stale = await redis.hget(TLS_KEY, SELF_SIGNED_FIELD);
489
+ const existing = servable(await decodeRecord(stale));
490
+ if (existing) {
491
+ return existing;
492
+ }
493
+
494
+ // Generated once: a lost write is contended again with the same certificate, not a new one
495
+ // - a keypair is the expensive part, and this runs before a listener binds its port.
496
+ if (!generated) {
497
+ generated = await createSelfSignedCertificate({ hostnames: names });
498
+ }
499
+
500
+ const record = {
501
+ cert: generated.cert,
502
+ privateKey: generated.privateKey,
503
+ hostnames: names,
504
+ updated: new Date().toISOString()
505
+ };
506
+
507
+ // Conditional on the record that was read, so concurrent replacement converges the way
508
+ // concurrent creation already did. Deleting the stale record and then HSETNX looked
509
+ // equivalent and was not: a certificate reload fans out to the API, SMTP and IMAP proxy
510
+ // workers at once, so after a hostname change all three find the same stale record, and
511
+ // the delete let each of them win an HSETNX in turn - every worker then served its own
512
+ // certificate while the page showed whichever wrote last.
513
+ const stored = await redis.hSetIfEquals(TLS_KEY, SELF_SIGNED_FIELD, await serializeRecord(record), stale || '');
514
+
515
+ if (stored) {
516
+ if (logger) {
517
+ logger.warn({
518
+ msg: 'Generated a self-signed TLS certificate. Clients can not verify it; pin the fingerprint or install a real certificate',
519
+ hostnames: names,
520
+ fingerprint: generated.fingerprint,
521
+ validTo: generated.validTo
522
+ });
523
+ }
524
+ return materialFrom('self-signed', record);
525
+ }
526
+
527
+ // The field changed under the write. Whoever won is read back at the top of the next round
528
+ // and served if this worker can; otherwise - removed from the page in between, unreadable,
529
+ // generated for other names - the write is contended again from what is there now. Serving
530
+ // the losing material would present a fingerprint that is stored nowhere and that the page
531
+ // never shows, the divergence the conditional write exists to prevent.
532
+ }
533
+
534
+ if (logger) {
535
+ logger.error({
536
+ msg: 'Could not store the self-signed TLS certificate, serving an unstored one',
537
+ hostnames: names,
538
+ fingerprint: generated.fingerprint,
539
+ attempts: SELF_SIGNED_WRITE_ATTEMPTS
540
+ });
541
+ }
542
+
543
+ return materialFrom('self-signed', {
544
+ cert: generated.cert,
545
+ privateKey: generated.privateKey,
546
+ hostnames: names,
547
+ updated: new Date().toISOString()
548
+ });
549
+ }
550
+
551
+ // The names the record was generated for, not the names its certificate reports. They are the same
552
+ // list, but a certificate normalizes what it holds - Node reads an IPv6 SAN back as
553
+ // "2001:db8:0:0:0:0:0:1" where the setting said "2001:db8::1" - and comparing against that would
554
+ // find a mismatch on every pass and regenerate the certificate forever.
555
+ function selfSignedIsStale(record, hostnames) {
556
+ const covered = [].concat(record.hostnames || []);
557
+ if (covered.length !== hostnames.length || hostnames.some(hostname => !covered.includes(hostname))) {
558
+ return true;
559
+ }
560
+
561
+ const parsed = describeCertificate(record.cert);
562
+ if (!parsed) {
563
+ return true;
564
+ }
565
+
566
+ return parsed.validTo.getTime() - Date.now() < SELF_SIGNED_RENEW_BEFORE;
567
+ }
568
+
569
+ async function deleteSelfSignedCertificate() {
570
+ return await redis.hdel(TLS_KEY, SELF_SIGNED_FIELD);
571
+ }
572
+
573
+ /**
574
+ * Reads the Let's Encrypt record for a name, without ever ordering one. Provisioning is the
575
+ * reconciler's job (lib/tls/provision.js); a listener starting up must not block on a CA.
576
+ *
577
+ * @param {Object} certs @postalsys/certs handler
578
+ * @param {string} hostname Name to look up
579
+ * @param {Object} [logger] Logger for a store that could not be read
580
+ * @returns {Promise<Object|false>} `{ cert, ca, privateKey, ...metadata }`
581
+ */
582
+ async function getAcmeCertificate(certs, hostname, logger) {
583
+ if (!certs || !hostname) {
584
+ return false;
585
+ }
586
+
587
+ let record;
588
+ try {
589
+ record = await certs.getCertificate(hostname, true);
590
+ } catch (err) {
591
+ // The listener still starts on whatever is left, but silently: a rotated EENGINE_SECRET
592
+ // fails the key decrypt and Redis can be down, and both looked like "no certificate here"
593
+ // with nothing in the log to say the stored one exists.
594
+ if (logger) {
595
+ logger.error({ msg: 'Failed to read the stored TLS certificate', hostname, err });
596
+ }
597
+ return false;
598
+ }
599
+
600
+ if (!record || record.status !== 'valid' || !record.cert || !record.privateKey) {
601
+ return false;
602
+ }
603
+
604
+ const material = materialFrom('acme', {
605
+ cert: record.cert,
606
+ ca: [].concat(record.ca || []).flatMap(entry => entry),
607
+ privateKey: record.privateKey
608
+ });
609
+
610
+ if (!material && logger) {
611
+ logger.error({ msg: 'The stored TLS certificate does not parse', hostname });
612
+ }
613
+
614
+ return material;
615
+ }
616
+
617
+ // The settings that say which built-in listeners speak TLS, read together with whatever else a
618
+ // caller needs so the answer costs no round trip of its own.
619
+ const LISTENER_TLS_SETTINGS = ['smtpServerEnabled', 'smtpServerTLSEnabled', 'imapProxyServerEnabled', 'imapProxyServerTLSEnabled'];
620
+
621
+ /**
622
+ * What each built-in server listener is set to, from values the caller already has.
623
+ *
624
+ * The one place the "enabled, and TLS on" rule is stated: the certificates page paints its
625
+ * listener tiles from this, and the reconciler decides from it whether a first order is worth
626
+ * placing, so the page cannot say a listener serves TLS while the reconciler thinks nothing does.
627
+ *
628
+ * @param {Object} values Settings, at least LISTENER_TLS_SETTINGS
629
+ * @returns {Object} `{ smtp: { enabled, tlsEnabled }, imapProxy: { enabled, tlsEnabled } }`
630
+ */
631
+ function listenerTlsFrom(values) {
632
+ const listener = (enabled, tlsEnabled) => ({ enabled: !!(values && values[enabled]), tlsEnabled: !!(values && values[tlsEnabled]) });
633
+
634
+ return {
635
+ smtp: listener('smtpServerEnabled', 'smtpServerTLSEnabled'),
636
+ imapProxy: listener('imapProxyServerEnabled', 'imapProxyServerTLSEnabled')
637
+ };
638
+ }
639
+
640
+ module.exports = {
641
+ TLS_KEY,
642
+ MANUAL_FIELD,
643
+ SELF_SIGNED_FIELD,
644
+ FALLBACK_HOSTNAME,
645
+ splitPemChain,
646
+ parseCertificate,
647
+ coversHostname,
648
+ describeCertificate,
649
+ describeX509,
650
+ materialFrom,
651
+ getCertificateHostnames,
652
+ normalizeHostname,
653
+ hostnamesFrom,
654
+ extraHostnamesFrom,
655
+ tlsSettingChanged,
656
+ acmeEligibleHostnames,
657
+ getManualCertificate,
658
+ peekManualCertificate,
659
+ setManualCertificate,
660
+ deleteManualCertificate,
661
+ getSelfSignedCertificate,
662
+ peekSelfSignedCertificate,
663
+ deleteSelfSignedCertificate,
664
+ getAcmeCertificate,
665
+ LISTENER_TLS_SETTINGS,
666
+ listenerTlsFrom
667
+ };