emailengine-app 2.80.0 → 2.81.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 (178) hide show
  1. package/.dockerignore +44 -0
  2. package/.github/docker-smoke-test.sh +16 -0
  3. package/.github/workflows/deploy.yml +4 -0
  4. package/.github/workflows/release.yaml +4 -0
  5. package/.github/workflows/test.yml +2 -0
  6. package/.release-please-manifest.json +1 -1
  7. package/CHANGELOG.md +56 -0
  8. package/Dockerfile +17 -9
  9. package/README.md +6 -0
  10. package/data/google-crawlers.json +1 -1
  11. package/docker-compose.yml +7 -1
  12. package/lib/api-routes/account-routes.js +239 -73
  13. package/lib/api-routes/blocklist-routes.js +24 -0
  14. package/lib/api-routes/delivery-test-routes.js +6 -0
  15. package/lib/api-routes/gateway-routes.js +30 -0
  16. package/lib/api-routes/license-routes.js +10 -0
  17. package/lib/api-routes/mcp-oauth-routes.js +3 -3
  18. package/lib/api-routes/mcp-routes.js +39 -21
  19. package/lib/api-routes/oauth2-app-routes.js +38 -1
  20. package/lib/api-routes/outbox-routes.js +6 -0
  21. package/lib/api-routes/permission-map.js +212 -42
  22. package/lib/api-routes/pubsub-routes.js +8 -0
  23. package/lib/api-routes/route-helpers.js +58 -11
  24. package/lib/api-routes/settings-routes.js +50 -4
  25. package/lib/api-routes/stats-routes.js +6 -0
  26. package/lib/api-routes/template-routes.js +21 -0
  27. package/lib/api-routes/token-routes.js +34 -2
  28. package/lib/api-routes/webhook-route-routes.js +13 -0
  29. package/lib/autodetect-imap-settings.js +4 -4
  30. package/lib/email-client/base-client.js +6 -3
  31. package/lib/email-client/credential-errors.js +4 -0
  32. package/lib/email-client/imap/login-failure.js +52 -0
  33. package/lib/email-client/imap/subconnection.js +2 -1
  34. package/lib/email-client/imap-client.js +3 -6
  35. package/lib/enum-descriptions.js +12 -2
  36. package/lib/imapproxy/imap-server.js +1 -1
  37. package/lib/mcp/oauth.js +46 -8
  38. package/lib/mcp/protocol.js +78 -35
  39. package/lib/mcp/tools.js +53 -17
  40. package/lib/privileged-settings.js +147 -0
  41. package/lib/schemas.js +60 -16
  42. package/lib/sentry.js +13 -2
  43. package/lib/settings.js +13 -0
  44. package/lib/tls/catalog.js +428 -0
  45. package/lib/tls/context.js +87 -161
  46. package/lib/tls/listeners.js +62 -0
  47. package/lib/tls/provision.js +1 -1
  48. package/lib/tls/status.js +128 -79
  49. package/lib/tls/store.js +3 -2
  50. package/lib/token-permission-view.js +253 -102
  51. package/lib/token-permissions.js +176 -26
  52. package/lib/tokens.js +7 -6
  53. package/lib/tools.js +5 -3
  54. package/lib/ui-routes/account-routes.js +195 -61
  55. package/lib/ui-routes/admin-config-routes.js +41 -21
  56. package/lib/ui-routes/admin-entities-routes.js +32 -22
  57. package/lib/ui-routes/mcp-consent-routes.js +72 -31
  58. package/lib/ui-routes/tls-config-routes.js +121 -74
  59. package/package.json +16 -16
  60. package/sbom.json +1 -1
  61. package/server.js +7 -1
  62. package/static/css/flyonui.css +1 -1
  63. package/static/css/public.css +41 -0
  64. package/static/css/src/app.tailwind.css +135 -4
  65. package/static/js/public.js +218 -0
  66. package/static/js/ui.js +89 -36
  67. package/static/licenses.html +55 -37
  68. package/translations/README.md +4 -3
  69. package/translations/de.mo +0 -0
  70. package/translations/de.po +296 -185
  71. package/translations/en.po +220 -128
  72. package/translations/es.mo +0 -0
  73. package/translations/es.po +558 -0
  74. package/translations/et.mo +0 -0
  75. package/translations/et.po +288 -181
  76. package/translations/fr.mo +0 -0
  77. package/translations/fr.po +295 -183
  78. package/translations/it.mo +0 -0
  79. package/translations/it.po +558 -0
  80. package/translations/ja.mo +0 -0
  81. package/translations/ja.po +268 -192
  82. package/translations/locales.json +24 -0
  83. package/translations/messages.pot +179 -127
  84. package/translations/nl.mo +0 -0
  85. package/translations/nl.po +288 -175
  86. package/translations/pl.mo +0 -0
  87. package/translations/pl.po +294 -181
  88. package/translations/sv.mo +0 -0
  89. package/translations/sv.po +555 -0
  90. package/translations/tr.mo +0 -0
  91. package/translations/tr.po +555 -0
  92. package/update-info.sh +12 -6
  93. package/views/account/login-redirect.hbs +6 -5
  94. package/views/account/passkeys.hbs +8 -8
  95. package/views/account/security.hbs +2 -2
  96. package/views/accounts/account.hbs +19 -21
  97. package/views/accounts/browse.hbs +1 -1
  98. package/views/accounts/edit.hbs +15 -15
  99. package/views/accounts/index.hbs +3 -3
  100. package/views/accounts/register/imap-server.hbs +27 -173
  101. package/views/accounts/register/validating.hbs +139 -0
  102. package/views/config/ai.hbs +15 -17
  103. package/views/config/branding.hbs +7 -7
  104. package/views/config/document-store/chat.hbs +9 -8
  105. package/views/config/document-store/index.hbs +14 -15
  106. package/views/config/document-store/mappings/index.hbs +5 -6
  107. package/views/config/document-store/mappings/new.hbs +1 -2
  108. package/views/config/document-store/pre-processing/index.hbs +4 -4
  109. package/views/config/email-processing.hbs +6 -6
  110. package/views/config/imap-proxy.hbs +7 -8
  111. package/views/config/license.hbs +9 -9
  112. package/views/config/logging.hbs +5 -7
  113. package/views/config/mcp.hbs +90 -58
  114. package/views/config/network.hbs +4 -4
  115. package/views/config/oauth/app.hbs +12 -12
  116. package/views/config/oauth/index.hbs +6 -6
  117. package/views/config/oauth/subscriptions.hbs +9 -9
  118. package/views/config/security.hbs +5 -7
  119. package/views/config/service.hbs +11 -10
  120. package/views/config/smtp.hbs +9 -12
  121. package/views/config/tls-upload.hbs +3 -3
  122. package/views/config/tls.hbs +281 -182
  123. package/views/config/webhooks.hbs +12 -15
  124. package/views/dashboard.hbs +9 -8
  125. package/views/gateways/edit.hbs +3 -3
  126. package/views/gateways/gateway.hbs +3 -3
  127. package/views/gateways/index.hbs +6 -6
  128. package/views/gateways/new.hbs +3 -3
  129. package/views/internals/index.hbs +15 -13
  130. package/views/layout/app.hbs +6 -6
  131. package/views/layout/login.hbs +32 -19
  132. package/views/layout/main.hbs +2 -2
  133. package/views/layout/prompt.hbs +15 -18
  134. package/views/layout/public.hbs +1 -1
  135. package/views/mcp/authorize.hbs +47 -45
  136. package/views/partials/accounts_table.hbs +5 -5
  137. package/views/partials/ace_assets.hbs +1 -1
  138. package/views/partials/add_account_modal.hbs +4 -4
  139. package/views/partials/address_list.hbs +4 -4
  140. package/views/partials/filter_editor_js.hbs +2 -2
  141. package/views/partials/gateway_form.hbs +5 -5
  142. package/views/partials/gateway_js.hbs +1 -1
  143. package/views/partials/mcp_access_levels.hbs +16 -9
  144. package/views/partials/mcp_account_limit.hbs +2 -2
  145. package/views/partials/mcp_tool_count.hbs +15 -14
  146. package/views/partials/oauth_config_header.hbs +2 -2
  147. package/views/partials/oauth_form.hbs +37 -42
  148. package/views/partials/public_alerts.hbs +1 -1
  149. package/views/partials/public_test_labels.hbs +15 -0
  150. package/views/partials/public_theme_init.hbs +1 -1
  151. package/views/partials/security_header.hbs +2 -2
  152. package/views/partials/template_form.hbs +4 -4
  153. package/views/partials/theme_init.hbs +1 -1
  154. package/views/partials/tls_security_card.hbs +4 -1
  155. package/views/partials/ui/form-field.hbs +6 -1
  156. package/views/partials/ui/setting-ref.hbs +12 -7
  157. package/views/partials/ui/stat-card.hbs +4 -1
  158. package/views/partials/ui/tabs.hbs +3 -7
  159. package/views/partials/webhook_form.hbs +9 -12
  160. package/views/partials/webhooks_editor_functions.hbs +1 -1
  161. package/views/reference/index.hbs +3 -3
  162. package/views/reference/redirect.hbs +1 -1
  163. package/views/reference/tag.hbs +1 -1
  164. package/views/reference/token.hbs +4 -4
  165. package/views/suppression-lists/index.hbs +8 -6
  166. package/views/suppression-lists/list.hbs +13 -8
  167. package/views/templates/edit.hbs +1 -1
  168. package/views/templates/index.hbs +10 -11
  169. package/views/templates/template.hbs +5 -5
  170. package/views/tokens/index.hbs +17 -17
  171. package/views/tokens/new.hbs +190 -93
  172. package/views/unsubscribe.hbs +1 -1
  173. package/views/webhooks/edit.hbs +1 -1
  174. package/views/webhooks/index.hbs +10 -11
  175. package/views/webhooks/new.hbs +1 -1
  176. package/views/webhooks/webhook.hbs +5 -6
  177. package/workers/api.js +9 -8
  178. package/workers/smtp.js +1 -1
