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
@@ -39,7 +39,18 @@ const { mcpFeatureEnabled } = require('../mcp');
39
39
  const { mcpResource } = require('../mcp/oauth');
40
40
  const { getToolRegistry } = require('../mcp/tools');
41
41
  const { serverUrl } = require('../openapi');
42
- 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
+ };
43
54
  const { locales } = require('../translations');
44
55
  const { settingsSchema } = require('../schemas');
45
56
  const { getOpenAiModels, OPEN_AI_MODELS, getExampleDocumentsPayloads, mcpToolGrants } = require('./route-helpers');
@@ -619,22 +630,32 @@ function init(args) {
619
630
  // into the one action they were derived from.
620
631
  const mcpTools = mcpToolGrants(server, request.logger);
621
632
 
622
- 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: [] };
623
639
  try {
624
- toolCatalog = getToolRegistry(server).tools.map(tool => ({
625
- name: tool.name,
626
- description: tool.description,
627
- badge: tool.annotations.openWorldHint
628
- ? { label: 'sends email', variant: 'warning' }
629
- : tool.annotations.destructiveHint
630
- ? { label: 'destructive', variant: 'error' }
631
- : tool.annotations.readOnlyHint
632
- ? { label: 'read-only', variant: 'success' }
633
- : { label: 'write', variant: 'info' }
634
- }));
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()];
635
655
  } catch (err) {
636
656
  request.logger.error({ msg: 'Failed to derive the MCP tool catalog', err });
637
657
  }
658
+ toolCatalog.total = toolCatalog.sections.reduce((sum, section) => sum + section.tools.length, toolCatalog.unreached.length);
638
659
 
639
660
  const serviceUrlConfigured = !!configuredOrigin;
640
661
 
@@ -664,15 +685,14 @@ function init(args) {
664
685
  oauthMethodBlocker,
665
686
  toolCatalog,
666
687
  // The same catalog reduced to what the tool count needs: one entry per tool with
667
- // 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
668
690
  mcpTools,
669
- // The whole access-level table, `full: null` included: the page script keys on
670
- // the same map the consent route mints from, so a level added there is offered
671
- // here without a second list to update
672
- mcpAccessPresets: MCP_ACCESS_LEVELS,
673
- // The generator's radio group renders through the shared mcp_access_levels
674
- // partial, from the same table the consent prompt offers
675
- 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,
676
696
  // The same gate as the token pages: minting needs an authenticated admin
677
697
  // session on this request, not just a password existing in Redis
678
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 => {
@@ -305,10 +306,10 @@ return payload;`)
305
306
  }
306
307
  );
307
308
 
308
- await request.flash({ type: 'info', message: `Webhook created` });
309
+ await request.flash({ type: 'info', message: `Webhook route created` });
309
310
  return h.redirect(adminUrl`/admin/webhooks/webhook/${createRequest.id}`);
310
311
  } catch (err) {
311
- await request.flash({ type: 'danger', message: `Couldn't create webhook. Try again.` });
312
+ await request.flash({ type: 'danger', message: `Couldn't create webhook route. Try again.` });
312
313
  request.logger.error({ msg: 'Failed to create webhook route', err });
313
314
 
314
315
  return h.view(
@@ -348,7 +349,7 @@ return payload;`)
348
349
  });
349
350
  }
350
351
 
351
- await request.flash({ type: 'danger', message: `Couldn't create webhook. Try again.` });
352
+ await request.flash({ type: 'danger', message: `Couldn't create webhook route. Try again.` });
352
353
  request.logger.debug({ msg: 'Failed to create webhook route', err });
353
354
 
354
355
  return h
@@ -620,10 +621,10 @@ return payload;`)
620
621
  }
621
622
  );
622
623
 
623
- await request.flash({ type: 'info', message: `Webhook saved` });
624
+ await request.flash({ type: 'info', message: `Webhook route saved` });
624
625
  return h.redirect(adminUrl`/admin/webhooks/webhook/${request.payload.webhook}`);
625
626
  } catch (err) {
626
- await request.flash({ type: 'danger', message: `Couldn't save webhook. Try again.` });
627
+ await request.flash({ type: 'danger', message: `Couldn't save webhook route. Try again.` });
627
628
  request.logger.error({ msg: 'Failed to update webhook route', err });
628
629
 
629
630
  let webhook = await webhooks.get(request.payload.webhook);
@@ -672,7 +673,7 @@ return payload;`)
672
673
  });
673
674
  }
674
675
 
675
- await request.flash({ type: 'danger', message: `Couldn't save webhook. Try again.` });
676
+ await request.flash({ type: 'danger', message: `Couldn't save webhook route. Try again.` });
676
677
  request.logger.debug({ msg: 'Failed to update webhook route', err });
677
678
 
678
679
  let webhook = await webhooks.get(request.payload.webhook);
@@ -763,13 +764,13 @@ return payload;`)
763
764
  try {
764
765
  await webhooks.del(request.payload.webhook);
765
766
 
766
- await request.flash({ type: 'info', message: `Webhook deleted` });
767
+ await request.flash({ type: 'info', message: `Webhook route deleted` });
767
768
 
768
769
  let accountWebhooksLink = new URL('/admin/webhooks', 'http://localhost');
769
770
 
770
771
  return h.redirect(accountWebhooksLink.pathname + accountWebhooksLink.search);
771
772
  } catch (err) {
772
- await request.flash({ type: 'danger', message: `Couldn't delete webhook. Try again.` });
773
+ await request.flash({ type: 'danger', message: `Couldn't delete webhook route. Try again.` });
773
774
  request.logger.error({ msg: 'Failed to delete webhook route', err, webhook: request.payload.webhook, remoteAddress: request.app.ip });
774
775
  return h.redirect(adminUrl`/admin/webhooks/webhook/${request.payload.webhook}`);
775
776
  }
@@ -783,7 +784,7 @@ return payload;`)
783
784
  },
784
785
 
785
786
  async failAction(request, h, err) {
786
- await request.flash({ type: 'danger', message: `Couldn't delete webhook. Try again.` });
787
+ await request.flash({ type: 'danger', message: `Couldn't delete webhook route. Try again.` });
787
788
  request.logger.debug({ msg: 'Failed to delete webhook route', err });
788
789
 
789
790
  return h.redirect('/admin/webhooks').takeover();
@@ -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.
@@ -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
  }