emailengine-app 2.80.0 → 2.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/.dockerignore +44 -0
  2. package/.github/docker-smoke-test.sh +16 -0
  3. package/.github/workflows/deploy.yml +4 -0
  4. package/.github/workflows/release.yaml +4 -0
  5. package/.github/workflows/test.yml +2 -0
  6. package/.release-please-manifest.json +1 -1
  7. package/CHANGELOG.md +56 -0
  8. package/Dockerfile +17 -9
  9. package/README.md +6 -0
  10. package/data/google-crawlers.json +1 -1
  11. package/docker-compose.yml +7 -1
  12. package/lib/api-routes/account-routes.js +239 -73
  13. package/lib/api-routes/blocklist-routes.js +24 -0
  14. package/lib/api-routes/delivery-test-routes.js +6 -0
  15. package/lib/api-routes/gateway-routes.js +30 -0
  16. package/lib/api-routes/license-routes.js +10 -0
  17. package/lib/api-routes/mcp-oauth-routes.js +3 -3
  18. package/lib/api-routes/mcp-routes.js +39 -21
  19. package/lib/api-routes/oauth2-app-routes.js +38 -1
  20. package/lib/api-routes/outbox-routes.js +6 -0
  21. package/lib/api-routes/permission-map.js +212 -42
  22. package/lib/api-routes/pubsub-routes.js +8 -0
  23. package/lib/api-routes/route-helpers.js +58 -11
  24. package/lib/api-routes/settings-routes.js +50 -4
  25. package/lib/api-routes/stats-routes.js +6 -0
  26. package/lib/api-routes/template-routes.js +21 -0
  27. package/lib/api-routes/token-routes.js +34 -2
  28. package/lib/api-routes/webhook-route-routes.js +13 -0
  29. package/lib/autodetect-imap-settings.js +4 -4
  30. package/lib/email-client/base-client.js +6 -3
  31. package/lib/email-client/credential-errors.js +4 -0
  32. package/lib/email-client/imap/login-failure.js +52 -0
  33. package/lib/email-client/imap/subconnection.js +2 -1
  34. package/lib/email-client/imap-client.js +3 -6
  35. package/lib/enum-descriptions.js +12 -2
  36. package/lib/imapproxy/imap-server.js +1 -1
  37. package/lib/mcp/oauth.js +46 -8
  38. package/lib/mcp/protocol.js +78 -35
  39. package/lib/mcp/tools.js +53 -17
  40. package/lib/privileged-settings.js +147 -0
  41. package/lib/schemas.js +60 -16
  42. package/lib/sentry.js +13 -2
  43. package/lib/settings.js +13 -0
  44. package/lib/tls/catalog.js +428 -0
  45. package/lib/tls/context.js +87 -161
  46. package/lib/tls/listeners.js +62 -0
  47. package/lib/tls/provision.js +1 -1
  48. package/lib/tls/status.js +128 -79
  49. package/lib/tls/store.js +3 -2
  50. package/lib/token-permission-view.js +253 -102
  51. package/lib/token-permissions.js +176 -26
  52. package/lib/tokens.js +7 -6
  53. package/lib/tools.js +5 -3
  54. package/lib/ui-routes/account-routes.js +195 -61
  55. package/lib/ui-routes/admin-config-routes.js +41 -21
  56. package/lib/ui-routes/admin-entities-routes.js +32 -22
  57. package/lib/ui-routes/mcp-consent-routes.js +72 -31
  58. package/lib/ui-routes/tls-config-routes.js +121 -74
  59. package/package.json +16 -16
  60. package/sbom.json +1 -1
  61. package/server.js +7 -1
  62. package/static/css/flyonui.css +1 -1
  63. package/static/css/public.css +41 -0
  64. package/static/css/src/app.tailwind.css +135 -4
  65. package/static/js/public.js +218 -0
  66. package/static/js/ui.js +89 -36
  67. package/static/licenses.html +55 -37
  68. package/translations/README.md +4 -3
  69. package/translations/de.mo +0 -0
  70. package/translations/de.po +296 -185
  71. package/translations/en.po +220 -128
  72. package/translations/es.mo +0 -0
  73. package/translations/es.po +558 -0
  74. package/translations/et.mo +0 -0
  75. package/translations/et.po +288 -181
  76. package/translations/fr.mo +0 -0
  77. package/translations/fr.po +295 -183
  78. package/translations/it.mo +0 -0
  79. package/translations/it.po +558 -0
  80. package/translations/ja.mo +0 -0
  81. package/translations/ja.po +268 -192
  82. package/translations/locales.json +24 -0
  83. package/translations/messages.pot +179 -127
  84. package/translations/nl.mo +0 -0
  85. package/translations/nl.po +288 -175
  86. package/translations/pl.mo +0 -0
  87. package/translations/pl.po +294 -181
  88. package/translations/sv.mo +0 -0
  89. package/translations/sv.po +555 -0
  90. package/translations/tr.mo +0 -0
  91. package/translations/tr.po +555 -0
  92. package/update-info.sh +12 -6
  93. package/views/account/login-redirect.hbs +6 -5
  94. package/views/account/passkeys.hbs +8 -8
  95. package/views/account/security.hbs +2 -2
  96. package/views/accounts/account.hbs +19 -21
  97. package/views/accounts/browse.hbs +1 -1
  98. package/views/accounts/edit.hbs +15 -15
  99. package/views/accounts/index.hbs +3 -3
  100. package/views/accounts/register/imap-server.hbs +27 -173
  101. package/views/accounts/register/validating.hbs +139 -0
  102. package/views/config/ai.hbs +15 -17
  103. package/views/config/branding.hbs +7 -7
  104. package/views/config/document-store/chat.hbs +9 -8
  105. package/views/config/document-store/index.hbs +14 -15
  106. package/views/config/document-store/mappings/index.hbs +5 -6
  107. package/views/config/document-store/mappings/new.hbs +1 -2
  108. package/views/config/document-store/pre-processing/index.hbs +4 -4
  109. package/views/config/email-processing.hbs +6 -6
  110. package/views/config/imap-proxy.hbs +7 -8
  111. package/views/config/license.hbs +9 -9
  112. package/views/config/logging.hbs +5 -7
  113. package/views/config/mcp.hbs +90 -58
  114. package/views/config/network.hbs +4 -4
  115. package/views/config/oauth/app.hbs +12 -12
  116. package/views/config/oauth/index.hbs +6 -6
  117. package/views/config/oauth/subscriptions.hbs +9 -9
  118. package/views/config/security.hbs +5 -7
  119. package/views/config/service.hbs +11 -10
  120. package/views/config/smtp.hbs +9 -12
  121. package/views/config/tls-upload.hbs +3 -3
  122. package/views/config/tls.hbs +281 -182
  123. package/views/config/webhooks.hbs +12 -15
  124. package/views/dashboard.hbs +9 -8
  125. package/views/gateways/edit.hbs +3 -3
  126. package/views/gateways/gateway.hbs +3 -3
  127. package/views/gateways/index.hbs +6 -6
  128. package/views/gateways/new.hbs +3 -3
  129. package/views/internals/index.hbs +15 -13
  130. package/views/layout/app.hbs +6 -6
  131. package/views/layout/login.hbs +32 -19
  132. package/views/layout/main.hbs +2 -2
  133. package/views/layout/prompt.hbs +15 -18
  134. package/views/layout/public.hbs +1 -1
  135. package/views/mcp/authorize.hbs +47 -45
  136. package/views/partials/accounts_table.hbs +5 -5
  137. package/views/partials/ace_assets.hbs +1 -1
  138. package/views/partials/add_account_modal.hbs +4 -4
  139. package/views/partials/address_list.hbs +4 -4
  140. package/views/partials/filter_editor_js.hbs +2 -2
  141. package/views/partials/gateway_form.hbs +5 -5
  142. package/views/partials/gateway_js.hbs +1 -1
  143. package/views/partials/mcp_access_levels.hbs +16 -9
  144. package/views/partials/mcp_account_limit.hbs +2 -2
  145. package/views/partials/mcp_tool_count.hbs +15 -14
  146. package/views/partials/oauth_config_header.hbs +2 -2
  147. package/views/partials/oauth_form.hbs +37 -42
  148. package/views/partials/public_alerts.hbs +1 -1
  149. package/views/partials/public_test_labels.hbs +15 -0
  150. package/views/partials/public_theme_init.hbs +1 -1
  151. package/views/partials/security_header.hbs +2 -2
  152. package/views/partials/template_form.hbs +4 -4
  153. package/views/partials/theme_init.hbs +1 -1
  154. package/views/partials/tls_security_card.hbs +4 -1
  155. package/views/partials/ui/form-field.hbs +6 -1
  156. package/views/partials/ui/setting-ref.hbs +12 -7
  157. package/views/partials/ui/stat-card.hbs +4 -1
  158. package/views/partials/ui/tabs.hbs +3 -7
  159. package/views/partials/webhook_form.hbs +9 -12
  160. package/views/partials/webhooks_editor_functions.hbs +1 -1
  161. package/views/reference/index.hbs +3 -3
  162. package/views/reference/redirect.hbs +1 -1
  163. package/views/reference/tag.hbs +1 -1
  164. package/views/reference/token.hbs +4 -4
  165. package/views/suppression-lists/index.hbs +8 -6
  166. package/views/suppression-lists/list.hbs +13 -8
  167. package/views/templates/edit.hbs +1 -1
  168. package/views/templates/index.hbs +10 -11
  169. package/views/templates/template.hbs +5 -5
  170. package/views/tokens/index.hbs +17 -17
  171. package/views/tokens/new.hbs +190 -93
  172. package/views/unsubscribe.hbs +1 -1
  173. package/views/webhooks/edit.hbs +1 -1
  174. package/views/webhooks/index.hbs +10 -11
  175. package/views/webhooks/new.hbs +1 -1
  176. package/views/webhooks/webhook.hbs +5 -6
  177. package/workers/api.js +9 -8
  178. package/workers/smtp.js +1 -1