package/lib/schemas.js CHANGED
@@ -1,6 +1,21 @@
1
1
  'use strict';
2
2
 
3
3
  const net = require('net');
4
+ const { LISTENERS: TLS_LISTENERS, CERTIFICATE_ID_PATTERN: TLS_CERTIFICATE_ID_PATTERN } = require('./tls/listeners');
5
+
6
+ // The certificate a listener presents by default, as a setting per listener (lib/tls/listeners.js
7
+ // names the keys, lib/tls/catalog.js decides from the value)
8
+ const tlsCertificateChoice = listener =>
9
+ Joi.string()
10
+ .empty('')
11
+ .allow(null)
12
+ .pattern(TLS_CERTIFICATE_ID_PATTERN)
13
+ .max(262)
14
+ .example('auto')
15
+ .description(
16
+ `The certificate the ${listener.name} presents by default (to a client that names no host, and for every name the certificate covers). "auto" lets EmailEngine decide: the material from ${listener.envPrefix}* when it is set, otherwise the certificate for the Service URL hostname. Otherwise an id from the TLS Certificates page: "manual", "self-signed", "acme:<hostname>", or "env:api" / "env:smtp" / "env:imapProxy". A name the default does not cover is still served its own certificate`
17
+ )
18
+ .label('TlsCertificateChoice');
4
19
  const Joi = require('joi');
