emailengine-app 2.79.9 → 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 (75) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +49 -0
  3. package/config/default.toml +5 -1
  4. package/data/google-crawlers.json +1 -1
  5. package/encrypt.js +43 -0
  6. package/lib/account/account-state.js +62 -0
  7. package/lib/account.js +34 -2
  8. package/lib/api-routes/account-routes.js +20 -0
  9. package/lib/api-routes/index.js +1 -1
  10. package/lib/api-routes/settings-routes.js +17 -2
  11. package/lib/autodetect-imap-settings.js +349 -47
  12. package/lib/cert-handler.js +62 -0
  13. package/lib/consts.js +50 -6
  14. package/lib/db.js +12 -0
  15. package/lib/egress-fetch.js +21 -9
  16. package/lib/email-client/base-client.js +234 -66
  17. package/lib/email-client/credential-errors.js +118 -0
  18. package/lib/email-client/gmail/gmail-api.js +2 -1
  19. package/lib/email-client/gmail-client.js +70 -64
  20. package/lib/email-client/imap/connection-errors.js +52 -0
  21. package/lib/email-client/imap/listing-diff.js +47 -6
  22. package/lib/email-client/imap/mailbox.js +457 -379
  23. package/lib/email-client/imap/subconnection.js +15 -11
  24. package/lib/email-client/imap/sync-operations.js +46 -59
  25. package/lib/email-client/imap-client.js +136 -95
  26. package/lib/email-client/message-builder.js +11 -11
  27. package/lib/email-client/outlook/graph-api.js +2 -1
  28. package/lib/email-client/outlook-client.js +219 -106
  29. package/lib/imap-proxy-auth.js +58 -3
  30. package/lib/imapproxy/imap-server.js +53 -62
  31. package/lib/lua/h-del-if-equals.lua +39 -0
  32. package/lib/lua/h-set-if-equals.lua +39 -0
  33. package/lib/routes-ui.js +4 -34
  34. package/lib/schemas.js +32 -0
  35. package/lib/security-headers.js +15 -0
  36. package/lib/tls/context.js +376 -0
  37. package/lib/tls/der.js +223 -0
  38. package/lib/tls/provision.js +555 -0
  39. package/lib/tls/self-signed.js +282 -0
  40. package/lib/tls/status.js +431 -0
  41. package/lib/tls/store.js +666 -0
  42. package/lib/tools.js +72 -27
  43. package/lib/ui-routes/account-routes.js +43 -30
  44. package/lib/ui-routes/admin-config-routes.js +22 -1
  45. package/lib/ui-routes/auth-routes.js +16 -1
  46. package/lib/ui-routes/internals-routes.js +3 -5
  47. package/lib/ui-routes/network-config-routes.js +54 -45
  48. package/lib/ui-routes/tls-config-routes.js +581 -0
  49. package/lib/utils/mailbox-path.js +51 -0
  50. package/lib/utils/severity.js +31 -0
  51. package/package.json +4 -4
  52. package/sbom.json +1 -1
  53. package/server.js +16 -0
  54. package/static/css/flyonui.css +1 -1
  55. package/static/css/src/app.tailwind.css +11 -0
  56. package/static/js/app.js +34 -0
  57. package/static/js/public.js +6 -2
  58. package/static/js/ui.js +8 -25
  59. package/static/licenses.html +328 -1257
  60. package/translations/messages.pot +87 -87
  61. package/views/account/login-redirect.hbs +22 -0
  62. package/views/config/imap-proxy.hbs +0 -3
  63. package/views/config/smtp.hbs +0 -3
  64. package/views/config/tls-upload.hbs +81 -0
  65. package/views/config/tls.hbs +492 -0
  66. package/views/partials/side_menu.hbs +1 -0
  67. package/views/partials/tls_security_card.hbs +25 -53
  68. package/views/partials/ui/alert-banner.hbs +3 -2
  69. package/views/partials/ui/badge.hbs +6 -2
  70. package/views/partials/ui/btn.hbs +5 -2
  71. package/workers/api.js +93 -134
  72. package/workers/imap-proxy.js +4 -1
  73. package/workers/smtp.js +51 -44
  74. package/views/partials/tls_security_js.hbs +0 -64
  75. package/views/partials/tls_security_modal.hbs +0 -22
