emailengine-app 2.79.0 → 2.79.2

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 (110) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +79 -0
  3. package/bin/emailengine.js +8 -1
  4. package/config/default.toml +6 -0
  5. package/data/google-crawlers.json +1 -1
  6. package/lib/account.js +137 -19
  7. package/lib/api-routes/account-routes.js +13 -1
  8. package/lib/api-routes/index.js +12 -0
  9. package/lib/api-routes/mailbox-routes.js +6 -0
  10. package/lib/api-routes/mcp-oauth-routes.js +259 -0
  11. package/lib/api-routes/mcp-routes.js +172 -0
  12. package/lib/api-routes/message-routes.js +125 -4
  13. package/lib/api-routes/outbox-routes.js +7 -0
  14. package/lib/api-routes/permission-map.js +101 -1
  15. package/lib/api-routes/route-helpers.js +87 -4
  16. package/lib/api-routes/route-metadata.js +24 -4
  17. package/lib/api-routes/settings-routes.js +37 -14
  18. package/lib/api-routes/submit-routes.js +41 -0
  19. package/lib/api-routes/template-routes.js +7 -0
  20. package/lib/api-routes/token-routes.js +292 -122
  21. package/lib/arf-detect.js +17 -4
  22. package/lib/bounce-detect.js +28 -17
  23. package/lib/consts.js +36 -1
  24. package/lib/db.js +6 -0
  25. package/lib/email-client/base-client.js +102 -117
  26. package/lib/email-client/gmail-client.js +91 -29
  27. package/lib/email-client/imap/mailbox.js +175 -101
  28. package/lib/email-client/imap-client.js +49 -2
  29. package/lib/email-client/outlook-client.js +20 -24
  30. package/lib/enum-descriptions.js +2 -1
  31. package/lib/field-usage.js +17 -1
  32. package/lib/lua/h-set-new-mark.lua +36 -0
  33. package/lib/lua/s-list-accounts.lua +5 -2
  34. package/lib/mcp/index.js +29 -0
  35. package/lib/mcp/inject.js +70 -0
  36. package/lib/mcp/json-schema.js +120 -0
  37. package/lib/mcp/listen.js +171 -0
  38. package/lib/mcp/oauth.js +324 -0
  39. package/lib/mcp/protocol.js +489 -0
  40. package/lib/mcp/resources.js +139 -0
  41. package/lib/mcp/tools.js +655 -0
  42. package/lib/message-port-stream.js +84 -1
  43. package/lib/oauth2-apps.js +84 -15
  44. package/lib/openapi/build-document.js +5 -1
  45. package/lib/openapi/index.js +3 -1
  46. package/lib/response-stream.js +52 -21
  47. package/lib/routes-ui.js +4 -0
  48. package/lib/schemas.js +26 -5
  49. package/lib/settings.js +23 -9
  50. package/lib/token-audit-log.js +32 -9
  51. package/lib/token-permission-view.js +104 -8
  52. package/lib/tokens.js +194 -68
  53. package/lib/tools.js +96 -0
  54. package/lib/ui-routes/account-routes.js +55 -6
  55. package/lib/ui-routes/admin-config-routes.js +114 -1
  56. package/lib/ui-routes/admin-entities-routes.js +103 -19
  57. package/lib/ui-routes/auth-routes.js +13 -0
  58. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  59. package/lib/ui-routes/oauth-config-routes.js +7 -7
  60. package/lib/ui-routes/route-helpers.js +143 -1
  61. package/lib/ui-routes/suppression-list-routes.js +14 -9
  62. package/lib/utils/decode-headers.js +42 -0
  63. package/lib/utils/header-map.js +48 -0
  64. package/lib/utils/network.js +9 -1
  65. package/lib/utils/unsafe-key.js +59 -0
  66. package/lib/web-safe-html.js +61 -0
  67. package/lib/webhook-routing.js +6 -2
  68. package/lib/webhooks.js +31 -8
  69. package/package.json +9 -8
  70. package/sbom.json +1 -1
  71. package/scripts/README.md +25 -0
  72. package/scripts/build-icon.js +77 -0
  73. package/server.js +39 -17
  74. package/static/css/flyonui.css +1 -1
  75. package/static/css/src/app.tailwind.css +98 -0
  76. package/static/emailengine.ico +0 -0
  77. package/static/js/ui.js +465 -1
  78. package/static/licenses.html +42 -22
  79. package/translations/messages.pot +57 -57
  80. package/views/accounts/account.hbs +8 -8
  81. package/views/accounts/browse.hbs +1 -1
  82. package/views/accounts/edit.hbs +2 -2
  83. package/views/config/mcp.hbs +361 -0
  84. package/views/config/oauth/index.hbs +7 -0
  85. package/views/gateways/edit.hbs +1 -1
  86. package/views/gateways/gateway.hbs +2 -2
  87. package/views/gateways/index.hbs +7 -7
  88. package/views/layout/prompt.hbs +62 -0
  89. package/views/mcp/authorize.hbs +136 -0
  90. package/views/partials/accounts_table.hbs +7 -7
  91. package/views/partials/head_assets.hbs +3 -3
  92. package/views/partials/mcp_access_levels.hbs +13 -0
  93. package/views/partials/mcp_account_limit.hbs +14 -0
  94. package/views/partials/mcp_tool_count.hbs +19 -0
  95. package/views/partials/side_menu.hbs +1 -0
  96. package/views/partials/ui/account-picker.hbs +59 -0
  97. package/views/partials/ui/code-block.hbs +26 -0
  98. package/views/partials/ui/menu-item.hbs +5 -0
  99. package/views/partials/ui/radio.hbs +41 -0
  100. package/views/partials/ui/tab.hbs +15 -10
  101. package/views/partials/ui/tabs.hbs +8 -5
  102. package/views/suppression-lists/list.hbs +1 -1
  103. package/views/templates/index.hbs +2 -2
  104. package/views/templates/template.hbs +5 -4
  105. package/views/tokens/index.hbs +30 -4
  106. package/views/tokens/new.hbs +517 -239
  107. package/winconf.js +148 -48
  108. package/workers/api.js +239 -95
  109. package/workers/imap.js +65 -72
  110. package/workers/webhooks.js +21 -1