5
20
  const config = require('@zone-eu/wild-config');
6
21
  const { getByteSize } = require('./tools');
@@ -77,7 +92,7 @@ const ACCOUNT_DISPLAY_STATES = [...Object.values(ACCOUNT_STATES), 'disconnected'
77
92
 
78
93
  const { ADDRESS_STRATEGIES } = require('./address-strategies');
79
94
  const { ENUM_DESCRIPTIONS } = require('./enum-descriptions');
80
- const { ACTION, GRANTABLE_GROUPS } = require('./api-routes/permission-map');
95
+ const { ACTION, GRANTABLE_GROUPS, IMPLICIT_GROUPS } = require('./api-routes/permission-map');
81
96
  const { FIELD_USAGE } = require('./field-usage');
82
97
 
83
98
  // Account identity as the API describes it. These live here rather than next to the routes that use
@@ -515,6 +530,8 @@ const settingsSchema = {
515
530
  )
516
531
  .label('TlsHostnames'),
517
532
 
533
+ ...Object.fromEntries(TLS_LISTENERS.map(listener => [listener.settingKey, tlsCertificateChoice(listener)])),
534
+
518
535
  /* ────────────── IMAP Proxy ────────────── */
519
536
 
520
537
  imapProxyServerEnabled: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').description('Enable the IMAP proxy server'),
@@ -2170,14 +2187,22 @@ const tokenRestrictionsSchema = Joi.object({
2170
2187
  // than accepting one and denying every request it makes. The request-time deny in
2171
2188
  // lib/token-permissions.js stays regardless - it has to, because tokens.setRawData() writes a record
2172
2189
  // with no schema at all.
2190
+ // One instance of each value schema, referenced from both the axis lists and the pair entries: the
2191
+ // OpenAPI generator names components after labels, and two schema objects carrying the same label
2192
+ // come out numbered.
2193
+ const tokenActionSchema = Joi.string()
2194
+ .valid(...Object.values(ACTION))
2195
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenAction })
2196
+ .label('TokenAction');
2197
+
2198
+ const tokenGroupSchema = Joi.string()
2199
+ .valid(...GRANTABLE_GROUPS)
2200
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenGroup })
2201
+ .label('TokenGroup');
2202
+
2173
2203
  const tokenPermissionsSchema = Joi.object({
2174
2204
  actions: Joi.array()
2175
- .items(
2176
- Joi.string()
2177
- .valid(...Object.values(ACTION))
2178
- .meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenAction })
2179
- .label('TokenAction')
2180
- )
2205
+ .items(tokenActionSchema)
2181
2206
  .single()
2182
2207
  .min(1)
2183
2208
  .example(['read', 'write'])
@@ -2185,25 +2210,44 @@ const tokenPermissionsSchema = Joi.object({
2185
2210
  .label('TokenActions'),
2186
2211
 
2187
2212
  groups: Joi.array()
2188
- .items(
2189
- Joi.string()
2190
- .valid(...GRANTABLE_GROUPS)
2191
- .meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenGroup })
2192
- .label('TokenGroup')
2193
- )
2213
+ .items(tokenGroupSchema)
2194
2214
  .single()
2195
2215
  .min(1)
2196
2216
  .example(['message', 'mailbox'])