package/lib/mcp/oauth.js CHANGED
@@ -5,10 +5,12 @@
5
5
  // It exists for exactly one flow: an MCP client that cannot be configured with a static access
6
6
  // token (claude.ai web connectors and similar) discovers this server through the protected
7
7
  // resource metadata, registers itself as a public client, sends the operator's browser to the
8
- // admin consent page, and exchanges the resulting code for an EmailEngine access token with the
9
- // `mcp` scope. Every credential this issues is an ordinary access token: visible on the admin
10
- // tokens page, revocable there, and bounded by SURFACE_GRANTS.mcp like any other mcp-scoped
11
- // token. There are no refresh tokens and no expiry by default - revocation is the lifecycle.
8
+ // admin consent page, and exchanges the resulting code for an EmailEngine access token carrying
9
+ // the MCP scopes the operator approved (`mcp-manage` for the instance, `mcp` for mail, or both).
10
+ // Every credential this issues is an ordinary access token: visible on the admin tokens page,
11
+ // revocable there, and bounded by the SURFACE_GRANTS table of each scope it holds like any other
12
+ // MCP-scoped token. There are no refresh tokens and no expiry by default - revocation is the
13
+ // lifecycle.
12
14
  //
13
15
  // What is implemented, spec-wise: OAuth 2.0 Dynamic Client Registration (RFC 7591, open