package/lib/tools.js CHANGED
@@ -389,10 +389,23 @@ function redactValidationError(err) {
389
389
  return err;
390
390
  }
391
391
 
392
+ // Shared token grammar for cid: references in HTML. Collection
393
+ // (collectCidReferences) and every cid: to data URI replace step must tokenize
394
+ // identically, otherwise the attachments fetched drift from the references
395
+ // replaced and inline images silently disappear. Exposed as a factory rather
396
+ // than one regex instance so no lastIndex state can leak between callers.
397
+ const CID_REFERENCE_SOURCE = String.raw`\bcid:([^"'\s>]+)`;
398
+
399
+ function cidReferenceRegex() {
400
+ return new RegExp(CID_REFERENCE_SOURCE, 'g');
401
+ }
402
+
392
403
  module.exports = {
393
404
  // keep the re-export, lib/utils/to-camel-case.js holds it so pure modules can use it too
394
405
  toCamelCase,
395
406
 
407
+ cidReferenceRegex,
408
+
396
409
  /**
397
410
  * Establish an admin session: every full session write goes through here
398
411
  * so the session always carries a random sid. The message browser binds
@@ -409,6 +422,89 @@ module.exports = {
409
422
  request.cookieAuth.set(Object.assign({}, sessionData, { sid: randomBytes(32).toString('hex') }));
410
423
  },
411
424
 
425
+ /**
426
+ * Whether a session cookie has been ended by a later "log out all sessions"
427
+ * or password change.
428
+ *
429
+ * The read side of the `passwordVersion` setAdminSession() stamps, and the
430
+ * one spelling of the comparison, because the same cookie carries two
431
+ * credentials and both have to end together: the admin session itself, and
432
+ * the browse page's `sess_` API token, which is HMAC'd to the cookie's sid
433
+ * and slides its own TTL on every use. They authenticate through different
434
+ * Hapi strategies in workers/api.js, so a rule written out twice is a rule
435
+ * one of them can be left out of - which is how the token outlived the
436
+ * click for a while.
437
+ *
438
+ * A zero or absent current version never ends a session: it means no local
439
+ * password exists (an unsecured instance), or nobody has ever bumped it,
440
+ * and a session stamped before the field existed must not be force-expired.
441
+ *
442
+ * @param {Number} currentPasswordVersion authData.passwordVersion, or 0
443
+ * @param {Object} session decoded session cookie
444
+ * @returns {Boolean} true when the session is over
445
+ */
446
+ isEndedSession(currentPasswordVersion, session) {
447
+ return !!currentPasswordVersion && currentPasswordVersion !== (session && session.passwordVersion);
448
+ },
449
+
450
+ /**
451
+ * Caps the decoded plain and html values of a text object at maxBytes,
452
+ * mirroring the IMAP getText() semantics: the limit applies per text type
453
+ * to the decoded string. The API clients (Gmail, MS Graph) receive the full
454
+ * text from the provider in one response, so unlike IMAP the limit cannot
455
+ * reduce what is downloaded, only what is passed on - without it a
456
+ * notifyTextSize / maxBytes cap is silently ignored on API accounts.
457
+ * Mutates the passed object; only the "plain" and "html" keys are touched,
458
+ * so an id reference or a flag riding on the same object is never clipped.
459
+ * For byte-exact UTF-8 truncation see truncateToBytes in lib/mcp/tools.js,
460
+ * a different contract that is kept separate on purpose.
461
+ * @param {Object} textContents Object carrying plain and/or html strings
462
+ * @param {Number} maxBytes Size limit per text type, falsy means no limit
463
+ * @returns {Boolean} true if any value was truncated
464
+ */
465
+ truncateTextContents(textContents, maxBytes) {
466
+ let hasMore = false;
467
+ if (maxBytes && textContents) {
468
+ for (let key of ['plain', 'html']) {
469
+ if (typeof textContents[key] === 'string' && textContents[key].length > maxBytes) {
470
+ textContents[key] = textContents[key].substr(0, maxBytes);
471
+ hasMore = true;
472
+ }
473
+ }
474
+ }
475
+ return hasMore;
476
+ },
477
+
478
+ /**
479
+ * Collects the content ids referenced through "cid:" links in an HTML string.
480
+ * Returned ids carry no "cid:" prefix or angle brackets. Use this with a Set
481
+ * lookup per attachment instead of scanning the full HTML once per attachment:
482
+ * the repeated synchronous scans cost attachment count times body size, which
483
+ * on a crafted message blocks the worker event loop past the heartbeat
484
+ * restart timeout. Tokenizes with the same grammar as the cid: replace steps
485
+ * (cidReferenceRegex), so a content id that is only a prefix of a referenced
486
+ * id, or that appears outside a cid: link, does not match. Each token is
487
+ * additionally added truncated at a closing parenthesis: the replace grammar
488
+ * does not stop at ")" and so never embeds CSS url(cid:...) references, but
489
+ * the attachment content they point at should still be fetched.
490
+ * @param {String} html HTML content to scan
491
+ * @returns {Set<String>} Content ids referenced in the HTML
492
+ */
493
+ collectCidReferences(html) {
494
+ let cids = new Set();
495
+ if (typeof html === 'string') {
496
+ for (let match of html.matchAll(cidReferenceRegex())) {
497
+ let cid = match[1];
498
+ cids.add(cid);
499
+ let parenPos = cid.indexOf(')');
500
+ if (parenPos > 0) {
501
+ cids.add(cid.substring(0, parenPos));
502
+ }
503
+ }
504
+ }
505
+ return cids;
506
+ },
507
+
412
508
  /**
413
509
  * Helper function to set specific bit in a buffer
414
510
  * @param {Buffer} buffer Buffer to edit
@@ -42,9 +42,9 @@ const {
42
42
  ACCOUNT_DISPLAY_STATES,
43
43
  signedFormBlobFields: signedBlobFields
44
44
  } = require('../schemas');
45
- const { formatAccountData, cachedTemplates, identityErrorView, ACCOUNT_STATE_DISPLAY } = require('./route-helpers');
45
+ const { formatAccountData, cachedTemplates, identityErrorView, ACCOUNT_STATE_DISPLAY, adminUrl, accountSuggestions } = require('./route-helpers');
46
46
  const { webhooks: Webhooks } = require('../webhooks');
47
- const { describeEffectiveRouting } = require('../webhook-routing');
47
+ const { describeEffectiveRouting, isDeliverableRoute } = require('../webhook-routing');
48
48
  const { matchesExpectedIdentity, resolveExpectedIdentity } = require('../account/expected-identity');
49
49
 
50
50
  const { REDIS_PREFIX, DEFAULT_PAGE_SIZE, NONCE_BYTES, MAX_FORM_TTL, MAX_FORM_PROBE_ATTEMPTS } = consts;
@@ -280,6 +280,48 @@ function init(args) {
280
280
  }
281
281
  });
282
282
 
283
+ // The data behind the account picker (views/partials/ui/account-picker.hbs), which every admin
284
+ // form that binds something to one account renders. A search endpoint rather than a list
285
+ // shipped with the page: an instance can hold far more accounts than a page could usefully
286
+ // carry, and the whole point of the control is that a person types part of what they are
287
+ // looking for.
288
+ //
289
+ // No auth options of its own: it inherits the admin surface's session default, exactly like the
290
+ // listing it is a narrower view of, and it exposes nothing that listing does not.
291
+ server.route({
292
+ method: 'GET',
293
+ path: '/admin/accounts/suggestions',
294
+
295
+ async handler(request) {
296
+ const { accounts, total } = await accountSuggestions(call, { query: request.query.query, logger: request.logger });
297
+
298
+ return {
299
+ accounts,
300
+ // What the box could not show, so the picker can say "keep typing" rather than
301
+ // letting a capped list read as the whole instance. The total itself is not
302
+ // returned: nothing renders it, and it would only be a third number to keep
303
+ // consistent with the other two.
304
+ more: Math.max(total - accounts.length, 0)
305
+ };
306
+ },
307
+
308
+ options: {
309
+ validate: {
310
+ options: {
311
+ stripUnknown: true,
312
+ abortEarly: false,
313
+ convert: true
314
+ },
315
+
316
+ failAction,
317
+
318
+ query: Joi.object({
319
+ query: Joi.string().trim().empty('').max(256).description('Search string matched against account id, name and address')
320
+ })
321
+ }
322
+ }
323
+ });
324
+
283
325
  server.route({
284
326
  method: 'POST',
285
327
  path: '/admin/accounts/new',
@@ -1368,6 +1410,11 @@ function init(args) {
1368
1410
  Webhooks.list(0, 1000)
1369
1411
  ]);
1370
1412
 
1413
+ // The listing carries route metadata only, but the worker's delivery gate also
1414
+ // requires a filter script, so the card needs the filter-presence markers for the
1415
+ // routes it is about to present as delivering
1416
+ const routeFilterInfo = await Webhooks.getFilterInfo(webhookRoutesList.webhooks.filter(isDeliverableRoute).map(route => route.id));
1417
+
1371
1418
  const webhookRouting = describeEffectiveRouting({
1372
1419
  webhooksEnabled: webhookSettings.webhooksEnabled,
1373
1420
  globalWebhooks: webhookSettings.webhooks,
@@ -1376,7 +1423,9 @@ function init(args) {
1376
1423
  inboxNewOnly: webhookSettings.inboxNewOnly,
1377
1424
  globalCustomHeaders: webhookSettings.webhooksCustomHeaders,
1378
1425
  accountCustomHeaders: accountData.webhooksCustomHeaders,
1379
- routes: webhookRoutesList.webhooks
1426
+ // Non-deliverable routes were not probed; their hasFilter stays undefined, which
1427
+ // describeEffectiveRouting() reads as "unknown" (and filters them out anyway)
1428
+ routes: webhookRoutesList.webhooks.map(route => Object.assign({}, route, { hasFilter: routeFilterInfo.get(route.id) }))
1380
1429
  });
1381
1430
 
1382
1431
  return h.view(
@@ -1478,7 +1527,7 @@ function init(args) {
1478
1527
  } catch (err) {
1479
1528
  await request.flash({ type: 'danger', message: `Couldn't delete account. Try again.` });
1480
1529
  request.logger.error({ msg: 'Failed to delete the account', err, account: request.params.account, remoteAddress: request.app.ip });
1481
- return h.redirect(`/admin/accounts/${request.params.account}`);
1530
+ return h.redirect(adminUrl`/admin/accounts/${request.params.account}`);
1482
1531
  }
1483
1532
  },
1484
1533
  options: {
@@ -1724,7 +1773,7 @@ function init(args) {
1724
1773
  const canReadMail = (accountData.imap || accountData.oauth2) && !(accountData.imap && accountData.imap.disabled) && !DISABLE_MESSAGE_BROWSER;
1725
1774
  if (!canReadMail) {
1726
1775
  await request.flash({ type: 'danger', message: `Mail access is disabled for this account` });
1727
- return h.redirect(`/admin/accounts/${request.params.account}`);
1776
+ return h.redirect(adminUrl`/admin/accounts/${request.params.account}`);
1728
1777
  }
1729
1778
 
1730
1779
  return h.view(
@@ -1955,7 +2004,7 @@ function init(args) {
1955
2004
 
1956
2005
  await accountObject.update(updates);
1957
2006
 
1958
- return h.redirect(`/admin/accounts/${request.params.account}`);
2007
+ return h.redirect(adminUrl`/admin/accounts/${request.params.account}`);
1959
2008
  } catch (err) {
1960
2009
  await request.flash({ type: 'danger', message: `Couldn't save account settings. Try again.` });
1961
2010
  request.logger.error({ msg: 'Failed to update account settings', err, account: request.params.account });
@@ -26,9 +26,14 @@ const { validateWebhookTarget } = require('../webhook-egress');
26
26
  const { sendWebhookRequest } = require('../webhook-request');
27
27
  const { llmPreProcess } = require('../llm-pre-process');
28
28
  const { documentStoreFeatureEnabled } = require('../document-store');
29
+ const { mcpFeatureEnabled } = require('../mcp');
30
+ const { mcpResource } = require('../mcp/oauth');
31
+ const { getToolRegistry } = require('../mcp/tools');
32
+ const { serverUrl } = require('../openapi');
33
+ const { MCP_ACCESS_LEVELS, MCP_ACCESS_LEVEL_OPTIONS } = require('../token-permission-view');
29
34
  const { locales } = require('../translations');
30
35
  const { settingsSchema } = require('../schemas');
31
- const { getOpenAiModels, OPEN_AI_MODELS, getExampleDocumentsPayloads } = require('./route-helpers');
36
+ const { getOpenAiModels, OPEN_AI_MODELS, getExampleDocumentsPayloads, mcpToolGrants } = require('./route-helpers');
32
37
  const { registerSettingsPage } = require('./settings-page');
33
38
 
34
39
  const {
@@ -555,6 +560,114 @@ function init(args) {
555
560
  }
556
561
  });
557
562
 
563
+ registerSettingsPage(server, {
564
+ path: '/admin/config/mcp',
565
+ view: 'config/mcp',
566
+ pageTitle: 'MCP',
567
+ menuKey: 'menuConfigMcp',
568
+ schema: {
569
+ mcpEnabled: settingsSchema.mcpEnabled.default(false),
570
+ mcpOAuthEnabled: settingsSchema.mcpOAuthEnabled.default(false)
571
+ },
572
+
573
+ async loadValues() {
574
+ const storedValues = await settings.getMulti('mcpEnabled', 'mcpOAuthEnabled');
575
+
576
+ return {
577
+ mcpEnabled: !!storedValues.mcpEnabled,
578
+ mcpOAuthEnabled: !!storedValues.mcpOAuthEnabled
579
+ };
580
+ },
581
+
582
+ async viewContext(request) {
583
+ const { serviceUrl, mcpOAuthEnabled } = await settings.getMulti('serviceUrl', 'mcpOAuthEnabled');
584
+
585
+ // The configured public address when a Service URL is set (the same derivation the
586
+ // OAuth metadata publishes as the resource identifier), otherwise the address this
587
+ // request arrived on - the same request-derived answer /swagger.json publishes
588
+ let configuredOrigin = null;
589
+ try {
590
+ configuredOrigin = serviceUrl ? new URL(serviceUrl).origin : null;
591
+ } catch (err) {
592
+ // an unparseable serviceUrl setting falls back to the request address
593
+ }
594
+
595
+ const mcpUrl = mcpResource(configuredOrigin || serverUrl(request));
596
+
597
+ // The catalog and the endpoint read one registry (lib/mcp/tools.js), so this list is
598
+ // exactly what an agent receives from tools/list - the operator approves what they
599
+ // can see, not a prose summary of it. The badge collapses the annotation hints back
600
+ // into the one action they were derived from.
601
+ const mcpTools = mcpToolGrants(server, request.logger);
602
+
603
+ let toolCatalog = [];
604
+ try {
605
+ toolCatalog = getToolRegistry(server).tools.map(tool => ({
606
+ name: tool.name,
607
+ description: tool.description,
608
+ badge: tool.annotations.openWorldHint
609
+ ? { label: 'sends email', variant: 'warning' }
610
+ : tool.annotations.destructiveHint
611
+ ? { label: 'destructive', variant: 'error' }
612
+ : tool.annotations.readOnlyHint
613
+ ? { label: 'read-only', variant: 'success' }
614
+ : { label: 'write', variant: 'info' }
615
+ }));
616
+ } catch (err) {
617
+ request.logger.error({ msg: 'Failed to derive the MCP tool catalog', err });
618
+ }
619
+
620
+ const serviceUrlConfigured = !!configuredOrigin;
621
+
622
+ // Which precondition blocks the OAuth connection method right now, or null when it
623
+ // is ready: the stored setting first (the page-local action), then a usable Service
624
+ // URL. This is what oauthOrigin() checks minus the mcpEnabled setting - deliberately,
625
+ // because the Connect tab's own "endpoint not enabled" alert owns that state and the
626
+ // badge must not double-report it; null with the deployment gate off for the same
627
+ // reason. The one value drives both the method tab's badge and the panel's warning,
628
+ // so the two cannot disagree. Stored state on purpose, not the posted form value:
629
+ // it reports what a connector would actually get today. The blocked method's tab
630
+ // stays clickable - a disabled tab cannot explain how to enable itself - and carries
631
+ // a "not enabled" badge instead.
632
+ let oauthMethodBlocker = null;
633
+ if (mcpFeatureEnabled) {
634
+ if (!mcpOAuthEnabled) {
635
+ oauthMethodBlocker = 'setting';
636
+ } else if (!serviceUrlConfigured) {
637
+ oauthMethodBlocker = 'serviceUrl';
638
+ }
639
+ }
640
+
641
+ return {
642
+ mcpFeatureEnabled,
643
+ mcpUrl,
644
+ serviceUrlConfigured,
645
+ oauthMethodBlocker,
646
+ toolCatalog,
647
+ // The same catalog reduced to what the tool count needs: one entry per tool with
648
+ // the operation it dispatches under and whether it can be bound to an account
649
+ mcpTools,
650
+ // The whole access-level table, `full: null` included: the page script keys on
651
+ // the same map the consent route mints from, so a level added there is offered
652
+ // here without a second list to update
653
+ mcpAccessPresets: MCP_ACCESS_LEVELS,
654
+ // The generator's radio group renders through the shared mcp_access_levels
655
+ // partial, from the same table the consent prompt offers
656
+ accessOptions: MCP_ACCESS_LEVEL_OPTIONS,
657
+ // The same gate as the token pages: minting needs an authenticated admin
658
+ // session on this request, not just a password existing in Redis
659
+ canProvision: request.auth.isAuthenticated
660
+ };
661
+ },
662
+
663
+ async applySettings(request) {
664
+ await settings.setMulti({
665
+ mcpEnabled: request.payload.mcpEnabled,
666
+ mcpOAuthEnabled: request.payload.mcpOAuthEnabled
667
+ });
668
+ }
669
+ });
670
+
558
671
  registerSettingsPage(server, {
559
672
  path: '/admin/config/ai',
560
673
  view: 'config/ai',
@@ -10,17 +10,23 @@ 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 { Account } = require('../account');
13
+ const { Account, accountExists } = require('../account');
14
+ const { isMcpEnabled } = require('../mcp');
14
15
  const { Gateway } = require('../gateway');
15
16
  const { templates } = require('../templates');
16
17
  const { webhooks } = require('../webhooks');
17
18
  const consts = require('../consts');
18
19
  const wellKnownServices = require('nodemailer/lib/well-known/services.json');
19
- const { authAwareLevel } = require('./route-helpers');
20
+ const { authAwareLevel, resolveKnownAccounts, adminUrl, mcpToolGrants, accountPickerEntry } = require('./route-helpers');
20
21
  const exampleWebhookPayloads = require('../payload-examples-webhooks.json');
21
22
 
22
23
  const { DEFAULT_PAGE_SIZE } = consts;
23
24
 
25
+ // Every scope the admin token form can mint - one list, because the listing's ?scope= filter
26
+ // validates against the same vocabulary and a scope added to one side must not leave the other
27
+ // behind. Deliberately wider than the /v1/tokens set, which excludes '*' and 'metrics'.
28
+ const ADMIN_TOKEN_SCOPES = ['*', 'api', 'metrics', 'smtp', 'imap-proxy', 'mcp'];
29
+
24
30
  const notificationTypes = Object.keys(consts)
25
31
  .map(key => {
26
32
  if (/_NOTIFY$/.test(key)) {
@@ -300,7 +306,7 @@ return payload;`)
300
306
  );
301
307
 
302
308
  await request.flash({ type: 'info', message: `Webhook created` });
303
- return h.redirect(`/admin/webhooks/webhook/${createRequest.id}`);
309
+ return h.redirect(adminUrl`/admin/webhooks/webhook/${createRequest.id}`);
304
310
  } catch (err) {
305
311
  await request.flash({ type: 'danger', message: `Couldn't create webhook. Try again.` });
306
312
  request.logger.error({ msg: 'Failed to create webhook route', err });
@@ -612,7 +618,7 @@ return payload;`)
612
618
  );
613
619
 
614
620
  await request.flash({ type: 'info', message: `Webhook saved` });
615
- return h.redirect(`/admin/webhooks/webhook/${request.payload.webhook}`);
621
+ return h.redirect(adminUrl`/admin/webhooks/webhook/${request.payload.webhook}`);
616
622
  } catch (err) {
617
623
  await request.flash({ type: 'danger', message: `Couldn't save webhook. Try again.` });
618
624
  request.logger.error({ msg: 'Failed to update webhook route', err });
@@ -760,7 +766,7 @@ return payload;`)
760
766
  } catch (err) {
761
767
  await request.flash({ type: 'danger', message: `Couldn't delete webhook. Try again.` });
762
768
  request.logger.error({ msg: 'Failed to delete webhook route', err, webhook: request.payload.webhook, remoteAddress: request.app.ip });
763
- return h.redirect(`/admin/webhooks/webhook/${request.payload.webhook}`);
769
+ return h.redirect(adminUrl`/admin/webhooks/webhook/${request.payload.webhook}`);
764
770
  }
765
771
  },
766
772
  options: {
@@ -1058,7 +1064,7 @@ return payload;`)
1058
1064
  );
1059
1065
 
1060
1066
  await request.flash({ type: 'info', message: `Template saved` });
1061
- return h.redirect(`/admin/templates/template/${request.payload.template}`);
1067
+ return h.redirect(adminUrl`/admin/templates/template/${request.payload.template}`);
1062
1068
  } catch (err) {
1063
1069
  await request.flash({ type: 'danger', message: `Couldn't save template. Try again.` });
1064
1070
  request.logger.error({ msg: 'Failed to update template', err });
@@ -1285,7 +1291,7 @@ return payload;`)
1285
1291
  );
1286
1292
 
1287
1293
  await request.flash({ type: 'info', message: `Template created` });
1288
- return h.redirect(`/admin/templates/template/${createRequest.id}`);
1294
+ return h.redirect(adminUrl`/admin/templates/template/${createRequest.id}`);
1289
1295
  } catch (err) {
1290
1296
  await request.flash({ type: 'danger', message: `Couldn't create template. Try again.` });
1291
1297
  request.logger.error({ msg: 'Failed to create template', err });
@@ -1420,7 +1426,7 @@ return payload;`)
1420
1426
  } catch (err) {
1421
1427
  await request.flash({ type: 'danger', message: `Couldn't delete template. Try again.` });
1422
1428
  request.logger.error({ msg: 'Failed to delete the template', err, template: request.payload.template, remoteAddress: request.app.ip });
1423
- return h.redirect(`/admin/templates/template/${request.payload.template}`);
1429
+ return h.redirect(adminUrl`/admin/templates/template/${request.payload.template}`);
1424
1430
  }
1425
1431
  },
1426
1432
  options: {
@@ -1792,7 +1798,7 @@ return payload;`)
1792
1798
  await request.flash({ type: 'success', message: `Updated SMTP gateway`, result });
1793
1799
  }
1794
1800
 
1795
- return h.redirect(`/admin/gateways/gateway/${encodeURIComponent(result.gateway)}?state=${result.state}`);
1801
+ return h.redirect(adminUrl`/admin/gateways/gateway/${result.gateway}?state=${result.state}`);
1796
1802
  } catch (err) {
1797
1803
  await request.flash({ type: 'danger', message: `Couldn't add gateway. Try again.` });
1798
1804
  request.logger.error({ msg: 'Failed to add new gateway', err });
@@ -1907,7 +1913,7 @@ return payload;`)
1907
1913
 
1908
1914
  await request.flash({ type: 'success', message: `Updated SMTP gateway`, result });
1909
1915
 
1910
- return h.redirect(`/admin/gateways/gateway/${encodeURIComponent(result.gateway)}`);
1916
+ return h.redirect(adminUrl`/admin/gateways/gateway/${result.gateway}`);
1911
1917
  } catch (err) {
1912
1918
  await request.flash({ type: 'danger', message: `Couldn't save gateway. Try again.` });
1913
1919
  request.logger.error({ msg: 'Failed to update gateway', err });
@@ -2141,7 +2147,7 @@ return payload;`)
2141
2147
  } catch (err) {
2142
2148
  await request.flash({ type: 'danger', message: `Couldn't delete gateway. Try again.` });
2143
2149
  request.logger.error({ msg: 'Failed to delete the gateway', err, gateway: request.params.gateway, remoteAddress: request.app.ip });
2144
- return h.redirect(`/admin/gateways/${request.params.gateway}`);
2150
+ return h.redirect(adminUrl`/admin/gateways/gateway/${request.params.gateway}`);
2145
2151
  }
2146
2152
  },
2147
2153
  options: {
@@ -2178,9 +2184,30 @@ return payload;`)
2178
2184
  accountData = await accountObject.loadAccountData();
2179
2185
  }
2180
2186
 
2181
- const data = await tokens.list(request.query.account, request.query.page - 1, request.query.pageSize, request.query.query);
2187
+ const data = await tokens.list(request.query.account, request.query.page - 1, request.query.pageSize, request.query.query, {
2188
+ // Every token on the instance, not just the unbound ones. A bound token lives in its
2189
+ // account's index, so without this the page that manages access tokens was the one
2190
+ // place a bound token could not be seen - and the form can now issue one directly.
2191
+ all: !request.query.account,
2192
+ // The deep-link filter the MCP pages use ("which agents are connected"), general
2193
+ // over every scope because the listing search cannot answer it - scopes are not
2194
+ // among the fields it matches
2195
+ scope: request.query.scope
2196
+ });
2197
+
2198
+ // A token outlives the account it was bound to: deleting an account drops that account's
2199
+ // token index but not the token records, and such a token still authenticates. So the
2200
+ // binding column has to tell a live account from a gone one rather than link every row
2201
+ // and let some of them lead to a 404.
2202
+ //
2203
+ // That column is the only reader of accountKnown, so the probe follows the same flag the
2204
+ // view renders on: an account-filtered page names one account, already loaded above, and
2205
+ // shows no column to put the answer in.
2206
+ const showAccountColumn = !accountData;
2207
+ const knownAccounts = showAccountColumn ? await resolveKnownAccounts(data.tokens) : new Map();
2182
2208
 
2183
2209
  data.tokens.forEach(entry => {
2210
+ entry.accountKnown = knownAccounts.get(entry.account);
2184
2211
  entry.access = entry.access || {};
2185
2212
  entry.access.timeStr =
2186
2213
  entry.access && entry.access.time && typeof entry.access.time.toISOString === 'function' ? entry.access.time.toISOString() : null;
@@ -2221,6 +2248,10 @@ return payload;`)
2221
2248
  url.searchParams.append('query', request.query.query);
2222
2249
  }
2223
2250
 
2251
+ if (request.query.scope) {
2252
+ url.searchParams.append('scope', request.query.scope);
2253
+ }
2254
+
2224
2255
  return url.pathname + url.search;
2225
2256
  };
2226
2257
 
@@ -2244,12 +2275,22 @@ return payload;`)
2244
2275
  menuTokens: true,
2245
2276
  data,
2246
2277
 
2278
+ // Redundant in the account-filtered listing, where the card header above the
2279
+ // table already names the one account every row belongs to
2280
+ showAccountColumn,
2281
+
2247
2282
  searchTarget: '/admin/tokens',
2248
2283
  searchPlaceholder: 'Search for access tokens…',
2249
2284
  query: request.query.query,
2285
+ // The active scope filter, so the page can say it is showing a subset and
2286
+ // offer the way out of it
2287
+ scopeFilter: request.query.scope,
2250
2288
  // The create button leads to a form that cannot submit without an admin session
2251
2289
  canProvision: request.auth.isAuthenticated,
2252
- searchHidden: request.query.account ? [{ name: 'account', value: request.query.account }] : null,
2290
+ searchHidden: [
2291
+ request.query.account ? { name: 'account', value: request.query.account } : null,
2292
+ request.query.scope ? { name: 'scope', value: request.query.scope } : null
2293
+ ].filter(entry => entry),
2253
2294
  total: data.total,
2254
2295
 
2255
2296
  account: accountData,
@@ -2288,7 +2329,16 @@ return payload;`)
2288
2329
  account: accountIdSchema.default(null),
2289
2330
  page: Joi.number().integer().min(1).max(1000000).default(1),
2290
2331
  pageSize: Joi.number().integer().min(1).max(250).default(DEFAULT_PAGE_SIZE),
2291
- query: Joi.string().empty('').example('prometheus').description('Filter by search term')
2332
+ // Trimmed like the /v1/tokens listing: an untrimmed whitespace-only value is a
2333
+ // query to the route and no query at all to the filter, so the listing would
2334
+ // read every record on the instance and then match all of them
2335
+ query: Joi.string().empty('').trim().example('prometheus').description('Filter by search term'),
2336
+ // The vocabulary the token form accepts, so the filter cannot name a scope
2337
+ // no token could carry
2338
+ scope: Joi.string()
2339
+ .empty('')
2340
+ .valid(...ADMIN_TOKEN_SCOPES)
2341
+ .description('Only tokens carrying this scope')
2292
2342
  })
2293
2343
  }
2294
2344
  }
@@ -2309,6 +2359,14 @@ return payload;`)
2309
2359
 
2310
2360
  const permissionModel = tokenPermissionView.formModel();
2311
2361
 
2362
+ // What an mcp-scoped token would actually be able to call, per (action, group) grant.
2363
+ // The form counts the surviving tools against the selected narrowing, which is the only
2364
+ // answer a reader of the two axes cannot work out for themselves: the MCP surface reaches
2365
+ // six of the thirteen sections, so a section ticked here can add nothing at all to it.
2366
+ // From the registry the endpoint itself dispatches through, like the MCP config page's
2367
+ // catalog, so the count cannot describe a tool set that has since changed.
2368
+ const mcpTools = mcpToolGrants(server, request.logger);
2369
+
2312
2370
  return h.view(
2313
2371
  'tokens/new',
2314
2372
  {
@@ -2316,7 +2374,6 @@ return payload;`)
2316
2374
  menuTokens: true,
2317
2375
  values: {
2318
2376
  scopesAll: true,
2319
- allAccounts: !request.query.account,
2320
2377
  account: request.query.account
2321
2378
  },
2322
2379
  // Same expression the POST gate uses, so the form and the thing it submits to
@@ -2328,7 +2385,22 @@ return payload;`)
2328
2385
  ...permissionModel,
2329
2386
  // Handed to the page as data rather than restated in its script
2330
2387
  permissionSurfacesJson: JSON.stringify(permissionModel.permissionSurfaces),
2388
+ mcpTools,
2389
+ // The same three access levels the OAuth consent prompt and the MCP config
2390
+ // page offer, from the same table, rendered through the same partial. An
2391
+ // mcp-scoped token is minted from three places and the levels have to mean
2392
+ // the same thing in all of them.
2393
+ accessOptions: tokenPermissionView.MCP_ACCESS_LEVEL_OPTIONS,
2394
+ mcpAccessPresets: tokenPermissionView.MCP_ACCESS_LEVELS,
2395
+ // Whether the endpoint an mcp-scoped token would talk to is actually serving.
2396
+ // Both halves of the gate, because a token minted against either one being off
2397
+ // is a credential for nothing, and the form is the last place to say so.
2398
+ mcpReady: await isMcpEnabled(),
2331
2399
  account: accountData,
2400
+ // The account picker's starting state, from the record already loaded above:
2401
+ // arriving from an account's own token list pre-binds the form, and the picker
2402
+ // shows that as the account it names rather than as a raw id
2403
+ selectedAccount: accountData ? accountPickerEntry(accountData) : null,
2332
2404
  accountTokensLink: accountTokensLink.pathname + accountTokensLink.search
2333
2405
  },
2334
2406
  {
@@ -2389,8 +2461,13 @@ return payload;`)
2389
2461
  }
2390
2462
 
2391
2463
  if (request.payload.account) {
2392
- let accountObject = new Account({ redis, account: request.payload.account });
2393
- await accountObject.loadAccountData();
2464
+ // Existence probe rather than a full account load: nothing here reads the record,
2465
+ // only whether the ID names one. The ID is typed into the form now rather than
2466
+ // carried over from an account page, so a typo is the likely cause and the answer
2467
+ // has to name the value that was not found.
2468
+ if (!(await accountExists(redis, request.payload.account))) {
2469
+ throw Boom.badRequest(`No account found with ID "${request.payload.account}"`);
2470
+ }
2394
2471
  data.account = request.payload.account;
2395
2472
  }
2396
2473
 
@@ -2426,7 +2503,7 @@ return payload;`)
2426
2503
  payload: Joi.object({
2427
2504
  description: Joi.string().empty('').trim().max(1024).required().example('Token description').description('Token description'),
2428
2505
  scopes: Joi.array()
2429
- .items(Joi.string().valid('*', 'api', 'metrics', 'smtp', 'imap-proxy'))
2506
+ .items(Joi.string().valid(...ADMIN_TOKEN_SCOPES))
2430
2507
  .required()
2431
2508
  .label('Scopes'),
2432
2509
  // Null when the restriction is off, which is what "not narrowed" means on the
@@ -2477,7 +2554,14 @@ return payload;`)
2477
2554
  return h.redirect('/admin/tokens').takeover();
2478
2555
  },
2479
2556
 
2480
- payload: Joi.object({ token: Joi.string().length(64).hex().required().example('123456').description('Access token') })
2557
+ payload: Joi.object({
2558
+ token: Joi.string()
2559
+ .length(64)
2560
+ .hex()
2561
+ .required()
2562
+ .example('1bc12baf7f0d5e51fe0a4e0eda06e1be5b8d6cc2c66b95dc0fbe4d2e9f5d5e1a')
2563
+ .description('Access token')
2564
+ })
2481
2565
  }
2482
2566
  }
2483
2567
  });
@@ -1251,6 +1251,19 @@ function init(args) {
1251
1251
  let authData = await settings.get('authData');
1252
1252
  let hasExistingPassword = !!(authData && authData.password);
1253
1253
  if (hasExistingPassword) {
1254
+ // The current-password field is a password check like the login form's, and
1255
+ // unthrottled it let a hijacked session guess the password at full speed - the
1256
+ // one thing a session alone is not supposed to reveal. Keyed on the account
1257
+ // rather than the address because the caller is already authenticated as it,
1258
+ // and the same budget as the login form's per-username limiter.
1259
+ let rateLimit = await h.checkRateLimit(`password:verify:${authData.user || 'admin'}`, 1, 10, 60);
1260
+ if (!rateLimit.success) {
1261
+ request.logger.warn({ msg: 'Rate limited', rateLimit, remoteAddress: request.app.ip });
1262
+ let err = new Error('Rate limited, please wait and try again');
1263
+ err.details = { password0: err.message };
1264
+ throw err;
1265
+ }
1266
+
1254
1267
  let valid;
1255
1268
  try {
1256
1269
  valid = await pbkdf2.verify(authData.password, request.payload.password0);