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
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.79.0"
2
+ ".": "2.79.2"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,84 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.79.2](https://github.com/postalsys/emailengine/compare/v2.79.1...v2.79.2) (2026-08-22)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **api:** confine browse-page session tokens and gate the SBOM ([7f3fc6e](https://github.com/postalsys/emailengine/commit/7f3fc6e464a6161286e1fa3ccd3cc933db7cf874))
9
+ * **api:** end browse-page session tokens when every session is logged out ([4040773](https://github.com/postalsys/emailengine/commit/40407733c79c4d65a223cc594b925015e201862a))
10
+ * **attachments:** collect cid references in one pass instead of scanning the HTML per attachment ([9dd6b0c](https://github.com/postalsys/emailengine/commit/9dd6b0c17ab6db174ef6cc6777fdee506e57bc3d))
11
+ * **deps:** refresh dependencies ([6e11a55](https://github.com/postalsys/emailengine/commit/6e11a55cd66e2609efb524e3494ad2ee5bcf0a11))
12
+ * **gmail:** stop a killer history entry from looping forever and apply the text size limit on API accounts ([cb6ca8a](https://github.com/postalsys/emailengine/commit/cb6ca8aab406cefbba3fbb9c973c0de30036fc1f))
13
+ * **imap:** recover addresses when the ENVELOPE reports none ([1e83178](https://github.com/postalsys/emailengine/commit/1e83178de8ba3f00250eb5fc90d0d869d294c3ec))
14
+ * **mcp:** advertise only the tools a credential can actually call ([abeb137](https://github.com/postalsys/emailengine/commit/abeb13749fbd103f4d9ef1cf438c13f789780300))
15
+ * **mcp:** carry the required cache hints on modern-era results ([6dd70b9](https://github.com/postalsys/emailengine/commit/6dd70b99d6158d9e0dabc3c9ea3dc3750c4fbf8a))
16
+ * **mcp:** close the defects a deep review found in the MCP surface ([c3fc7ba](https://github.com/postalsys/emailengine/commit/c3fc7ba2dc8b8f8d4eea379ddbdcc788fbf1a9c6))
17
+ * **mcp:** make connecting an agent a one-step operation ([914dff5](https://github.com/postalsys/emailengine/commit/914dff58d423b8e84a29332e74cf023cfbbabfa8))
18
+ * **mcp:** make token restrictions work over MCP and tighten the OAuth edges ([b1f1dc0](https://github.com/postalsys/emailengine/commit/b1f1dc09902a2a68924fd5cec3dbeed070cd871f))
19
+ * **mcp:** narrow the agent tool schemas, and let webSafeHtml skip inlined images ([e381af0](https://github.com/postalsys/emailengine/commit/e381af01e4494532396879651025193ccd0ab969))
20
+ * **mcp:** offer three access levels when connecting an agent, and make its tokens findable ([15e7bda](https://github.com/postalsys/emailengine/commit/15e7bda7a012096785ca2c87f6b580e2eaab8dac))
21
+ * **mcp:** position MCP support as a labeled beta ([a19a612](https://github.com/postalsys/emailengine/commit/a19a6123c5a4f794325ac96d8bade18d473a68fe))
22
+ * **mcp:** return web-safe bodies and infer the bound account ([923bb25](https://github.com/postalsys/emailengine/commit/923bb25d02471fd9e98a8dc7a2008d794682990f))
23
+ * **mcp:** serve the Model Context Protocol at /mcp as an opt-in beta ([1907015](https://github.com/postalsys/emailengine/commit/190701506978df65d410c3652f09e48bb723dfa0))
24
+ * **mcp:** show the tool count wherever an mcp token is minted ([a85d8f6](https://github.com/postalsys/emailengine/commit/a85d8f67f043a01bebdc969401244d95fbbd116c))
25
+ * **mcp:** tell agents how to reply to and forward a message ([a3f17ad](https://github.com/postalsys/emailengine/commit/a3f17adb0ee5ce276347f5cb883bb984e6eeb0a2))
26
+ * **mcp:** update the consent integration test for the access-level radio ([f4b6b18](https://github.com/postalsys/emailengine/commit/f4b6b1877aa1073c3b3b5cbd9144f7c3fe13d6e1))
27
+ * **submit:** stop a reply borrowing recipients it should not have ([1032605](https://github.com/postalsys/emailengine/commit/10326056db2df7839463789215757c36bf45c34d))
28
+ * **ui:** count the MCP tools a bound token actually receives ([5bbdee3](https://github.com/postalsys/emailengine/commit/5bbdee3beb425887d1cc52846252034bf673da80))
29
+ * **ui:** explain the OAuth connector form on the MCP config page ([b7db99a](https://github.com/postalsys/emailengine/commit/b7db99a03a2b466c7b43b0e324441ad851ece6d1))
30
+ * **ui:** give MCP tokens their own access-level editor on the token form ([308a217](https://github.com/postalsys/emailengine/commit/308a2178e994e656ea88674b1dc0b6372723f51a))
31
+ * **ui:** make the MCP pages vendor-neutral and the consent wording plain ([f0f0e8e](https://github.com/postalsys/emailengine/commit/f0f0e8e5c5a49c2add8688eb746b42e1b51a9e4f))
32
+ * **ui:** nest the MCP OAuth switch under the endpoint switch ([bb619b4](https://github.com/postalsys/emailengine/commit/bb619b4e3329b576a7ccae1787687e3f78922191))
33
+ * **ui:** pick an account in the send-test dialog too ([6dcdbb5](https://github.com/postalsys/emailengine/commit/6dcdbb54918dbfcfc3ff78304d80f45fa64436a4))
34
+ * **ui:** pick an account instead of typing its id ([11be805](https://github.com/postalsys/emailengine/commit/11be8057cd8415ed083349ed40f74c390e1ece3a))
35
+ * **ui:** render the MCP client consent page as an authorization prompt ([4626123](https://github.com/postalsys/emailengine/commit/4626123fc72936ea79d6319010b9f181e6ed06b0))
36
+ * **ui:** separate the collapsible cards on the MCP config page ([691f0d4](https://github.com/postalsys/emailengine/commit/691f0d46eec36927fc128c2f72e785401413b4d7))
37
+ * **ui:** show each app's client id in the OAuth2 apps listing ([0cc36e0](https://github.com/postalsys/emailengine/commit/0cc36e0ee7e067ed54df6c04c3c16e048585d02e))
38
+ * **ui:** split the MCP connect tab into connection-method sub-tabs ([ec632bd](https://github.com/postalsys/emailengine/commit/ec632bd75bc9cbe02403dac98099f47e0b6aa50e))
39
+ * **ui:** split the MCP page into Settings and Connect an agent tabs ([301c7d0](https://github.com/postalsys/emailengine/commit/301c7d0ed5d0108c46732752018860290bc27093))
40
+ * **ui:** stack the agent generator fields in one column ([9a1ab8e](https://github.com/postalsys/emailengine/commit/9a1ab8ec7f890be7707966bc72e1aec4d7dcdf29))
41
+ * **windows:** set CompanyName and ship a multi-size icon in the exe ([33b7842](https://github.com/postalsys/emailengine/commit/33b784211b5d630ae4b716662edc2b5008c75752))
42
+
43
+ ## [2.79.1](https://github.com/postalsys/emailengine/compare/v2.79.0...v2.79.1) (2026-08-19)
44
+
45
+
46
+ ### Bug Fixes
47
+
48
+ * **admin:** flag webhook routes that can never deliver on the account page ([416f612](https://github.com/postalsys/emailengine/commit/416f612b616380371f825d673c0b80ad0f975924))
49
+ * **admin:** percent-encode an account or gateway ID interpolated into a link ([522d267](https://github.com/postalsys/emailengine/commit/522d2673eeb33c2f9cc85e7faf78550b99afe361))
50
+ * **admin:** percent-encode every ID a redirect interpolates ([d21c2ab](https://github.com/postalsys/emailengine/commit/d21c2ab5d5892fb94e85a2962a2a252fc865a03d))
51
+ * **admin:** probe a listing's accounts in one round trip ([a9a4c8a](https://github.com/postalsys/emailengine/commit/a9a4c8aeeb30b16b09f22e62847bb93671e8e46d))
52
+ * **admin:** stop reporting a suppression-list read failure as a missing list ([bd414a9](https://github.com/postalsys/emailengine/commit/bd414a94e7ff51f3c6cd68241ff3b94c8996ed2d))
53
+ * **downloads:** end a cross-thread transfer when the peer closes the channel ([8875e79](https://github.com/postalsys/emailengine/commit/8875e799b7d2d365822f3666160450e137130673))
54
+ * **downloads:** notice a consumer that closed the channel before the transfer began ([ce295e6](https://github.com/postalsys/emailengine/commit/ce295e6060c556a0223bbc7bce11078513cbd0ae))
55
+ * **downloads:** stop an aborted attachment download from killing the IMAP worker ([f937993](https://github.com/postalsys/emailengine/commit/f937993b47c518683da3137eebcc7188c8bd9f3e))
56
+ * **gmail:** keep prototype-shaped header names from breaking message formatting ([a494f13](https://github.com/postalsys/emailengine/commit/a494f1308f04fd24dc1ce9bceb27a46ca326fa71))
57
+ * **headers:** drop a __proto__ field name when parsing a header block ([fae64fd](https://github.com/postalsys/emailengine/commit/fae64fd5754f8236b51c26f6095df5c81f299a90))
58
+ * **headers:** drop a constructor field name too, and guard the bounced-message map ([b5fcf32](https://github.com/postalsys/emailengine/commit/b5fcf32003d99254e8288ad2c7d330d14d138637))
59
+ * **headers:** drop a prototype-shaped field name the camelCase step re-creates ([77a3beb](https://github.com/postalsys/emailengine/commit/77a3bebaff9ca61de2ebff875cd50cd9648533c6))
60
+ * **imap:** keep a prototype-shaped content subtype from breaking a text fetch ([d90e013](https://github.com/postalsys/emailengine/commit/d90e0131f236a085bf10537f567b267de0a25481))
61
+ * **imap:** release the mailbox lock when a download resolves without a stream ([8513432](https://github.com/postalsys/emailengine/commit/8513432f9968061eb01fef8e90654904ebdce3cf))
62
+ * **imap:** return the connection to its mailbox after a download or text fetch ([33db6a2](https://github.com/postalsys/emailengine/commit/33db6a20ed64112d9f5c446f89abb82fb9f33101))
63
+ * **imap:** return the connection to its mailbox after deleting one ([0cac841](https://github.com/postalsys/emailengine/commit/0cac8418a296b0bea41c646bcaa539b2862eed69))
64
+ * **imap:** return the connection to its mailbox after renaming one ([6014093](https://github.com/postalsys/emailengine/commit/601409377c19f7f16eb9d8d60d88b5b906ecf1b1))
65
+ * **imap:** stop a secondary connection's task from re-selecting the primary mailbox ([d12a046](https://github.com/postalsys/emailengine/commit/d12a046eaa5d9ef584bc8c88778fcfedc3e3d533))
66
+ * **metrics:** derive the Prometheus queue gauges from BullMQ itself ([7968678](https://github.com/postalsys/emailengine/commit/796867886a2d8ba9ad0e8fee8e9d53dea1af5b3d))
67
+ * **oauth2:** harden the legacy app migration and restore the auth-failure alert ([50710be](https://github.com/postalsys/emailengine/commit/50710bebe5b4c108313add39beabe74e6c0dd0f8))
68
+ * **reference:** leave the deprecated token aliases out of the published document ([1ff4697](https://github.com/postalsys/emailengine/commit/1ff46975d47f130289d2cb2702d11cedbf16a6b6))
69
+ * **reports:** drop every prototype-shaped name a camelCased report can carry ([77abf0e](https://github.com/postalsys/emailengine/commit/77abf0ee7b3266de92885e66ae48824598dc822f))
70
+ * **settings:** refuse masked credential values posted back to the settings API ([7e51155](https://github.com/postalsys/emailengine/commit/7e51155641b72f2622d0d6f7c31d94e2b01ef9fa))
71
+ * **settings:** seed the trial Sentry default atomically ([1e276f8](https://github.com/postalsys/emailengine/commit/1e276f8ef0dac49a6c4fe3470fff572f57cfab94))
72
+ * **startup:** name the prepared-settings keys that get ignored ([9e23ceb](https://github.com/postalsys/emailengine/commit/9e23ceb9d20dff5f7c64690f71f307bf427bac59))
73
+ * **tokens:** bind an access token to an account from the create form ([6f4fc93](https://github.com/postalsys/emailengine/commit/6f4fc936ef254710b7bc99582776c6d1700d7195))
74
+ * **tokens:** keep the audit log page size default inside its own range ([c688756](https://github.com/postalsys/emailengine/commit/c6887564e0ef20e9e5c2b4ec4a5560d3eec3fc8d))
75
+ * **tokens:** raise the audit log retention cap and bound the account it stores ([6c8039a](https://github.com/postalsys/emailengine/commit/6c8039a1fb2bc5325a8b815a79b51d4f318a059f))
76
+ * **tokens:** register the pre-2.79 token endpoints as deprecated aliases ([5cb2887](https://github.com/postalsys/emailengine/commit/5cb2887c6c6c94e7b3dd9686f5223ae6b7dafb29))
77
+ * **tokens:** revoke an account's access tokens when the account is deleted ([61c9a17](https://github.com/postalsys/emailengine/commit/61c9a178c8a55b4f869fc8d204755519f48a3e48))
78
+ * **tokens:** show account-bound tokens on the Access Tokens page ([716ca0d](https://github.com/postalsys/emailengine/commit/716ca0dc5a56a9d853c5064f4c059fbefd8b0551))
79
+ * **tokens:** stop a whitespace-only search from reading every record ([eb1f398](https://github.com/postalsys/emailengine/commit/eb1f398f5a99c613e4fe30d5e91a93cd80399603))
80
+ * **webhooks:** log the reason a delivery is skipped ([c34df7d](https://github.com/postalsys/emailengine/commit/c34df7d0fbe1724e2bea8baa1d66ce3e7a3e3f40))
81
+
3
82
  ## [2.79.0](https://github.com/postalsys/emailengine/compare/v2.78.0...v2.79.0) (2026-08-18)
4
83
 
5
84
 
@@ -112,6 +112,13 @@ const GLOBAL_OPTIONS = [
112
112
  type: 'boolean',
113
113
  default: false,
114
114
  group: 'Document Store (deprecated)'
115
+ },
116
+ {
117
+ name: '--mcp.enabled',
118
+ description: 'Register the MCP endpoint at /mcp (the mcpEnabled runtime setting still has to be turned on)',
119
+ type: 'boolean',
120
+ default: true,
121
+ group: 'MCP'
115
122
  }
116
123
  ];
117
124
 
@@ -497,7 +504,7 @@ function run() {
497
504
  switch (tokensCmd) {
498
505
  case 'issue':
499
506
  {
500
- let allowedScopes = ['*', 'api', 'metrics', 'smtp', 'imap-proxy'];
507
+ let allowedScopes = ['*', 'api', 'metrics', 'smtp', 'imap-proxy', 'mcp'];
501
508
  let scopes = []
502
509
  .concat(argv.scope || [])
503
510
  .concat(argv.s || [])
@@ -36,6 +36,12 @@ proxy = false # Set to true if using HAProxy with send-proxy option
36
36
  # all document-store API/UI endpoints are only available when this is enabled.
37
37
  enabled = false
38
38
 
39
+ [mcp]
40
+ # MCP (Model Context Protocol) endpoint at /mcp. This deployment-level gate controls whether
41
+ # the endpoint exists in the route table at all; the runtime on/off switch is the mcpEnabled
42
+ # setting (Configuration > MCP in the admin UI), which starts out disabled.
43
+ enabled = true
44
+
39
45
  [dbs]
40
46
  # redis connection
41
47
  redis = "redis://127.0.0.1:6379/8"
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-08-14T14:46:51.000000",
2
+ "creationTime": "2026-08-21T14:46:19.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
package/lib/account.js CHANGED
@@ -14,7 +14,8 @@ const {
14
14
  isEmail,
15
15
  resolveDelegatedAccount,
16
16
  escapeRedisGlob,
17
- getMailboxStatusKey
17
+ getMailboxStatusKey,
18
+ cidReferenceRegex
18
19
  } = require('./tools');
19
20
  const { MessageChannel } = require('worker_threads');
20
21
  const { MessagePortReadable } = require('./message-port-stream');
@@ -25,13 +26,15 @@ const settings = require('./settings');
25
26
  const { buildRetentionPolicy } = require('./queue-retention');
26
27
  const { isDocumentStoreEnabled, documentStoreFeatureEnabled } = require('./document-store');
27
28
  const redisScanDelete = require('./redis-scan-delete');
29
+ const { extractMultiValues } = require('./redis-operations');
28
30
  const outbox = require('./outbox');
31
+ const tokens = require('./tokens');
29
32
  const { customAlphabet } = require('nanoid');
30
33
  const Lock = require('ioredfour');
31
34
  const { redis } = require('./db');
32
35
  const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
33
36
  const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY } = require('./consts');
34
- const { messageWebSafeHtml } = require('./web-safe-html');
37
+ const { messageWebSafeHtml, webSafeTextResponse, applyWebSafeHtmlOptions } = require('./web-safe-html');
35
38
  const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
36
39
  const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
37
40
  const { decodeStoredMailboxEntry } = require('./email-client/imap/listing-diff');
@@ -161,6 +164,22 @@ class Account {
161
164
  return !!accountData.smtp;
162
165
  }
163
166
 
167
+ /**
168
+ * Lists accounts, filtered by state and by a substring search.
169
+ *
170
+ * The provider enrichment below is not optional, however little of it a caller reads: it
171
+ * resolves each account's OAuth2 app, and `isApi` falls out of that. getDisplayState() reads
172
+ * `isApi` to decide whether a stored state can be trusted when the run index is behind, so an
173
+ * API account listed without it reports `init` rather than what it is actually doing. A "lean"
174
+ * listing that skipped the loop was tried and reverted for exactly that: it made the cheap
175
+ * fields cheaper and the one field every caller renders wrong.
176
+ *
177
+ * @param {String|Array} state - state filter, 'errors' for every attention state, falsy for all
178
+ * @param {String} query - substring matched against account id, name and address
179
+ * @param {Number} page - zero-based page
180
+ * @param {Number} limit - page size
181
+ * @returns {Promise<Object>} `{ total, pages, page, query, state, accounts }`
182
+ */
164
183
  async listAccounts(state, query, page, limit) {
165
184
  limit = Number(limit) || 20;
166
185
  page = Math.max(Number(page) || 0, 0);
@@ -177,7 +196,19 @@ class Account {
177
196
  }
178
197
  let filterState = Array.isArray(state) ? state.join(',') : state || '*';
179
198
 
180
- let result = await this.redis.sListAccounts(`${REDIS_PREFIX}ia:accounts`, filterState, skip, limit, `${REDIS_PREFIX}`, query);
199
+ // The search is a plain substring match against the lowercased fields, and two things about
200
+ // that were left to the caller to get right:
201
+ //
202
+ // - the needle was passed through as typed, so anything with a capital in it matched
203
+ // nothing at all - on a search box, the account you can see is the one you cannot find.
204
+ // The script folds the needle too, so any caller gets a case-insensitive search; this
205
+ // fold is the one that also covers non-ASCII, which string.lower() leaves alone.
206
+ // - "no search" was spelled `false` by some callers, and ioredis sends that as the string
207
+ // "false", which the script then dutifully searched for. Anything that is not a string
208
+ // is one of those, and means no search.
209
+ let search = typeof query === 'string' ? query.toLowerCase() : '';
210
+
211
+ let result = await this.redis.sListAccounts(`${REDIS_PREFIX}ia:accounts`, filterState, skip, limit, `${REDIS_PREFIX}`, search);
181
212
 
182
213
  let accounts = result[2].map(formatAccountListingResponse).map(this.unserializeAccountData.bind(this));
183
214
  let oauthApps = new Map();
@@ -1249,7 +1280,6 @@ class Account {
1249
1280
  .unlink(`${REDIS_PREFIX}iar:b:${this.account}`) // bounce list
1250
1281
  .unlink(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
1251
1282
  .unlink(`${REDIS_PREFIX}iaq:${this.account}`) // delayed message queue
1252
- .unlink(`${REDIS_PREFIX}iat:${this.account}`) // access tokens
1253
1283
  .unlink(`${REDIS_PREFIX}iac:${this.account}`) // cache hash
1254
1284
  .unlink(`${REDIS_PREFIX}iap:${this.account}`) // external event notification queue
1255
1285
 
@@ -1268,6 +1298,18 @@ class Account {
1268
1298
 
1269
1299
  let result = await pipeline.exec();
1270
1300
 
1301
+ // The account's access tokens go with it - see tokens.deleteForAccount(), which owns the
1302
+ // account's token index too. Deliberately on this side of the transaction: while the account
1303
+ // record exists a token can still be minted against it, and both mint paths check that
1304
+ // record first, so revoking once it is unlinked closes all but a vanishing window. Best
1305
+ // effort, like the queued messages below - the account still has to go, and anything left
1306
+ // behind stays on the access token listing, marked as bound to a deleted account.
1307
+ try {
1308
+ await tokens.deleteForAccount(this.account);
1309
+ } catch (err) {
1310
+ this.logger.error({ msg: 'Failed to delete the access tokens of an account', account: this.account, err });
1311
+ }
1312
+
1271
1313
  // Results are positional: [0] is the outbox HKEYS, [1] the account key UNLINK. Both indexes
1272
1314
  // move if a command is inserted ahead of them.
1273
1315
  let queuedMessageIds = (result && result[0] && result[0][1]) || [];
@@ -1717,6 +1759,13 @@ class Account {
1717
1759
  }
1718
1760
 
1719
1761
  async getText(text, options) {
1762
+ if (options.webSafeHtml) {
1763
+ // Both bodies are needed to build the web-safe rendering: the generator falls back to
1764
+ // the plaintext part when the message carries no HTML one, and the thread-collapse
1765
+ // analysis reads whichever of the two the extractor picks.
1766
+ options = Object.assign({}, options, { textType: '*' });
1767
+ }
1768
+
1720
1769
  if (options.documentStore && (await isDocumentStoreEnabled())) {
1721
1770
  await this.loadAccountData(this.account, false);
1722
1771
 
@@ -1751,7 +1800,7 @@ class Account {
1751
1800
  }
1752
1801
  }
1753
1802
 
1754
- return response;
1803
+ return this.textResponse(response, options);
1755
1804
  }
1756
1805
 
1757
1806
  await this.loadAccountData(this.account, true);
@@ -1765,15 +1814,17 @@ class Account {
1765
1814
  });
1766
1815
 
1767
1816
  // IMAP backend returns false for unknown messages and folders
1768
- return this.assertMessageFound(textData);
1817
+ return this.textResponse(this.assertMessageFound(textData), options);
1818
+ }
1819
+
1820
+ // The one exit of getText(), so the document-store branch and the live one cannot answer a
1821
+ // webSafeHtml request differently
1822
+ async textResponse(textData, options) {
1823
+ return options.webSafeHtml ? webSafeTextResponse(textData) : textData;
1769
1824
  }
1770
1825
 
1771
1826
  async getMessage(message, options) {
1772
- if (options.webSafeHtml) {
1773
- options.textType = '*';
1774
- options.embedAttachedImages = true;
1775
- options.preProcessHtml = true;
1776
- }
1827
+ applyWebSafeHtmlOptions(options);
1777
1828
 
1778
1829
  if (options.documentStore && (await isDocumentStoreEnabled())) {
1779
1830
  await this.loadAccountData(this.account, false);
@@ -1841,15 +1892,28 @@ class Account {
1841
1892
  }
1842
1893
 
1843
1894
  if (options.embedAttachedImages && messageData.text && messageData.text.html && messageData.attachments && messageData.attachments.length) {
1844
- let attachmentsToDownload = [];
1895
+ // map both content id forms (bare and <bracketed>) to the first attachment carrying them,
1896
+ // so the passes below cost one lookup per reference instead of a scan of all attachments
1897
+ let attachmentsByContentId = new Map();
1898
+ for (let attachment of messageData.attachments) {
1899
+ if (!attachment.contentId) {
1900
+ continue;
1901
+ }
1902
+ for (let key of [attachment.contentId, attachment.contentId.replace(/^<(.*)>$/, '$1')]) {
1903
+ if (!attachmentsByContentId.has(key)) {
1904
+ attachmentsByContentId.set(key, attachment);
1905
+ }
1906
+ }
1907
+ }
1845
1908
 
1846
1909
  // first pass, find attachments to inline
1847
- messageData.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1848
- let attachment = messageData.attachments.find(attachment => [`<${cidMatch}>`, cidMatch].includes(attachment.contentId));
1910
+ let attachmentsToDownload = new Set();
1911
+ for (let match of messageData.text.html.matchAll(cidReferenceRegex())) {
1912
+ let attachment = attachmentsByContentId.get(match[1]);
1849
1913
  if (attachment && !attachment.content) {
1850
- attachmentsToDownload.push(attachment);
1914
+ attachmentsToDownload.add(attachment);
1851
1915
  }
1852
- });
1916
+ }
1853
1917
 
1854
1918
  // download large inline attachments not stored in ES
1855
1919
  for (let attachment of attachmentsToDownload) {
@@ -1872,8 +1936,8 @@ class Account {
1872
1936
  }
1873
1937
 
1874
1938
  // second pass, replace placeholders with inline attachments
1875
- messageData.text.html = messageData.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1876
- let attachment = messageData.attachments.find(attachment => [`<${cidMatch}>`, cidMatch].includes(attachment.contentId));
1939
+ messageData.text.html = messageData.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1940
+ let attachment = attachmentsByContentId.get(cidMatch);
1877
1941
  if (attachment && attachment.content) {
1878
1942
  return `data:${attachment.contentType || 'application/octet-stream'};base64,${attachment.content}`;
1879
1943
  }
@@ -3001,4 +3065,58 @@ async function accountExists(redis, account) {
3001
3065
  return (await redis.hexists(`${REDIS_PREFIX}iad:${account}`, 'account')) === 1;
3002
3066
  }
3003
3067
 
3004
- module.exports = { Account, accountExists };
3068
+ /**
3069
+ * Same question as accountExists(), asked about a list of accounts in one round trip.
3070
+ *
3071
+ * lib/db.js enables no auto-pipelining, so probing a listing page's accounts one at a time is a
3072
+ * socket write each - up to 250 on the admin listings that call this.
3073
+ *
3074
+ * @param {Object} redis - Redis client
3075
+ * @param {Array} accounts - Account IDs to probe
3076
+ * @returns {Promise<Map<String, Boolean>>} keyed by account ID, in the order given
3077
+ */
3078
+ async function accountsExist(redis, accounts) {
3079
+ if (!accounts || !accounts.length) {
3080
+ return new Map();
3081
+ }
3082
+
3083
+ let pipeline = redis.pipeline();
3084
+ for (let account of accounts) {
3085
+ pipeline = pipeline.hexists(`${REDIS_PREFIX}iad:${account}`, 'account');
3086
+ }
3087
+
3088
+ // A pipeline reports a per-command failure in its results rather than rejecting, and
3089
+ // extractMultiValues() reads such an entry as undefined - an account that could not be probed is
3090
+ // not an account that is known to exist
3091
+ let values = extractMultiValues(await pipeline.exec());
3092
+
3093
+ return new Map(accounts.map((account, i) => [account, values[i] === 1]));
3094
+ }
3095
+
3096
+ /**
3097
+ * The display fields of one account, without loading or decrypting anything.
3098
+ *
3099
+ * What a form that already holds an account id needs in order to show it back as something a
3100
+ * person recognises: a name, an address and a connection state. loadAccountData() answers the same
3101
+ * question by reading and decrypting the whole record, which is a lot of work for three strings on
3102
+ * a page that is not about that account.
3103
+ *
3104
+ * @param {Object} redis - Redis client
3105
+ * @param {String} account - Account ID
3106
+ * @returns {Promise<Object|null>} `{ account, name, email, state }`, or null when no such account exists
3107
+ */
3108
+ async function accountSummary(redis, account) {
3109
+ if (!account) {
3110
+ return null;
3111
+ }
3112
+
3113
+ // `account` is the existence marker (see accountExists); the rest are optional on a record
3114
+ let [exists, name, email, state] = await redis.hmget(`${REDIS_PREFIX}iad:${account}`, 'account', 'name', 'email', 'state');
3115
+ if (!exists) {
3116
+ return null;
3117
+ }
3118
+
3119
+ return { account, name: name || '', email: email || '', state: state || 'init' };
3120
+ }
3121
+
3122
+ module.exports = { Account, accountExists, accountsExist, accountSummary };
@@ -32,7 +32,7 @@ const {
32
32
  ENUM_DESCRIPTIONS
33
33
  } = require('../schemas');
34
34
 
35
- const { REDIS_PREFIX, MAX_FORM_TTL, NONCE_BYTES } = require('../consts');
35
+ const { REDIS_PREFIX, MAX_FORM_TTL, NONCE_BYTES, MCP_MAX_PAGE_SIZE } = require('../consts');
36
36
  const BEHAVIOR = require('./behavior-notes');
37
37
  const { IMPACT } = require('./operation-impact');
38
38
  const { FIELD_USAGE } = require('../field-usage');
@@ -798,6 +798,13 @@ async function init(args) {
798
798
  tags: ['api', 'Account'],
799
799
 
800
800
  plugins: {
801
+ mcp: {
802
+ name: 'list_accounts',
803
+ title: 'List accounts',
804
+ description:
805
+ 'List the email accounts on this instance, paged. Use the returned account id as the account argument of the other tools. Check the state field: only connected accounts can be read.',
806
+ bounds: { pageSize: MCP_MAX_PAGE_SIZE }
807
+ },
801
808
  openapi: {
802
809
  responses: apiResponses('Returns a page of accounts with their connection states.', 400, 401, 403, 429, 500)
803
810
  }
@@ -1045,6 +1052,11 @@ async function init(args) {
1045
1052
  tags: ['api', 'Account'],
1046
1053
 
1047
1054
  plugins: {
1055
+ mcp: {
1056
+ name: 'get_account',
1057
+ title: 'Get account',
1058
+ description: 'Get one account: its display name, email address, connection state and sync status. Credentials are masked.'
1059
+ },
1048
1060
  openapi: {
1049
1061
  'x-ee-behavior': [BEHAVIOR.NO_QUOTA_ON_API_ACCOUNTS],
1050
1062
  responses: apiResponses('Returns the account configuration, connection state and sync status.', 400, 401, 403, 404, 429, 500)
@@ -31,6 +31,8 @@ const deliveryTestRoutes = require('./delivery-test-routes');
31
31
  const blocklistRoutes = require('./blocklist-routes');
32
32
  const submitRoutes = require('./submit-routes');
33
33
  const changesRoutes = require('./changes-routes');
34
+ const mcpRoutes = require('./mcp-routes');
35
+ const mcpOauthRoutes = require('./mcp-oauth-routes');
34
36
 
35
37
  /**
36
38
  * Registers every /v1 route module on the supplied Hapi server.
@@ -48,6 +50,7 @@ const changesRoutes = require('./changes-routes');
48
50
  * @param {Number} args.MAX_BODY_SIZE
49
51
  * @param {Number} args.MAX_PAYLOAD_TIMEOUT
50
52
  * @param {Boolean} args.documentStoreFeatureEnabled - gate for the deprecated Document Store
53
+ * @param {Boolean} args.mcpFeatureEnabled - gate for the MCP endpoint
51
54
  * @param {Object} args.oauth2Schema
52
55
  * @param {Object} args.imapSchema
53
56
  * @param {Object} args.smtpSchema
@@ -68,6 +71,7 @@ async function registerApiRoutes(args) {
68
71
  MAX_BODY_SIZE,
69
72
  MAX_PAYLOAD_TIMEOUT,
70
73
  documentStoreFeatureEnabled,
74
+ mcpFeatureEnabled,
71
75
  oauth2Schema,
72
76
  imapSchema,
73
77
  smtpSchema,
@@ -155,6 +159,14 @@ async function registerApiRoutes(args) {
155
159
 
156
160
  // setup the account state change stream (SSE)
157
161
  await changesRoutes({ server, CORS_CONFIG });
162
+
163
+ // setup the MCP endpoint and its OAuth discovery/registration/token routes (only when the
164
+ // deployment gate is on; the OAuth routes additionally answer 404 until the mcpOAuthEnabled
165
+ // setting is turned on)
166
+ if (mcpFeatureEnabled) {
167
+ await mcpRoutes({ server, CORS_CONFIG, MAX_BODY_SIZE, MAX_PAYLOAD_TIMEOUT });
168
+ await mcpOauthRoutes({ server });
169
+ }
158
170
  }
159
171
 
160
172
  module.exports = registerApiRoutes;
@@ -79,6 +79,12 @@ async function init(args) {
79
79
  tags: ['api', 'Mailbox'],
80
80
 
81
81
  plugins: {
82
+ mcp: {
83
+ name: 'list_mailboxes',
84
+ title: 'List mailboxes',
85
+ description:
86
+ 'List the folders of an account with message counts and special-use roles (Inbox, Sent, Trash and so on). Folder paths from here are what list_messages, search_messages and move_message take.'
87
+ },
82
88
  openapi: {
83
89
  responses: apiResponses(
84
90
  'Returns the account folder tree, including special-use designations and message counts.',