14
16
  // registration for public clients only, rate limited per IP), authorization code + PKCE S256
@@ -42,6 +44,25 @@ const CODE_TTL = 10 * 60;
42
44
  // schema too, so the validation layer and the policy here cannot drift apart.
43
45
  const MAX_REDIRECT_URIS = 10;
44
46
 
47
+ // The scopes this server issues, in the order the discovery documents advertise them and the
48
+ // order a token response lists them: management first, because that is what the consent page
49
+ // offers by default, and mail on request. A client that sends `scope=mcp` in its authorization
50
+ // request is asking for mail access; the consent page pre-ticks it, the person still decides.
51
+ const MCP_OAUTH_SCOPES = ['mcp-manage', 'mcp'];
52
+
53
+ /**
54
+ * The subset of the issuable scopes a list names, in canonical order. Anything else is dropped:
55
+ * the scope vocabulary is this server's to define, and an unknown value is not a narrower or
56
+ * wider grant, only noise from a client guessing.
57
+ *
58
+ * @param {Array|String} scopes - a scope list, or a space-separated scope string from the wire
59
+ * @returns {Array<String>}
60
+ */
61
+ function normalizeScopes(scopes) {
62
+ const requested = new Set(typeof scopes === 'string' ? scopes.split(/\s+/) : [].concat(scopes || []));
63
+ return MCP_OAUTH_SCOPES.filter(scope => requested.has(scope));
64
+ }
65
+
45
66
  const clientKey = clientId => `${REDIS_PREFIX}mcp:oauth:client:${clientId}`;
46
67
  const codeKey = code => `${REDIS_PREFIX}mcp:oauth:code:${code}`;
47
68
 
@@ -205,10 +226,19 @@ function isAcceptableResource(resource, origin) {
205
226
  * Mints a single-use authorization code after the admin approved the consent page.
206
227
  *
207
228
  * @param {Object} opts - clientId, redirectUri, codeChallenge, resource, account (optional
208
- * binding for the token), description (for the admin tokens listing)
229
+ * binding for the token), scopes (the MCP scopes the operator approved), permissions,
230
+ * description (for the admin tokens listing)
209
231
  * @returns {Promise<String>} the code
210
232
  */
