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
@@ -108,6 +108,33 @@ const GROUP = {
108
108
  // mailbox a reader of the protocol trace as well.
109
109
  LOGS: 'logs',
110
110
 
111
+ // Instance settings and the two queues. A write here reaches the global webhook target and
112
+ // every notification knob, and is disclosed as such wherever the grant is offered. The keys
113
+ // that would make the holder more than a settings editor are refused to a narrowed token by
114
+ // assertNoPrivilegedSettings() in ./route-helpers.js, keyed on PRIVILEGED_SETTINGS_KEYS in
115
+ // lib/privileged-settings.js, which also renders the phrase every description of the rule uses.
116
+ SETTINGS: 'settings',
117
+
118
+ // OAuth2 applications. Secrets are write-only (every read masks them), but a write can move
119
+ // an application's redirect URL, which is where the provider sends authorization codes.
120
+ OAUTH2: 'oauth2',
121
+
122
+ // The license: read it, apply one, remove it
123
+ LICENSE: 'license',
124
+
125
+ // Access tokens: list, inspect, read the audit log of, revoke. Minting is NOT here - it stays
126
+ // in ADMIN, because a token that can mint tokens can widen itself.
127
+ TOKEN: 'token',
128
+
129
+ // Adding accounts and gateways, and reconfiguring them, including where they connect. Its own
130
+ // group rather than a write on `account` or `gateway` because both records keep their stored
131
+ // credential across a partial update, so a change to nothing but `host` makes the next
132
+ // connection authenticate to the new host with the old password - a token issued with write
133
+ // access to accounts before this group existed must not gain that. Disclosed on every screen
134
+ // that offers the grant. `proxy` in these payloads is refused to a narrowed token by
135
+ // assertNoNetworkOverride(), like the submit payloads.
136
+ PROVISIONING: 'provisioning',
137
+
111
138
  // Never grantable. See NEVER_GRANTABLE below.
112
139
  ADMIN: 'admin'
113
140
  };
@@ -121,6 +148,31 @@ const NEVER_GRANTABLE = new Set([GROUP.ADMIN]);
121
148
 
122
149
  const GRANTABLE_GROUPS = Object.values(GROUP).filter(group => !NEVER_GRANTABLE.has(group));
123
150
 
151
+ // What a two-axis record that omits `groups` reaches: the sections that were grantable when the
152
+ // two-axis form shipped in 2.79.0, and nothing added since. The record's schema promised "omit to
153
+ // allow all of them", and every record written under that promise was written when these were all
154
+ // there was. Reading an absent axis as the live GRANTABLE_GROUPS would have handed every such
155
+ // record the five instance sections the admin split created - a `{ actions: ['read', 'write'] }`
156
+ // token minted through the API on 2.79 would have woken up on 2.80 able to retarget an account's
157
+ // host and move the webhook target. So the instance sections are reachable only by a record that
158
+ // names them, and a section added later joins GRANTABLE_GROUPS and not this list.
159
+ // test/token-permissions-test.js pins it to these thirteen names.
160
+ const IMPLICIT_GROUPS = Object.freeze([
161
+ GROUP.ACCOUNT,
162
+ GROUP.MAILBOX,
163
+ GROUP.MESSAGE,
164
+ GROUP.SUBMIT,
165
+ GROUP.OUTBOX,
166
+ GROUP.EXPORT,
167
+ GROUP.TEMPLATE,
168
+ GROUP.BLOCKLIST,
169
+ GROUP.WEBHOOK,
170
+ GROUP.GATEWAY,
171
+ GROUP.EVENTS,
172
+ GROUP.DIAGNOSTICS,
173
+ GROUP.LOGS
174
+ ]);
175
+
124
176
  // Every grant a non-HTTP surface can exercise once it has authenticated, rather than the one it
125
177
  // nominally performs. These surfaces are checked once at login and never again, so a token is
126
178
  // admitted only if it holds ALL of them.
