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
@@ -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');
@@ -29,7 +39,18 @@ const { mcpFeatureEnabled } = require('../mcp');
29
39
  const { mcpResource } = require('../mcp/oauth');
30
40
  const { getToolRegistry } = require('../mcp/tools');
31
41
  const { serverUrl } = require('../openapi');
32
- const { MCP_ACCESS_LEVELS, MCP_ACCESS_LEVEL_OPTIONS } = require('../token-permission-view');
42
+ const { MCP_SECTIONS } = require('../token-permission-view');
43
+ const { ACTION } = require('../api-routes/permission-map');
44
+
45
+ // How the MCP config page badges a tool: by the action it dispatches under, read off the grant
46
+ // rather than the annotation hints - openWorldHint does not imply sending, the lookups and
47
+ // connection tests declare it too
48
+ const TOOL_BADGES = {
49
+ [ACTION.SEND]: { label: 'sends email', variant: 'warning' },
50
+ [ACTION.DESTRUCTIVE]: { label: 'destructive', variant: 'error' },
51
+ [ACTION.READ]: { label: 'read-only', variant: 'success' },
52
+ [ACTION.WRITE]: { label: 'write', variant: 'info' }
53
+ };
33
54
  const { locales } = require('../translations');
34
55
  const { settingsSchema } = require('../schemas');
35
56
  const { getOpenAiModels, OPEN_AI_MODELS, getExampleDocumentsPayloads, mcpToolGrants } = require('./route-helpers');
@@ -372,7 +393,18 @@ function init(args) {
372
393
  // write would leave the old URL in place after a save meant to clear it
373
394
  data.serviceUrl = request.payload.serviceUrl ? new URL(request.payload.serviceUrl).origin : null;
374
395
 
396
+ // Compared before the write, and only for the reload: this form submits the service URL
397
+ // on every save, so reloading on the write alone would hand three listeners a new
398
+ // certificate every time somebody changed the timezone.
399
+ const serviceUrlChanged = data.serviceUrl !== (await settings.get('serviceUrl'));
400
+
375
401
  await settings.setMulti(data);
402
+
403
+ // The service URL names the first hostname EmailEngine serves TLS for, so changing it
404
+ // here changes what the listeners have to offer exactly as the TLS page's own hostname
405
+ // list does. Without this the listeners kept answering with a certificate for the
406
+ // previous name until something restarted them.
407
+ await maybeReloadTlsCertificates(call, request.logger, serviceUrlChanged ? ['serviceUrl'] : [], { action: 'settings' });
376
408
  }
377
409
  });
378
410
 