@@ -0,0 +1,431 @@
1
+ 'use strict';
2
+
3
+ // The certificate model the admin UI renders.
4
+ //
5
+ // Everything here used to be a single badge next to a checkbox whose tooltip carried the
6
+ // fingerprint, computed for the service domain and for nothing else. It could not say what a
7
+ // listener was actually serving, when the certificate expired, where it came from, or why the last
8
+ // order failed - and one of its four states, "Self-signed", described something that did not exist.
9
+ //
10
+ // Pure apart from the two stores it reads, so the page and the tests see the same model.
11
+
12
+ const settings = require('../settings');
13
+ const { ACME_DIRECTORY_URL, ACME_ENVIRONMENT } = require('../consts');
14
+ const {
15
+ hostnamesFrom,
16
+ extraHostnamesFrom,
17
+ acmeEligibleHostnames,
18
+ peekManualCertificate,
19
+ peekSelfSignedCertificate,
20
+ parseCertificate,
21
+ coversHostname,
22
+ normalizeHostname
23
+ } = require('./store');
24
+ const { resolveHostname, sourcesFor } = require('./context');
25
+ const { getProvisioningStatus } = require('./provision');
26
+ const { worstBy } = require('../utils/severity');
27
+
28
+ // Below this many days left, a certificate is worth pointing at even though it still works.
29
+ const EXPIRY_WARNING_DAYS = 14;
30
+
31
+ // How the recorded message is rendered, which is not always how the certificate is: a failed order
32
+ // sits under a certificate that is still perfectly valid, and a failed renewal under one that is
33
+ // still being served. A declined request ("skipped") is an explanation of why nothing happened,
34
+ // not a failure. Anything not listed is progress, and reads as information.
35
+ const STATUS_VARIANTS = {
36
+ failed: 'error',
37
+ skipped: 'info',
38
+ renewalFailed: 'warning'
39
+ };
40
+
41
+ // The recorded states whose message the page shows as a line under the hostname. A successful
42
+ // order also records a message, but the certificate row already says everything it would.
43
+ const REASON_STATES = new Set(['failed', 'skipped', 'renewalFailed', 'queued', 'ordering']);
44
+
45
+ // The header badge when no listener is serving TLS at all.
46
+ const TLS_OFF_LABEL = { type: 'neutral', text: 'TLS off', title: 'No listener is serving TLS' };
47
+
48
+ const SOURCE_LABELS = {
49
+ env: 'Environment',
50
+ manual: 'Uploaded',
51
+ acme: "Let's Encrypt",
52
+ 'self-signed': 'Self-signed'
53
+ };
54
+
55
+ // The same sources inside a sentence: "serving mail.example.com from ..."
56
+ const SOURCE_PHRASES = {
57
+ env: 'the TLS environment variables',
58
+ manual: 'the uploaded certificate',
59
+ acme: "Let's Encrypt",
60
+ 'self-signed': 'the self-signed fallback'
61
+ };
62
+
63
+ function daysUntil(date) {
64
+ if (!date) {
65
+ return null;
66
+ }
67
+ return Math.floor((date.getTime() - Date.now()) / (24 * 3600 * 1000));
68
+ }
69
+
70
+ /**
71
+ * A listener's report, with its dates back as dates.
72
+ *
73
+ * @param {Object} report Certificate description from a listener's state payload
74
+ * @returns {Object} The same description, usable by certificateLabel() and publicView()
75
+ */
76
+ function rehydrateReport(report) {
77
+ // The report reaches a page as JSON out of a Redis hash, so every date in it is an ISO string
78
+ return Object.assign({}, report, {
79
+ validFrom: report.validFrom ? new Date(report.validFrom) : null,
80
+ validTo: report.validTo ? new Date(report.validTo) : null
81
+ });
82
+ }
83
+
84
+ /**
85
+ * The certificate a listener is serving for a hostname out of environment or config-file material.
86
+ *
87
+ * That material is per listener and per process, so this module cannot read it, and a hostname
88
+ * served only through EENGINE_SMTP_TLS_CERT used to be described as having no certificate at all
89
+ * while every listener served it perfectly well. The listeners report which configured names they
90
+ * resolved to that material, so the answer is a lookup in that list rather than a second, weaker
91
+ * reimplementation of name matching against the report's own name list.
92
+ *
93
+ * @param {Object[]} reports Certificate descriptions from the listener state payloads
94
+ * @param {string} hostname Name to describe
95
+ * @returns {Object|false} The certificate, or false when no listener reports one for that name
96
+ */
97
+ function reportedEnvCertificate(reports, hostname) {
98
+ const name = normalizeHostname(hostname);
99
+ if (!name) {
100
+ return false;
101
+ }
102
+
103
+ const report = reports.find(entry => entry.source === 'env' && [].concat(entry.envHostnames || []).includes(name));
104
+
105
+ return report ? rehydrateReport(report) : false;
106
+ }
107
+
108
+ /**
109
+ * The countdown text for a certificate inside its warning window. Only reachable for a
110
+ * certificate that has not expired, so the smallest value is today.
111
+ *
112
+ * @param {number} daysRemaining Whole days until expiry, possibly zero
113
+ * @returns {string} Badge text
114
+ */
115
+ function expiryText(daysRemaining) {
116
+ if (daysRemaining <= 0) {
117
+ return 'Expires today';
118
+ }
119
+ return daysRemaining === 1 ? 'Expires in 1 day' : `Expires in ${daysRemaining} days`;
120
+ }
121
+
122
+ /**
123
+ * The badge for one certificate: colour, text and the sentence behind it.
124
+ *
125
+ * Severity follows consequence. Red means an order failed or a listener is serving something
126
+ * clients will reject; a name nothing serves yet is neutral, and a self-signed certificate is a
127
+ * warning only while a listener is actually presenting it. "Missing" is not a state: a listener
128
+ * with TLS on always has the self-signed fallback, so a name without a stored certificate is one
129
+ * nobody has needed a certificate for.
130
+ *
131
+ * @param {Object|false} certificate Resolved certificate, or false when there is none
132
+ * @param {Object} [status] Recorded provisioning state for the hostname
133
+ * @param {Object} [opts]
134
+ * @param {boolean} [opts.served=true] Whether a listener with TLS on is presenting this name
135
+ * @param {boolean} [opts.canRequest=false] Whether asking Let's Encrypt for the name would do anything
136
+ * @returns {Object} `{ type, text, title }`
137
+ */
138
+ function certificateLabel(certificate, status, opts) {
139
+ const served = !opts || opts.served !== false;
140
+ const canRequest = !!(opts && opts.canRequest);
141
+
142
+ // Both states are "an order is happening": the reconciler is asked to run, then it runs. A page
143
+ // rendered between the two used to fall through to whatever the stored certificate said.
144
+ if (status && (status.state === 'ordering' || status.state === 'queued')) {
145
+ return { type: 'info', text: 'Requesting', title: status.message || 'Requesting a certificate' };
146
+ }
147
+
148
+ if (!certificate) {
149
+ if (status && status.state === 'failed') {
150
+ return { type: 'error', text: 'Failed', title: status.message || 'Could not get a certificate' };
151
+ }
152
+ if (canRequest) {
153
+ return { type: 'neutral', text: 'Not requested', title: 'No certificate has been requested for this name yet' };
154
+ }
155
+ return {
156
+ type: 'neutral',
157
+ text: 'Self-signed',
158
+ title: 'A self-signed certificate is generated for this name the first time a listener needs one'
159
+ };
160
+ }
161
+
162
+ const now = Date.now();
163
+
164
+ if (certificate.validFrom && certificate.validFrom.getTime() > now) {
165
+ return { type: 'warning', text: 'Not yet valid', title: `Valid from ${certificate.validFrom.toISOString()}` };
166
+ }
167
+
168
+ if (certificate.validTo && certificate.validTo.getTime() < now) {
169
+ return { type: 'error', text: 'Expired', title: `Expired on ${certificate.validTo.toISOString()}` };
170
+ }
171
+
172
+ // A renewal that failed while the current certificate is still usable. The certificate itself
173
+ // is fine, so every check below would call it Valid and the operator would never learn that it
174
+ // has stopped being renewed - which is the whole failure mode: the badge stays green until the
175
+ // day the certificate expires.
176
+ if (status && status.state === 'renewalFailed') {
177
+ return { type: 'warning', text: 'Renewal failed', title: status.message || 'The last renewal attempt failed' };
178
+ }
179
+
180
+ if (certificate.source === 'self-signed') {
181
+ if (!served) {
182
+ return { type: 'neutral', text: 'Self-signed', title: 'Generated on this instance. Clients can not verify it, and no listener is serving it yet.' };
183
+ }
184
+ return {
185
+ type: 'warning',
186
+ text: 'Self-signed',
187
+ title: 'Clients can not verify this certificate. Pin its fingerprint or install a real one.'
188
+ };
189
+ }
190
+
191
+ const daysRemaining = daysUntil(certificate.validTo);
192
+
193
+ if (daysRemaining !== null && daysRemaining <= EXPIRY_WARNING_DAYS) {
194
+ return { type: 'warning', text: expiryText(daysRemaining), title: `Expires on ${certificate.validTo.toISOString()}` };
195
+ }
196
+
197
+ if (certificate.source === 'env') {
198
+ return { type: 'info', text: 'From environment', title: 'Supplied through the TLS environment variables or the config file' };
199
+ }
200
+
201
+ return { type: 'success', text: 'Valid', title: certificate.fingerprint || 'Valid certificate' };
202
+ }
203
+
204
+ /**
205
+ * Strips the private key and normalizes what the views render.
206
+ *
207
+ * @param {Object|false} certificate Resolved certificate
208
+ * @returns {Object|false} View-safe copy
209
+ */
210
+ function publicView(certificate) {
211
+ if (!certificate) {
212
+ return false;
213
+ }
214
+
215
+ return {
216
+ source: certificate.source,
217
+ sourceLabel: SOURCE_LABELS[certificate.source] || certificate.source,
218
+ sourcePhrase: SOURCE_PHRASES[certificate.source] || certificate.source,
219
+ subject: certificate.subject,
220
+ issuer: certificate.issuer,
221
+ serialNumber: certificate.serialNumber,
222
+ fingerprint: certificate.fingerprint,
223
+ fingerprint256: certificate.fingerprint256,
224
+ altNames: certificate.altNames || [],
225
+ // Which configured names a listener resolved to this material, which only the listener
226
+ // knows for environment material - see reportedEnvCertificate()
227
+ envHostnames: certificate.envHostnames || [],
228
+ validFrom: certificate.validFrom,
229
+ validTo: certificate.validTo,
230
+ // ISO strings as well as the dates: handlebars has no date formatter, and the page
231
+ // localizes these client-side from the machine-readable form (the .local-time and
232
+ // .relative-time handlers in static/js/app.js).
233
+ validFromIso: certificate.validFrom ? certificate.validFrom.toISOString() : null,
234
+ validToIso: certificate.validTo ? certificate.validTo.toISOString() : null,
235
+ selfSigned: !!certificate.selfSigned,
236
+ chainLength: 1 + [].concat(certificate.ca || []).length
237
+ };
238
+ }
239
+
240
+ /**
241
+ * The certificate summary the SMTP and IMAP proxy pages show next to their own TLS checkbox.
242
+ *
243
+ * It takes the provisioning state as well as the certificate, because those pages read a listener's
244
+ * own report rather than the stored model: without the state they could only ever say "Valid",
245
+ * including while a renewal had been failing for weeks.
246
+ *
247
+ * @param {Object} opts
248
+ * @param {Object|null} opts.reported Certificate description from the listener's state payload
249
+ * @param {string|null} opts.hostname Name clients connect to
250
+ * @param {Object} [opts.status] Recorded provisioning state for that name
251
+ * @returns {Object} `{ hostname, certificate, label }`; the last two are null when the listener has
252
+ * reported nothing, so a caller has one shape to render either way
253
+ */
254
+ function listenerCertificateSummary(opts) {
255
+ const { reported, hostname, status } = opts || {};
256
+
257
+ if (!reported) {
258
+ return { hostname: hostname || null, certificate: null, label: null };
259
+ }
260
+
261
+ const certificate = rehydrateReport(reported);
262
+
263
+ // A listener that reported a certificate is presenting it, so the label reads as served
264
+ return { hostname: hostname || null, certificate: publicView(certificate), label: certificateLabel(certificate, status || null, { served: true }) };
265
+ }
266
+
267
+ /**
268
+ * One badge for several: the worst of the labels given, or the "TLS off" label when there are none.
269
+ * The page header wears it, so the tab an operator lands on agrees with the tiles under it.
270
+ *
271
+ * @param {Array<Object|null>} labels Labels from certificateLabel(); empty entries are skipped
272
+ * @returns {Object} `{ type, text, title }`
273
+ */
274
+ function summarizeLabels(labels) {
275
+ const present = [].concat(labels || []).filter(label => label && label.type);
276
+
277
+ if (!present.length) {
278
+ return TLS_OFF_LABEL;
279
+ }
280
+
281
+ return worstBy(present, label => label.type);
282
+ }
283
+
284
+ /**
285
+ * Whether asking for a certificate is the thing to do for a name: it could be ordered, and what it
286
+ * has now is nothing, the fallback, or a certificate in trouble. A valid one is left alone (the
287
+ * reconciler renews it), and so is one already being ordered.
288
+ *
289
+ * @param {Object} entry `{ canRequest, certificate, label, status }`, the certificate unwrapped
290
+ * @returns {boolean}
291
+ */
292
+ function wantsCertificate(entry) {
293
+ if (!entry.canRequest) {
294
+ return false;
295
+ }
296
+ if (entry.status && (entry.status.state === 'ordering' || entry.status.state === 'queued')) {
297
+ return false;
298
+ }
299
+ if (!entry.certificate || entry.certificate.source === 'self-signed') {
300
+ return true;
301
+ }
302
+ return entry.label.type === 'error' || entry.label.type === 'warning';
303
+ }
304
+
305
+ /**
306
+ * Builds the whole certificate model: what is configured, what is installed for each name, where it
307
+ * came from, and what the last provisioning attempt did.
308
+ *
309
+ * @param {Object} opts
310
+ * @param {Object} opts.certs @postalsys/certs handler
311
+ * @param {Object[]|Promise} [opts.reported] Certificates the listeners report serving, for the names
312
+ * no stored source answers for. A promise is accepted, so
313
+ * a page reading the listeners can do it alongside this
314
+ * @returns {Promise<Object>} The model
315
+ */
316
+ async function buildCertificateStatus(opts) {
317
+ const { certs } = opts || {};
318
+
319
+ // Everything the model needs, in one round of reads rather than five in a row. The hostname
320
+ // list is derived from settings this already has, so it costs no second lookup.
321
+ // Both stored certificates are peeked, not loaded: nothing here serves them, so nothing here
322
+ // needs their private keys decrypted into the API worker.
323
+ const [values, manual, selfSigned, provisioning, listenerReports] = await Promise.all([
324
+ settings.getMulti('serviceUrl', 'tlsProvisioning', 'tlsHostnames'),
325
+ peekManualCertificate(),
326
+ peekSelfSignedCertificate(),
327
+ getProvisioningStatus(),
328
+ (opts && opts.reported) || []
329
+ ]);
330
+
331
+ const reported = [].concat(listenerReports || []).filter(entry => entry);
332
+
333
+ const mode = values.tlsProvisioning || 'acme';
334
+ const hostnames = hostnamesFrom(values);
335
+ const eligible = acmeEligibleHostnames(hostnames);
336
+
337
+ const sources = sourcesFor(mode);
338
+ const manualX509 = manual ? parseCertificate(manual.cert) : null;
339
+ const selfSignedX509 = selfSigned ? parseCertificate(selfSigned.cert) : null;
340
+
341
+ // The same resolver the listeners use, so the page cannot describe a certificate the listener
342
+ // would not serve - which is the confusion this page exists to end. Env material is not passed:
343
+ // it is per listener and per process, and the listeners report it themselves, which is what
344
+ // reportedEnvCertificate() reads below.
345
+ const resolved = await Promise.all(hostnames.map(hostname => resolveHostname({ certs, hostname, sources, manual, manualX509 })));
346
+
347
+ // A listener reports a certificate only while it has TLS on, so a report is what says a name is
348
+ // being presented to clients at all. That is what turns the self-signed fallback from a note
349
+ // into a warning.
350
+ const served = reported.length > 0;
351
+
352
+ // The names this page adds and removes. Whatever is configured and not among them is the
353
+ // Service URL's own name, which is set on the General page.
354
+ const extraHostnames = extraHostnamesFrom(values);
355
+
356
+ const certificates = hostnames.map((hostname, index) => {
357
+ const certificate = resolved[index] || reportedEnvCertificate(reported, hostname) || (coversHostname(selfSignedX509, hostname) ? selfSigned : false);
358
+ const status = provisioning[hostname] || null;
359
+ const acmeEligible = eligible.includes(hostname);
360
+ // Whether asking for a certificate now would do anything at all
361
+ const canRequest = mode === 'acme' && acmeEligible;
362
+ const label = certificateLabel(certificate, status, { served, canRequest });
363
+
364
+ return {
365
+ hostname,
366
+ isServiceHostname: !extraHostnames.includes(hostname),
367
+ acmeEligible,
368
+ canRequest,
369
+ wanted: wantsCertificate({ canRequest, status, certificate, label }),
370
+ certificate: publicView(certificate),
371
+ label,
372
+ status,
373
+ // The one line the page shows under the name: why the last order failed, why a request
374
+ // was declined, or that one is under way. The page script paints the same states from
375
+ // the change feed, so its table (views/config/tls.hbs) mirrors STATUS_VARIANTS.
376
+ reason:
377
+ status && REASON_STATES.has(status.state) && status.message
378
+ ? { variant: STATUS_VARIANTS[status.state] || 'info', message: status.message }
379
+ : null
380
+ };
381
+ });
382
+
383
+ return {
384
+ mode,
385
+ serviceUrl: values.serviceUrl || '',
386
+ hostnames,
387
+ certificates,
388
+ served,
389
+ // Whether the page-level "Request certificates" action has anything to do
390
+ anyWanted: certificates.some(entry => entry.wanted),
391
+ manual: publicView(manual),
392
+ selfSigned: publicView(selfSigned),
393
+ acme: {
394
+ directoryUrl: ACME_DIRECTORY_URL,
395
+ environment: ACME_ENVIRONMENT,
396
+ // A staging certificate is signed by a root nobody trusts, and the badge would
397
+ // otherwise call it valid.
398
+ staging: /staging/i.test(ACME_DIRECTORY_URL)
399
+ }
400
+ };
401
+ }
402
+
403
+ /**
404
+ * What a listener reports serving, from its recorded state - and only while it is listening.
405
+ *
406
+ * The state record keeps the payload of the last transition that carried one, and the exit, spawn
407
+ * and initialize transitions carry none, so a listener that died went on reporting the certificate
408
+ * it served before it did, for as long as the respawn backoff took. A report is what turns every
409
+ * self-signed row on the certificates page into a warning, so a crashed listener painted a state no
410
+ * listener was in.
411
+ *
412
+ * @param {Object} [serverState] `{ state, payload }` from getServerStatus()
413
+ * @returns {Object|null} The reported certificate, or null when nothing is being served
414
+ */
415
+ function reportedListenerTls(serverState) {
416
+ if (!serverState || serverState.state !== 'listening') {
417
+ return null;
418
+ }
419
+ return (serverState.payload && serverState.payload.tls) || null;
420
+ }
421
+
422
+ module.exports = {
423
+ buildCertificateStatus,
424
+ certificateLabel,
425
+ summarizeLabels,
426
+ listenerCertificateSummary,
427
+ reportedListenerTls,
428
+ publicView,
429
+ rehydrateReport,
430
+ SOURCE_LABELS
431
+ };