@@ -164,23 +216,79 @@ const SURFACE_GRANTS = {
164
216
  { action: ACTION.SEND, group: GROUP.SUBMIT },
165
217
  { action: ACTION.READ, group: GROUP.OUTBOX },
166
218
  { action: ACTION.READ, group: GROUP.TEMPLATE }
219
+ ],
220
+
221
+ // The management half of the MCP endpoint: the same door, checked per request the same way,
222
+ // but a second scope with its own table. A second scope rather than a longer `mcp` list on
223
+ // purpose: the "Full access" level of the consent page used to mint a token with no
224
+ // permissions record, bounded by the `mcp` table alone, and growing that table would have
225
+ // handed every such token the management tools on upgrade. This one leaves every issued
226
+ // credential exactly as wide as it was.
227
+ //
228
+ // Reads about the instance, the writes that operate it, and the deletions an administrator
229
+ // makes. Deliberately absent: `send/submit` (mail, in the table above), `export` (one call
230
+ // archives an account), `events` (a stream, not a tool), `destructive/license` (no agent use
231
+ // case, only harm), and every `admin` route. The three read pairs shared with the mail table
232
+ // are shared on purpose - an agent managing the instance needs to list accounts too.
233
+ 'mcp-manage': [
234
+ { action: ACTION.READ, group: GROUP.ACCOUNT },
235
+ { action: ACTION.WRITE, group: GROUP.ACCOUNT },
236
+ { action: ACTION.DESTRUCTIVE, group: GROUP.ACCOUNT },
237
+ { action: ACTION.READ, group: GROUP.SETTINGS },
238
+ { action: ACTION.WRITE, group: GROUP.SETTINGS },
239
+ { action: ACTION.READ, group: GROUP.OAUTH2 },
240
+ { action: ACTION.WRITE, group: GROUP.OAUTH2 },
241
+ { action: ACTION.DESTRUCTIVE, group: GROUP.OAUTH2 },
242
+ { action: ACTION.READ, group: GROUP.LICENSE },
243
+ { action: ACTION.WRITE, group: GROUP.LICENSE },
244
+ { action: ACTION.READ, group: GROUP.TOKEN },
245
+ { action: ACTION.DESTRUCTIVE, group: GROUP.TOKEN },
246
+ { action: ACTION.READ, group: GROUP.PROVISIONING },
247
+ { action: ACTION.WRITE, group: GROUP.PROVISIONING },
248
+ { action: ACTION.READ, group: GROUP.GATEWAY },
249
+ { action: ACTION.DESTRUCTIVE, group: GROUP.GATEWAY },
250
+ { action: ACTION.READ, group: GROUP.WEBHOOK },
251
+ { action: ACTION.READ, group: GROUP.BLOCKLIST },
252
+ { action: ACTION.WRITE, group: GROUP.BLOCKLIST },
253
+ { action: ACTION.DESTRUCTIVE, group: GROUP.BLOCKLIST },
254
+ { action: ACTION.READ, group: GROUP.TEMPLATE },
255
+ { action: ACTION.WRITE, group: GROUP.TEMPLATE },
256
+ { action: ACTION.DESTRUCTIVE, group: GROUP.TEMPLATE },
257
+ { action: ACTION.READ, group: GROUP.OUTBOX },
258
+ { action: ACTION.DESTRUCTIVE, group: GROUP.OUTBOX },
259
+ { action: ACTION.READ, group: GROUP.DIAGNOSTICS },
260
+ { action: ACTION.READ, group: GROUP.LOGS }
167
261
  ]
168
262
  };
169
263
 
264
+ // The two MCP scopes by what they are for, so the modules that reason about "the management
265
+ // half" and "the mail half" (the access sections, the instructions, the catalog grouping) name
266
+ // them through this rather than spelling the slugs again.
267
+ const MCP_SCOPES = {
268
+ manage: 'mcp-manage',
269
+ mail: 'mcp'
270
+ };
271
+
170
272
  // The quantifier over SURFACE_GRANTS differs by surface, and consumers must not hard-code their
171
273
  // own: the login-time surfaces (smtp, imap-proxy, metrics) admit a token only if it holds ALL of
172
274
  // their grants, because they are checked once and then hand over a session; a per-request
173
275
  // surface admits a request when ANY single grant covers it, because every request is checked on
174
276
  // its own. The admin token form renders its scope warning from this distinction too.
175
- const PER_REQUEST_SURFACES = new Set(['mcp']);
277
+ const PER_REQUEST_SURFACES = new Set([MCP_SCOPES.mail, MCP_SCOPES.manage]);
176
278
 
177
- function grantListAdmits(grants, grant) {
178
- return (grants || []).some(entry => entry.action === grant.action && entry.group === grant.group);
179
- }
279
+ // The `action:group` spelling of a pair, the key every set of pairs below is built on
280
+ const grantKey = grant => `${grant.action}:${grant.group}`;
281
+
282
+ const grantKeySet = grants => new Set((grants || []).map(grantKey));
283
+
284
+ // One membership set per surface, built once: the per-request predicate below runs for every
285
+ // tool of every tools/list and for every MCP-dispatched request, and the management table has
286
+ // two dozen entries
287
+ const SURFACE_GRANT_KEYS = Object.fromEntries(Object.entries(SURFACE_GRANTS).map(([scope, grants]) => [scope, grantKeySet(grants)]));
180
288
 
