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,555 @@
1
+ 'use strict';
2
+
3
+ // Getting a certificate, and knowing why you did not get one.
4
+ //
5
+ // Provisioning used to happen on the click of the "Enable TLS" checkbox: a foreground HTTP request
6
+ // held open for the length of an ACME order, behind a modal spinner, before the setting it belonged
7
+ // to had been saved. It failed the way that arrangement has to fail. A reverse proxy with a thirty
8
+ // second timeout killed the request while the order carried on; a failure silently unchecked the
9
+ // box, so the page stopped matching the stored setting; and the reason never reached the operator,
10
+ // because acquireCert() answers a failed order by returning the previous record, which for a first
11
+ // certificate is nothing at all.
12
+ //
13
+ // So provisioning is a background task with a recorded state, and the UI watches that state. The
14
+ // reconciler below is the only thing that orders certificates; the button in the admin UI asks it
15
+ // to run now rather than doing the work itself.
16
+
17
+ const crypto = require('crypto');
18
+ const { fetch: fetchCmd } = require('undici');
19
+
20
+ const { redis } = require('../db');
21
+ const settings = require('../settings');
22
+ const { REDIS_PREFIX, BLOCK_TLS_RENEW, TLS_RETRY_AFTER_FAILURE, TLS_PREFLIGHT_TTL, TLS_PREFLIGHT_TIMEOUT } = require('../consts');
23
+ const { emitChangeEvent, reloadTlsCertificates, httpAgent } = require('../tools');
24
+ const { validateWebhookTarget } = require('../webhook-egress');
25
+ const { hostnamesFrom, acmeEligibleHostnames, LISTENER_TLS_SETTINGS, listenerTlsFrom } = require('./store');
26
+ const { apiTlsConfig } = require('./context');
27
+
28
+ const STATUS_KEY = `${REDIS_PREFIX}tls:status`;
29
+ const PROBE_KEY = `${REDIS_PREFIX}tls:probe`;
30
+
31
+ // Orders this worker has in flight. Not a lock - the certificate library holds a Redis lock per
32
+ // domain, so two workers ordering at once is already handled. This only stops one worker from
33
+ // stacking background tasks for the same name while an order is running.
34
+ const inFlight = new Set();
35
+
36
+ /**
37
+ * Reads the recorded provisioning state for every hostname.
38
+ *
39
+ * @returns {Promise<Object>} Hostname to `{ state, message, attempted, ... }`
40
+ */
41
+ async function getProvisioningStatus() {
42
+ const entries = await redis.hgetall(STATUS_KEY);
43
+ const status = {};
44
+
45
+ for (const hostname of Object.keys(entries || {})) {
46
+ try {
47
+ status[hostname] = JSON.parse(entries[hostname]);
48
+ } catch (err) {
49
+ // a record that does not parse is a record that says nothing
50
+ }
51
+ }
52
+
53
+ return status;
54
+ }
55
+
56
+ /**
57
+ * Records provisioning state and tells any open admin page about it. The event is what replaces the
58
+ * blocking modal: the page that asked for a certificate sees the order start, succeed or fail
59
+ * without holding a request open for it.
60
+ *
61
+ * @param {Object} logger Worker logger
62
+ * @param {string} hostname Name being provisioned
63
+ * @param {Object} status State to record
64
+ * @returns {Promise<Object>} The recorded state
65
+ */
66
+ async function setProvisioningStatus(logger, hostname, status) {
67
+ const record = Object.assign({ hostname, updated: new Date().toISOString() }, status);
68
+
69
+ try {
70
+ await redis.hset(STATUS_KEY, hostname, JSON.stringify(record));
71
+ } catch (err) {
72
+ logger.error({ msg: 'Failed to store certificate provisioning state', hostname, err });
73
+ }
74
+
75
+ await emitChangeEvent(logger, null, 'tlsCertificateState', record.state, record);
76
+
77
+ return record;
78
+ }
79
+
80
+ async function clearProvisioningStatus(hostname) {
81
+ return await redis.hdel(STATUS_KEY, hostname);
82
+ }
83
+
84
+ /**
85
+ * Arms a token the ACME challenge route will answer, so the preflight can prove that a request from
86
+ * the public internet reaches this instance's challenge path.
87
+ *
88
+ * @returns {Promise<Object>} `{ token, value }`
89
+ */
90
+ async function armPreflightProbe() {
91
+ const token = `ee-preflight-${crypto.randomBytes(16).toString('hex')}`;
92
+ const value = crypto.randomBytes(32).toString('base64url');
93
+
94
+ // One command, so the key cannot outlive its expiry by having the second leg fail.
95
+ await redis.set(`${PROBE_KEY}:${token}`, value, 'EX', TLS_PREFLIGHT_TTL);
96
+
97
+ return { token, value };
98
+ }
99
+
100
+ /**
101
+ * The answer for a probe token, if one is armed. Called by the ACME challenge route before it hands
102
+ * the token to the certificate library.
103
+ *
104
+ * @param {string} token Token from the request path
105
+ * @returns {Promise<string|false>} The expected response body
106
+ */
107
+ async function resolvePreflightProbe(token) {
108
+ if (!token || !/^ee-preflight-[0-9a-f]{32}$/.test(token)) {
109
+ return false;
110
+ }
111
+
112
+ return (await redis.get(`${PROBE_KEY}:${token}`)) || false;
113
+ }
114
+
115
+ /**
116
+ * Checks whether a Let's Encrypt http-01 challenge for this hostname could succeed, by making the
117
+ * request the CA will make.
118
+ *
119
+ * This is the check that pays for itself. Automatic certificates need the name to resolve and port
120
+ * 80 to reach EmailEngine's challenge path, neither of which is visible from the admin UI, and both
121
+ * of which fail as an opaque ACME error minutes later. Here they fail immediately, by name.
122
+ *
123
+ * The request goes to a hostname the operator configured as their own service URL, and only its
124
+ * status code and whether the body matched a token EmailEngine just generated are reported back.
125
+ *
126
+ * @param {Object} opts
127
+ * @param {string} opts.hostname Name to check
128
+ * @param {Object} opts.logger Worker logger
129
+ * @returns {Promise<Object>} `{ success, hostname, message, url, status }`
130
+ */
131
+ async function runPreflight(opts) {
132
+ const { hostname, logger } = opts;
133
+
134
+ const probe = await armPreflightProbe();
135
+ const url = `http://${hostname}/.well-known/acme-challenge/${probe.token}`;
136
+
137
+ // The same egress policy webhooks and autodiscovery are held to. The hostname is configuration
138
+ // rather than caller input, but it is still a name the server is asked to fetch, and a name
139
+ // that resolves into a blocked range is one Let's Encrypt could never reach either - so
140
+ // refusing it is both the safe answer and the true one.
141
+ if (validateWebhookTarget) {
142
+ try {
143
+ await validateWebhookTarget(url);
144
+ } catch (err) {
145
+ return {
146
+ success: false,
147
+ hostname,
148
+ url,
149
+ message: `${hostname} resolves to an address this instance will not connect to (${err.message}). Let's Encrypt could not reach it either.`
150
+ };
151
+ }
152
+ }
153
+
154
+ let res;
155
+ try {
156
+ res = await fetchCmd(url, {
157
+ method: 'GET',
158
+ redirect: 'follow',
159
+ // The webhook dispatcher re-applies the policy as its connect-time lookup, so the
160
+ // address vetted above is the address connected to, on the first hop and on any
161
+ // redirect the CA would also follow.
162
+ dispatcher: httpAgent.webhook,
163
+ signal: AbortSignal.timeout(TLS_PREFLIGHT_TIMEOUT),
164
+ headers: { 'User-Agent': 'EmailEngine ACME preflight' }
165
+ });
166
+ } catch (err) {
167
+ logger.info({ msg: 'Certificate preflight could not reach the challenge path', hostname, url, err });
168
+
169
+ return {
170
+ success: false,
171
+ hostname,
172
+ url,
173
+ message: `Could not reach http://${hostname}/ from this server (${err.cause ? err.cause.message || err.message : err.message}). The name has to resolve to this machine and port 80 has to reach EmailEngine.`
174
+ };
175
+ }
176
+
177
+ if (!res.ok) {
178
+ return {
179
+ success: false,
180
+ hostname,
181
+ url,
182
+ status: res.status,
183
+ message: `http://${hostname}/.well-known/acme-challenge/ answered ${res.status}. Something other than EmailEngine is serving that path.`
184
+ };
185
+ }
186
+
187
+ const body = (await res.text()).trim();
188
+
189
+ if (body !== probe.value) {
190
+ return {
191
+ success: false,
192
+ hostname,
193
+ url,
194
+ status: res.status,
195
+ message: `http://${hostname}/ is reachable but answered with content from a different server. Point port 80 for this name at EmailEngine, or forward /.well-known/acme-challenge/ to it.`
196
+ };
197
+ }
198
+
199
+ return {
200
+ success: true,
201
+ hostname,
202
+ url,
203
+ status: res.status,
204
+ message: `Let's Encrypt can reach this instance at http://${hostname}/`
205
+ };
206
+ }
207
+
208
+ /**
209
+ * The stored record for a name, without ever asking the certificate authority for one.
210
+ *
211
+ * @param {Object} certs @postalsys/certs handler
212
+ * @param {string} hostname Name to look up
213
+ * @returns {Promise<Object|false>} The record, or false when there is none
214
+ */
215
+ async function readStoredRecord(certs, hostname) {
216
+ try {
217
+ return (await certs.getCertificate(hostname, true)) || false;
218
+ } catch (err) {
219
+ return false;
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Orders (or renews) the certificate for one hostname and records what happened.
225
+ *
226
+ * @param {Object} opts
227
+ * @param {Object} opts.certs @postalsys/certs handler
228
+ * @param {Object} opts.logger Worker logger
229
+ * @param {string} opts.hostname Name to provision
230
+ * @param {Object|false} [opts.before] The stored record, when the caller has already read it
231
+ * @returns {Promise<Object>} `{ success, changed, hostname, message }`
232
+ */
233
+ async function provisionHostname(opts) {
234
+ const { certs, logger, hostname } = opts;
235
+
236
+ // Only the fingerprint of it is used, to tell an installed certificate from an unchanged one,
237
+ // and the reconciler has already read the record to decide whether to order at all.
238
+ const before = opts.before !== undefined ? opts.before : await readStoredRecord(certs, hostname);
239
+
240
+ await setProvisioningStatus(logger, hostname, { state: 'ordering', message: `Requesting a certificate for ${hostname}` });
241
+
242
+ let record;
243
+ let failure;
244
+
245
+ try {
246
+ record = await certs.getCertificate(hostname, false);
247
+ } catch (err) {
248
+ failure = err.message;
249
+ logger.error({ msg: 'Failed to provision a TLS certificate', hostname, err });
250
+ }
251
+
252
+ if (record && record.status === 'valid' && record.cert) {
253
+ const changed = !before || before.fingerprint !== record.fingerprint;
254
+
255
+ // A renewal that failed while a usable certificate was already stored comes back as that
256
+ // certificate, still `valid` so the listener keeps serving it, with the reason attached.
257
+ // Reading only the status reported "the certificate is up to date" to an operator whose
258
+ // challenge routing or CA access had broken, and kept saying it on every pass while the
259
+ // certificate walked towards its expiry date.
260
+ //
261
+ // `renewalError` and not `lastError`: the first describes this call, the second describes
262
+ // the record and outlives the failure it names, because acquireCert() answers from the
263
+ // stored record whenever renewal is not due or another worker is already on it.
264
+ const renewError = record.renewalError;
265
+ if (renewError && renewError.err) {
266
+ await setProvisioningStatus(logger, hostname, {
267
+ state: 'renewalFailed',
268
+ attempted: Date.now(),
269
+ // The failure's own time, so a page rendered days later does not read as if the
270
+ // renewal had just been attempted
271
+ failedAt: renewError.time || null,
272
+ fingerprint: record.fingerprint,
273
+ validTo: record.validTo,
274
+ message: `Could not renew the certificate for ${hostname}, still serving the current one: ${renewError.err}`
275
+ });
276
+
277
+ // The material is usable, so `changed` still drives the listener reload - only the
278
+ // reporting says the renewal did not happen
279
+ return { success: false, changed, hostname, message: renewError.err };
280
+ }
281
+
282
+ await setProvisioningStatus(logger, hostname, {
283
+ state: 'valid',
284
+ attempted: Date.now(),
285
+ fingerprint: record.fingerprint,
286
+ validTo: record.validTo,
287
+ message: changed ? `Installed a certificate for ${hostname}` : `The certificate for ${hostname} is up to date`
288
+ });
289
+
290
+ return { success: true, changed, hostname };
291
+ }
292
+
293
+ // acquireCert() answers a blocked or unvalidatable domain by returning what was already
294
+ // stored, which for a first certificate is nothing. The reason it did not say is in the
295
+ // record it wrote, so read it back rather than reporting "failed" and nothing else.
296
+ if (!failure) {
297
+ let stored;
298
+ try {
299
+ stored = await certs.getCertificate(hostname, true);
300
+ } catch (err) {
301
+ stored = false;
302
+ }
303
+
304
+ failure =
305
+ (stored && stored.lastError && stored.lastError.err) ||
306
+ `Could not get a certificate for ${hostname}. Check that the name resolves to this server and that port 80 is reachable.`;
307
+ }
308
+
309
+ await setProvisioningStatus(logger, hostname, { state: 'failed', attempted: Date.now(), message: failure });
310
+
311
+ return { success: false, changed: false, hostname, message: failure };
312
+ }
313
+
314
+ /**
315
+ * Whether any listener would present a certificate to a client right now.
316
+ *
317
+ * A first order is gated on this. A certificate nothing serves is not needed, and ordering one
318
+ * anyway is not harmless: most instances sit behind a reverse proxy that terminates TLS itself,
319
+ * with a public https Service URL and port 80 routed somewhere else, and every one of them would
320
+ * otherwise start an http-01 order on the timer the moment it upgraded, fail it, and go on failing
321
+ * it every retry interval for good - against the CA's failed-validation limit, with an error in
322
+ * the log each time, for a certificate the operator never asked for. The old code had the same
323
+ * gate by construction: the one thing that ordered a first certificate was a listener's TLS
324
+ * checkbox. Renewals are not gated - a certificate that exists is kept valid, as it always was -
325
+ * and neither is the button, which is an explicit request.
326
+ *
327
+ * @param {Object} values Settings, at least LISTENER_TLS_SETTINGS (the API listener is read from
328
+ * the environment, which every process shares)
329
+ * @returns {boolean} True when some listener has TLS switched on
330
+ */
331
+ function listenersServeTls(values) {
332
+ return !!apiTlsConfig() || Object.values(listenerTlsFrom(values)).some(listener => listener.enabled && listener.tlsEnabled);
333
+ }
334
+
335
+ /**
336
+ * Whether a stored record holds a certificate a listener could serve.
337
+ *
338
+ * @param {Object|false} record The stored record
339
+ * @returns {boolean}
340
+ */
341
+ function hasValidCertificate(record) {
342
+ return !!(record && record.cert && record.status === 'valid');
343
+ }
344
+
345
+ /**
346
+ * Decides whether a hostname needs an order right now.
347
+ *
348
+ * @param {Object} opts
349
+ * @param {Object} opts.certs @postalsys/certs handler
350
+ * @param {string} opts.hostname Name to consider
351
+ * @param {Object} opts.status Recorded provisioning state for that name
352
+ * @param {Object|false} [opts.record] The stored record, when the caller has already read it
353
+ * @returns {Promise<boolean>} True when an order should be attempted
354
+ */
355
+ async function needsProvisioning(opts) {
356
+ const { certs, hostname, status } = opts;
357
+
358
+ const attempted = (status && status.attempted) || 0;
359
+
360
+ const record = opts.record !== undefined ? opts.record : await readStoredRecord(certs, hostname);
361
+
362
+ // No certificate at all. The renewal timer used to require an existing record before it would
363
+ // do anything, so a name that had never been provisioned - or whose record was lost with a
364
+ // flushed Redis or a restored backup - was never provisioned by the timer either, and the
365
+ // listener stayed down until somebody clicked the checkbox twice.
366
+ if (!hasValidCertificate(record)) {
367
+ return Date.now() - attempted > TLS_RETRY_AFTER_FAILURE;
368
+ }
369
+
370
+ if (record.lastCheck && record.lastCheck > new Date(Date.now() - BLOCK_TLS_RENEW)) {
371
+ return false;
372
+ }
373
+
374
+ // Asks Let's Encrypt whether the certificate should be replaced yet, through ACME Renewal
375
+ // Information, falling back to a threshold scaled to the lifetime the CA issued. Asking matters
376
+ // because a mass revocation is the one case where the CA needs a certificate replaced long
377
+ // before its own schedule would.
378
+ try {
379
+ return await certs.checkRenewalDue(hostname, record);
380
+ } catch (err) {
381
+ return false;
382
+ }
383
+ }
384
+
385
+ /**
386
+ * Asks for certificates now, from the admin UI's button.
387
+ *
388
+ * The whole vocabulary of provisioning states lives here rather than half of it in a route: a
389
+ * request that the reconciler declines - because automatic certificates are switched off, or
390
+ * because a CA cannot validate the name - has to record why, or the badge reads "Requesting"
391
+ * forever with nothing on the way to replace it.
392
+ *
393
+ * Returns as soon as the work is scheduled. An ACME order takes seconds at best and minutes when
394
+ * the CA is retrying, and the request that asks for one used to be held open for all of it.
395
+ *
396
+ * @param {Object} opts
397
+ * @param {Object} opts.certs @postalsys/certs handler
398
+ * @param {Object} opts.logger Worker logger
399
+ * @param {Function} opts.call Worker call function, for the listener reload
400
+ * @param {string[]} opts.hostnames Names to provision
401
+ * @returns {Promise<Object>} `{ accepted, declined }`
402
+ */
403
+ async function requestProvisioning(opts) {
404
+ const { certs, logger, call, hostnames } = opts;
405
+
406
+ const mode = (await settings.get('tlsProvisioning')) || 'acme';
407
+ const eligible = acmeEligibleHostnames(hostnames);
408
+
409
+ const accepted = [];
410
+ const declined = [];
411
+ // What this call put in flight, which is not the same list as what it reports as accepted: a
412
+ // name another click is already ordering is accepted too, and scheduling it a second time
413
+ // starts a second order that overwrites the running one's state and reports its own failure
414
+ // when the certificate library's per-domain lock times out under it.
415
+ const scheduled = [];
416
+
417
+ for (const hostname of hostnames) {
418
+ let reason = null;
419
+
420
+ if (mode !== 'acme') {
421
+ reason = 'Automatic certificates are switched off for this instance';
422
+ } else if (!eligible.includes(hostname)) {
423
+ reason = `Let's Encrypt can not validate ${hostname}. Automatic certificates need a public domain name.`;
424
+ } else if (inFlight.has(hostname)) {
425
+ // Already ordering. Saying so beats silently starting a second order, and beats
426
+ // overwriting the state the running order is reporting through.
427
+ accepted.push(hostname);
428
+ continue;
429
+ }
430
+
431
+ if (reason) {
432
+ declined.push({ hostname, reason });
433
+ await setProvisioningStatus(logger, hostname, { state: 'skipped', attempted: Date.now(), message: reason });
434
+ continue;
435
+ }
436
+
437
+ accepted.push(hostname);
438
+ scheduled.push(hostname);
439
+ inFlight.add(hostname);
440
+ await setProvisioningStatus(logger, hostname, { state: 'queued', message: 'Waiting to request a certificate' });
441
+ }
442
+
443
+ if (scheduled.length) {
444
+ reconcileCertificates({ certs, logger, call, hostnames: scheduled, force: true })
445
+ .catch(err => logger.error({ msg: 'Certificate provisioning failed', err }))
446
+ .finally(() => {
447
+ // Only the names this call added, so a second click does not release the first
448
+ // click's order and let a third one stack on top of it.
449
+ for (const hostname of scheduled) {
450
+ inFlight.delete(hostname);
451
+ }
452
+ });
453
+ }
454
+
455
+ return { accepted, declined };
456
+ }
457
+
458
+ /**
459
+ * One pass of the reconciler: brings every configured hostname to a valid certificate, and reloads
460
+ * the listeners when anything changed.
461
+ *
462
+ * @param {Object} opts
463
+ * @param {Object} opts.certs @postalsys/certs handler
464
+ * @param {Object} opts.logger Worker logger
465
+ * @param {Function} opts.call Worker call function, for the listener reload
466
+ * @param {string[]} [opts.hostnames] Names to reconcile; defaults to the configured ones
467
+ * @param {boolean} [opts.force] Order even when the recorded state says to wait
468
+ * @returns {Promise<Object>} `{ results, changed }`
469
+ */
470
+ async function reconcileCertificates(opts) {
471
+ const { certs, logger, call, force } = opts;
472
+
473
+ // Everything the pass decides from, in one round of reads: the settings together (the
474
+ // hostname list and the listener switches derive from them), and the recorded state alongside
475
+ // - it serves both the cleanup below and the per-hostname pacing further down.
476
+ const [values, status] = await Promise.all([
477
+ settings.getMulti('tlsProvisioning', 'serviceUrl', 'tlsHostnames', ...LISTENER_TLS_SETTINGS),
478
+ getProvisioningStatus()
479
+ ]);
480
+
481
+ const mode = values.tlsProvisioning || 'acme';
482
+
483
+ const configured = hostnamesFrom(values);
484
+ const targets = opts.hostnames || configured;
485
+ const hostnames = acmeEligibleHostnames(targets);
486
+
487
+ // Whether a name with no certificate gets a first order on this pass; a forced pass is an
488
+ // explicit request and is not asked. See listenersServeTls().
489
+ const wanted = force || listenersServeTls(values);
490
+
491
+ // Derived rather than hooked on the settings form: tlsHostnames, tlsProvisioning and serviceUrl
492
+ // are all writable through the REST API too, and a state record for a name nobody serves any
493
+ // more reads as a broken instance.
494
+ if (!opts.hostnames) {
495
+ for (const hostname of Object.keys(status)) {
496
+ if (!configured.includes(hostname)) {
497
+ await clearProvisioningStatus(hostname);
498
+ }
499
+ }
500
+ }
501
+
502
+ if (mode !== 'acme' || !hostnames.length) {
503
+ return { results: [], changed: false, skipped: mode !== 'acme' ? mode : 'no-eligible-hostname' };
504
+ }
505
+
506
+ const results = [];
507
+ let changed = false;
508
+
509
+ for (const hostname of hostnames) {
510
+ // Read once per name: the renewal decision and the fingerprint comparison that decides
511
+ // whether the listeners have to be reloaded both want the stored record.
512
+ const before = await readStoredRecord(certs, hostname);
513
+
514
+ // A name with no usable certificate is only ordered for while a listener would serve it
515
+ if (!force && !wanted && !hasValidCertificate(before)) {
516
+ continue;
517
+ }
518
+
519
+ if (!force && !(await needsProvisioning({ certs, hostname, status: status[hostname], record: before }))) {
520
+ continue;
521
+ }
522
+
523
+ const result = await provisionHostname({ certs, logger, hostname, before });
524
+ results.push(result);
525
+ changed = changed || result.changed;
526
+
527
+ // The library records its own last-check time on the renewal path; do it here too so a
528
+ // renewal that was skipped or failed does not have the check repeated on the next pass.
529
+ try {
530
+ await certs.setCertificateData(hostname, { lastCheck: new Date() });
531
+ } catch (err) {
532
+ logger.error({ msg: 'Failed to record the certificate check time', hostname, err });
533
+ }
534
+ }
535
+
536
+ if (changed) {
537
+ await reloadTlsCertificates(call, logger, { hostnames });
538
+ }
539
+
540
+ return { results, changed };
541
+ }
542
+
543
+ module.exports = {
544
+ requestProvisioning,
545
+ getProvisioningStatus,
546
+ setProvisioningStatus,
547
+ clearProvisioningStatus,
548
+ armPreflightProbe,
549
+ resolvePreflightProbe,
550
+ runPreflight,
551
+ provisionHostname,
552
+ listenersServeTls,
553
+ needsProvisioning,
554
+ reconcileCertificates
555
+ };