emailengine-app 2.79.8 → 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 (182) hide show
  1. package/.github/dependabot.yml +22 -0
  2. package/.github/workflows/test.yml +39 -0
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +69 -0
  5. package/DOCKER_DEPLOYMENT.md +6 -7
  6. package/Dockerfile +35 -11
  7. package/config/default.toml +7 -2
  8. package/copy-static-files.sh +23 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +43 -0
  11. package/lib/account/account-state.js +62 -0
  12. package/lib/account.js +60 -3
  13. package/lib/api-routes/account-routes.js +20 -0
  14. package/lib/api-routes/bull-board-routes.js +3 -2
  15. package/lib/api-routes/index.js +1 -1
  16. package/lib/api-routes/route-helpers.js +8 -0
  17. package/lib/api-routes/settings-routes.js +17 -2
  18. package/lib/auth-token.js +73 -2
  19. package/lib/autodetect-imap-settings.js +379 -69
  20. package/lib/cert-handler.js +62 -0
  21. package/lib/consts.js +58 -7
  22. package/lib/db.js +12 -0
  23. package/lib/egress-fetch.js +145 -0
  24. package/lib/email-client/base-client.js +234 -66
  25. package/lib/email-client/credential-errors.js +118 -0
  26. package/lib/email-client/gmail/gmail-api.js +2 -1
  27. package/lib/email-client/gmail-client.js +70 -64
  28. package/lib/email-client/imap/connection-errors.js +52 -0
  29. package/lib/email-client/imap/listing-diff.js +47 -6
  30. package/lib/email-client/imap/mailbox.js +457 -379
  31. package/lib/email-client/imap/subconnection.js +15 -11
  32. package/lib/email-client/imap/sync-operations.js +46 -59
  33. package/lib/email-client/imap-client.js +136 -95
  34. package/lib/email-client/message-builder.js +11 -11
  35. package/lib/email-client/outlook/graph-api.js +2 -1
  36. package/lib/email-client/outlook-client.js +219 -106
  37. package/lib/export.js +35 -2
  38. package/lib/handlebars-helpers.js +129 -0
  39. package/lib/imap-proxy-auth.js +96 -21
  40. package/lib/imapproxy/imap-core/README.md +1 -0
  41. package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
  42. package/lib/imapproxy/imap-server.js +56 -66
  43. package/lib/lua/h-del-if-equals.lua +39 -0
  44. package/lib/lua/h-set-if-equals.lua +39 -0
  45. package/lib/openapi/index.js +3 -0
  46. package/lib/outbox.js +28 -3
  47. package/lib/rate-limit.js +23 -4
  48. package/lib/routes-ui.js +4 -34
  49. package/lib/schemas.js +42 -3
  50. package/lib/security-headers.js +411 -0
  51. package/lib/sentry.js +36 -4
  52. package/lib/smtp-auth.js +86 -7
  53. package/lib/tls/context.js +376 -0
  54. package/lib/tls/der.js +223 -0
  55. package/lib/tls/provision.js +555 -0
  56. package/lib/tls/self-signed.js +282 -0
  57. package/lib/tls/status.js +431 -0
  58. package/lib/tls/store.js +666 -0
  59. package/lib/tools.js +337 -147
  60. package/lib/ui-routes/account-routes.js +47 -33
  61. package/lib/ui-routes/admin-config-routes.js +22 -1
  62. package/lib/ui-routes/auth-routes.js +16 -1
  63. package/lib/ui-routes/export-routes.js +4 -0
  64. package/lib/ui-routes/internals-routes.js +3 -5
  65. package/lib/ui-routes/mcp-consent-routes.js +7 -0
  66. package/lib/ui-routes/network-config-routes.js +58 -48
  67. package/lib/ui-routes/route-helpers.js +24 -8
  68. package/lib/ui-routes/smtp-test-routes.js +7 -0
  69. package/lib/ui-routes/tls-config-routes.js +581 -0
  70. package/lib/utils/mailbox-path.js +51 -0
  71. package/lib/utils/severity.js +31 -0
  72. package/lib/webhook-egress.js +5 -0
  73. package/package.json +21 -24
  74. package/sbom.json +1 -1
  75. package/server.js +53 -36
  76. package/static/css/flyonui.css +1 -1
  77. package/static/css/src/app.tailwind.css +11 -0
  78. package/static/js/ace/css/ace.css +1462 -0
  79. package/static/js/ace/css/kuroir-1.png +0 -0
  80. package/static/js/ace/css/kuroir-2.png +0 -0
  81. package/static/js/ace/css/main-1.png +0 -0
  82. package/static/js/ace/css/main-10.svg +4 -0
  83. package/static/js/ace/css/main-11.svg +5 -0
  84. package/static/js/ace/css/main-12.svg +4 -0
  85. package/static/js/ace/css/main-13.png +0 -0
  86. package/static/js/ace/css/main-14.png +0 -0
  87. package/static/js/ace/css/main-15.png +0 -0
  88. package/static/js/ace/css/main-16.png +0 -0
  89. package/static/js/ace/css/main-17.png +0 -0
  90. package/static/js/ace/css/main-18.png +0 -0
  91. package/static/js/ace/css/main-19.png +0 -0
  92. package/static/js/ace/css/main-2.png +0 -0
  93. package/static/js/ace/css/main-20.png +0 -0
  94. package/static/js/ace/css/main-21.png +0 -0
  95. package/static/js/ace/css/main-22.png +0 -0
  96. package/static/js/ace/css/main-23.png +0 -0
  97. package/static/js/ace/css/main-24.png +0 -0
  98. package/static/js/ace/css/main-25.svg +1 -0
  99. package/static/js/ace/css/main-26.png +0 -0
  100. package/static/js/ace/css/main-3.png +0 -0
  101. package/static/js/ace/css/main-4.png +0 -0
  102. package/static/js/ace/css/main-5.svg +7 -0
  103. package/static/js/ace/css/main-6.svg +9 -0
  104. package/static/js/ace/css/main-7.svg +7 -0
  105. package/static/js/ace/css/main-8.svg +9 -0
  106. package/static/js/ace/css/main-9.svg +6 -0
  107. package/static/js/ace/css/theme/kuroir.css +78 -0
  108. package/static/js/ace/css/theme/tomorrow_night.css +128 -0
  109. package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
  110. package/static/js/ace/css/theme/xcode.css +106 -0
  111. package/static/js/ace/css/tomorrow_night-1.png +0 -0
  112. package/static/js/ace/css/tomorrow_night-2.png +0 -0
  113. package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
  114. package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
  115. package/static/js/ace/css/xcode-1.png +0 -0
  116. package/static/js/ace/css/xcode-2.png +0 -0
  117. package/static/js/app.js +34 -0
  118. package/static/js/ee-client.js +256 -102
  119. package/static/js/public.js +13 -2
  120. package/static/js/ui.js +40 -25
  121. package/static/licenses.html +393 -1282
  122. package/static/vendor/simplewebauthn/browser.min.js +2 -2
  123. package/translations/messages.pot +203 -157
  124. package/views/account/login-redirect.hbs +22 -0
  125. package/views/accounts/account.hbs +15 -37
  126. package/views/accounts/browse.hbs +3 -1
  127. package/views/accounts/edit.hbs +1 -1
  128. package/views/accounts/register/imap-server.hbs +1 -1
  129. package/views/config/ai.hbs +1 -1
  130. package/views/config/branding.hbs +2 -2
  131. package/views/config/document-store/chat.hbs +1 -1
  132. package/views/config/document-store/index.hbs +1 -1
  133. package/views/config/imap-proxy.hbs +1 -4
  134. package/views/config/license.hbs +1 -1
  135. package/views/config/mcp.hbs +1 -1
  136. package/views/config/network.hbs +14 -16
  137. package/views/config/oauth/app.hbs +2 -2
  138. package/views/config/service.hbs +1 -1
  139. package/views/config/smtp.hbs +1 -4
  140. package/views/config/tls-upload.hbs +81 -0
  141. package/views/config/tls.hbs +492 -0
  142. package/views/config/webhooks.hbs +2 -2
  143. package/views/error.hbs +4 -2
  144. package/views/internals/index.hbs +1 -1
  145. package/views/layout/app.hbs +3 -11
  146. package/views/mcp/authorize.hbs +1 -1
  147. package/views/partials/ace_assets.hbs +13 -0
  148. package/views/partials/add_account_modal.hbs +1 -1
  149. package/views/partials/address_list.hbs +4 -4
  150. package/views/partials/filter_editor_js.hbs +2 -2
  151. package/views/partials/gateway_js.hbs +1 -1
  152. package/views/partials/oauth_form.hbs +1 -1
  153. package/views/partials/public_theme_init.hbs +1 -1
  154. package/views/partials/side_menu.hbs +1 -0
  155. package/views/partials/template_form.hbs +2 -2
  156. package/views/partials/test_send.hbs +7 -4
  157. package/views/partials/theme_init.hbs +1 -1
  158. package/views/partials/tls_security_card.hbs +25 -53
  159. package/views/partials/ui/alert-banner.hbs +3 -2
  160. package/views/partials/ui/badge.hbs +6 -2
  161. package/views/partials/ui/btn.hbs +5 -2
  162. package/views/partials/ui/details.hbs +2 -2
  163. package/views/partials/webhooks_editor_functions.hbs +1 -1
  164. package/views/reference/redirect.hbs +1 -1
  165. package/views/templates/template.hbs +2 -2
  166. package/views/tokens/new.hbs +1 -1
  167. package/views/unsubscribe.hbs +1 -1
  168. package/views/webhooks/webhook.hbs +2 -2
  169. package/workers/api.js +131 -242
  170. package/workers/export.js +1 -5
  171. package/workers/imap-proxy.js +4 -1
  172. package/workers/imap.js +1 -3
  173. package/workers/smtp.js +59 -83
  174. package/workers/submit.js +6 -12
  175. package/workers/webhooks.js +6 -17
  176. package/static/front/EmailEngine_logo_horiz.png +0 -0
  177. package/static/front/EmailEngine_logo_vert.png +0 -0
  178. package/static/front/index.html +0 -57
  179. package/static/front/logo.png +0 -0
  180. package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
  181. package/views/partials/tls_security_js.hbs +0 -64
  182. package/views/partials/tls_security_modal.hbs +0 -22