181
289
  /**
182
290
  * Whether one operation is inside a surface's grant list. This is the per-request quantifier -
183
- * the api-token strategy asks it for the `mcp` scope, and test/mcp-tools-test.js asserts every
291
+ * the api-token strategy asks it for the MCP scopes, and test/mcp-tools-test.js asserts every
184
292
  * exposed tool against it, so the guardrail and the enforcement share one predicate.
185
293
  *
186
294
  * @param {String} scope - a SURFACE_GRANTS key
@@ -188,7 +296,44 @@ function grantListAdmits(grants, grant) {
188
296
  * @returns {Boolean}
189
297
  */
190
298
  function surfaceAdmits(scope, grant) {
191
- return grantListAdmits(SURFACE_GRANTS[scope], grant);
299
+ const keys = SURFACE_GRANT_KEYS[scope];
300
+ return !!keys && keys.has(grantKey(grant));
301
+ }
302
+
303
+ /**
304
+ * Whether the per-request surface scopes a token holds admit one operation.
305
+ *
306
+ * The rule the api-token strategy applies to an MCP-dispatched request: a token holding `mcp`,
307
+ * `mcp-manage` or both is admitted to a route when any held scope's table covers the route's
308
+ * grant. Written once here so the strategy and tools/list (through surfaceBoundAdmits) cannot
309
+ * disagree about which scope reaches which tool.
310
+ *
311
+ * @param {Array} scopes - the token's scope list
312
+ * @param {{action: String, group: String}} grant - the operation, from routeGrant()
313
+ * @returns {Boolean}
314
+ */
315
+ function perRequestSurfaceAdmits(scopes, grant) {
316
+ return Array.isArray(scopes) && scopes.some(scope => PER_REQUEST_SURFACES.has(scope) && surfaceAdmits(scope, grant));
317
+ }
318
+
319
+ /**
320
+ * Whether a token's scopes leave one operation reachable over MCP at all.
321
+ *
322
+ * A token with no scope list, with `*`, or with `api` reaches every route its permissions allow,
323
+ * so the bound is only the surface tables of the per-request scopes it holds. For tools/list,
324
+ * which advertises a credential the tools it can actually call: the permission record is the
325
+ * other half of that answer, and lib/token-permissions.js owns it.
326
+ *
327
+ * @param {Object} tokenData - the token record, as the auth strategy leaves it in artifacts
328
+ * @param {{action: String, group: String}} grant - the operation, from routeGrant()
329
+ * @returns {Boolean}
330
+ */
331
+ function surfaceBoundAdmits(tokenData, grant) {
332
+ const scopes = tokenData && tokenData.scopes;
333
+ if (!Array.isArray(scopes) || scopes.includes('*') || scopes.includes('api')) {
334
+ return true;
335
+ }
336
+ return perRequestSurfaceAdmits(scopes, grant);
192
337
  }
193
338
 
194
339
  /**
@@ -233,11 +378,13 @@ const SESSION_TOKEN_GRANTS = [
233
378
  * @param {String} [opts.account] - the account the request names, from request.params
234
379
  * @returns {Boolean}
235
380
  */
381
+ const SESSION_TOKEN_GRANT_KEYS = grantKeySet(SESSION_TOKEN_GRANTS);
382
+
236
383
  function sessionTokenAdmits(grant, opts) {
237
384
  if (!opts || !opts.account) {
238
385
  return false;
239
386
  }
240
- return grantListAdmits(SESSION_TOKEN_GRANTS, grant);
387
+ return SESSION_TOKEN_GRANT_KEYS.has(grantKey(grant));
241
388
  }
242
389
 
243
390
  // Membership sets for the two vocabularies. lib/token-permissions.js rejects a record naming
