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,480 @@
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 { hostnamesFrom, extraHostnamesFrom, acmeEligibleHostnames, coversHostname, LISTENER_TLS_SETTINGS, listenerTlsFrom } = require('./store');
15
+ const { apiTlsConfig } = require('./context');
16
+ const { getProvisioningStatus } = require('./provision');
17
+ const { worstBy } = require('../utils/severity');
18
+ const { LISTENERS, TLS_CERTIFICATE_SETTINGS, AUTO } = require('./listeners');
19
+ const {
20
+ sourcesFor,
21
+ certificateId,
22
+ parseCertificateId,
23
+ describeEntry,
24
+ isSelectable,
25
+ listCertificates,
26
+ admittedFor,
27
+ resolveDefaultCertificate,
28
+ entryForName,
29
+ listenerView
30
+ } = require('./catalog');
31
+
32
+ // Below this many days left, a certificate is worth pointing at even though it still works.
33
+ const EXPIRY_WARNING_DAYS = 14;
34
+
35
+ // How the recorded message is rendered, which is not always how the certificate is: a failed order
36
+ // sits under a certificate that is still perfectly valid, and a failed renewal under one that is
37
+ // still being served. A declined request ("skipped") is an explanation of why nothing happened,
38
+ // not a failure. Anything not listed is progress, and reads as information.
39
+ const STATUS_VARIANTS = {
40
+ failed: 'error',
41
+ skipped: 'info',
42
+ renewalFailed: 'warning'
43
+ };
44
+
45
+ // The recorded states whose message the page shows as a line under the hostname. A successful
46
+ // order also records a message, but the certificate row already says everything it would.
47
+ const REASON_STATES = new Set(['failed', 'skipped', 'renewalFailed', 'queued', 'ordering']);
48
+
49
+ // The header badge when no listener is serving TLS at all.
50
+ const TLS_OFF_LABEL = { type: 'neutral', text: 'TLS off', title: 'No listener is serving TLS' };
51
+
52
+ const SOURCE_LABELS = {
53
+ env: 'Environment',
54
+ manual: 'Uploaded',
55
+ acme: "Let's Encrypt",
56
+ 'self-signed': 'Self-signed'
57
+ };
58
+
59
+ function daysUntil(date) {
60
+ if (!date) {
61
+ return null;
62
+ }
63
+ return Math.floor((date.getTime() - Date.now()) / (24 * 3600 * 1000));
64
+ }
65
+
66
+ /**
67
+ * A listener's report, with its dates back as dates.
68
+ *
69
+ * @param {Object} report Certificate description from a listener's state payload
70
+ * @returns {Object} The same description, usable by certificateLabel() and publicView()
71
+ */
72
+ function rehydrateReport(report) {
73
+ // The report reaches a page as JSON out of a Redis hash, so every date in it is an ISO string
74
+ return Object.assign({}, report, {
75
+ validFrom: report.validFrom ? new Date(report.validFrom) : null,
76
+ validTo: report.validTo ? new Date(report.validTo) : null
77
+ });
78
+ }
79
+
80
+ /**
81
+ * The countdown text for a certificate inside its warning window. Only reachable for a
82
+ * certificate that has not expired, so the smallest value is today.
83
+ *
84
+ * @param {number} daysRemaining Whole days until expiry, possibly zero
85
+ * @returns {string} Badge text
86
+ */
87
+ function expiryText(daysRemaining) {
88
+ if (daysRemaining <= 0) {
89
+ return 'Expires today';
90
+ }
91
+ return daysRemaining === 1 ? 'Expires in 1 day' : `Expires in ${daysRemaining} days`;
92
+ }
93
+
94
+ /**
95
+ * The badge for one certificate: colour, text and the sentence behind it.
96
+ *
97
+ * Severity follows consequence. Red means an order failed or a listener is serving something
98
+ * clients will reject; a name nothing serves yet is neutral, and a self-signed certificate is a
99
+ * warning only while a listener is actually presenting it. "Missing" is not a state: a listener
100
+ * with TLS on always has the self-signed fallback, so a name without a stored certificate is one
101
+ * nobody has needed a certificate for.
102
+ *
103
+ * @param {Object|false} certificate Resolved certificate, or false when there is none
104
+ * @param {Object} [status] Recorded provisioning state for the hostname
105
+ * @param {Object} [opts]
106
+ * @param {boolean} [opts.served=true] Whether a listener with TLS on is presenting this name
107
+ * @param {boolean} [opts.canRequest=false] Whether asking Let's Encrypt for the name would do anything
108
+ * @returns {Object} `{ type, text, title }`
109
+ */
110
+ function certificateLabel(certificate, status, opts) {
111
+ const served = !opts || opts.served !== false;
112
+ const canRequest = !!(opts && opts.canRequest);
113
+
114
+ // Both states are "an order is happening": the reconciler is asked to run, then it runs. A page
115
+ // rendered between the two used to fall through to whatever the stored certificate said.
116
+ if (status && (status.state === 'ordering' || status.state === 'queued')) {
117
+ return { type: 'info', text: 'Requesting', title: status.message || 'Requesting a certificate' };
118
+ }
119
+
120
+ if (!certificate) {
121
+ if (status && status.state === 'failed') {
122
+ return { type: 'error', text: 'Failed', title: status.message || 'Could not get a certificate' };
123
+ }
124
+ if (canRequest) {
125
+ return { type: 'neutral', text: 'Not requested', title: 'No certificate has been requested for this name yet' };
126
+ }
127
+ return {
128
+ type: 'neutral',
129
+ text: 'Self-signed',
130
+ title: 'A self-signed certificate is generated for this name the first time a listener needs one'
131
+ };
132
+ }
133
+
134
+ const now = Date.now();
135
+
136
+ if (certificate.validFrom && certificate.validFrom.getTime() > now) {
137
+ return { type: 'warning', text: 'Not yet valid', title: `Valid from ${certificate.validFrom.toISOString()}` };
138
+ }
139
+
140
+ if (certificate.validTo && certificate.validTo.getTime() < now) {
141
+ return { type: 'error', text: 'Expired', title: `Expired on ${certificate.validTo.toISOString()}` };
142
+ }
143
+
144
+ // A renewal that failed while the current certificate is still usable. The certificate itself
145
+ // is fine, so every check below would call it Valid and the operator would never learn that it
146
+ // has stopped being renewed - which is the whole failure mode: the badge stays green until the
147
+ // day the certificate expires.
148
+ if (status && status.state === 'renewalFailed') {
149
+ return { type: 'warning', text: 'Renewal failed', title: status.message || 'The last renewal attempt failed' };
150
+ }
151
+
152
+ if (certificate.source === 'self-signed') {
153
+ if (!served) {
154
+ return { type: 'neutral', text: 'Self-signed', title: 'Generated on this instance. Clients can not verify it, and no listener is serving it yet.' };
155
+ }
156
+ return {
157
+ type: 'warning',
158
+ text: 'Self-signed',
159
+ title: 'Clients can not verify this certificate. Pin its fingerprint or install a real one.'
160
+ };
161
+ }
162
+
163
+ const daysRemaining = daysUntil(certificate.validTo);
164
+
165
+ if (daysRemaining !== null && daysRemaining <= EXPIRY_WARNING_DAYS) {
166
+ return { type: 'warning', text: expiryText(daysRemaining), title: `Expires on ${certificate.validTo.toISOString()}` };
167
+ }
168
+
169
+ if (certificate.source === 'env') {
170
+ return { type: 'info', text: 'From environment', title: 'Supplied through the TLS environment variables or the config file' };
171
+ }
172
+
173
+ return { type: 'success', text: 'Valid', title: certificate.fingerprint || 'Valid certificate' };
174
+ }
175
+
176
+ /**
177
+ * Strips the private key and normalizes what the views render.
178
+ *
179
+ * @param {Object|false} certificate Resolved certificate
180
+ * @returns {Object|false} View-safe copy
181
+ */
182
+ function publicView(certificate) {
183
+ if (!certificate) {
184
+ return false;
185
+ }
186
+
187
+ const words = describeEntry(certificate);
188
+
189
+ return {
190
+ // The id the listeners' settings refer to it by, and the words the page lists it under
191
+ id: certificateId(certificate),
192
+ label: words.label,
193
+ detail: words.detail,
194
+ source: certificate.source,
195
+ // The one-word source, for a sentence that says what kind of certificate a name has
196
+ sourceLabel: SOURCE_LABELS[certificate.source] || certificate.source,
197
+ subject: certificate.subject,
198
+ issuer: certificate.issuer,
199
+ serialNumber: certificate.serialNumber,
200
+ fingerprint: certificate.fingerprint,
201
+ fingerprint256: certificate.fingerprint256,
202
+ altNames: certificate.altNames || [],
203
+ validFrom: certificate.validFrom,
204
+ validTo: certificate.validTo,
205
+ // ISO strings as well as the dates: handlebars has no date formatter, and the page
206
+ // localizes these client-side from the machine-readable form (the .local-time and
207
+ // .relative-time handlers in static/js/app.js).
208
+ validFromIso: certificate.validFrom ? certificate.validFrom.toISOString() : null,
209
+ validToIso: certificate.validTo ? certificate.validTo.toISOString() : null,
210
+ selfSigned: !!certificate.selfSigned,
211
+ chainLength: 1 + [].concat(certificate.ca || []).length
212
+ };
213
+ }
214
+
215
+ /**
216
+ * The certificate summary the SMTP and IMAP proxy pages show next to their own TLS checkbox.
217
+ *
218
+ * It takes the provisioning state as well as the certificate, because those pages read a listener's
219
+ * own report rather than the stored model: without the state they could only ever say "Valid",
220
+ * including while a renewal had been failing for weeks.
221
+ *
222
+ * @param {Object} opts
223
+ * @param {Object|null} opts.reported Certificate description from the listener's state payload
224
+ * @param {string|null} opts.hostname Name clients connect to
225
+ * @param {Object} [opts.status] Recorded provisioning state for that name
226
+ * @returns {Object} `{ hostname, certificate, label }`; the last two are null when the listener has
227
+ * reported nothing, so a caller has one shape to render either way
228
+ */
229
+ function listenerCertificateSummary(opts) {
230
+ const { reported, hostname, status } = opts || {};
231
+
232
+ if (!reported) {
233
+ return { hostname: hostname || null, certificate: null, label: null };
234
+ }
235
+
236
+ const certificate = rehydrateReport(reported);
237
+
238
+ // A listener that reported a certificate is presenting it, so the label reads as served
239
+ return { hostname: hostname || null, certificate: publicView(certificate), label: certificateLabel(certificate, status || null, { served: true }) };
240
+ }
241
+
242
+ /**
243
+ * One badge for several: the worst of the labels given, or the "TLS off" label when there are none.
244
+ * The page header wears it, so the tab an operator lands on agrees with the tiles under it.
245
+ *
246
+ * @param {Array<Object|null>} labels Labels from certificateLabel(); empty entries are skipped
247
+ * @returns {Object} `{ type, text, title }`
248
+ */
249
+ function summarizeLabels(labels) {
250
+ const present = [].concat(labels || []).filter(label => label && label.type);
251
+
252
+ if (!present.length) {
253
+ return TLS_OFF_LABEL;
254
+ }
255
+
256
+ return worstBy(present, label => label.type);
257
+ }
258
+
259
+ /**
260
+ * Whether asking for a certificate is the thing to do for a name: it could be ordered, and what it
261
+ * has now is nothing, the fallback, or a certificate in trouble. A valid one is left alone (the
262
+ * reconciler renews it), and so is one already being ordered.
263
+ *
264
+ * @param {Object} entry `{ canRequest, certificate, label, status }`, the certificate unwrapped
265
+ * @returns {boolean}
266
+ */
267
+ function wantsCertificate(entry) {
268
+ if (!entry.canRequest) {
269
+ return false;
270
+ }
271
+ if (entry.status && (entry.status.state === 'ordering' || entry.status.state === 'queued')) {
272
+ return false;
273
+ }
274
+ if (!entry.certificate || entry.certificate.source === 'self-signed') {
275
+ return true;
276
+ }
277
+ return entry.label.type === 'error' || entry.label.type === 'warning';
278
+ }
279
+
280
+ /**
281
+ * Builds the whole certificate model: what is configured, what answers each name, every
282
+ * certificate the instance holds, which of them each listener presents by default, and what the
283
+ * last provisioning attempt did.
284
+ *
285
+ * @param {Object} opts
286
+ * @param {Object} opts.certs @postalsys/certs handler
287
+ * @param {boolean|Promise<boolean>} [opts.served] Whether some listener with TLS on is presenting
288
+ * certificates to clients at all. A promise is
289
+ * accepted, so a page reading the listeners can do
290
+ * it alongside this
291
+ * @returns {Promise<Object>} The model
292
+ */
293
+ async function buildCertificateStatus(opts) {
294
+ const { certs } = opts || {};
295
+
296
+ // Everything the model needs, in one round of reads. The hostname list is derived from
297
+ // settings this already has, so it costs no second lookup; the catalog is peeked, not
298
+ // loaded, since nothing here serves it.
299
+ const [values, provisioning, served] = await Promise.all([
300
+ settings.getMulti('serviceUrl', 'tlsProvisioning', 'tlsHostnames', ...TLS_CERTIFICATE_SETTINGS, ...LISTENER_TLS_SETTINGS),
301
+ getProvisioningStatus(),
302
+ (opts && opts.served) || false
303
+ ]);
304
+
305
+ const mode = values.tlsProvisioning || 'acme';
306
+ const hostnames = hostnamesFrom(values);
307
+ const eligible = acmeEligibleHostnames(hostnames);
308
+ const sources = sourcesFor(mode);
309
+
310
+ const catalog = await listCertificates({ certs, hostnames });
311
+ const selfSigned = catalog.find(entry => entry.source === 'self-signed');
312
+
313
+ // What a name has before any listener's own material or default is applied: the stored
314
+ // sources, then the self-signed fallback for a name nothing else covers. That is the row; a
315
+ // listener that answers differently for the name says so under it.
316
+ const shared = admittedFor(catalog, { listener: null, sources });
317
+ const rowEntry = hostname =>
318
+ shared.find(entry => coversHostname(entry.x509, hostname)) || (selfSigned && coversHostname(selfSigned.x509, hostname) ? selfSigned : null);
319
+
320
+ // Each listener, decided the way the listener decides it
321
+ const switches = listenerTlsFrom(values);
322
+ const apiServesTls = !!apiTlsConfig();
323
+
324
+ const views = LISTENERS.map(listener => {
325
+ const view = listenerView({ catalog, hostnames, sources, listener: listener.key, requested: values[listener.settingKey] });
326
+ const settingsFor = listener.key === 'api' ? { enabled: true, tlsEnabled: apiServesTls } : switches[listener.key];
327
+ return Object.assign({ listener, tlsOn: !!(settingsFor.enabled && settingsFor.tlsEnabled), settingsFor }, view);
328
+ });
329
+
330
+ // The names this page adds and removes. Whatever is configured and not among them is the
331
+ // Service URL's own name, which is set on the General page.
332
+ const extraHostnames = extraHostnamesFrom(values);
333
+
334
+ const certificates = hostnames.map(hostname => {
335
+ const entry = rowEntry(hostname);
336
+ const certificate = entry ? entry.material : false;
337
+ const status = provisioning[hostname] || null;
338
+ const acmeEligible = eligible.includes(hostname);
339
+ // Whether asking for a certificate now would do anything at all
340
+ const canRequest = mode === 'acme' && acmeEligible;
341
+ const label = certificateLabel(certificate, status, { served, canRequest });
342
+
343
+ // The listeners with TLS on that answer this name with something other than the row's
344
+ // certificate: their own environment material, or a chosen default that covers the name.
345
+ // Said here, on the row, rather than left for the operator to derive from three tables.
346
+ const servedBy = views
347
+ .filter(view => view.tlsOn)
348
+ .map(view => ({ view, answer: entryForName(hostname, view) }))
349
+ .filter(({ answer }) => answer && answer !== entry)
350
+ .map(({ view, answer }) => ({ key: view.listener.key, name: view.listener.name, label: answer.label }));
351
+
352
+ return {
353
+ hostname,
354
+ isServiceHostname: !extraHostnames.includes(hostname),
355
+ acmeEligible,
356
+ canRequest,
357
+ wanted: wantsCertificate({ canRequest, status, certificate, label }),
358
+ certificate: publicView(certificate),
359
+ label,
360
+ status,
361
+ servedBy,
362
+ // The one line the page shows under the name: why the last order failed, why a request
363
+ // was declined, or that one is under way. The page script paints the same states from
364
+ // the change feed, so its table (views/config/tls.hbs) mirrors STATUS_VARIANTS.
365
+ reason:
366
+ status && REASON_STATES.has(status.state) && status.message
367
+ ? { variant: STATUS_VARIANTS[status.state] || 'info', message: status.message }
368
+ : null
369
+ };
370
+ });
371
+
372
+ // Every certificate the instance holds, with the listeners that present it by default. The
373
+ // self-signed entry is listed generated or not: it is a choice a listener can be given.
374
+ const catalogView = catalog.map(entry => {
375
+ const usedBy = views
376
+ .filter(view => view.fallback === entry)
377
+ .map(view => ({
378
+ key: view.listener.key,
379
+ // A chosen default is the listener's name; an automatic one says so
380
+ label: view.selection === 'selected' ? view.listener.name : `${view.listener.name} (automatic)`
381
+ }));
382
+
383
+ return {
384
+ id: entry.id,
385
+ source: entry.source,
386
+ hostname: entry.hostname || null,
387
+ label: entry.label,
388
+ detail: entry.detail,
389
+ certificate: publicView(entry.material),
390
+ // The badge follows the certificate itself; a certificate no listener presents is
391
+ // not "served", whatever the listeners report
392
+ status: certificateLabel(entry.material, null, { served: served && usedBy.length > 0, canRequest: false }),
393
+ usedBy
394
+ };
395
+ });
396
+
397
+ // One entry per listener: what it presents, how that came to be, and the dropdown to change
398
+ // it - the automatic choice named for what it currently amounts to, then every certificate
399
+ // that exists. The dropdown reads "Automatic" for a stored choice that no longer exists, so
400
+ // saving the page as it stands writes the automatic choice the listener already fell back to.
401
+ const listeners = views.map(view => {
402
+ const { listener, settingsFor } = view;
403
+ const auto =
404
+ view.selection === 'selected'
405
+ ? resolveDefaultCertificate({ catalog, entries: view.entries, primary: hostnames[0], listener: listener.key, requested: AUTO }).entry
406
+ : view.fallback;
407
+ const missing = view.selection === 'missing';
408
+ const requestedWords = missing ? describeEntry(parseCertificateId(view.requested) || { source: view.requested }) : null;
409
+
410
+ const options = [{ id: AUTO, label: `Automatic: ${auto ? auto.label : 'Self-signed fallback'}`, selected: view.requested === AUTO || missing }].concat(
411
+ catalog.filter(isSelectable).map(entry => ({
412
+ id: entry.id,
413
+ label: entry.label,
414
+ covers: entry.material ? (entry.material.altNames || []).join(', ') : 'generated on first use',
415
+ selected: view.requested === entry.id
416
+ }))
417
+ );
418
+
419
+ return Object.assign({}, listener, settingsFor, {
420
+ requested: view.requested,
421
+ selection: view.selection,
422
+ // The words for a chosen certificate that is gone, for the warning under the dropdown
423
+ missingLabel: requestedWords ? requestedWords.label : null,
424
+ defaultId: view.fallback ? view.fallback.id : null,
425
+ options
426
+ });
427
+ });
428
+
429
+ return {
430
+ mode,
431
+ serviceUrl: values.serviceUrl || '',
432
+ hostnames,
433
+ certificates,
434
+ served,
435
+ // Whether the page-level "Request certificates" action has anything to do
436
+ anyWanted: certificates.some(entry => entry.wanted),
437
+ // Whether the two stored certificates exist, for the upload link and the regenerate dialog
438
+ manual: catalog.some(entry => entry.source === 'manual'),
439
+ selfSigned: publicView(selfSigned ? selfSigned.material : false),
440
+ catalog: catalogView,
441
+ listeners,
442
+ acme: {
443
+ directoryUrl: ACME_DIRECTORY_URL,
444
+ environment: ACME_ENVIRONMENT,
445
+ // A staging certificate is signed by a root nobody trusts, and the badge would
446
+ // otherwise call it valid.
447
+ staging: /staging/i.test(ACME_DIRECTORY_URL)
448
+ }
449
+ };
450
+ }
451
+
452
+ /**
453
+ * What a listener reports serving, from its recorded state - and only while it is listening.
454
+ *
455
+ * The state record keeps the payload of the last transition that carried one, and the exit, spawn
456
+ * and initialize transitions carry none, so a listener that died went on reporting the certificate
457
+ * it served before it did, for as long as the respawn backoff took. A report is what turns every
458
+ * self-signed row on the certificates page into a warning, so a crashed listener painted a state no
459
+ * listener was in.
460
+ *
461
+ * @param {Object} [serverState] `{ state, payload }` from getServerStatus()
462
+ * @returns {Object|null} The reported certificate, or null when nothing is being served
463
+ */
464
+ function reportedListenerTls(serverState) {
465
+ if (!serverState || serverState.state !== 'listening') {
466
+ return null;
467
+ }
468
+ return (serverState.payload && serverState.payload.tls) || null;
469
+ }
470
+
471
+ module.exports = {
472
+ buildCertificateStatus,
473
+ certificateLabel,
474
+ summarizeLabels,
475
+ listenerCertificateSummary,
476
+ reportedListenerTls,
477
+ publicView,
478
+ rehydrateReport,
479
+ SOURCE_LABELS
480
+ };