@@ -598,22 +630,32 @@ function init(args) {
598
630
  // into the one action they were derived from.
599
631
  const mcpTools = mcpToolGrants(server, request.logger);
600
632
 
601
- let toolCatalog = [];
633
+ // The catalog, split the way the scopes split it: one bucket per access section in
634
+ // section order, each tool filed under the first section whose scope covers it (so
635
+ // the account reads both scopes share sit under management, marked as shared), and
636
+ // anything no scope covers in a bucket of its own - a guardrail keeps that one empty,
637
+ // and the page says so rather than filing such a tool under a scope it did not check.
638
+ const toolCatalog = { sections: [], unreached: [] };
602
639
  try {
603
- toolCatalog = getToolRegistry(server).tools.map(tool => ({
604
- name: tool.name,
605
- description: tool.description,
606
- badge: tool.annotations.openWorldHint
607
- ? { label: 'sends email', variant: 'warning' }
608
- : tool.annotations.destructiveHint
609
- ? { label: 'destructive', variant: 'error' }
610
- : tool.annotations.readOnlyHint
611
- ? { label: 'read-only', variant: 'success' }
612
- : { label: 'write', variant: 'info' }
613
- }));
640
+ const grantsByName = new Map(mcpTools.map(entry => [entry.name, entry]));
641
+ const buckets = new Map(Object.values(MCP_SECTIONS).map(section => [section.scope, { label: section.label, scope: section.scope, tools: [] }]));
642
+ for (const tool of getToolRegistry(server).tools) {
643
+ const grant = grantsByName.get(tool.name);
644
+ const surfaces = (grant && grant.surfaces) || [];
645
+ const entry = {
646
+ name: tool.name,
647
+ description: tool.description,
648
+ badge: (grant && TOOL_BADGES[grant.action]) || TOOL_BADGES[ACTION.WRITE],
649
+ shared: surfaces.length > 1
650
+ };
651
+ const bucket = [...buckets.keys()].find(scope => surfaces.includes(scope));
652
+ (bucket ? buckets.get(bucket).tools : toolCatalog.unreached).push(entry);
653
+ }
654
+ toolCatalog.sections = [...buckets.values()];
614
655
  } catch (err) {
615
656
  request.logger.error({ msg: 'Failed to derive the MCP tool catalog', err });
616
657
  }
658
+ toolCatalog.total = toolCatalog.sections.reduce((sum, section) => sum + section.tools.length, toolCatalog.unreached.length);
617
659
 
618
660
  const serviceUrlConfigured = !!configuredOrigin;
619
661
 
@@ -643,15 +685,14 @@ function init(args) {
643
685
  oauthMethodBlocker,
644
686
  toolCatalog,
645
687
  // The same catalog reduced to what the tool count needs: one entry per tool with
646
- // the operation it dispatches under and whether it can be bound to an account
688
+ // the operation it dispatches under, the scopes that reach it and whether it can
689
+ // be bound to an account
647
690
  mcpTools,
648
- // The whole access-level table, `full: null` included: the page script keys on
649
- // the same map the consent route mints from, so a level added there is offered
650
- // here without a second list to update
651
- mcpAccessPresets: MCP_ACCESS_LEVELS,
652
- // The generator's radio group renders through the shared mcp_access_levels
653
- // partial, from the same table the consent prompt offers
654
- accessOptions: MCP_ACCESS_LEVEL_OPTIONS,
691
+ // The two access sections with their levels and what each mints: the generator's
692
+ // radio groups render through the shared mcp_access_levels partial and its script
693
+ // mints from the same table the consent prompt does, so a level added there is
694
+ // offered here without a second list to update
695
+ mcpSections: MCP_SECTIONS,
655
696
  // The same gate as the token pages: minting needs an authenticated admin
656
697
  // session on this request, not just a password existing in Redis
657
698
  canProvision: request.auth.isAuthenticated
@@ -10,6 +10,7 @@ const getSecret = require('../get-secret');
10
10
  const { failAction, verifyAccountInfo, formatPartialSecretKey } = require('../tools');
11
11
  const { templateSchemas, accountIdSchema, tokenPermissionsSchema } = require('../schemas');
12
12
  const tokenPermissionView = require('../token-permission-view');
13
+ const { PRIVILEGED_SETTINGS_SUMMARY } = require('../privileged-settings');
13
14
  const { Account, accountExists } = require('../account');
14
15
  const { isMcpEnabled } = require('../mcp');
15
16
  const { Gateway } = require('../gateway');
@@ -25,7 +26,7 @@ const { DEFAULT_PAGE_SIZE } = consts;
25
26
  // Every scope the admin token form can mint - one list, because the listing's ?scope= filter
26
27
  // validates against the same vocabulary and a scope added to one side must not leave the other
27
28
  // behind. Deliberately wider than the /v1/tokens set, which excludes '*' and 'metrics'.
28
- const ADMIN_TOKEN_SCOPES = ['*', 'api', 'metrics', 'smtp', 'imap-proxy', 'mcp'];
29
+ const ADMIN_TOKEN_SCOPES = ['*', 'api', 'metrics', 'smtp', 'imap-proxy', 'mcp', 'mcp-manage'];
29
30
 
30
31
  const notificationTypes = Object.keys(consts)
31
32
  .map(key => {
@@ -2312,7 +2313,9 @@ return payload;`)
2312
2313
  query: request.query.query,
2313
2314
  // The active scope filter, so the page can say it is showing a subset and
2314
2315
  // offer the way out of it
2315
- scopeFilter: request.query.scope,
2316
+ // Rendered inside 'Tokens with the "..." scope', so a multi-scope filter reads
2317
+ // as the alternatives it is
2318
+ scopeFilter: request.query.scope ? request.query.scope.join('" or "') : null,
2316
2319
  // The create button leads to a form that cannot submit without an admin session
2317
2320
  canProvision: request.auth.isAuthenticated,
2318
2321
  searchHidden: [
@@ -2362,11 +2365,16 @@ return payload;`)
2362
2365
  // read every record on the instance and then match all of them
2363
2366
  query: Joi.string().empty('').trim().example('prometheus').description('Filter by search term'),
2364
2367
  // The vocabulary the token form accepts, so the filter cannot name a scope
2365
- // no token could carry
2366
- scope: Joi.string()
2367
- .empty('')
2368
- .valid(...ADMIN_TOKEN_SCOPES)
2369
- .description('Only tokens carrying this scope')
2368
+ // no token could carry. Repeatable (?scope=a&scope=b), because the MCP pages
2369
+ // ask for the tokens of both MCP scopes at once.
2370
+ scope: Joi.array()
2371
+ .items(
2372
+ Joi.string()
2373
+ .empty('')
2374
+ .valid(...ADMIN_TOKEN_SCOPES)
2375
+ )
2376
+ .single()
2377
+ .description('Only tokens carrying one of these scopes')
2370
2378
  })
2371
2379
  }