@@ -270,7 +417,7 @@ function routeKey(method, path) {
270
417
  // build rather than drifting.
271
418
  const GROUP_ROUTES = {
272
419
  // Reading an account and operating on its connection. Creating one and editing its
273
- // configuration are NOT here - see the note on those two entries under ADMIN.
420
+ // configuration are NOT here - see the note on those two entries under PROVISIONING.
274
421
  [GROUP.ACCOUNT]: [
275
422
  'GET /v1/accounts',
276
423
  'GET /v1/account/{account}',
@@ -335,9 +482,9 @@ const GROUP_ROUTES = {
335
482
 
336
483
  [GROUP.WEBHOOK]: ['GET /v1/webhookRoutes', 'GET /v1/webhookRoutes/webhookRoute/{webhookRoute}'],
337
484
 
338
- // Reading a gateway and removing one. The two WRITES are in ADMIN below, because they can
339
- // redirect where the stored relay credentials are sent - so they are deliberately absent here
340
- // rather than listed in both places.
485
+ // Reading a gateway and removing one. The two WRITES are in PROVISIONING below, because they
486
+ // can redirect where the stored relay credentials are sent - so they are deliberately absent
487
+ // here rather than listed in both places.
341
488
  [GROUP.GATEWAY]: ['GET /v1/gateways', 'GET /v1/gateway/{gateway}', 'DELETE /v1/gateway/{gateway}'],
342
489
 
343
490
  [GROUP.EVENTS]: ['GET /v1/changes'],
@@ -357,55 +504,52 @@ const GROUP_ROUTES = {
357
504
 
358
505
  [GROUP.LOGS]: ['GET /v1/logs/{account}'],
359
506
 
360
- // Everything that hands out a lasting credential or widens what the instance can do. This block
361
- // is the safety property of the whole model: while a narrowed token cannot reach any of it, it
362
- // cannot read the settings blob, cannot read a stored OAuth2 credential, and cannot mint or
363
- // revoke a token, so it cannot widen itself.
364
- [GROUP.ADMIN]: [
365
- 'GET /v1/settings',
366
- 'POST /v1/settings',
367
- 'GET /v1/settings/queue/{queue}',
368
- 'PUT /v1/settings/queue/{queue}',
507
+ // The five groups below used to be the admin block. They were split out so an agent that
508
+ // manages the instance can hold them, and each went to a NEW group rather than into one that
509
+ // already existed: a record cannot name a group that did not exist when it was written, and a
510
+ // record that names no groups at all reaches IMPLICIT_GROUPS, which stops at the split, so no
511
+ // token issued before the split gained a route from it. test/api-routes-table-test.js asserts
512
+ // the pre-split groups still hold exactly the routes they held.
513
+
514
+ [GROUP.SETTINGS]: ['GET /v1/settings', 'POST /v1/settings', 'GET /v1/settings/queue/{queue}', 'PUT /v1/settings/queue/{queue}'],
369
515
 
516
+ [GROUP.OAUTH2]: [
370
517
  'GET /v1/oauth2',
371
518
  'POST /v1/oauth2',
372
519
  'GET /v1/oauth2/{app}',
373
520
  'PUT /v1/oauth2/{app}',
374
521
  'DELETE /v1/oauth2/{app}',
375
- 'POST /v1/oauth2/{app}/verify',
522
+ 'POST /v1/oauth2/{app}/verify'
523
+ ],
376
524
 
377
- 'GET /v1/license',
378
- 'POST /v1/license',
379
- 'DELETE /v1/license',
525
+ [GROUP.LICENSE]: ['GET /v1/license', 'POST /v1/license', 'DELETE /v1/license'],
380
526
 
381
- 'POST /v1/tokens',
382
- 'DELETE /v1/tokens/{token}',
527
+ // Everything about tokens except minting one, which is under ADMIN
528
+ [GROUP.TOKEN]: [
383
529
  'GET /v1/tokens',
384
- // Who read whose mail with this credential. Admin because the trail is at least as sensitive
385
- // as the requests in it, and a narrowed token has no business reading its own audit record.
530
+ 'DELETE /v1/tokens/{token}',
531
+ // Who read whose mail with this credential. The trail is at least as sensitive as the
532
+ // requests in it, which the group description says.
386
533
  'GET /v1/tokens/{token}',
387
534
  'GET /v1/tokens/{token}/log',
388
- // Deprecated pre-2.79 aliases of the three above (see lib/api-routes/token-routes.js)
389
- 'POST /v1/token',
535
+ // Deprecated pre-2.79 aliases (see lib/api-routes/token-routes.js)
390
536
  'DELETE /v1/token/{token}',
391
- 'GET /v1/tokens/account/{account}',
392
-
393
- // Returns a live OAuth2 access token for the account: a mail credential in its own right,
394
- // which outlives any narrowing on the token that fetched it
395
- 'GET /v1/account/{account}/oauth-token',
537
+ 'GET /v1/tokens/account/{account}'
538
+ ],
396
539
 
540
+ [GROUP.PROVISIONING]: [
397
541
  // Editing an account is a credential operation even when the payload carries no credential,
398
- // which is why it sits here and not in the grantable `account` group. `imap`, `smtp` and
399
- // `oauth2` accept `partial: true`, and Account.persistUpdate() then merges the STORED object
400
- // over the payload (lib/account.js:858), so `auth.pass` survives a request that only changes
542
+ // which is why it sits here and not in the `account` group. `imap`, `smtp` and `oauth2`
543
+ // accept `partial: true`, and Account.persistUpdate() then merges the STORED object over
544
+ // the payload (lib/account.js:858), so `auth.pass` survives a request that only changes
401
545
  // `host`. An 'imap' key also arms the reconnect gate, so the worker promptly authenticates
402
- // to the new host with the old password. The same route retargets `proxy` and the
403
- // per-account `webhooks` URL, which would stream future message notifications - body text
404
- // included, up to notifyTextSize - somewhere else entirely.
546
+ // to the new host with the old password. The same route retargets the per-account
547
+ // `webhooks` URL, which would stream future message notifications - body text included, up
548
+ // to notifyTextSize - somewhere else entirely. `proxy` is the one field refused outright.
405
549
  'PUT /v1/account/{account}',
406
550
 
407
551
  // Adds an account, so it widens what the instance holds. Grouped with the hosted form below
408
- // for the same reason, and it can set the same webhook and proxy targets as the edit above.
552
+ // for the same reason, and it can set the same webhook target as the edit above.
409
553
  'POST /v1/account',
410
554
 
411
555
  // The same shape as the account edit above, and for the same reason. Gateway.update() writes
@@ -420,7 +564,23 @@ const GROUP_ROUTES = {
420
564
  'POST /v1/authentication/form',
421
565
 
422
566
  // Connects to a supplied host with supplied credentials
423
- 'POST /v1/verifyAccount',
567
+ 'POST /v1/verifyAccount'
568
+ ],
569
+
570
+ // Everything that hands out a lasting credential or reads one back. This block is the safety
571
+ // property of the whole model: while a narrowed token cannot reach any of it, it cannot mint a
572
+ // token and cannot read a live provider credential, so it cannot widen itself. The settings and
573
+ // provisioning writes above can change a great deal, but nothing they change hands the caller
574
+ // a credential it did not already hold - the keys that would (operator code, proxies, secrets)
575
+ // are refused to a narrowed token per key.
576
+ [GROUP.ADMIN]: [
577
+ 'POST /v1/tokens',
578
+ // Deprecated pre-2.79 alias of the mint (see lib/api-routes/token-routes.js)
579
+ 'POST /v1/token',
580
+
581
+ // Returns a live OAuth2 access token for the account: a mail credential in its own right,
582
+ // which outlives any narrowing on the token that fetched it
583
+ 'GET /v1/account/{account}/oauth-token',
424
584
 
425
585
  // The deprecated Document Store. Disabled by default and leaving the releases on
426
586
  // 2026-10-01, so keeping it out of the grantable vocabulary means the removal does not
@@ -482,11 +642,16 @@ module.exports = {
482
642
  ACTION,
483
643
  GROUP,
484
644
  SURFACE_GRANTS,
645
+ MCP_SCOPES,
485
646
  PER_REQUEST_SURFACES,
647
+ grantKey,
486
648
  surfaceAdmits,
649
+ perRequestSurfaceAdmits,
650
+ surfaceBoundAdmits,
487
651
  SESSION_TOKEN_GRANTS,
488
652
  sessionTokenAdmits,
489
653
  GRANTABLE_GROUPS,
654
+ IMPLICIT_GROUPS,
490
655
  ACTION_VALUES,
491
656
  GROUP_VALUES,
492
657
  NEVER_GRANTABLE,
@@ -5,6 +5,7 @@ const { failAction } = require('../tools');
5
5
  const { oauth2Apps } = require('../oauth2-apps');
6
6
  const { pubSubErrorSchema, apiResponses } = require('../schemas');
7
7
  const { handleError, flattenOAuthAppMeta } = require('./route-helpers');
8
+ const { MCP_MAX_PAGE_SIZE } = require('../consts');
8
9
 
9
10
  async function init(args) {
10
11
  const { server, CORS_CONFIG } = args;
@@ -39,6 +40,13 @@ async function init(args) {
39
40
  tags: ['api', 'OAuth2 Applications'],
40
41
 
41
42
  plugins: {
43
+ mcp: {
44
+ name: 'get_pubsub_status',
45
+ title: 'Get Gmail Pub/Sub status',
46
+ description:
47
+ 'List the Gmail Pub/Sub push subscriptions of the OAuth2 applications and their state, paged. A Gmail account falls back to polling while its subscription is missing.',
48
+ bounds: { pageSize: MCP_MAX_PAGE_SIZE }
49
+ },
42
50
  openapi: {
43
51
  responses: apiResponses('Returns the Pub/Sub subscription state for each configured Gmail application.', 400, 401, 403, 429, 500)
44
52
  }
@@ -3,6 +3,7 @@
3
3
  const Boom = require('@hapi/boom');
4
4
  const { isDeepStrictEqual } = require('node:util');
5
5
  const tokenPermissions = require('../token-permissions');
6
+ const settings = require('../settings');
6
7
 
7
8
  // Shared helpers for the extracted API route modules under lib/api-routes/.
8
9
 
@@ -155,7 +156,7 @@ function maskUrlPassword(url) {
155
156
  }
156
157
 
157
158
  // Stored values that are URLs which may embed a password.
158
- const URL_SECRET_KEYS = ['proxy', 'proxyUrl', 'httpProxyUrl', 'webhooks', 'targetUrl'];
159
+ const URL_SECRET_KEYS = ['proxy', 'proxyUrl', 'httpProxyUrl', 'webhooks', 'targetUrl', 'sentryDsn', 'documentStoreUrl'];
159
160
 
160
161
  // Stored values that are {key, value} header lists whose values are credentials.
161
162
  const HEADER_SECRET_KEYS = ['customHeaders', 'webhooksCustomHeaders'];
@@ -340,26 +341,72 @@ function assertNoNetworkOverride(request) {
340
341
  return;
341
342
  }
342
343
 
343
- // Set by the api-token strategy for a `sess_` credential. Marked on the request rather than
344
- // faked into a permissions record: the session bound is a grant list, which the two axes cannot
345
- // express without widening it, and a record that says more than the rule would be read as
346
- // policy by the next thing that looks at it.
347
- const sessionToken = !!(request.app && request.app.sessionToken);
348
-
349
- // Asked of the module that enforces the narrowing rather than by testing `permissions` for
350
- // truthiness, so `{}` and an unreadable record are read here exactly as they are at the
351
- // strategy. `artifacts` is the token record the api-token strategy resolved.
352
- if (!sessionToken && !tokenPermissions.inspect(request.auth && request.auth.artifacts).narrowed) {
344
+ if (!isRestrictedCredential(request)) {
353
345
  return;
354
346
  }
355
347
 
356
348
  throw Boom.forbidden('A token with restricted permissions can not override the connection route');
357
349
  }
358
350
 
351
+ /**
352
+ * Whether the credential behind a request is bounded below the full API.
353
+ *
354
+ * Two kinds are. A narrowed token, one carrying a `permissions` record. And a browse-page session
355
+ * token, which is bounded by SESSION_TOKEN_GRANTS rather than by a record and so reads as
356
+ * unnarrowed to the permission check - it is marked on the request by the api-token strategy
357
+ * rather than faked into a record, because the session bound is a grant list the two axes cannot
358
+ * express without widening it. The permission verdict is asked of the module that enforces it
359
+ * rather than read off `permissions` for truthiness, so `{}` and an unreadable record count here
360
+ * exactly as they do at the strategy. `artifacts` is the token record the strategy resolved.
361
+ *
362
+ * An unnarrowed API token is not restricted: it already reaches everything, so the payload rules
363
+ * that key on this would cost it a documented capability and buy nothing.
364
+ *
365
+ * @param {Object} request - the Hapi request
366
+ * @returns {Boolean}
367
+ */
368
+ function isRestrictedCredential(request) {
369
+ if (request.app && request.app.sessionToken) {
370
+ return true;
371
+ }
372
+ return tokenPermissions.inspect(request.auth && request.auth.artifacts).narrowed;
373
+ }
374
+
375
+ /**
376
+ * Refuses a settings request that names a privileged key, when the credential making it is
377
+ * narrowed.
378
+ *
379
+ * `read/settings` and `write/settings` are grantable permissions, and the settings blob is the
380
+ * one endpoint whose fields span every trust level: `serviceUrl` beside `openAiPreProcessingFn`,
381
+ * which is operator code run inside the instance, and `scriptEnv`, where the admin UI tells
382
+ * operators to keep the API keys their scripts use. The second payload rule in the model after
383
+ * assertNoNetworkOverride(), and like it a static list rather than an interpretation of a value:
384
+ * PRIVILEGED_SETTINGS_KEYS in lib/privileged-settings.js says which keys, and the MCP settings tools hide the
385
+ * same keys from their schemas, so the grants mean the same thing on both surfaces. Applied to
386
+ * reads as well as writes, because several of the keys are secrets a narrowed credential is
387
+ * promised it cannot read, and the write guard alone left them readable.
388
+ *
389
+ * Refused as a whole rather than applied minus the privileged keys, because a partial answer that
390
+ * silently dropped fields would read to the caller as success.
391
+ *
392
+ * @param {Object} request - the Hapi request
393
+ * @param {Array<String>} keys - the settings the request names (payload keys, or the query flags set)
394
+ * @param {String} [verb] - 'change' or 'read', for the refusal
395
+ */
396
+ function assertNoPrivilegedSettings(request, keys, verb = 'change') {
397
+ const privileged = settings.privilegedKeys.filter(key => keys.includes(key));
398
+ if (!privileged.length || !isRestrictedCredential(request)) {
399
+ return;
400
+ }
401
+
402
+ throw Boom.forbidden(`A token with restricted permissions can not ${verb} ${privileged.join(', ')}`);
403
+ }
404
+
359
405
  module.exports = {
360
406
  handleError,
361
407
  logApiError,
362
408
  throwNotFound,
409
+ assertNoPrivilegedSettings,
363
410
  flattenOAuthAppMeta,
364
411
  maskCustomHeaders,
365
412
  maskUrlPassword,
@@ -3,11 +3,13 @@
3
3
  const Joi = require('joi');
4
4
  const { QUEUES_BY_NAME } = require('../db');
5
5
  const settings = require('../settings');
6
+ const { PRIVILEGED_SETTINGS_SUMMARY } = require('../privileged-settings');
6
7
  const consts = require('../consts');
7
- const { failAction } = require('../tools');
8
+ const { failAction, maybeReloadTlsCertificates, TLS_MATERIAL_SETTINGS } = require('../tools');
9
+ const { tlsSettingChanged } = require('../tls/store');
8
10
  const { queueStats } = require('../queue-stats');
9
11
  const Boom = require('@hapi/boom');
10
- const { handleError, maskSecrets, containsMaskedSecret, isMaskedRoundTrip, MASKED } = require('./route-helpers');
12
+ const { handleError, maskSecrets, containsMaskedSecret, isMaskedRoundTrip, assertNoPrivilegedSettings, MASKED } = require('./route-helpers');
11
13
  const { settingsSchema, settingsQuerySchema, apiResponses, ENUM_DESCRIPTIONS } = require('../schemas');
12
14
 
13
15
  // Response variant of the settings schema. Secret values are masked and returned as booleans,
@@ -31,8 +33,19 @@ settingsOutputSchema.eventTypes = Joi.array()
31
33
  .description('Supported webhook event types')
32
34
  .label('EventTypesList');
33
35
 
36
+ // The settings the two MCP settings tools offer: every key of the schema except the privileged
37
+ // ones (PRIVILEGED_SETTINGS_KEYS in lib/privileged-settings.js) and the ones the schema hides from the
38
+ // published document (`swaggerHidden`, the deprecated aliases), which the tool schema converter
39
+ // drops as well. Derived rather than listed, so a setting added to the schema is offered and one
40
+ // added to the privileged list is withdrawn without a second edit here. The REST handler refuses
41
+ // the privileged keys to a narrowed credential, so the `write/settings` grant means the same thing
42
+ // on both surfaces; test/settings-privileged-keys-test.js asserts the tool schema and the list
43
+ // agree.
44
+ const isHiddenSetting = key => (settingsSchema[key].describe().metas || []).some(meta => meta && meta.swaggerHidden);
45
+ const MCP_SETTINGS_KEYS = Object.keys(settingsSchema).filter(key => !settings.privilegedKeys.includes(key) && !isHiddenSetting(key));
46
+
34
47
  async function init(args) {
35
- const { server, notify, CORS_CONFIG } = args;
48
+ const { server, call, notify, CORS_CONFIG } = args;
36
49
 
37
50
  server.route({
38
51
  method: 'GET',
@@ -41,6 +54,14 @@ async function init(args) {
41
54
  async handler(request) {
42
55
  let values = {};
43
56
  try {
57
+ // Before the first read, like the write below: the keys a narrowed credential may
58
+ // not change are the ones it may not read either
59
+ assertNoPrivilegedSettings(
60
+ request,
61
+ Object.keys(request.query).filter(key => request.query[key]),
62
+ 'read'
63
+ );
64
+
44
65
  for (let key of Object.keys(request.query)) {
45
66
  if (request.query[key]) {
46
67
  if (key === 'eventTypes') {
@@ -69,9 +90,8 @@ async function init(args) {
69
90
  // covers the values that are hidden behind a boolean, which is not the same set:
70
91
  // proxyUrl, httpProxyUrl, webhooks and webhooksCustomHeaders are returned as values
71
92
  // (they are useful to read back) and used to be returned in full, so this endpoint
72
- // disclosed exactly what the account getters were masking. It sits in the
73
- // never-grantable admin group, so no narrowed token reaches it - but leaving the
74
- // asymmetry here is how the next reader learns the wrong pattern.
93
+ // disclosed exactly what the account getters were masking. A narrowed credential is
94
+ // refused the privileged keys above; this is what the unnarrowed one gets.
75
95
  maskSecrets(values);
76
96
 
77
97
  return values;
@@ -82,6 +102,12 @@ async function init(args) {
82
102
  tags: ['api', 'Settings'],
83
103
 
84
104
  plugins: {
105
+ mcp: {
106
+ name: 'get_settings',
107
+ title: 'Get settings',
108
+ description: `Read instance settings. Set each setting you want returned to true. Secrets come back as a boolean saying whether a value is stored, credentials inside URLs are masked, and eventTypes lists the webhook event names the instance supports. Settings that would widen this credential (${PRIVILEGED_SETTINGS_SUMMARY}) are not offered.`,
109
+ keep: MCP_SETTINGS_KEYS.concat(['eventTypes'])
110
+ },
85
111
  openapi: {
86
112
  responses: apiResponses('Returns the values of the settings requested via query arguments. Secrets are masked.', 400, 401, 403, 429, 500)
87
113
  }
@@ -117,7 +143,12 @@ async function init(args) {
117
143
 
118
144
  async handler(request) {
119
145
  let applied = {};
146
+ // Only the keys whose value actually changed, unlike `applied` - see tlsSettingChanged()
147
+ let tlsChanged = [];
120
148
  try {
149
+ // Before the first write, so a refused payload leaves nothing half-applied
150
+ assertNoPrivilegedSettings(request, Object.keys(request.payload));
151
+
121
152
  for (let key of Object.keys(request.payload)) {
122
153
  let value = request.payload[key];
123
154
 
@@ -141,6 +172,10 @@ async function init(args) {
141
172
  await settings.clear('webhookErrorFlag');
142
173
  }
143
174
 
175
+ if (TLS_MATERIAL_SETTINGS.includes(key) && tlsSettingChanged(key, await settings.get(key), value)) {
176
+ tlsChanged.push(key);
177
+ }
178
+
144
179
  await settings.set(key, value);
145
180
  applied[key] = value;
146
181
  }
@@ -154,6 +189,14 @@ async function init(args) {
154
189
  // key fails, the earlier ones are already stored and the other workers still have
155
190
  // to reload for them, or they keep running on settings Redis no longer holds.
156
191
  notify('settings', applied);
192
+
193
+ // What a listener serves is not carried by that broadcast, and no worker acts on
194
+ // it. Until this was here, an instance switched to "self-signed only" through the
195
+ // API went on offering its Let's Encrypt certificate, and a name added to
196
+ // tlsHostnames was answered with the certificate that predates it, until something
197
+ // restarted the workers. Each command reports its own failure, so this cannot mask
198
+ // the error being thrown out of the catch.
199
+ await maybeReloadTlsCertificates(call, request.logger, tlsChanged, { action: 'settings' });
157
200
  }
158
201
 
159
202
  return { updated: Object.keys(applied) };
@@ -164,6 +207,12 @@ async function init(args) {
164
207
  tags: ['api', 'Settings'],
165
208
 
166
209
  plugins: {
210
+ mcp: {
211
+ name: 'update_settings',
212
+ title: 'Update settings',
213
+ description: `Change instance settings. Send only the keys to change; they take effect immediately on every worker. Covers where webhooks are delivered and which events are sent, notification shaping, branding, sync strategy, queue retention and AI processing. Confirm with the user before changing the webhook target. The settings that would widen this credential (${PRIVILEGED_SETTINGS_SUMMARY}) are not offered.`,
214
+ keep: MCP_SETTINGS_KEYS
215
+ },
167
216
  openapi: {
168
217
  responses: apiResponses('Returns the list of setting keys that were updated.', 400, 401, 403, 429, 500)
169
218
  }
@@ -237,6 +286,12 @@ async function init(args) {
237
286
  tags: ['api', 'Settings'],
238
287
 
239
288
  plugins: {
289
+ mcp: {
290
+ name: 'get_queue',
291
+ title: 'Get queue state',
292
+ description:
293
+ 'Get the state of a job queue: whether it is paused and how many jobs are active, waiting and delayed. `notify` carries webhook deliveries, `submit` carries outbound mail.'
294
+ },
240
295
  openapi: {
241
296
  responses: apiResponses('Returns the job counts and paused state for the queue.', 400, 401, 403, 429, 500)
242
297
  }
@@ -339,6 +394,12 @@ async function init(args) {
339
394
  tags: ['api', 'Settings'],
340
395
 
341
396
  plugins: {
397
+ mcp: {
398
+ name: 'set_queue_state',
399
+ title: 'Pause or resume a queue',
400
+ description:
401
+ 'Pause or resume a job queue. Set paused to true to stop the queue from processing jobs (they keep accumulating), false to resume it.'
402
+ },
342
403
  openapi: {
343
404
  responses: apiResponses('Returns the queue state after the change.', 400, 401, 403, 429, 500)
344
405
  }
@@ -30,6 +30,12 @@ async function init(args) {
30
30
  tags: ['api', 'Stats'],
31
31
 
32
32
  plugins: {
33
+ mcp: {
34
+ name: 'get_instance_stats',
35
+ title: 'Get instance statistics',
36
+ description:
37
+ 'Get instance-wide statistics: the running version, the license, how many accounts are connected, disconnected or failing, and message and webhook counters for the last `seconds` (default one day). The first call to make when asked how the instance is doing.'
38
+ },
33
39
  openapi: {
34
40
  responses: apiResponses('Returns counters, connection states and process information for this instance.', 400, 401, 403, 429, 500)
35
41
  }