@@ -17,9 +17,11 @@ const { redis, documentsQueue } = require('../db');
17
17
  const getSecret = require('../get-secret');
18
18
  const capa = require('../capa');
19
19
  const { Account, authFailureDisabledAt, isOperatorDisabled } = require('../account');
20
+ const { formatGmailWatch } = require('../account/account-state');
20
21
  const { Gateway } = require('../gateway');
21
22
  const { autodetectImapSettings, resolveAppPassword, getAppPassword } = require('../autodetect-imap-settings');
22
23
  const { atomicIncrement } = require('../redis-operations');
24
+ const { OAUTH_REDIRECT_FORM_DIRECTIVES } = require('../security-headers');
23
25
  const { oauth2Apps, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
24
26
  const {
25
27
  getServiceHostname,
@@ -44,7 +46,6 @@ const {
44
46
  } = require('../schemas');
45
47
  const {
46
48
  formatAccountData,
47
- cachedTemplates,
48
49
  identityErrorView,
49
50
  ACCOUNT_STATE_DISPLAY,
50
51
  adminUrl,
@@ -791,7 +792,13 @@ function init(args) {
791
792
 
792
793
  let serverSettings;
793
794
  try {
794
- serverSettings = await autodetectImapSettings(request.payload.email, request.app.gt);
795
+ // The password the user just typed is passed along because hosted Exchange refuses
796
+ // to answer autodiscovery anonymously; it only ever reaches the autodiscovery host
797
+ // named by the address domain's own DNS, and only after that host has asked for it
798
+ serverSettings = await autodetectImapSettings(request.payload.email, request.app.gt, {
799
+ user: request.payload.email,
800
+ pass: request.payload.password
801
+ });
795
802
  } catch (err) {
796
803
  request.logger.debug({ msg: 'Failed to resolve email server settings', email: request.payload.email, err });
797
804
  }
@@ -1411,35 +1418,36 @@ function init(args) {
1411
1418
  accountData.path = null;
1412
1419
  }
1413
1420
 
1414
- let gmailWatch =
1415
- accountData.watchResponse || accountData.watchFailure
1416
- ? {
1417
- lastCheckStr: accountData.lastWatch && accountData.lastWatch.toISOString(),
1418
- expiresStr:
1419
- accountData.watchResponse && accountData.watchResponse.expiration
1420
- ? new Date(Number(accountData.watchResponse.expiration)).toISOString()
1421
- : false
1422
- }
1423
- : false;
1424
-
1425
- if (gmailWatch) {
1426
- gmailWatch.active = gmailWatch.expiresStr && new Date(gmailWatch.expiresStr) > new Date();
1427
- gmailWatch.stateLabel = gmailWatch.active ? 'Active' : 'Expired';
1428
- if (accountData.watchFailure) {
1429
- gmailWatch.error = accountData.watchFailure.err;
1430
- if (!gmailWatch.active) {
1431
- gmailWatch.stateLabel = 'Failed';
1432
- }
1433
-
1434
- if (accountData.watchFailure.req) {
1435
- gmailWatch.request = {
1436
- url: accountData.watchFailure.req.url,
1437
- status: accountData.watchFailure.req.status,
1438
- contentType: accountData.watchFailure.req.contentType,
1439
- response: accountData.watchFailure.req.response
1440
- };
1441
- }
1442
- }
1421
+ // State comes from the same derivation the API reports, so the page and the response
1422
+ // cannot disagree about whether push is working. The reason and the failed request stay
1423
+ // here and out of the API: both are text the provider wrote, and this page is behind an
1424
+ // admin session. NB! a watch that is still armed but whose last renewal failed now
1425
+ // reads Failed rather than Active - it used to show the expiry alone and hide the
1426
+ // failure in a tooltip, which said nothing was wrong right up to the day it lapsed
1427
+ let watchState = formatGmailWatch(accountData);
1428
+ let gmailWatch = watchState
1429
+ ? {
1430
+ lastCheckStr: watchState.lastCheck,
1431
+ expiresStr: watchState.expires || false,
1432
+ active: watchState.state === 'active',
1433
+ stateLabel: { active: 'Active', error: 'Failed', expired: 'Expired' }[watchState.state] || 'Unknown',
1434
+ // The reason and the failed request are read straight off the record here and
1435
+ // deliberately absent from the shared derivation: both carry text the
1436
+ // provider wrote, including the operator's own Pub/Sub topic path, and this
1437
+ // page is behind an admin session while the API field is not
1438
+ error: accountData.watchFailure ? accountData.watchFailure.err || 'Failed to set up Gmail pubsub watch' : false
1439
+ }
1440
+ : false;
1441
+
1442
+ // Not "watchFailure truthy means gmailWatch is": the derivation reports nothing for an
1443
+ // account whose application has no Pub/Sub app, whatever record a previous one left
1444
+ if (gmailWatch && accountData.watchFailure && accountData.watchFailure.req) {
1445
+ gmailWatch.request = {
1446
+ url: accountData.watchFailure.req.url,
1447
+ status: accountData.watchFailure.req.status,
1448
+ contentType: accountData.watchFailure.req.contentType,
1449
+ response: accountData.watchFailure.req.response
1450
+ };
1443
1451
  }
1444
1452
 
1445
1453
  const canReadMail = (accountData.imap || accountData.oauth2) && !(accountData.imap && accountData.imap.disabled) && !DISABLE_MESSAGE_BROWSER;
@@ -1530,8 +1538,6 @@ function init(args) {
1530
1538
  ),
1531
1539
  gateways: gateways && gateways.gateways,
1532
1540
 
1533
- testSendTemplate: cachedTemplates.testSend,
1534
-
1535
1541
  accountForm: await getSignedFormData({
1536
1542
  account: request.params.account,
1537
1543
  name: accountData.name,
@@ -1568,6 +1574,10 @@ function init(args) {
1568
1574
  },
1569
1575
 
1570
1576
  options: {
1577
+ // The "Re-authenticate" modal posts to /accounts/new, which answers with a redirect to the
1578
+ // provider's authorization page. Without this the admin preset's `form-action 'self'` blocks
1579
+ // the submission, even though the form posts to this instance
1580
+ plugins: { securityHeaders: { directives: OAUTH_REDIRECT_FORM_DIRECTIVES } },
1571
1581
  validate: {
1572
1582
  options: {
1573
1583
  stripUnknown: true,
@@ -1938,6 +1948,10 @@ function init(args) {
1938
1948
  },
1939
1949
 
1940
1950
  options: {
1951
+ // Rendered email HTML keeps its remote images, which no other admin page loads. Its
1952
+ // stylesheet needs no exception: the widget stamps the nonce the page passes it
1953
+ // (styleNonce in views/accounts/browse.hbs) onto the element it appends
1954
+ plugins: { securityHeaders: { directives: { 'img-src': "'self' data: https:" } } },
1941
1955
  validate: {
1942
1956
  options: {
1943
1957
  stripUnknown: true,
@@ -20,7 +20,17 @@ const consts = require('../consts');
20
20
  const getSecret = require('../get-secret');
21
21
  const timezonesList = require('timezones-list').default;
22
22
  const { redis, submitQueue, notifyQueue, documentsQueue } = require('../db');
23
- const { getByteSize, formatByteSize, getDuration, failAction, readEnvValue, readEnvList, httpAgent, splitUrlCredentials } = require('../tools');
23
+ const {
24
+ getByteSize,
25
+ formatByteSize,
26
+ getDuration,
27
+ failAction,
28
+ readEnvValue,
29
+ readEnvList,
30
+ httpAgent,
31
+ splitUrlCredentials,
32
+ maybeReloadTlsCertificates
33
+ } = require('../tools');
24
34
  const { validateWebhookTarget } = require('../webhook-egress');
25
35
  const { sendWebhookRequest } = require('../webhook-request');
26
36
  const { llmPreProcess } = require('../llm-pre-process');
@@ -372,7 +382,18 @@ function init(args) {
372
382
  // write would leave the old URL in place after a save meant to clear it
373
383
  data.serviceUrl = request.payload.serviceUrl ? new URL(request.payload.serviceUrl).origin : null;
374
384
 
385
+ // Compared before the write, and only for the reload: this form submits the service URL
386
+ // on every save, so reloading on the write alone would hand three listeners a new
387
+ // certificate every time somebody changed the timezone.
388
+ const serviceUrlChanged = data.serviceUrl !== (await settings.get('serviceUrl'));
389
+
375
390
  await settings.setMulti(data);
391
+
392
+ // The service URL names the first hostname EmailEngine serves TLS for, so changing it
393
+ // here changes what the listeners have to offer exactly as the TLS page's own hostname
394
+ // list does. Without this the listeners kept answering with a certificate for the
395
+ // previous name until something restarted them.
396
+ await maybeReloadTlsCertificates(call, request.logger, serviceUrlChanged ? ['serviceUrl'] : [], { action: 'settings' });
376
397
  }
377
398
  });
378
399
 
@@ -169,7 +169,22 @@ function init(args) {
169
169
  // discovery failure) so the local form remains as an emergency fallback.
170
170
  let forceLogin = sso.OIDC_FORCED && !!providers.oidc;
171
171
  if (forceLogin && !request.query.sso_denied && !request.query.loggedout) {
172
- return h.redirect('/admin/login/oidc');
172
+ // Rendered rather than redirected, so that a form submission whose session expired
173
+ // is not killed by the admin form-action policy - see the view for the whole story.
174
+ // NB! rendering drains the flash queue, so a message queued just before the login
175
+ // bounce is shown for the frame this page is up rather than on the login form.
176
+ return h.view(
177
+ 'account/login-redirect',
178
+ {
179
+ pageTitle: 'Login',
180
+ menuLogin: true,
181
+ providers,
182
+ ssoRedirectUrl: '/admin/login/oidc'
183
+ },
184
+ {
185
+ layout: 'login'
186
+ }
187
+ );
173
188
  }
174
189
 
175
190
  let passkeysAvailable = await passkeys.hasPasskeys();
@@ -141,6 +141,10 @@ function init(args) {
141
141
  }
142
142
  },
143
143
  options: {
144
+ // Crumb validates the crumb field of POST payloads only, so a DELETE sent by the page
145
+ // script passed with no CSRF check at all. Restful mode checks the X-CSRF-Token header
146
+ // instead, which is what the account page sends with this request
147
+ plugins: { crumb: { restful: true } },
144
148
  validate: {
145
149
  options: {
146
150
  stripUnknown: true,
@@ -12,14 +12,12 @@ const { Account } = require('../account');
12
12
  const { redis } = require('../db');
13
13
  const { DEFAULT_PAGE_SIZE } = require('../consts');
14
14
  const { formatAccountData } = require('./route-helpers');
15
+ const { severityRank } = require('../utils/severity');
15
16
 
16
17
  // Worker kinds in the order they are shown on the internals page (known kinds first; any
17
18
  // unrecognized kind is appended so nothing is dropped).
18
19
  const THREAD_TYPE_ORDER = ['main', 'api', 'imap', 'webhooks', 'submit', 'export', 'smtp', 'imapProxy', 'documents'];
19
20
 
20
- // Severity ranking for the per-group health roll-up (higher wins).
21
- const STATUS_RANK = { success: 0, neutral: 1, warning: 2, error: 3 };
22
-
23
21
  // "Recently restarted" detection. Workers normally come online within seconds of the main
24
22
  // process; one that came online much later was respawned after a crash (uncaught exception).
25
23
  // A worker is flagged only when it started well after main (RESTART_GRACE, beyond any normal
@@ -130,7 +128,7 @@ function init(args) {
130
128
  typeof threadInfo.online === 'number' &&
131
129
  threadInfo.online - mainOnline > WORKER_RESTART_GRACE &&
132
130
  now - threadInfo.online < WORKER_RESTART_RECENT_WINDOW &&
133
- STATUS_RANK[threadInfo.statusVariant] < STATUS_RANK.warning
131
+ severityRank(threadInfo.statusVariant) < severityRank('warning')
134
132
  ) {
135
133
  threadInfo.statusVariant = 'warning';
136
134
  threadInfo.statusLabel = 'Recently restarted';
@@ -190,7 +188,7 @@ function init(args) {
190
188
  // Health roll-up = worst member status.
191
189
  let rollup = list.reduce(
192
190
  (worst, threadInfo) =>
193
- STATUS_RANK[threadInfo.statusVariant] > STATUS_RANK[worst.variant]
191
+ severityRank(threadInfo.statusVariant) > severityRank(worst.variant)
194
192
  ? { variant: threadInfo.statusVariant, label: threadInfo.statusLabel }
195
193
  : worst,
196
194
  { variant: 'success', label: 'Healthy' }
@@ -36,6 +36,11 @@ const { MCP_ACCESS_LEVELS, MCP_ACCESS_LEVEL_OPTIONS, MCP_GRANT_WORDING } = requi
36
36
  const { mcpFeatureEnabled } = require('../mcp');
37
37
  const { oauthOrigin, getClient, touchClient, createAuthorizationCode, isAcceptableResource } = require('../mcp/oauth');
38
38
 
39
+ // Both consent routes answer with a redirect to the OAuth client's registered redirect_uri,
40
+ // often http://localhost for a native client, and Chrome checks the redirect target of a form
41
+ // submission against form-action - so neither carries that directive
42
+ const CONSENT_SECURITY_HEADERS = { securityHeaders: { directives: { 'form-action': null } } };
43
+
39
44
  // The OAuth request parameters, carried through the GET render and posted back with the
40
45
  // decision. state is a client-side value with no format promises; the size bounds are only
41
46
  // there so the consent form cannot be used to store arbitrary blobs in a hidden field.
@@ -201,6 +206,7 @@ async function init(args) {
201
206
  },
202
207
 
203
208
  options: {
209
+ plugins: CONSENT_SECURITY_HEADERS,
204
210
  validate: {
205
211
  options: {
206
212
  stripUnknown: true,
@@ -304,6 +310,7 @@ async function init(args) {
304
310
  },
305
311
 
306
312
  options: {
313
+ plugins: CONSENT_SECURITY_HEADERS,
307
314
  validate: {
308
315
  options: {
309
316
  stripUnknown: true,
@@ -4,7 +4,7 @@
4
4
  // (/admin/config/{network*,imap-proxy,smtp*,browser}). Extracted verbatim from
5
5
  // lib/routes-ui.js. The network page also reloads/deletes the autodetected public
6
6
  // interfaces; the SMTP/IMAP-proxy pages manage the built-in MSA and IMAP proxy servers
7
- // (including on-demand TLS certificate provisioning).
7
+ // (the TLS toggle each of them owns; the certificate itself lives on /admin/config/tls).
8
8
 
9
9
  const Joi = require('joi');
10
10
  const os = require('os');
@@ -13,10 +13,13 @@ const { parentPort } = require('worker_threads');
13
13
  const settings = require('../settings');
14
14
  const { redis } = require('../db');
15
15
  const { REDIS_PREFIX } = require('../consts');
16
- const { failAction, getServiceHostname, reloadTlsServers } = require('../tools');
16
+ const { failAction, getServiceHostname, maybeReloadTlsCertificates } = require('../tools');
17
17
  const { ADDRESS_STRATEGIES, settingsSchema } = require('../schemas');
18
18
  const { updatePublicInterfaces } = require('../utils/network');
19
- const { getServerStatus, cachedTemplates } = require('./route-helpers');
19
+ const { getServerStatus, compiledFragments } = require('./route-helpers');
20
+ const { listenerCertificateSummary, reportedListenerTls } = require('../tls/status');
21
+ const { getCertificateHostnames } = require('../tls/store');
22
+ const { getProvisioningStatus } = require('../tls/provision');
20
23
  const { registerSettingsPage } = require('./settings-page');
21
24
 
22
25
  const configSmtpSchema = {
@@ -146,7 +149,6 @@ function init(args) {
146
149
  imapStrategies: ADDRESS_STRATEGIES.map(entry => Object.assign({ selected: values.imapStrategy === entry.key }, entry)),
147
150
 
148
151
  addresses: await listPublicInterfaces([].concat(values.localAddresses || [])),
149
- addressListTemplate: cachedTemplates.addressList,
150
152
  defaultSmtpEhloName: await getServiceHostname()
151
153
  };
152
154
  },
@@ -186,7 +188,9 @@ function init(args) {
186
188
 
187
189
  return {
188
190
  success: true,
189
- addresses: await listPublicInterfaces(localAddresses)
191
+ // The page swaps its table body for this: the same partial the page was
192
+ // rendered with, so a rescan cannot drift from first paint
193
+ html: compiledFragments.addressList({ addresses: await listPublicInterfaces(localAddresses) })
190
194
  };
191
195
  } catch (err) {
192
196
  request.logger.error({ msg: 'Failed loading public IP addresses', err });
@@ -258,8 +262,17 @@ function init(args) {
258
262
  }
259
263
  });
260
264
 
261
- // Context shared by the SMTP server and IMAP proxy pages: live server state,
262
- // bindable interface addresses, and the TLS certificate for the service domain
265
+ // Context shared by the SMTP server and IMAP proxy pages: live server state, bindable
266
+ // interface addresses, and a summary of the certificate the listener is serving.
267
+ //
268
+ // A summary, not a control. These pages decide whether their listener speaks TLS; the
269
+ // certificate belongs to the instance and is managed on /admin/config/tls. Rendering it used to
270
+ // provision one as a side effect of ticking a checkbox.
271
+ //
272
+ // The certificate comes from the listener's own state payload rather than being inferred from
273
+ // the configuration: a listener reports what it loaded, which is the thing an operator is
274
+ // looking at this page to find out, and environment-supplied material is not visible any other
275
+ // way. The stored model is the fallback for a listener that has not reported yet.
263
276
  const serverPageContext = async (h, serverType) => {
264
277
  let availableAddresses = new Set(
265
278
  Object.values(os.networkInterfaces())
@@ -268,13 +281,39 @@ function init(args) {
268
281
  );
269
282
  availableAddresses.add('0.0.0.0');
270
283
 
284
+ const [serverState, hostnames] = await Promise.all([getServerStatus(serverType), getCertificateHostnames()]);
285
+
286
+ // The name clients connect to, which is the first certificate hostname rather than "a name
287
+ // Let's Encrypt could validate" - a listener serves a self-signed certificate for an
288
+ // address literal just as much as an issued one for a public domain.
289
+ const primaryHostname = hostnames[0] || null;
290
+ const reported = reportedListenerTls(serverState);
291
+
292
+ // The provisioning state comes along with the certificate: it is what turns the badge into
293
+ // "Requesting", "Failed" or "Renewal failed". Without it this page could only ever read
294
+ // "Valid", including under a renewal that had been failing for weeks. Read only for a
295
+ // listener that reported one; the stored model below carries its own copy of it.
296
+ const provisioning = reported ? await getProvisioningStatus() : {};
297
+
298
+ let tlsSummary = listenerCertificateSummary({
299
+ reported,
300
+ hostname: primaryHostname,
301
+ status: provisioning[primaryHostname] || null
302
+ });
303
+
304
+ if (!tlsSummary.certificate) {
305
+ const status = await h.tlsStatus();
306
+ const primary = status.certificates[0] || null;
307
+ if (primary) {
308
+ tlsSummary = { hostname: primary.hostname, certificate: primary.certificate, label: primary.label };
309
+ }
310
+ }
311
+
271
312
  return {
272
- serverState: await getServerStatus(serverType),
313
+ serverState,
273
314
  availableAddresses: Array.from(availableAddresses).join(','),
274
315
 
275
- serviceDomain: await h.serviceDomain(),
276
- serviceUrl: await settings.get('serviceUrl'),
277
- certificateData: await h.getCertificate()
316
+ tlsSummary
278
317
  };
279
318
  };
280
319
 
@@ -357,55 +396,26 @@ function init(args) {
357
396
  }
358
397
  });
359
398
 
360
- server.route({
361
- method: 'POST',
362
- path: '/admin/config/smtp/certificate',
363
- async handler(request, h) {
364
- try {
365
- // What is installed before provisioning, so the reload below fires only when a new
366
- // certificate actually arrived and repeated clicks do not keep restarting both
367
- // servers.
368
- let existingCertificateData = await h.getCertificate();
369
-
370
- let certificateData = await h.getCertificate(true);
371
- if (!certificateData) {
372
- throw new Error(`Failed to provision a certificate`);
373
- }
374
-
375
- if (certificateData.fingerprint && certificateData.fingerprint !== (existingCertificateData && existingCertificateData.fingerprint)) {
376
- await reloadTlsServers(call, request.logger, { domain: certificateData.domain });
377
- }
378
-
379
- return {
380
- success: true,
381
- domain: certificateData.domain,
382
- fingerprint: certificateData.fingerprint,
383
- altNames: certificateData.altNames,
384
- validTo: certificateData.validTo && certificateData.validTo.toISOString(),
385
- label: certificateData.label
386
- };
387
- } catch (err) {
388
- request.logger.error({ msg: 'Failed to provision a certificate', err });
389
- return {
390
- success: false,
391
- error: err.message
392
- };
393
- }
394
- }
395
- });
396
-
397
399
  server.route({
398
400
  method: 'POST',
399
401
  path: '/admin/config/browser',
400
402
  async handler(request) {
403
+ const written = [];
401
404
  for (let key of ['serviceUrl', 'language', 'timezone']) {
402
405
  if (request.payload[key]) {
403
406
  let existingValue = await settings.get(key);
404
407
  if (existingValue === null) {
405
408
  await settings.set(key, request.payload[key]);
409
+ written.push(key);
406
410
  }
407
411
  }
408
412
  }
413
+
414
+ // Learning the service URL for the first time is what gives a fresh install the name it
415
+ // serves TLS for. Until the listeners hear about it they keep the certificate they
416
+ // started with, which covers the localhost fallback and nothing an operator typed.
417
+ await maybeReloadTlsCertificates(call, request.logger, written, { action: 'settings' });
418
+
409
419
  return { success: true };
410
420
  },
411
421
  options: {
@@ -6,20 +6,20 @@
6
6
  // be extracted without stranding a helper its sibling groups still need. Pure functions
7
7
  // and cached data only - this module registers no routes.
8
8
  //
9
- // Every symbol below was moved verbatim from lib/routes-ui.js. The only change is in
10
- // cachedTemplates: its __dirname-relative paths gain one extra '..' because this file
11
- // lives one directory deeper (lib/ui-routes/) than the original (lib/).
9
+ // Every symbol below was moved verbatim from lib/routes-ui.js, apart from compiledFragments,
10
+ // which replaced the raw template sources the monolith handed to the browser.
12
11
 
13
12
  const Boom = require('@hapi/boom');
14
13
  const util = require('util');
15
14
  const fs = require('fs');
16
15
  const pathlib = require('path');
17
16
  const psl = require('psl');
17
+ const handlebars = require('handlebars');
18
18
 
19
19
  const settings = require('../settings');
20
20
  const { redis } = require('../db');
21
21
  const { toolGrants } = require('../mcp/tools');
22
- const { Account, accountsExist, accountSummary, isAuthFailureDisabled } = require('../account');
22
+ const { Account, accountsExist, accountSummary, isAuthFailureDisabled, isAccessTokenInvalidated } = require('../account');
23
23
  const { REDIS_PREFIX, DEFAULT_PAGE_SIZE } = require('../consts');
24
24
  const { oauth2ProviderData } = require('../oauth2-apps');
25
25
  const exampleDocumentsPayloads = require('../payload-examples-documents.json');
@@ -44,9 +44,22 @@ const OPEN_AI_MODELS = [
44
44
  }
45
45
  ];
46
46
 
47
- const cachedTemplates = {
48
- addressList: fs.readFileSync(pathlib.join(__dirname, '..', '..', 'views', 'partials', 'address_list.hbs'), 'utf-8'),
49
- testSend: fs.readFileSync(pathlib.join(__dirname, '..', '..', 'views', 'partials', 'test_send.hbs'), 'utf-8')
47
+ // Partials a page renders again after it has loaded: the delivery-test results and the address
48
+ // list after an IP rescan. They used to be shipped to the browser as source and compiled there,
49
+ // which runs `new Function` and would need 'unsafe-eval' in the Content-Security-Policy the
50
+ // admin surface sends. Compiled once here instead, outside vision but on the same handlebars
51
+ // instance it renders with, so the helpers and partials registered on it resolve at render
52
+ // time; the JSON endpoints return the rendered HTML. Not going through vision is deliberate: its
53
+ // per-request view context consumes the pending flash messages. What a fragment therefore lacks
54
+ // is that context - no `cspNonce`, so a fragment can never carry an inline <script>.
55
+ const FRAGMENT_COMPILE_OPTIONS = { preventIndent: true }; // matches the vision compileOptions in workers/api.js
56
+
57
+ const compiledFragments = {
58
+ addressList: handlebars.compile(
59
+ fs.readFileSync(pathlib.join(__dirname, '..', '..', 'views', 'partials', 'address_list.hbs'), 'utf-8'),
60
+ FRAGMENT_COMPILE_OPTIONS
61
+ ),
62
+ testSend: handlebars.compile(fs.readFileSync(pathlib.join(__dirname, '..', '..', 'views', 'partials', 'test_send.hbs'), 'utf-8'), FRAGMENT_COMPILE_OPTIONS)
50
63
  };
51
64
 
52
65
  const getOpenAiModels = async (models, selectedModel) => {
@@ -244,6 +257,9 @@ function formatAccountData(account, gt) {
244
257
  account.oauth2.expiresStr = account.oauth2.expires ? account.oauth2.expires.toISOString() : false;
245
258
  account.oauth2.generatedStr = account.oauth2.generated ? account.oauth2.generated.toISOString() : false;
246
259
 
260
+ // the view names the state instead of printing the inverted range the invalidation leaves
261
+ account.oauth2.accessTokenInvalidated = isAccessTokenInvalidated(account.oauth2);
262
+
247
263
  if (account.outlookSubscription) {
248
264
  account.outlookSubscription.subscriptionExpiresStr = account.outlookSubscription.expirationDateTime
249
265
  ? account.outlookSubscription.expirationDateTime.toISOString()
@@ -593,7 +609,7 @@ module.exports = {
593
609
  accountPickerSelection,
594
610
  identityErrorView,
595
611
  OPEN_AI_MODELS,
596
- cachedTemplates,
612
+ compiledFragments,
597
613
  getOpenAiModels,
598
614
  closedAfterConnectMessage,
599
615
  accountStateLabel,
@@ -13,6 +13,7 @@ const getSecret = require('../get-secret');
13
13
  const { failAction, httpAgent } = require('../tools');
14
14
  const { accountIdSchema } = require('../schemas');
15
15
  const { REDIS_PREFIX } = require('../consts');
16
+ const { compiledFragments } = require('./route-helpers');
16
17
  const packageData = require('../../package.json');
17
18
 
18
19
  const SMTP_TEST_HOST = 'https://api.nodemailer.com';
@@ -207,6 +208,12 @@ ${now}`,
207
208
  if (testResponse.spf && testResponse.spf.status && testResponse.spf.status.comment) {
208
209
  testResponse.spf.status.comment = testResponse.spf.status.comment.replace(/^[^:\s]+:s*/, '');
209
210
  }
211
+
212
+ if (testResponse.status === 'success') {
213
+ // The page shows the results through this fragment rather than
214
+ // compiling the template in the browser, which the admin CSP forbids
215
+ testResponse.html = compiledFragments.testSend(testResponse);
216
+ }
210
217
  }
211
218
 
212
219
  return testResponse;