2372
2380
  }
@@ -2410,16 +2418,18 @@ return payload;`)
2410
2418
  // is why the mint is refused rather than merely discouraged. Rendering the form
2411
2419
  // anyway meant filling it in and losing the work to a 403.
2412
2420
  canProvision: request.auth.isAuthenticated,
2421
+ // The settings a restricted token is refused, in the words every description
2422
+ // of that rule uses, rendered from the list the rule reads
2423
+ privilegedSettingsSummary: PRIVILEGED_SETTINGS_SUMMARY,
2413
2424
  ...permissionModel,
2414
2425
  // Handed to the page as data rather than restated in its script
2415
2426
  permissionSurfacesJson: JSON.stringify(permissionModel.permissionSurfaces),
2416
2427
  mcpTools,
2417
- // The same three access levels the OAuth consent prompt and the MCP config
2418
- // page offer, from the same table, rendered through the same partial. An
2419
- // mcp-scoped token is minted from three places and the levels have to mean
2420
- // the same thing in all of them.
2421
- accessOptions: tokenPermissionView.MCP_ACCESS_LEVEL_OPTIONS,
2422
- mcpAccessPresets: tokenPermissionView.MCP_ACCESS_LEVELS,
2428
+ // The same two access sections the OAuth consent prompt and the MCP config
2429
+ // page offer, from the same table, rendered through the same partial. An MCP
2430
+ // token is minted from three places and the levels have to mean the same
2431
+ // thing in all of them.
2432
+ mcpSections: tokenPermissionView.MCP_SECTIONS,
2423
2433
  // Whether the endpoint an mcp-scoped token would talk to is actually serving.
2424
2434
  // Both halves of the gate, because a token minted against either one being off
2425
2435
  // is a credential for nothing, and the form is the last place to say so.
@@ -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();
@@ -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' }
@@ -32,9 +32,9 @@ const { accountExists } = require('../account');
32
32
  const { accountPickerSelection, mcpToolGrants } = require('./route-helpers');
33
33
  const { failAction } = require('../tools');
34
34
  const { accountIdSchema } = require('../schemas');
35
- const { MCP_ACCESS_LEVELS, MCP_ACCESS_LEVEL_OPTIONS, MCP_GRANT_WORDING } = require('../token-permission-view');
35
+ const { MCP_SECTIONS, mcpGrantsFor, mcpLevelNames } = require('../token-permission-view');
36
36
  const { mcpFeatureEnabled } = require('../mcp');
37
- const { oauthOrigin, getClient, touchClient, createAuthorizationCode, isAcceptableResource } = require('../mcp/oauth');
37
+ const { oauthOrigin, getClient, touchClient, createAuthorizationCode, isAcceptableResource, normalizeScopes } = require('../mcp/oauth');
38
38
 
39
39
  // Both consent routes answer with a redirect to the OAuth client's registered redirect_uri,
40
40
  // often http://localhost for a native client, and Chrome checks the redirect target of a form
@@ -101,10 +101,14 @@ async function init(args) {
101
101
  // lookup exactly when there is a choice on the form to show back
102
102
  const selectedAccount = canProvision && values && values.account ? await accountPickerSelection(values.account, server.logger) : null;
103
103
 
104
- // Read-only unless the operator picked otherwise; a re-render after a validation error
105
- // keeps whatever they chose. The template compares this against each option itself
106
- // (the `equals` helper), so the level is one value rather than three booleans.
107
- const accessLevel = values && Object.hasOwn(MCP_ACCESS_LEVELS, values.access) ? values.access : 'read';
104
+ // Management at Observe and no mail access unless the request or the operator said
105
+ // otherwise; a re-render after a validation error keeps whatever they chose. One value per
106
+ // section, which the template compares against each level itself (the `equals` helper).
107
+ const selectedLevels = {};
108
+ for (const [key, section] of Object.entries(MCP_SECTIONS)) {
109
+ const posted = values && values[key];
110
+ selectedLevels[key] = mcpLevelNames(section).includes(posted) ? posted : section.defaultLevel;
111
+ }
108
112
 
109
113
  // From the registry the endpoint dispatches through, so the count under the radios cannot
110
114
  // describe a tool set that has since changed
@@ -118,21 +122,18 @@ async function init(args) {
118
122
  clientName: (client && client.client_name) || 'An MCP client',
119
123
  redirectHost: redirectHostOf(redirectUri),
120
124
 
121
- // What approving actually grants, in plain words, derived once at load from the
122
- // same tables the enforcement reads - hand-written prose here would drift the
123
- // first time the tool set changes
124
- grantWording: MCP_GRANT_WORDING,
125
-
126
- accessLevel,
127
- // The radio group itself renders through the shared mcp_access_levels partial
128
- accessOptions: MCP_ACCESS_LEVEL_OPTIONS,
125
+ // The two sections and their levels, with what approving each one actually grants
126
+ // in plain words, derived once at load from the same tables the enforcement reads -
127
+ // hand-written prose here would drift the first time the tool set changes. The
128
+ // radio groups render through the shared mcp_access_levels partial.
129
+ mcpSections: MCP_SECTIONS,
130
+ selectedLevels,
129
131
 
130
- // The tool count under the radios, through the shared mcp_tool_count partial. The
132
+ // The tool count under the sections, through the shared mcp_tool_count partial. The
131
133
  // grant sentences above it say what a level allows in the permission vocabulary;
132
134
  // this says which tools the client ends up holding, which is the thing the person
133
135
  // approving is actually being asked about.
134
136
  mcpTools,
135
- mcpAccessPresets: MCP_ACCESS_LEVELS,
136
137
 
137
138
  selectedAccount,
138
139
 
@@ -191,6 +192,22 @@ async function init(args) {
191
192
 
192
193
  await touchClient(client.client_id);
193
194
 
195
+ // The `scope` parameter is a hint for the starting position of the form, never a
196
+ // grant: a client asking for `mcp` is asking for mail access, so the mail section
197
+ // starts at its narrowest level; one asking only for `mcp` starts with no management
198
+ // access, since it did not ask for any. A request naming no scope starts where the
199
+ // page starts anyway, management at Observe and mail declined. The person still
200
+ // decides.
201
+ const requested = normalizeScopes(request.query.scope);
202
+ const hinted = {};
203
+ for (const [key, section] of Object.entries(MCP_SECTIONS)) {
204
+ if (requested.includes(section.scope)) {
205
+ hinted[key] = section.levels[0].value;
206
+ } else if (requested.length) {
207
+ hinted[key] = 'none';
208
+ }
209
+ }
210
+
194
211
  return renderConsent(h, {
195
212
  client,
196
213
  redirectUri: request.query.redirect_uri,
@@ -200,7 +217,8 @@ async function init(args) {
200
217
  redirect_uri: request.query.redirect_uri,
201
218
  state: request.query.state,
202
219
  code_challenge: request.query.code_challenge,
203
- resource: request.query.resource
220
+ resource: request.query.resource,
221
+ ...hinted
204
222
  }
205
223
  });
206
224
  },
@@ -281,12 +299,28 @@ async function init(args) {
281
299
  });
282
300
  }
283
301
 
284
- // Read-only is the default here exactly as it is on the admin generator, and for a
285
- // stronger reason: this flow issues credentials to the least controllable clients on
286
- // the least controllable devices. The radio always posts a value, so the schema
287
- // default only ever fires for a stale or hand-crafted POST - and defaulting that to
288
- // 'read' means an omitted field mints the narrowest token, not the widest.
289
- const access = request.payload.access;
302
+ // Management at Observe and no mail access are the defaults here exactly as they are
303
+ // on the admin generator, and for a stronger reason: this flow issues credentials to
304
+ // the least controllable clients on the least controllable devices. The radios always
305
+ // post a value, so the schema defaults only ever fire for a stale or hand-crafted POST
306
+ // - and they mint the narrowest useful token, not the widest.
307
+ const choice = {};
308
+ for (const key of Object.keys(MCP_SECTIONS)) {
309
+ choice[key] = request.payload[key];
310
+ }
311
+ const { scopes, permissions } = mcpGrantsFor(choice);
312
+
313
+ if (!scopes.length) {
314
+ // Every section declined is not a narrow token, it is no token: re-rendered with
315
+ // the reason rather than minting a credential that can do nothing
316
+ return renderConsent(h, {
317
+ client,
318
+ redirectUri: request.payload.redirect_uri,
319
+ canProvision: true,
320
+ values: request.payload,
321
+ errors: { access: 'Choose at least one kind of access, or deny the request.' }
322
+ });
323
+ }
290
324
 
291
325
  const code = await createAuthorizationCode({
292
326
  clientId: client.client_id,
@@ -294,7 +328,8 @@ async function init(args) {
294
328
  codeChallenge: request.payload.code_challenge,
295
329
  resource: request.payload.resource || null,
296
330
  account,
297
- permissions: MCP_ACCESS_LEVELS[access],
331
+ scopes,
332
+ permissions,
298
333
  description: `MCP: ${client.client_name || redirectHostOf(request.payload.redirect_uri)}${account ? ` (${account})` : ''}`
299
334
  });
300
335
 
@@ -303,7 +338,7 @@ async function init(args) {
303
338
  client: client.client_id,
304
339
  clientName: client.client_name,
305
340
  account,
306
- access
341
+ levels: choice
307
342
  });
308
343
 
309
344
  return redirectToClient(h, authRequest, { code });
@@ -324,12 +359,18 @@ async function init(args) {
324
359
  Object.assign({}, oauthParamsSchema, {
325
360
  decision: Joi.string().valid('approve', 'deny').required(),
326
361
  account: accountIdSchema.allow('').default(null),
327
- // The keys of MCP_ACCESS_LEVELS, defaulting to the narrowest: a payload
328
- // that names no level (a stale form, a hand-crafted POST) mints the
329
- // read-only token, never the wide one
330
- access: Joi.string()
331
- .valid(...Object.keys(MCP_ACCESS_LEVELS))
332
- .default('read')
362
+ // One field per section, validated against the levels the table has plus
363
+ // `none`, defaulting to the section's own default - the narrowest useful
364
+ // choice: a payload that names no level (a stale form, a hand-crafted POST)
365
+ // mints a management token that can only observe, and no mail access
366
+ ...Object.fromEntries(
367
+ Object.entries(MCP_SECTIONS).map(([key, section]) => [
368
+ key,
369
+ Joi.string()
370
+ .valid(...mcpLevelNames(section))
371
+ .default(section.defaultLevel)
372
+ ])
373
+ )
333
374
  })
334
375
  )
335
376
  }
@@ -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
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 = {
@@ -259,8 +262,17 @@ function init(args) {
259
262
  }
260
263
  });
261
264
 
262
- // Context shared by the SMTP server and IMAP proxy pages: live server state,
263
- // 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.
264
276
  const serverPageContext = async (h, serverType) => {
265
277
  let availableAddresses = new Set(
266
278
  Object.values(os.networkInterfaces())
@@ -269,13 +281,39 @@ function init(args) {
269
281
  );
270
282
  availableAddresses.add('0.0.0.0');
271
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
+
272
312
  return {
273
- serverState: await getServerStatus(serverType),
313
+ serverState,
274
314
  availableAddresses: Array.from(availableAddresses).join(','),
275
315
 
276
- serviceDomain: await h.serviceDomain(),
277
- serviceUrl: await settings.get('serviceUrl'),
278
- certificateData: await h.getCertificate()
316
+ tlsSummary
279
317
  };
280
318
  };
281
319
 
@@ -358,55 +396,26 @@ function init(args) {
358
396
  }
359
397
  });
360
398
 
361
- server.route({
362
- method: 'POST',
363
- path: '/admin/config/smtp/certificate',
364
- async handler(request, h) {
365
- try {
366
- // What is installed before provisioning, so the reload below fires only when a new
367
- // certificate actually arrived and repeated clicks do not keep restarting both
368
- // servers.
369
- let existingCertificateData = await h.getCertificate();
370
-
371
- let certificateData = await h.getCertificate(true);
372
- if (!certificateData) {
373
- throw new Error(`Failed to provision a certificate`);
374
- }
375
-
376
- if (certificateData.fingerprint && certificateData.fingerprint !== (existingCertificateData && existingCertificateData.fingerprint)) {
377
- await reloadTlsServers(call, request.logger, { domain: certificateData.domain });
378
- }
379
-
380
- return {
381
- success: true,
382
- domain: certificateData.domain,
383
- fingerprint: certificateData.fingerprint,
384
- altNames: certificateData.altNames,
385
- validTo: certificateData.validTo && certificateData.validTo.toISOString(),
386
- label: certificateData.label
387
- };
388
- } catch (err) {
389
- request.logger.error({ msg: 'Failed to provision a certificate', err });
390
- return {
391
- success: false,
392
- error: err.message
393
- };
394
- }
395
- }
396
- });
397
-
398
399
  server.route({
399
400
  method: 'POST',
400
401
  path: '/admin/config/browser',
401
402
  async handler(request) {
403
+ const written = [];
402
404
  for (let key of ['serviceUrl', 'language', 'timezone']) {
403
405
  if (request.payload[key]) {
404
406
  let existingValue = await settings.get(key);
405
407
  if (existingValue === null) {
406
408
  await settings.set(key, request.payload[key]);
409
+ written.push(key);
407
410
  }
408
411
  }
409
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
+
410
419
  return { success: true };
411
420
  },
412
421
  options: {