211
233
  async function createAuthorizationCode(opts) {
234
+ const scopes = normalizeScopes(opts.scopes);
235
+ if (!scopes.length) {
236
+ // A code that mints a token with no surface is a token that can do nothing; the consent
237
+ // page refuses the combination before it gets here, so this is the belt to that brace -
238
+ // and a caller that forgot the argument fails here rather than minting a mail credential
239
+ throw oauthFailure('invalid_scope', 'No MCP scope was approved');
240
+ }
241
+
212
242
  const code = crypto.randomBytes(32).toString('base64url');
213
243
 
214
244
  const record = {
@@ -217,8 +247,9 @@ async function createAuthorizationCode(opts) {
217
247
  codeChallenge: opts.codeChallenge,
218
248
  resource: opts.resource || null,
219
249
  account: opts.account || null,
250
+ scopes,
220
251
  // The narrowing the operator approved, applied to the token this code mints. Absent
221
- // means unnarrowed within the mcp scope, the same shape the admin generator posts.
252
+ // means unnarrowed within the scopes, the same shape the admin generator posts.
222
253
  permissions: opts.permissions || null,
223
254
  description: opts.description,
224
255
  created: Date.now()
@@ -293,10 +324,14 @@ async function redeemAuthorizationCode({ code, clientId, redirectUri, codeVerifi
293
324
  throw oauthFailure('invalid_target', 'The resource parameter does not match the authorization request');
294
325
  }
295
326
 
327
+ // A code minted before the scopes were recorded on it carries none; it was issued for the
328
+ // one scope the flow had then
329
+ const scopes = Array.isArray(record.scopes) && record.scopes.length ? record.scopes : ['mcp'];
330
+
296
331
  const token = await tokens.provision({
297
332
  account: record.account || undefined,
298
333
  description: record.description,
299
- scopes: ['mcp'],
334
+ scopes,
300
335
  permissions: record.permissions || undefined,
301
336
  ip,
302
337
  metadata: JSON.stringify({ issuer: 'mcp-oauth', client: record.clientId })
@@ -305,13 +340,16 @@ async function redeemAuthorizationCode({ code, clientId, redirectUri, codeVerifi
305
340
  return {
306
341
  access_token: token,
307
342
  token_type: 'Bearer',
308
- scope: 'mcp'
343
+ // RFC 6749 3.3: space separated, and what was actually granted
344
+ scope: scopes.join(' ')
309
345
  };
310
346
  }
311
347
 
312
348
  module.exports = {
313
349
  oauthOrigin,
314
350
  mcpResource,
351
+ MCP_OAUTH_SCOPES,
352
+ normalizeScopes,
315
353
  registerClient,
316
354
  getClient,
317
355
  touchClient,
@@ -24,6 +24,7 @@
24
24
 
25
25
  const packageData = require('../../package.json');
26
26
  const { COLLAPSE_CLASS } = require('../consts');
27
+ const { MCP_SCOPES } = require('../api-routes/permission-map');
27
28
 
28
29
  const MODERN_PROTOCOL_VERSION = '2026-07-28';
29
30
  const LEGACY_PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18'];
@@ -46,47 +47,90 @@ const ERROR_CODES = {
46
47
 
47
48
  const SERVER_INFO = { name: 'EmailEngine', version: packageData.version };
48
49
 
49
- // Everything the instructions say that does not depend on which credential is asking. The collapse
50
- // marker earns its line here: it is a machine-readable "show more" boundary, and an agent that
51
- // knows the class name can read the new part of a thread without the quoted copies of everything
52
- // before it. The send warning is the other one that matters, and having it in one place is why it
53
- // cannot be edited in the generic set and forgotten in the bound one.
54
- const COMMON_INSTRUCTIONS = [
55
- 'Message ids come from list_messages or search_messages.',
56
- `Message bodies are returned as sanitized HTML; quoted reply and forward history is wrapped in a <details class="${COLLAPSE_CLASS}"> element, ` +
57
- 'so what the sender actually wrote is everything outside it.',
58
- 'send_message delivers real email to real recipients - confirm with the user before calling it.'
59
- ];
50
+ // What the instructions say about each tool set, keyed by the scope that carries it. The mail
51
+ // lines earn their place: the collapse marker is a machine-readable "show more" boundary, and an
52
+ // agent that knows the class name can read the new part of a thread without the quoted copies of
53
+ // everything before it, and the send warning is the other one that matters. The management lines
54
+ // name what to confirm, because settings apply at once and several of the tools are one-way, and
55
+ // a client may or may not surface the tool descriptions. One place per set, so a line cannot be
56
+ // edited for one credential shape and forgotten for another.
57
+ const SURFACE_INSTRUCTIONS = {
58
+ [MCP_SCOPES.manage]: [
59
+ 'Settings and configuration changes take effect immediately.',
60
+ 'Confirm with the user before changing where webhooks or notifications are delivered, before changing where an account or gateway connects, and before anything destructive: deleting, revoking, flushing.',
61
+ 'To add a mailbox, prefer create_account_setup_link so the user signs in themselves and no password passes through this conversation.'
62
+ ],
63
+ [MCP_SCOPES.mail]: [
64
+ 'Message ids come from list_messages or search_messages.',
65
+ `Message bodies are returned as sanitized HTML; quoted reply and forward history is wrapped in a <details class="${COLLAPSE_CLASS}"> element, ` +
66
+ 'so what the sender actually wrote is everything outside it.',
67
+ 'send_message delivers real email to real recipients - confirm with the user before calling it.'
68
+ ]
69
+ };
60
70
 
61
71
  /**
62
72
  * The instructions shown to the calling model by clients that surface them.
63
73
  *
64
- * Only the opening differs, and it differs on the one thing that changes what the agent can do:
65
- * the generic set tells it to list the accounts and pass an id, which a bound credential can do
66
- * neither of - the listing tools are not advertised to it, and its tools carry no `account`
67
- * argument because the endpoint already knows which account they act on. Saying so up front is
68
- * what stops the agent looking for a way to supply one.
74
+ * Written for the credential that is asking, on the two things that change what the agent can do.
75
+ * Which tool sets it holds, as the scopes its advertised catalog exercises: a management
76
+ * credential is told to start from the instance and what to confirm, a mail credential is told
77
+ * how messages are shaped, and one holding both hears both. And whether it is bound to one
78
+ * account: the generic opening tells the agent to list the accounts and pass an id, which a bound
79
+ * credential can do neither of - the listing tools are not advertised to it, and its tools carry
80
+ * no `account` argument because the endpoint already knows which account they act on. Saying so
81
+ * up front is what stops the agent looking for a way to supply one.
69
82
  *
70
83
  * Kept short either way: this rides along on every discover/initialize response.
71
84
  *
72
- * @param {String} [account] - the bound account id, for an account-bound credential
85
+ * @param {Object} [profile]
86
+ * @param {String} [profile.account] - the bound account id, for an account-bound credential
87
+ * @param {Array<String>} [profile.surfaces] - the per-request scopes the credential's catalog exercises
88
+ * @param {Boolean} [profile.hasTools] - whether the advertised catalog has anything in it, for a
89
+ * credential that exercises no scope on its own: the tools both sets share say nothing
90
+ * about either, and a credential narrowed to only those still has something to call
73
91
  * @returns {String} instructions
74
92
  */
75
- function serverInstructions(account) {
76
- const opening = account
77
- ? [
78
- `EmailEngine gives access to the email account '${account}' on this instance.`,
79
- 'This credential reaches that one account and no other, so the tools take no account argument - it is applied for you.'
80
- ]
81
- : [
82
- 'EmailEngine gives access to the email accounts registered on this instance.',
83
- 'Call list_accounts first and use the returned account id as the `account` argument of the other tools.'
84
- ];
85
-
86
- return opening.concat(COMMON_INSTRUCTIONS).join(' ');
87
- }
93
+ function serverInstructions(profile) {
94
+ const { account = null, surfaces = [], hasTools = false } = profile || {};
95
+ const manage = surfaces.includes(MCP_SCOPES.manage);
96
+ const mail = surfaces.includes(MCP_SCOPES.mail);
97
+
98
+ const opening = ['EmailEngine is a self-hosted email sync service.'];
99
+
100
+ if (account) {
101
+ opening.push(
102
+ `This credential is bound to the email account '${account}' on this instance and reaches no other, so the tools take no account argument - it is applied for you.`
103
+ );
104
+ if (manage) {
105
+ opening.push('It can operate that account: inspect its state and logs, reconnect or sync it, change its configuration, or remove it.');
106
+ }
107
+ } else {
108
+ if (manage) {
109
+ opening.push(
110
+ 'This credential manages this instance: accounts, settings, OAuth2 applications, SMTP gateways, access tokens and the license. Start with get_instance_stats and list_accounts.'
111
+ );
112
+ }
113
+ if (mail) {
114
+ opening.push(
115
+ (manage ? 'It also reaches mailbox contents.' : 'This credential gives access to the email accounts registered on this instance.') +
116
+ ' Call list_accounts first and use the returned account id as the `account` argument of the mail tools.'
117
+ );
118
+ }
119
+ }
120
+
121
+ if (!manage && !mail) {
122
+ // Told so rather than handed a workflow it cannot perform
123
+ opening.push(
124
+ hasTools
125
+ ? 'This credential is offered only the tools both tool sets share; ask the operator to widen it for anything else.'
126
+ : 'This credential is offered no tools; ask the operator to widen it.'
127
+ );
128
+ }
88
129
 
89
- const SERVER_INSTRUCTIONS = serverInstructions();
130
+ // Management lines before mail lines, whatever order the surfaces arrived in
131
+ const held = Object.values(MCP_SCOPES).filter(scope => surfaces.includes(scope));
132
+ return opening.concat(...held.map(scope => SURFACE_INSTRUCTIONS[scope])).join(' ');
133
+ }
90
134
 
91
135
  // URL hostnames that mean "this machine" for the transport policies below: the Origin check
92
136
  // here and the loopback redirect-URI rule in lib/mcp/oauth.js read the same list, so the two
@@ -253,7 +297,7 @@ function capabilities(era) {
253
297
  * listTools() => [tool definitions],
254
298
  * callTool(name, args) => tool result (throws {rpcCode, message} for protocol errors),
255
299
  * listResources() => [resources], readResource(uri) => contents,
256
- * instructions - optional per-credential replacement for SERVER_INSTRUCTIONS,
300
+ * instructions - the per-credential instructions, from serverInstructions(),
257
301
  * acceptsEventStream - whether the request's Accept header admits text/event-stream
258
302
  * @returns {Promise<Object>} { httpStatus, body } for a JSON response (body undefined for 202),
259
303
  * or { listen: { id, filter } } when a subscriptions/listen request was accepted and
@@ -341,7 +385,7 @@ async function processModern({ body, id, isNotification, params, metaVersion, he
341
385
  const result = completeResult(body.method, {
342
386
  supportedVersions: SUPPORTED_PROTOCOL_VERSIONS,
343
387
  capabilities: capabilities('modern'),
344
- instructions: ctx.instructions || SERVER_INSTRUCTIONS,
388
+ instructions: ctx.instructions,
345
389
  _meta: { [META_SERVER_INFO]: SERVER_INFO }
346
390
  });
347
391
  return { httpStatus: 200, body: rpcResult(id, result) };
@@ -403,7 +447,7 @@ async function processLegacy({ body, id, isNotification, params, headers, ctx })
403
447
  protocolVersion: negotiated,
404
448
  capabilities: capabilities('legacy'),
405
449
  serverInfo: SERVER_INFO,
406
- instructions: ctx.instructions || SERVER_INSTRUCTIONS
450
+ instructions: ctx.instructions
407
451
  };
408
452
  return { httpStatus: 200, body: rpcResult(id, result) };
409
453
  }
@@ -484,6 +528,5 @@ module.exports = {
484
528
  SUPPORTED_PROTOCOL_VERSIONS,
485
529
  META_PROTOCOL_VERSION,
486
530
  SERVER_INFO,
487
- SERVER_INSTRUCTIONS,
488
531
  serverInstructions
489
532
  };
package/lib/mcp/tools.js CHANGED
@@ -15,7 +15,7 @@
15
15
  // account binding, IP restrictions, rate limits and the token audit log all apply exactly as they
16
16
  // do over REST. This module never touches Redis and never bypasses a handler.
17
17
 
18
- const { routeGrant, ACTION } = require('../api-routes/permission-map');
18
+ const { routeGrant, surfaceAdmits, surfaceBoundAdmits, PER_REQUEST_SURFACES, ACTION } = require('../api-routes/permission-map');
19
19
  const tokenPermissions = require('../token-permissions');
20
20
  const { mcpOptions } = require('../api-routes/route-metadata');
21
21
  const { joiToJsonSchema } = require('./json-schema');
@@ -40,7 +40,7 @@ const TRUNCATION_NOTICE = size => `\n\n[Result truncated by EmailEngine: the ful
40
40
 
41
41
  // Every key a plugins.mcp block may carry. The one place the block's shape is written down, so a
42
42
  // misspelling is a build failure rather than a knob that quietly does nothing.
43
- const MCP_OPTION_KEYS = new Set(['name', 'title', 'description', 'keep', 'omit', 'force', 'bounds', 'binary', 'resourceUriTemplate', 'endpoint']);
43
+ const MCP_OPTION_KEYS = new Set(['name', 'title', 'description', 'keep', 'omit', 'force', 'bounds', 'binary', 'resourceUriTemplate', 'endpoint', 'openWorld']);
44
44
 
45
45
  // One registry per Hapi server, built on first use and held for the life of the worker - route
46
46
  // definitions cannot change while it runs, and the build walks every joi schema of every wrapped
@@ -241,9 +241,10 @@ function buildToolRegistry(routes) {
241
241
  title: options.title,
242
242
  readOnlyHint: grant.action === ACTION.READ,
243
243
  destructiveHint: grant.action === ACTION.DESTRUCTIVE,
244
- // Sending mail reaches arbitrary external recipients; everything else stays inside
245
- // the connected mailboxes
246
- openWorldHint: grant.action === ACTION.SEND
244
+ // Sending mail reaches arbitrary external recipients. A tool whose grant does not
245
+ // imply that but whose purpose is reaching a host outside the instance - the
246
+ // autodiscovery lookup, the connection tests - declares `openWorld` itself.
247
+ openWorldHint: grant.action === ACTION.SEND || !!options.openWorld
247
248
  };
248
249
 
249
250
  const inputSchema = {
@@ -273,6 +274,10 @@ function buildToolRegistry(routes) {
273
274
  // questions about the catalog: tools/list uses it to show a permission-narrowed
274
275
  // token only the tools its record can actually call
275
276
  grant,
277
+ // The per-request scopes whose table covers that operation, in the order the scopes
278
+ // are declared: the other half of what tools/list filters on, and what the admin
279
+ // pages group and count by
280
+ surfaces: [...PER_REQUEST_SURFACES].filter(scope => surfaceAdmits(scope, grant)),
276
281
  binary: !!options.binary,
277
282
  resourceUriTemplate: options.resourceUriTemplate
278
283
  });
@@ -280,7 +285,15 @@ function buildToolRegistry(routes) {
280
285
 
281
286
  const tools = [...byName.values()].map(entry => entry.definition).sort((a, b) => a.name.localeCompare(b.name, 'en'));
282
287
 
283
- return { tools, byName };
288
+ // The catalog reduced to what the admin pages count and group by, in tools/list order. Built
289
+ // here with the registry rather than on each read: the registry is immutable for the life of
290
+ // the worker and three admin pages plus the MCP door read this.
291
+ const grants = tools.map(tool => {
292
+ const entry = byName.get(tool.name);
293
+ return Object.assign({ name: tool.name, accountScoped: entry.sources.has('account'), surfaces: entry.surfaces }, entry.grant);
294
+ });
295
+
296
+ return { tools, byName, grants };
284
297
  }
285
298
 
286
299
  /**
@@ -553,6 +566,11 @@ function toolVisibleTo(entry, { tokenData, boundAccount }) {
553
566
  if (boundAccount && !entry.sources.has('account')) {
554
567
  return false;
555
568
  }
569
+ // The scope bound first: a credential holding only the mail scope is not offered the
570
+ // management tools however wide its permissions record, and the other way round
571
+ if (!surfaceBoundAdmits(tokenData, entry.grant)) {
572
+ return false;
573
+ }
556
574
  return tokenPermissions.check({ tokenData, operation: entry.grant }).allowed;
557
575
  }
558
576
 
@@ -625,27 +643,45 @@ function listToolsFor(server, { tokenData, boundAccount }) {
625
643
  * which is what the two permission axes alone cannot tell a reader. Kept here rather than having
626
644
  * callers walk `byName`, so the dispatch table stays this module's business.
627
645
  *
628
- * `accountScoped` is what the binding half of toolVisibleTo() reads, carried along because the
629
- * admin pages have to apply the same two filters in a browser, where neither this module nor the
630
- * permission checker can be called. test/mcp-tools-test.js asserts that the two-allowlist model
631
- * those pages use agrees with toolVisibleTo() over the whole catalog, so the prediction cannot
632
- * drift away from the rule it predicts.
646
+ * `accountScoped` and `surfaces` are what the binding and scope halves of toolVisibleTo() read,
647
+ * carried along because the admin pages have to apply the same filters in a browser, where
648
+ * neither this module nor the permission checker can be called. test/mcp-tools-test.js asserts
649
+ * that the model those pages use agrees with toolVisibleTo() over the whole catalog, so the
650
+ * prediction cannot drift away from the rule it predicts.
633
651
  *
634
652
  * @param {Object} server - the Hapi server
635
- * @returns {Array<{name: String, action: String, group: String, accountScoped: Boolean}>}
653
+ * @returns {Array<{name: String, action: String, group: String, accountScoped: Boolean, surfaces: Array<String>}>}
636
654
  */
637
655
  function toolGrants(server) {
638
- const { tools, byName } = getToolRegistry(server);
639
- return tools.map(tool => {
640
- const entry = byName.get(tool.name);
641
- return Object.assign({ name: tool.name, accountScoped: entry.sources.has('account') }, entry.grant);
642
- });
656
+ return getToolRegistry(server).grants;
657
+ }
658
+
659
+ /**
660
+ * The per-request scopes a catalog actually exercises: a scope is held when a tool only that
661
+ * scope's table covers is in the catalog. The tools both tables cover (the account reads) say
662
+ * nothing about either. What the instructions are written from, so a narrowed record that
663
+ * empties a scope out is described accurately.
664
+ *
665
+ * @param {Object} server - the Hapi server
666
+ * @param {Array} catalog - tool definitions, as listToolsFor() returns them
667
+ * @returns {Array<String>} scopes, in declaration order
668
+ */
669
+ function catalogSurfaces(server, catalog) {
670
+ const names = new Set(catalog.map(tool => tool.name));
671
+ const held = new Set();
672
+ for (const entry of getToolRegistry(server).grants) {
673
+ if (entry.surfaces.length === 1 && names.has(entry.name)) {
674
+ held.add(entry.surfaces[0]);
675
+ }
676
+ }
677
+ return [...PER_REQUEST_SURFACES].filter(scope => held.has(scope));
643
678
  }
644
679
 
645
680
  module.exports = {
646
681
  buildToolRegistry,
647
682
  getToolRegistry,
648
683
  toolGrants,
684
+ catalogSurfaces,
649
685
  toolVisibleTo,
650
686
  toolDefinitionFor,
651
687
  listToolsFor,
@@ -0,0 +1,147 @@
1
+ 'use strict';
2
+
3
+ // The settings a narrowed credential may never read or write: what assertNoPrivilegedSettings()
4
+ // in lib/api-routes/route-helpers.js refuses on GET and POST /v1/settings, and what the two MCP
5
+ // settings tools leave out of their schemas (MCP_SETTINGS_KEYS in lib/api-routes/settings-routes.js).
6
+ // `read/settings` and `write/settings` are grantable permissions, and the settings blob is the one
7
+ // endpoint whose fields span every trust level, so these are the keys that would make a settings
8
+ // editor more than a settings editor.
9
+ //
10
+ // Grouped by the reason each cluster is on the list, and each group carries the words every
11
+ // description of the rule uses for it: the settings tools, the `settings` permission group in the
12
+ // OpenAPI document and the token form all render PRIVILEGED_SETTINGS_SUMMARY, so a key added here
13
+ // is described everywhere at once rather than in copies that drift.
14
+ //
15
+ // A leaf module on purpose: lib/enum-descriptions.js is pure prose loaded by lib/schemas.js, and
16
+ // lib/settings.js opens Redis, so the list has to live below both. The TLS listener table is the
17
+ // one import, dependency-free for the same reason (lib/tls/listeners.js).
18
+
19
+ const { TLS_CERTIFICATE_SETTINGS } = require('./tls/listeners');
20
+
21
+ const PRIVILEGED_SETTINGS_GROUPS = [
22
+ {
23
+ // Operator code run inside the instance, and the environment it sees
24
+ label: 'operator scripts',
25
+ keys: ['openAiPreProcessingFn', 'scriptEnv']
26
+ },
27
+ {
28
+ // Signs hosted authentication links and unsubscribe links
29
+ label: 'the link signing secret',
30
+ keys: ['serviceSecret']
31
+ },
32
+ {
33
+ // Where account credentials are fetched from
34
+ label: 'the authentication server',
35
+ keys: ['authServer']
36
+ },
37
+ {
38
+ // Trust of X-Forwarded-For, which the admin address perimeter is checked against, and the
39
+ // outbound address list
40
+ label: 'proxy trust and local addresses',
41
+ keys: ['enableApiProxy', 'localAddresses']
42
+ },
43
+ {
44
+ // Every IMAP, SMTP and HTTP connection, credentials included, goes through these
45
+ label: 'proxies',
46
+ keys: ['proxyEnabled', 'proxyUrl', 'httpProxyEnabled', 'httpProxyUrl']
47
+ },
48
+ {
49
+ // The built-in listeners: what they are, where they bind, whether they demand a credential
50
+ // and whether they speak TLS. The SMTP submission server's authentication switch is the
51
+ // sharpest of these - with it off, the server takes the sending account from a client
52
+ // header, so a settings grant would turn into unauthenticated sending as any account - but a
53
+ // narrowed credential must not move a listener onto a public interface or downgrade it to
54
+ // cleartext either, however delayed the restart that applies it.
55
+ label: 'the built-in listeners',
56
+ keys: [
57
+ 'smtpServerEnabled',
58
+ 'smtpServerHost',
59
+ 'smtpServerPort',
60
+ 'smtpServerAuthEnabled',
61
+ 'smtpServerPassword',
62
+ 'smtpServerProxy',
63
+ 'smtpServerTLSEnabled',
64
+ 'imapProxyServerEnabled',
65
+ 'imapProxyServerHost',
66
+ 'imapProxyServerPort',
67
+ 'imapProxyServerPassword',
68
+ 'imapProxyServerProxy',
69
+ 'imapProxyServerTLSEnabled'
70
+ ]
71
+ },
72
+ {
73
+ // Which stored certificate each listener presents, the API's included, and the mode that
74
+ // decides which certificates may be served at all: switched to self-signed, every listener
75
+ // presents the unverifiable certificate, which is a downgrade for every client that checks
76
+ // and an opening for the ones told not to. The hostname list places orders with the CA.
77
+ label: 'TLS certificates and provisioning',
78
+ keys: [...TLS_CERTIFICATE_SETTINGS, 'tlsProvisioning', 'tlsHostnames']
79
+ },
80
+ {
81
+ // The origin everything else is anchored to: the first hostname certificates are ordered
82
+ // for, the issuer and resource the MCP OAuth discovery documents name, where the hosted
83
+ // setup links point (the form where end users type mail passwords), and the signal that
84
+ // marks the cookies Secure. A settings editor that could move it would re-anchor all of
85
+ // that at once. notificationBaseUrl, the documented override, stays ordinary: it only names
86
+ // where Microsoft Graph delivers its change notifications, which carry no content.
87
+ label: 'the service URL',
88
+ keys: ['serviceUrl']
89
+ },
90
+ {
91
+ // Switches certificate checking off for every IMAP and SMTP connection the instance makes,
92
+ // which is the on-path reader's way to the account credentials
93
+ label: 'mail certificate checking',
94
+ keys: ['ignoreMailCertErrors']
95
+ },
96
+ {
97
+ // The AI key, and the base URL it is sent to: a narrowed credential that could point the
98
+ // latter at its own host would receive the former as a bearer header on the next request
99
+ label: 'the AI key and endpoint',
100
+ keys: ['openAiAPIKey', 'openAiAPIUrl']
101
+ },
102
+ {
103
+ // Credential-bearing (the example is an Authorization header)
104
+ label: 'custom webhook headers',
105
+ keys: ['webhooksCustomHeaders']
106
+ },
107
+ {
108
+ // HTML injected into the hosted pages, where end users type mail passwords
109
+ label: 'hosted page markup',
110
+ keys: ['templateHeader', 'templateHtmlHead']
111
+ },
112
+ {
113
+ // A credential must not change the door it came through, enable credential issuance, or
114
+ // switch off its own audit trail
115
+ label: 'the MCP and audit switches',
116
+ keys: ['mcpEnabled', 'mcpOAuthEnabled', 'tokenAuditLog']
117
+ },
118
+ {
119
+ // The deprecated Document Store's endpoint and credentials
120
+ label: 'the Document Store',
121
+ keys: [
122
+ 'documentStoreEnabled',
123
+ 'documentStoreUrl',
124
+ 'documentStoreIndex',
125
+ 'documentStoreAuthEnabled',
126
+ 'documentStoreUsername',
127
+ 'documentStorePassword',
128
+ 'documentStoreGenerateEmbeddings',
129
+ 'documentStorePreProcessingEnabled'
130
+ ]
131
+ },
132
+ {
133
+ // The error reporting target
134
+ label: 'error reporting',
135
+ keys: ['sentryEnabled', 'sentryDsn']
136
+ }
137
+ ];
138
+
139
+ const PRIVILEGED_SETTINGS_KEYS = PRIVILEGED_SETTINGS_GROUPS.flatMap(group => group.keys);
140
+
141
+ // The groups as one phrase, "operator scripts, the link signing secret, ..., and error reporting",
142
+ // for every description that says what a narrowed credential is refused
143
+ const PRIVILEGED_SETTINGS_SUMMARY = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }).format(
144
+ PRIVILEGED_SETTINGS_GROUPS.map(group => group.label)
145
+ );
146
+
147
+ module.exports = { PRIVILEGED_SETTINGS_GROUPS, PRIVILEGED_SETTINGS_KEYS, PRIVILEGED_SETTINGS_SUMMARY };