2197
- .description('Which parts of the API this token may reach. Omit to allow all of them')
2198
- .label('TokenGroups')
2217
+ .description(
2218
+ `Which parts of the API this token may reach. Omitted, the token reaches every section except the instance sections (${GRANTABLE_GROUPS.filter(
2219
+ group => !IMPLICIT_GROUPS.includes(group)
2220
+ )
2221
+ .map(group => `\`${group}\``)
2222
+ .join(', ')}), which have to be named`
2223
+ )
2224
+ .label('TokenGroups'),
2225
+
2226
+ grants: Joi.array()
2227
+ .items(
2228
+ Joi.object({
2229
+ action: tokenActionSchema.required(),
2230
+ group: tokenGroupSchema.required()
2231
+ }).label('TokenGrant')
2232
+ )
2233
+ .min(1)
2234
+ .example([
2235
+ { action: 'read', group: 'message' },
2236
+ { action: 'write', group: 'template' }
2237
+ ])
2238
+ .description(
2239
+ 'Exact (action, group) pairs this token may perform, for a narrowing the two axes cannot express, such as reading one section while changing another. Stands alone: a record that sets `grants` may not set `actions` or `groups`'
2240
+ )
2241
+ .label('TokenGrants')
2199
2242
  })
2243
+ .without('grants', ['actions', 'groups'])
2200
2244
  .min(1)
2201
2245
  .empty(Joi.valid('', false))
2202
2246
  .allow(null)
2203
2247
  .example({ actions: ['read'], groups: ['message', 'mailbox'] })
2204
2248
  .label('TokenPermissions')
2205
2249
  .description(
2206
- 'Restricts a token below its scope. Each axis is an allowlist that only narrows, and both apply together, so an operation must match the actions AND the groups. Endpoints that hand out credentials or change instance configuration can never be reached by a token that sets this field, whatever it lists'
2250
+ 'Restricts a token below its scope. Written either as two axes, `actions` and `groups`, which are allowlists that apply together so an operation must match both, or as `grants`, a list of exact (action, group) pairs. Endpoints that hand out credentials can never be reached by a token that sets this field, whatever it lists'
2207
2251
  );
2208
2252
 
2209
2253
  const ipSchema = Joi.string()
package/lib/sentry.js CHANGED
@@ -12,6 +12,17 @@ let Sentry;
12
12
  let workerName;
13
13
  let activeDsn = false;
14
14
 
15
+ // Sentry only orders a project's releases by semver when the version carries a package prefix:
16
+ // Release.is_semver_version() refuses anything without an "@", and the server then falls back to
17
+ // ordering by the date each version was first seen. EmailEngine reported a bare "2.79.6", so an
18
+ // instance that met 2.79.8 before 2.79.6 sorted the older release as the newer one, and
19
+ // "resolve in release" reopened the issue it had just closed.
20
+ //
21
+ // The prefix is the npm package name, not the "@postalsys/emailengine-app" licence identifier
22
+ // used elsewhere: Relay rejects a scoped name outright ("bad characters in release name"), which
23
+ // would leave the release unparseable rather than merely unordered.
24
+ const SENTRY_RELEASE = `${packageData.name}@${packageData.version}`;
25
+
15
26
  // Sentry's own transport speaks Node http/https and knows only the http_proxy environment
16
27
  // variables (HTTP proxies, no SOCKS), so a proxy configured in EmailEngine would not cover error
17
28
  // reports. Deliveries go through the shared dispatcher instead, read at send time so a proxy
@@ -50,7 +61,7 @@ function startSentry(dsn) {
50
61
 
51
62
  Sentry.init({
52
63
  dsn,
53
- release: packageData.version,
64
+ release: SENTRY_RELEASE,
54
65
  transport: makeTransport,
55
66
  // Error capture only: skip the OpenTelemetry setup and the default
56
67
  // integrations that patch http/fetch/console on hot paths. Sentry's own
@@ -176,4 +187,4 @@ function initSentry(worker) {
176
187
  setImmediate(checkSettings);
177
188
  }
178
189
 
179
- module.exports = { initSentry, makeTransport };
190
+ module.exports = { initSentry, makeTransport, SENTRY_RELEASE };
package/lib/settings.js CHANGED
@@ -7,6 +7,7 @@ const config = require('@zone-eu/wild-config');
7
7
  const getSecret = require('./get-secret');
8
8
 
9
9
  const { DEFAULT_MAX_LOG_LINES, REDIS_PREFIX } = require('./consts');
10
+ const { PRIVILEGED_SETTINGS_KEYS } = require('./privileged-settings');
10
11
 
11
12
  config.service = config.service || {};
12
13
 
@@ -40,6 +41,15 @@ const CREDENTIAL_BEARING_KEYS = ['webhooks', 'webhooksCustomHeaders', 'proxyUrl'
40
41
 
41
42
  const ENCRYPTED_KEYS = SECRET_KEYS.concat(CREDENTIAL_BEARING_KEYS);
42
43
 
44
+ // Settings a narrowed access token may not read or write, whatever its record grants. `write/settings` is
45
+ // a grantable permission, and most of the settings blob is what it says: webhook targets,
46
+ // notification shaping, sync strategy, listener ports. These keys are different in kind - each one
47
+ // would make the holder more than a settings editor - so assertNoPrivilegedSettings() in
48
+ // lib/api-routes/route-helpers.js refuses them to a restricted credential, and the MCP settings
49
+ // tool never offers them. An unnarrowed API token is unaffected, as it is for `proxy`.
50
+ //
51
+ // Listed beside SECRET_KEYS because the three lists are read together: a key that is a secret is
52
+ // privileged, but the privileged list is wider than the secrets.
43
53
  // getValue() runs on an uncached read path - settings.get() is called several times per synced
44
54
  // message and once per webhook delivery - and a decrypt/parse failure is permanent rather than
45
55
  // transient (a rotated EENGINE_SECRET, a corrupt stored value). Reporting every occurrence would
@@ -56,6 +66,9 @@ module.exports = {
56
66
  // masked, so a consumer that hides values has to read this list, not encryptedKeys.
57
67
  secretKeys: SECRET_KEYS,
58
68
 
69
+ // What a narrowed token may never read or write, see lib/privileged-settings.js
70
+ privilegedKeys: PRIVILEGED_SETTINGS_KEYS,
71
+
59
72
  /**
60
73
  * Whether admin authentication is configured for this instance.
61
74
  *
@@ -0,0 +1,428 @@
1
+ 'use strict';
2
+
3
+ // Every certificate this instance could present, under one id each (lib/tls/listeners.js), and
4
+ // what each listener makes of the list: the certificate it presents by default, and the one that
5
+ // answers each configured name.
6
+ //
7
+ // Until this module existed, material from EENGINE_SMTP_TLS_* and its siblings was not a
8
+ // certificate at all as far as the rest of the code was concerned: each listener loaded its own,
9
+ // served it ahead of everything else, and the admin page could only describe it second-hand from
10
+ // what the listener reported. It could not be chosen, and nothing else could be chosen over it.
11
+ // Here it is an entry like the uploaded, issued and self-signed ones, and what a listener presents
12
+ // when a client names no host (or a host nothing else covers) is a setting per listener, with the
13
+ // environment material as its automatic choice rather than its only possible one.
14
+ //
15
+ // Nothing here serves anything and nothing here renders anything. lib/tls/context.js turns a
16
+ // listener's view into secure contexts, lib/tls/status.js turns every listener's view into the
17
+ // page, and both get the view from listenerView() below, so they cannot disagree about it.
18
+
19
+ const config = require('@zone-eu/wild-config');
20
+
21
+ const { loadTlsConfig } = require('../tools');
22
+ const {
23
+ parseCertificate,
24
+ coversHostname,
25
+ materialFrom,
26
+ normalizeHostname,
27
+ getManualCertificate,
28
+ peekManualCertificate,
29
+ peekSelfSignedCertificate,
30
+ getAcmeCertificate
31
+ } = require('./store');
32
+ const { LISTENERS, AUTO, MANUAL_ID, SELF_SIGNED_ID, CERTIFICATE_ID_PATTERN, listenerByKey } = require('./listeners');
33
+
34
+ // The `[api.tls]` section as the operator wrote it, taken before the API worker reads its file
35
+ // paths into it and then merges the material it resolved back over it (workers/api.js), which
36
+ // would otherwise put whatever that listener ended up serving on the page as "from the
37
+ // environment". The file paths are read here once; the environment is applied per read below,
38
+ // because a test sets it and because that is cheap.
39
+ const API_TLS_FILE = (() => {
40
+ const section = config.api && config.api.tls && typeof config.api.tls === 'object' ? Object.assign({}, config.api.tls) : {};
41
+ loadTlsConfig(section, 'EENGINE_API_TLS_');
42
+ return section;
43
+ })();
44
+
45
+ // Which stored sources a certificate-source setting admits for a name. The setting is the
46
+ // certificate SOURCE, so it decides what is served and not only whether an order is placed:
47
+ // picking "self-signed only" while a Let's Encrypt certificate was still being served is the
48
+ // class of bug the source rework exists to remove - the UI describing behaviour the code does not
49
+ // have. Material from the environment is admitted by every mode: it is not a source EmailEngine
50
+ // chose. So is a certificate a listener was explicitly told to present.
51
+ const MODE_SOURCES = {
52
+ acme: { manual: true, acme: true },
53
+ manual: { manual: true, acme: false },
54
+ 'self-signed': { manual: false, acme: false }
55
+ };
56
+
57
+ function sourcesFor(mode) {
58
+ return MODE_SOURCES[mode] || MODE_SOURCES.acme;
59
+ }
60
+
61
+ /**
62
+ * The id a piece of material is listed and stored under.
63
+ *
64
+ * @param {Object} material Material from any store, with its `source`
65
+ * @returns {string|null} The id, or null for material that has none (it is not listed)
66
+ */
67
+ function certificateId(material) {
68
+ if (!material) {
69
+ return null;
70
+ }
71
+ switch (material.source) {
72
+ case 'env':
73
+ return material.listener ? `env:${material.listener}` : null;
74
+ case 'manual':
75
+ return MANUAL_ID;
76
+ case 'acme':
77
+ return material.hostname ? `acme:${material.hostname}` : null;
78
+ case 'self-signed':
79
+ return SELF_SIGNED_ID;
80
+ default:
81
+ return null;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Takes an id apart, so a page can name a certificate that is gone.
87
+ *
88
+ * @param {string} id Certificate id
89
+ * @returns {Object|null} `{ source, listener?, hostname? }`, or null when it is not one
90
+ */
91
+ function parseCertificateId(id) {
92
+ const value = (id || '').toString().trim();
93
+ if (!value || value === AUTO || !CERTIFICATE_ID_PATTERN.test(value)) {
94
+ return null;
95
+ }
96
+ if (value === MANUAL_ID) {
97
+ return { source: 'manual' };
98
+ }
99
+ if (value === SELF_SIGNED_ID) {
100
+ return { source: 'self-signed' };
101
+ }
102
+ if (value.startsWith('env:')) {
103
+ return { source: 'env', listener: value.slice(4) };
104
+ }
105
+ return { source: 'acme', hostname: normalizeHostname(value.slice(5)) };
106
+ }
107
+
108
+ /**
109
+ * What a setting holds, folded: nothing and "auto" are the same answer, and so is a value the
110
+ * schema would refuse - a listener does not die on a bad setting, it decides for itself.
111
+ *
112
+ * @param {*} value Stored setting value
113
+ * @returns {string} An id, or "auto"
114
+ */
115
+ function requestedCertificate(value) {
116
+ const id = (value || '').toString().trim();
117
+ return id && id !== AUTO && CERTIFICATE_ID_PATTERN.test(id) ? id : AUTO;
118
+ }
119
+
120
+ /**
121
+ * The material a listener's environment prefix, or the config file, supplies.
122
+ *
123
+ * Read from the shared environment rather than from the listener's own options, so every worker
124
+ * sees the same bytes for every listener - which is what lets one listener be told to present
125
+ * another's certificate, and what lets the page list it.
126
+ *
127
+ * @param {string} key Listener key
128
+ * @param {Object} [logger] Logger for material that is set but does not parse
129
+ * @returns {Object|false} `{ source: 'env', listener, cert, ca, privateKey, passphrase, ...metadata }`
130
+ */
131
+ function envMaterialFor(key, logger) {
132
+ const listener = listenerByKey(key);
133
+ if (!listener) {
134
+ return false;
135
+ }
136
+
137
+ const ref = key === 'api' ? Object.assign({}, API_TLS_FILE) : {};
138
+ loadTlsConfig(ref, listener.envPrefix);
139
+
140
+ if (!ref.cert || !ref.key) {
141
+ return false;
142
+ }
143
+
144
+ const material = materialFrom('env', {
145
+ listener: key,
146
+ cert: ref.cert,
147
+ ca: [].concat(ref.ca || []).filter(entry => entry),
148
+ privateKey: ref.key,
149
+ passphrase: ref.passphrase || undefined
150
+ });
151
+
152
+ // Reported rather than silently dropped, which used to leave the listener quietly serving
153
+ // the fallback instead of what it was configured with
154
+ if (!material && logger) {
155
+ logger.error({ msg: 'The TLS certificate supplied through the environment does not parse', listener: key, prefix: listener.envPrefix });
156
+ }
157
+
158
+ return material;
159
+ }
160
+
161
+ /**
162
+ * The words a certificate is listed under.
163
+ *
164
+ * @param {Object} entry `{ source, listener?, hostname? }`
165
+ * @returns {{ label: string, detail: (string|null) }}
166
+ */
167
+ function describeEntry(entry) {
168
+ switch (entry.source) {
169
+ case 'env': {
170
+ const listener = listenerByKey(entry.listener);
171
+ return { label: `Environment (${listener ? listener.name : entry.listener})`, detail: listener ? listener.envNote : null };
172
+ }
173
+ case 'manual':
174
+ return { label: 'Uploaded certificate', detail: null };
175
+ case 'acme':
176
+ return { label: `Let's Encrypt for ${entry.hostname}`, detail: null };
177
+ case 'self-signed':
178
+ return { label: 'Self-signed fallback', detail: null };
179
+ default:
180
+ return { label: entry.source, detail: null };
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Whether a listener can be told to present this entry: it has material, or it is the self-signed
186
+ * fallback, which is generated the first time a listener needs it.
187
+ *
188
+ * @param {Object} entry Catalog entry
189
+ * @returns {boolean}
190
+ */
191
+ function isSelectable(entry) {
192
+ return !!(entry && (entry.material || entry.id === SELF_SIGNED_ID));
193
+ }
194
+
195
+ function entryFrom(fields, material) {
196
+ return Object.assign(
197
+ { id: certificateId(fields), material: material || false, x509: material ? parseCertificate(material.cert) : false },
198
+ fields,
199
+ describeEntry(fields)
200
+ );
201
+ }
202
+
203
+ /**
204
+ * Every certificate the instance could present, in page order - which is also precedence order
205
+ * for a name: environment material, the upload, the issued certificates in hostname priority,
206
+ * the fallback.
207
+ *
208
+ * The self-signed entry is always listed, generated or not: it is an option a listener may be
209
+ * told to present, and the listener generates it on first use the way it always has. Listing
210
+ * never generates it.
211
+ *
212
+ * @param {Object} opts
213
+ * @param {Object} [opts.certs] @postalsys/certs handler, or null to list no issued certificate
214
+ * @param {string[]} opts.hostnames Configured hostnames, in priority order
215
+ * @param {boolean} [opts.withPrivateKey=false] Whether the uploaded certificate's key is decrypted
216
+ * into its entry. A listener needs it; a page does not.
217
+ * Issued material carries its key either way, which
218
+ * is how the certificate library returns it
219
+ * @param {Object} [opts.logger] Logger for a store that could not be read
220
+ * @returns {Promise<Object[]>} Entries `{ id, source, listener?, hostname?, label, detail, material, x509 }`
221
+ */
222
+ async function listCertificates(opts) {
223
+ const { certs, logger } = opts || {};
224
+ const hostnames = [].concat((opts && opts.hostnames) || []);
225
+ const withPrivateKey = !!(opts && opts.withPrivateKey);
226
+
227
+ // Independent reads, in one round: this runs before a listener binds its port
228
+ const [manual, issued, selfSigned] = await Promise.all([
229
+ withPrivateKey ? getManualCertificate() : peekManualCertificate(),
230
+ Promise.all(hostnames.map(hostname => getAcmeCertificate(certs, hostname, logger))),
231
+ peekSelfSignedCertificate()
232
+ ]);
233
+
234
+ const entries = [];
235
+
236
+ for (const listener of LISTENERS) {
237
+ const material = envMaterialFor(listener.key, logger);
238
+ if (material) {
239
+ entries.push(entryFrom({ source: 'env', listener: listener.key }, material));
240
+ }
241
+ }
242
+
243
+ if (manual) {
244
+ entries.push(entryFrom({ source: 'manual' }, manual));
245
+ }
246
+
247
+ hostnames.forEach((hostname, index) => {
248
+ if (issued[index]) {
249
+ // With the name it was issued for: that is what the certificate's id is made of
250
+ entries.push(entryFrom({ source: 'acme', hostname }, Object.assign({ hostname }, issued[index])));
251
+ }
252
+ });
253
+
254
+ entries.push(entryFrom({ source: 'self-signed' }, selfSigned));
255
+
256
+ return entries;
257
+ }
258
+
259
+ /**
260
+ * The entries a name may resolve to on a listener, in precedence order: the listener's own
261
+ * environment material, then the upload and the issued certificates as far as the source setting
262
+ * admits them. The fallback is not among them; it is what a caller adds for a name none of these
263
+ * cover.
264
+ *
265
+ * @param {Object[]} catalog What listCertificates() returned
266
+ * @param {Object} opts
267
+ * @param {string|null} [opts.listener] Listener key; null admits no environment material
268
+ * @param {Object} opts.sources What the source setting admits, from sourcesFor()
269
+ * @returns {Object[]} The admitted entries, catalog order
270
+ */
271
+ function admittedFor(catalog, opts) {
272
+ const { listener, sources } = opts;
273
+
274
+ return catalog.filter(entry => {
275
+ if (!entry.material) {
276
+ return false;
277
+ }
278
+ switch (entry.source) {
279
+ case 'env':
280
+ return !!listener && entry.listener === listener;
281
+ case 'manual':
282
+ return !!sources.manual;
283
+ case 'acme':
284
+ return !!sources.acme;
285
+ default:
286
+ return false;
287
+ }
288
+ });
289
+ }
290
+
291
+ /**
292
+ * The certificate a listener presents by default: to a client that names no host, and for every
293
+ * name the certificate covers.
294
+ *
295
+ * An explicit choice is honored as long as the certificate exists, whatever the source setting
296
+ * admits - it is an instruction, the way environment material always was. Otherwise the automatic
297
+ * choice: the listener's own environment material (an operator who set EENGINE_SMTP_TLS_CERT meant
298
+ * the SMTP server to present it), then whatever answers the primary hostname, then any certificate
299
+ * answering a name at all, then the self-signed fallback, so a listener that has been switched on
300
+ * always starts.
301
+ *
302
+ * @param {Object} opts
303
+ * @param {Object[]} opts.catalog What listCertificates() returned
304
+ * @param {Object[]} opts.entries The entries answering configured names, primary first
305
+ * @param {string} [opts.primary] The primary hostname
306
+ * @param {string|null} [opts.listener] Listener key
307
+ * @param {*} [opts.requested] The listener's setting value
308
+ * @returns {Object} `{ entry, selection, requested }` - `selection` is "selected", "auto", or
309
+ * "missing" when the requested certificate no longer exists and the automatic
310
+ * choice stands in for it
311
+ */
312
+ function resolveDefaultCertificate(opts) {
313
+ const { catalog, entries, primary, listener } = opts;
314
+ const requested = requestedCertificate(opts.requested);
315
+
316
+ if (requested !== AUTO) {
317
+ const chosen = catalog.find(entry => entry.id === requested && isSelectable(entry));
318
+ if (chosen) {
319
+ return { entry: chosen, selection: 'selected', requested };
320
+ }
321
+ }
322
+
323
+ const selection = requested === AUTO ? 'auto' : 'missing';
324
+
325
+ const own = listener ? catalog.find(entry => entry.source === 'env' && entry.listener === listener && entry.material) : null;
326
+ const forPrimary = primary ? entries.find(entry => coversHostname(entry.x509, primary)) : null;
327
+ const entry = own || forPrimary || entries[0] || catalog.find(candidate => candidate.id === SELF_SIGNED_ID);
328
+
329
+ return { entry, selection, requested };
330
+ }
331
+
332
+ /**
333
+ * Which entry answers a client asking for a name: the default when it covers the name, otherwise
334
+ * whichever per-hostname entry does, otherwise the default. The one rule the SNI callback and the
335
+ * page both follow.
336
+ *
337
+ * @param {string} servername Name the client sent, or nothing
338
+ * @param {Object} view `{ fallback, entries }`, each entry with a parsed `x509`
339
+ * @returns {Object|null} The entry to serve
340
+ */
341
+ function entryForName(servername, view) {
342
+ const { fallback, entries } = view;
343
+ const name = normalizeHostname(servername);
344
+
345
+ if (name) {
346
+ if (fallback && coversHostname(fallback.x509, name)) {
347
+ return fallback;
348
+ }
349
+ const match = (entries || []).find(entry => coversHostname(entry.x509, name));
350
+ if (match) {
351
+ return match;
352
+ }
353
+ }
354
+
355
+ return fallback || null;
356
+ }
357
+
358
+ /**
359
+ * What one listener makes of the catalog: the entry answering each configured name, the default,
360
+ * and whether the self-signed fallback is needed for any of it.
361
+ *
362
+ * A configured name that neither the default nor any admitted entry covers gets the self-signed
363
+ * fallback, which covers every configured name, rather than a certificate that fails the client's
364
+ * name check just the same and is not what the page says the name has.
365
+ *
366
+ * @param {Object} opts
367
+ * @param {Object[]} opts.catalog What listCertificates() returned
368
+ * @param {string[]} opts.hostnames Configured hostnames, primary first
369
+ * @param {Object} opts.sources What the source setting admits, from sourcesFor()
370
+ * @param {string|null} [opts.listener] Listener key
371
+ * @param {*} [opts.requested] The listener's setting value
372
+ * @returns {Object} `{ fallback, entries, selection, requested, uncovered, needsSelfSigned }` -
373
+ * `entries` are the distinct entries answering some configured name, hostname
374
+ * order, with the self-signed entry appended when a name needs it;
375
+ * `needsSelfSigned` says the fallback material has to exist for this view to
376
+ * serve, whether generated or not yet
377
+ */
378
+ function listenerView(opts) {
379
+ const { catalog, sources, listener, requested } = opts;
380
+ const hostnames = [].concat(opts.hostnames || []);
381
+
382
+ const admitted = admittedFor(catalog, { listener: listener || null, sources });
383
+
384
+ // The first admitted entry covering each name, deduplicated in hostname order
385
+ const entries = [];
386
+ for (const hostname of hostnames) {
387
+ const match = admitted.find(entry => coversHostname(entry.x509, hostname));
388
+ if (match && !entries.includes(match)) {
389
+ entries.push(match);
390
+ }
391
+ }
392
+
393
+ const choice = resolveDefaultCertificate({ catalog, entries, primary: hostnames[0], listener: listener || null, requested });
394
+ const fallback = choice.entry;
395
+
396
+ const uncovered = hostnames.filter(
397
+ hostname => !(fallback && coversHostname(fallback.x509, hostname)) && !entries.some(entry => coversHostname(entry.x509, hostname))
398
+ );
399
+
400
+ const selfSigned = catalog.find(entry => entry.id === SELF_SIGNED_ID);
401
+ if (uncovered.length && selfSigned && fallback !== selfSigned && !entries.includes(selfSigned)) {
402
+ entries.push(selfSigned);
403
+ }
404
+
405
+ return {
406
+ fallback,
407
+ entries,
408
+ selection: choice.selection,
409
+ requested: choice.requested,
410
+ uncovered,
411
+ needsSelfSigned: !!((fallback && fallback.id === SELF_SIGNED_ID) || uncovered.length)
412
+ };
413
+ }
414
+
415
+ module.exports = {
416
+ sourcesFor,
417
+ certificateId,
418
+ parseCertificateId,
419
+ requestedCertificate,
420
+ envMaterialFor,
421
+ describeEntry,
422
+ isSelectable,
423
+ listCertificates,
424
+ admittedFor,
425
+ resolveDefaultCertificate,
426
+ entryForName,
427
+ listenerView
428
+ };