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
@@ -8,8 +8,8 @@ const { oauth2Apps } = require('../oauth2-apps');
8
8
  const getSecret = require('../get-secret');
9
9
  const msgpack = require('../msgpack');
10
10
  const he = require('he');
11
- const { emitChangeEvent, prepareUrl } = require('../tools');
12
- const { messageWebSafeHtml } = require('../web-safe-html');
11
+ const { emitChangeEvent, prepareUrl, collectCidReferences, cidReferenceRegex, truncateTextContents } = require('../tools');
12
+ const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
13
13
  const crypto = require('crypto');
14
14
  const { Gateway } = require('../gateway');
15
15
  const { detectMimeType, detectExtension } = require('nodemailer/lib/mime-funcs/mime-types');
@@ -17,6 +17,7 @@ const { detectMimeType, detectExtension } = require('nodemailer/lib/mime-funcs/m
17
17
  // Import Graph API module for MS Graph API handling
18
18
  const graphApi = require('./outlook/graph-api');
19
19
  const { buildRawSendMailRequest, buildStructuredSendMailRequest, buildDraftSendRequest } = require('./outlook/send-request');
20
+ const { pushHeaderValue } = require('../utils/header-map');
20
21
 
21
22
  const {
22
23
  REDIS_PREFIX,
@@ -1602,11 +1603,7 @@ class OutlookClient extends BaseClient {
1602
1603
  async getMessage(emailId, options) {
1603
1604
  options = options || {};
1604
1605
 
1605
- if (options.webSafeHtml) {
1606
- options.textType = '*';
1607
- options.embedAttachedImages = true;
1608
- options.preProcessHtml = true;
1609
- }
1606
+ applyWebSafeHtmlOptions(options);
1610
1607
 
1611
1608
  await this.prepare();
1612
1609
 
@@ -1716,13 +1713,9 @@ class OutlookClient extends BaseClient {
1716
1713
  name = (name || '').toString().trim().toLowerCase();
1717
1714
 
1718
1715
  value = (value || '').toString().trim();
1719
- if (!(name in headers)) {
1720
- headers[name] = [];
1721
- }
1722
- if (!Array.isArray(headers[name])) {
1716
+ if (!pushHeaderValue(headers, name, value)) {
1723
1717
  continue;
1724
1718
  }
1725
- headers[name].push(value);
1726
1719
 
1727
1720
  // Extract specific headers for easier access
1728
1721
  switch (name) {
@@ -1740,6 +1733,7 @@ class OutlookClient extends BaseClient {
1740
1733
  extended: true,
1741
1734
  path,
1742
1735
  textType: options.textType,
1736
+ maxBytes: options.maxBytes,
1743
1737
  showPath: options.showPath
1744
1738
  });
1745
1739
 
@@ -1765,11 +1759,12 @@ class OutlookClient extends BaseClient {
1765
1759
  // Embed attached images as data URLs
1766
1760
  if (options.embedAttachedImages && formattedMessage.text?.html && formattedMessage.attachments) {
1767
1761
  let attachmentMap = new Map();
1762
+ let cidReferences = collectCidReferences(formattedMessage.text.html);
1768
1763
 
1769
1764
  // Collect all referenced inline attachments
1770
1765
  for (let attachment of formattedMessage.attachments) {
1771
1766
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
1772
- if (contentId && !attachmentMap.has(contentId) && formattedMessage.text.html.indexOf(`cid:${contentId}`) >= 0) {
1767
+ if (contentId && !attachmentMap.has(contentId) && cidReferences.has(contentId)) {
1773
1768
  attachmentMap.set(contentId, {
1774
1769
  attachment,
1775
1770
  content: await this.getAttachmentContent(attachment.id, {
@@ -1780,7 +1775,7 @@ class OutlookClient extends BaseClient {
1780
1775
  }
1781
1776
 
1782
1777
  // Replace cid: references with data URLs
1783
- formattedMessage.text.html = formattedMessage.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1778
+ formattedMessage.text.html = formattedMessage.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1784
1779
  if (attachmentMap.has(cidMatch)) {
1785
1780
  let { content } = attachmentMap.get(cidMatch);
1786
1781
  if (content.content) {
@@ -1954,13 +1949,9 @@ class OutlookClient extends BaseClient {
1954
1949
  let { name, value } = header;
1955
1950
  name = (name || '').toString().trim().toLowerCase();
1956
1951
  value = (value || '').toString().trim();
1957
- if (!(name in headers)) {
1958
- headers[name] = [];
1959
- }
1960
- if (!Array.isArray(headers[name])) {
1952
+ if (!pushHeaderValue(headers, name, value)) {
1961
1953
  continue;
1962
1954
  }
1963
- headers[name].push(value);
1964
1955
  if (name === 'in-reply-to') {
1965
1956
  messageData.inReplyTo = value;
1966
1957
  }
@@ -1972,6 +1963,7 @@ class OutlookClient extends BaseClient {
1972
1963
  extended: true,
1973
1964
  path,
1974
1965
  textType: options.textType,
1966
+ maxBytes: options.maxBytes,
1975
1967
  showPath: options.showPath
1976
1968
  });
1977
1969
 
@@ -2111,7 +2103,7 @@ class OutlookClient extends BaseClient {
2111
2103
  }
2112
2104
  }
2113
2105
 
2114
- response.hasMore = false;
2106
+ response.hasMore = truncateTextContents(response, options.maxBytes);
2115
2107
 
2116
2108
  return response;
2117
2109
  }
@@ -2215,6 +2207,7 @@ class OutlookClient extends BaseClient {
2215
2207
  case 'attachments': {
2216
2208
  messageUploadObj.attachments = [];
2217
2209
  let attachmentCounter = 0;
2210
+ let cidReferences = collectCidReferences(emailObject.html);
2218
2211
  for (let attachment of emailObject.attachments || []) {
2219
2212
  let attachmentEntry = {
2220
2213
  '@odata.type': '#microsoft.graph.fileAttachment'
@@ -2232,7 +2225,7 @@ class OutlookClient extends BaseClient {
2232
2225
  if (attachment.cid) {
2233
2226
  // make sure that cid links to not use <content-id> format, otherwise this will be replaced
2234
2227
  attachmentEntry.contentId = attachment.cid.replace(/^[\s<]*|[\s>]*$/g, '');
2235
- if (emailObject.html?.indexOf(attachmentEntry.contentId) >= 0) {
2228
+ if (cidReferences.has(attachmentEntry.contentId)) {
2236
2229
  attachmentEntry.isInline = true;
2237
2230
  emailObject.html.replace(new RegExp(`cid:<${attachment.cid}>`, 'g'), `cid:${attachment.cid}`);
2238
2231
  }
@@ -3721,7 +3714,7 @@ class OutlookClient extends BaseClient {
3721
3714
  * Handles all message properties and attachments
3722
3715
  */
3723
3716
  formatMessage(messageData, options) {
3724
- let { extended, path, textType, showPath, minimalFields } = options || {};
3717
+ let { extended, path, textType, maxBytes, showPath, minimalFields } = options || {};
3725
3718
 
3726
3719
  let date = messageData.receivedDateTime ? new Date(messageData.receivedDateTime) : undefined;
3727
3720
  if (date?.toString() === 'Invalid Date') {
@@ -3791,6 +3784,8 @@ class OutlookClient extends BaseClient {
3791
3784
  }
3792
3785
  }
3793
3786
 
3787
+ const textHasMore = truncateTextContents(textContents, maxBytes);
3788
+
3794
3789
  let message = {
3795
3790
  id: messageData.id,
3796
3791
 
@@ -3829,7 +3824,7 @@ class OutlookClient extends BaseClient {
3829
3824
  encodedSize: encodedTextSize,
3830
3825
  plain: textContents?.plain?.toString(),
3831
3826
  html: textContents?.html?.toString(),
3832
- hasMore: textContents?.plain || textContents?.html ? false : undefined
3827
+ hasMore: textContents?.plain || textContents?.html ? textHasMore : undefined
3833
3828
  },
3834
3829
 
3835
3830
  preview: messageData.bodyPreview
@@ -3842,6 +3837,7 @@ class OutlookClient extends BaseClient {
3842
3837
 
3843
3838
  // Process attachments
3844
3839
  if (messageData.attachments?.length) {
3840
+ let cidReferences = collectCidReferences(message.text.html);
3845
3841
  message.attachments = messageData.attachments.map(entry => {
3846
3842
  const attachment = {
3847
3843
  // Encode both message ID and attachment ID for later retrieval
@@ -3859,7 +3855,7 @@ class OutlookClient extends BaseClient {
3859
3855
  // Normalize content ID format
3860
3856
  attachment.contentId = entry.contentId.replace(/^<*/, '<').replace(/>*$/, '>');
3861
3857
  // Check if attachment is embedded in HTML
3862
- if (textContents?.html?.indexOf(`cid:${attachment.contentId.replace(/^[\s<]*|[\s>]*$/g, '')}`) >= 0) {
3858
+ if (cidReferences.has(attachment.contentId.replace(/^[\s<]*|[\s>]*$/g, ''))) {
3863
3859
  attachment.embedded = true;
3864
3860
  }
3865
3861
  }
@@ -92,7 +92,8 @@ const ENUM_DESCRIPTIONS = {
92
92
  tokenScope: {
93
93
  api: 'Call the REST API',
94
94
  smtp: 'Authenticate against the built-in SMTP submission server',
95
- 'imap-proxy': 'Authenticate against the built-in IMAP proxy'
95
+ 'imap-proxy': 'Authenticate against the built-in IMAP proxy',
96
+ mcp: 'Connect AI agents through the MCP endpoint. Admits only the operations the MCP tool set wraps, and is not valid for plain REST calls'
96
97
  },
97
98
 
98
99
  // The verb axis of a narrowed token. Each operation requires exactly one of these, published
@@ -37,6 +37,12 @@ const AUTH_USAGE =
37
37
  'Send this for ordinary password authentication. Omit it when `useAuthServer` is on, because EmailEngine then fetches credentials from your authentication server for every connection and a stored password would be dead configuration.\n\n' +
38
38
  'On an update this replaces the whole credentials object unless `partial` is also set.';
39
39
 
40
+ // The collapse marker is part of the output contract, and both web-safe options promise it. Said
41
+ // once here so the two published descriptions cannot end up describing it differently.
42
+ const COLLAPSE_MARKER_USAGE =
43
+ `Quoted thread history is folded into one collapsed \`<details class="${COLLAPSE_CLASS}">\` element so you can hide it behind a single control. ` +
44
+ 'Its `<summary>` is deliberately empty, so supply your own label.';
45
+
40
46
  const FIELD_USAGE = {
41
47
  accountId:
42
48
  'Set this when your own system already has an identifier for the mailbox, for example a user id, so you can address the account later without storing a second id. Leave it `null` and EmailEngine generates one, which comes back in the response.\n\n' +
@@ -116,7 +122,17 @@ const FIELD_USAGE = {
116
122
 
117
123
  webSafeHtml:
118
124
  'Turn this on when you are rendering the message in your own UI and want EmailEngine to do the sanitising. It is a shorthand that overrides `textType`, `preProcessHtml` and `embedAttachedImages`.\n\n' +
119
- `Quoted thread history is folded into one collapsed \`<details class="${COLLAPSE_CLASS}">\` element so you can hide it behind a single control. Its \`<summary>\` is deliberately empty, so supply your own label.`,
125
+ 'Send `embedAttachedImages=false` alongside it when the body is going to be read rather than displayed - see that parameter.\n\n' +
126
+ COLLAPSE_MARKER_USAGE,
127
+
128
+ embedAttachedImages:
129
+ 'Inlining every referenced attachment as a data URI is what makes a rendering self-contained, and it is also what makes it several times larger. Leave it off for a body that is going to be read rather than displayed.\n\n' +
130
+ 'This is the one part of the `webSafeHtml` shorthand you can keep: an explicit `false` alongside it leaves the `cid:` references as they are and the attachments to be fetched separately, without giving up the sanitising or the single HTML rendering.',
131
+
132
+ webSafeText:
133
+ 'Turn this on when you are rendering the body in your own UI and want EmailEngine to do the sanitising. Both MIME parts are fetched and folded into one sanitised HTML rendering, which is generated from the plaintext part when the message carries no HTML one.\n\n' +
134
+ 'The response then carries `html` and no `plain`: the two would be the same message twice. ' +
135
+ COLLAPSE_MARKER_USAGE,
120
136
 
121
137
  useOutlookSearch:
122
138
  'Turn this on for MS Graph accounts when you need to search fields that the default `$filter` mode cannot reach: `to`, `cc`, `bcc`, `larger`, `smaller`, `body`, `before`, `sentBefore`, `since` and `sentSince`.\n\n' +
@@ -0,0 +1,36 @@
1
+ --[[
2
+ Script: h-set-new-mark.lua
3
+ Purpose: Sets a hash field value only if the field doesn't already exist, and stamps a second
4
+ marker field in the same atomic step when it does. Used for seeded defaults that a
5
+ marker field declares "still owned by the seeder": writing the two separately leaves a
6
+ crash window where the seeded value exists without its marker and can never be told
7
+ apart from an explicit choice.
8
+
9
+ KEYS:
10
+ [1] hashKey - The hash key to operate on
11
+
12
+ ARGV:
13
+ [1] entryKey - The hash field name
14
+ [2] value - The value to set
15
+ [3] markerKey - The marker field name, written only when the value field was created
16
+ [4] markerValue - The marker value
17
+
18
+ Returns:
19
+ 1 if the value field didn't exist and both fields were written
20
+ 0 if the value field already exists (no operation, the marker is not touched)
21
+ --]]
22
+
23
+ local hashKey = KEYS[1];
24
+ local entryKey = ARGV[1];
25
+
26
+ local value = ARGV[2];
27
+ local markerKey = ARGV[3];
28
+ local markerValue = ARGV[4];
29
+
30
+ if redis.call("HEXISTS", hashKey, entryKey) == 0 then
31
+ redis.call("HSET", hashKey, entryKey, value);
32
+ redis.call("HSET", hashKey, markerKey, markerValue);
33
+ return 1; -- New field created and marked
34
+ else
35
+ return 0; -- Field already exists, no operation
36
+ end;
@@ -11,7 +11,10 @@ ARGV:
11
11
  [2] skip - Number of matching entries to skip (pagination offset)
12
12
  [3] count - Maximum number of entries to return
13
13
  [4] prefix - Key prefix for account data hashes (e.g., "ee:")
14
- [5] strsearch - Case-insensitive substring to search in account, name, or email fields
14
+ [5] strsearch - Case-insensitive substring to search in account, name, or email fields.
15
+ Folded here as well as by the caller, so a caller that passes it as typed still gets a
16
+ case-insensitive search. string.lower() folds ASCII only; a caller that has to match
17
+ non-ASCII has to fold the needle itself before passing it in.
15
18
 
16
19
  Returns:
17
20
  Array with:
@@ -28,7 +31,7 @@ local filterState = ARGV[1];
28
31
  local skip = tonumber(ARGV[2]) or 0;
29
32
  local count = tonumber(ARGV[3]) or 0;
30
33
  local prefix = ARGV[4];
31
- local strsearch = ARGV[5];
34
+ local strsearch = string.lower(ARGV[5] or '');
32
35
 
33
36
  -- filterState may be a comma-separated list; build a lookup set once
34
37
  local stateSet = nil;
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ const config = require('@zone-eu/wild-config');
4
+ const settings = require('../settings');
5
+ const { hasEnvValue, readEnvValue, getBoolean } = require('../tools');
6
+
7
+ // Deployment-level gate for the MCP (Model Context Protocol) endpoint. When this is false the
8
+ // /mcp routes are not registered at all, so the surface does not exist on the instance. Set via
9
+ // the --mcp.enabled CLI flag / [mcp] enabled config or EENGINE_MCP_ENABLED. Defaults to true -
10
+ // unlike the Document Store gate this one exists for operators who want the endpoint compiled
11
+ // out of the route table, not to hide an unfinished feature.
12
+ //
13
+ // The runtime on/off switch is the `mcpEnabled` setting below, which starts out false and is
14
+ // flipped in the admin UI, so a fresh instance does not expose a new surface until someone
15
+ // turns it on.
16
+ const mcpFeatureEnabled = hasEnvValue('EENGINE_MCP_ENABLED')
17
+ ? getBoolean(readEnvValue('EENGINE_MCP_ENABLED'))
18
+ : getBoolean(config.mcp ? config.mcp.enabled : true);
19
+
20
+ // Effective runtime state: the feature must be available (gate) AND enabled in settings. When
21
+ // the gate is off this is always false, mirroring isDocumentStoreEnabled() in
22
+ // lib/document-store.js.
23
+ const isMcpEnabled = async () => mcpFeatureEnabled && !!(await settings.get('mcpEnabled'));
24
+
25
+ // The one error every first-time integrator hits, so every surface that reports it names the
26
+ // switch the same way
27
+ const MCP_DISABLED_MESSAGE = 'MCP support is not enabled on this instance. An admin can turn it on under Configuration > MCP, or by setting mcpEnabled';
28
+
29
+ module.exports = { mcpFeatureEnabled, isMcpEnabled, MCP_DISABLED_MESSAGE };
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+
3
+ // Dispatches an in-process API request on behalf of an MCP caller.
4
+ //
5
+ // server.inject() rather than any internal shortcut, so the injected request is a real API
6
+ // request: the api-token strategy re-validates the caller's credential, and scope checks, token
7
+ // permissions, account binding, IP restrictions, rate limits and the token audit log all apply
8
+ // exactly as they would over REST. This is the single dispatch path for MCP tools and resources -
9
+ // there is deliberately no second one that skips any of it.
10
+ //
11
+ // The mirroring rule this file owns: every request attribute a token restriction reads
12
+ // (credential, client IP, Referer) must be copied onto the inner request so the strategy's
13
+ // checks re-run at full fidelity, while once-per-call stateful effects (rate-limit spend,
14
+ // last-use record, audit row) are spent at the /mcp door and skipped inside via the
15
+ // mcpInternal marker. A restriction input missing from the mirror silently breaks that
16
+ // restriction's tokens over MCP - that is how the Referer omission slipped through once.
17
+
18
+ /**
19
+ * @param {Object} opts
20
+ * @param {Object} opts.server - the Hapi server
21
+ * @param {Object} opts.request - the outer /mcp request (credential, client IP, timeout header)
22
+ * @param {String} opts.method - HTTP method of the API route
23
+ * @param {String} opts.url - path (plus query string) of the API route
24
+ * @param {Object} [opts.payload] - JSON payload
25
+ * @returns {Promise<Object>} the Hapi injection response
26
+ */
27
+ async function apiInject({ server, request, method, url, payload }) {
28
+ const headers = {};
29
+
30
+ // The credential of the MCP request itself, whichever way it arrived - the strategy accepts
31
+ // ?access_token= too, and the injected request must carry the same credential rather than a
32
+ // copy of the transport it came in on. The `preauth` caller of the disableTokens mode
33
+ // carries no credential and needs none on the inner request either.
34
+ const token = request.auth && request.auth.credentials && request.auth.credentials.token;
35
+ if (token) {
36
+ headers.authorization = `Bearer ${token}`;
37
+ }
38
+
39
+ if (request.headers['x-ee-timeout']) {
40
+ headers['x-ee-timeout'] = request.headers['x-ee-timeout'];
41
+ }
42
+
43
+ // Token referrer restrictions re-run on the inner request, and the outer request's Referer
44
+ // is the value they are about; without it a referrer-restricted token cleared the /mcp door
45
+ // and then failed every injected call
46
+ if (request.headers.referer) {
47
+ headers.referer = request.headers.referer;
48
+ }
49
+
50
+ if (payload !== undefined) {
51
+ headers['content-type'] = 'application/json';
52
+ }
53
+
54
+ return server.inject({
55
+ method,
56
+ url,
57
+ headers,
58
+ payload,
59
+ // The resolved client address of the outer request, so token IP allowlists and the audit
60
+ // trail see the real caller rather than the loopback address of an internal dispatch
61
+ remoteAddress: (request.app && request.app.ip) || undefined,
62
+ // Marks the request as MCP-dispatched for the api-token strategy: the `mcp` surface
63
+ // scope is honored only on requests carrying this flag, and request.app cannot be set
64
+ // from the network, so the marker is not forgeable. The license info rides along so the
65
+ // inner run's onRequest does not repeat an IPC for an answer that cannot differ.
66
+ app: { mcpInternal: true, licenseInfo: request.app && request.app.licenseInfo }
67
+ });
68
+ }
69
+
70
+ module.exports = { apiInject };
@@ -0,0 +1,120 @@
1
+ 'use strict';
2
+
3
+ // Converts joi schemas into the JSON Schema (2020-12 dialect) shape MCP tool definitions carry.
4
+ //
5
+ // Reuses the OpenAPI SchemaConverter from lib/openapi/joi-schema.js rather than walking joi's
6
+ // describe() output a second time: that converter is the one place the repo reads joi schemas,
7
+ // and a second reader would drift from it. The converter is asked to inline everything
8
+ // (useDefinitions: false, so no #/components/schemas refs can appear), and the OpenAPI 3.0
9
+ // idioms in its output are then rewritten into their JSON Schema equivalents:
10
+ //
11
+ // - `nullable: true` becomes `type: [..., "null"]` (and null joins an enum when one exists)
12
+ // - the singular `example` becomes the standard `examples` array
13
+ // - the `x-*` vendor extensions (x-meta, x-constraint, x-format, x-convert) are dropped -
14
+ // they carry joi rules for the API reference renderer, which no MCP client reads, and the
15
+ // spec reserves x-mcp-header for transport behavior, so unknown x- keys are noise at best.
16
+ // One of them is not renderer detail though: `x-meta.enumDescriptions` says what each value
17
+ // of an enum MEANS, which is the difference between a model picking a value and guessing
18
+ // one. It is folded into the description before the key goes, so the meanings survive in the
19
+ // one field every client shows.
20
+ //
21
+ // Everything else the converter emits (properties, required, enum, anyOf, minimum/maxLength and
22
+ // friends) is already valid 2020-12.
23
+
24
+ const { SchemaConverter } = require('../openapi/joi-schema');
25
+
26
+ function toJsonSchema(node) {
27
+ if (Array.isArray(node)) {
28
+ return node.map(entry => toJsonSchema(entry));
29
+ }
30
+
31
+ if (!node || typeof node !== 'object') {
32
+ return node;
33
+ }
34
+
35
+ const result = {};
36
+
37
+ // Collected before the loop drops the key it lives on, and appended after the description is
38
+ // known - the two can arrive in either order.
39
+ const enumDescriptions = node['x-meta'] && node['x-meta'].enumDescriptions;
40
+
41
+ for (const [key, value] of Object.entries(node)) {
42
+ if (/^x-/.test(key)) {
43
+ continue;
44
+ }
45
+
46
+ switch (key) {
47
+ case 'nullable':
48
+ // handled below, once `type` and `enum` are known
49
+ continue;
50
+
51
+ case 'example':
52
+ result.examples = [value];
53
+ continue;
54
+
55
+ case 'properties': {
56
+ const mapped = {};
57
+ for (const [property, schema] of Object.entries(value)) {
58
+ mapped[property] = toJsonSchema(schema);
59
+ }
60
+ result[key] = mapped;
61
+ continue;
62
+ }
63
+
64
+ // The only nesting keywords the converter emits: alternatives and .when() collapse
65
+ // into anyOf, array items stay items. Nothing produces allOf/oneOf/not.
66
+ case 'items':
67
+ case 'anyOf':
68
+ result[key] = toJsonSchema(value);
69
+ continue;
70
+
71
+ default:
72
+ result[key] = value;
73
+ }
74
+ }
75
+
76
+ if (enumDescriptions && typeof enumDescriptions === 'object') {
77
+ // Only the values this schema actually offers, in the order it offers them, so a shared
78
+ // table describing more values than one field accepts cannot widen it in the prose
79
+ const described = (Array.isArray(result.enum) ? result.enum : Object.keys(enumDescriptions))
80
+ .filter(value => enumDescriptions[value])
81
+ .map(value => `"${value}" - ${enumDescriptions[value]}`);
82
+
83
+ if (described.length) {
84
+ result.description = `${result.description ? `${result.description}. ` : ''}${described.join('; ')}`;
85
+ }
86
+ }
87
+
88
+ if (node.nullable === true) {
89
+ if (typeof result.type === 'string') {
90
+ result.type = [result.type, 'null'];
91
+ } else if (Array.isArray(result.anyOf)) {
92
+ // alternatives().allow(null): the converter parks nullable next to anyOf, where
93
+ // there is no type keyword to widen - null becomes one more accepted branch
94
+ result.anyOf = result.anyOf.concat({ type: 'null' });
95
+ }
96
+ if (Array.isArray(result.enum) && !result.enum.includes(null)) {
97
+ result.enum = result.enum.concat(null);
98
+ }
99
+ }
100
+
101
+ return result;
102
+ }
103
+
104
+ /**
105
+ * Converts a compiled joi schema into a JSON Schema object for an MCP tool definition.
106
+ *
107
+ * @param {Object} schema - a joi schema
108
+ * @returns {Object|undefined} JSON Schema, or undefined when the schema documents nothing
109
+ */
110
+ function joiToJsonSchema(schema) {
111
+ if (!schema || typeof schema.describe !== 'function') {
112
+ return undefined;
113
+ }
114
+
115
+ const converted = new SchemaConverter().convert(schema, { useDefinitions: false });
116
+
117
+ return converted ? toJsonSchema(converted) : undefined;
118
+ }
119
+
120
+ module.exports = { joiToJsonSchema };
@@ -0,0 +1,171 @@
1
+ 'use strict';
2
+
3
+ // subscriptions/listen: the long-lived notification stream of the modern (2026-07-28) protocol
4
+ // revision, bridged from the account state-change fanout that already feeds /v1/changes and the
5
+ // admin dashboard.
6
+ //
7
+ // What is honored, and why only this: `resourceSubscriptions` on account resource URIs
8
+ // (emailengine://account/{id}), delivered as notifications/resources/updated whenever that
9
+ // account's state changes. The other filter fields are omitted from the acknowledgment, which
10
+ // per the spec means "not honored": the tool list is static for the life of the worker, so
11
+ // toolsListChanged would never fire, and prompts do not exist here.
12
+ //
13
+ // Authorization is per subscribed account, enforced by injecting GET /v1/account/{account} with
14
+ // the caller's own credential at accept time - a URI the credential cannot read is silently
15
+ // dropped from the acknowledged subset, exactly as the spec expects unsupported entries to be.
16
+ // This deliberately reuses the REST enforcement rather than inventing a subscription-specific
17
+ // rule; the acknowledgment tells the client what survived.
18
+ //
19
+ // Every stream lives in the API worker that accepted it. The main thread already fans account
20
+ // state changes out to every API worker for the admin SSE feed, so with multiple API workers
21
+ // each one feeds its own streams and nothing needs affinity.
22
+
23
+ const { openSseStream } = require('../response-stream');
24
+ const { apiInject } = require('./inject');
25
+ const { accountUri, parseAccountUri } = require('./resources');
26
+
27
+ // Live MCP listen streams in this worker. Deliberately not the change-feed registry in
28
+ // lib/response-stream.js: these streams carry JSON-RPC frames, and the two fanouts must not
29
+ // receive each other's messages.
30
+ const mcpListenStreams = new Set();
31
+
32
+ const META_SUBSCRIPTION_ID = 'io.modelcontextprotocol/subscriptionId';
33
+
34
+ // Accept-time authorization injects one full API request per subscribed URI - token read,
35
+ // permission check, account read - so a listen request is an amplifier by construction. Three
36
+ // bounds keep it one: how many URIs a request may name, how many of those checks run at once,
37
+ // and how many streams a single credential may hold open.
38
+ //
39
+ // The stream cap counts what THIS worker holds, because that is what the registry below can see -
40
+ // with EENGINE_WORKERS_API above 1 a credential can hold the cap on each of them. That is the
41
+ // right bound anyway: the cost this limits is per-worker (the registry walk on every fanout, the
42
+ // sockets on that process), and nothing here needs an instance-wide count.
43
+ const MAX_RESOURCE_SUBSCRIPTIONS = 20;
44
+ const AUTH_CHECK_CONCURRENCY = 5;
45
+ const MAX_STREAMS_PER_CREDENTIAL = 4;
46
+
47
+ /**
48
+ * The credential a stream belongs to, for the per-credential stream cap. Token records are keyed
49
+ * by their hash; the `preauth` caller of the disableTokens mode has no record and shares one
50
+ * bucket, which is correct - it is one anonymous caller as far as this instance can tell.
51
+ */
52
+ function credentialId(request) {
53
+ return (request.auth && request.auth.artifacts && request.auth.artifacts.id) || 'preauth';
54
+ }
55
+
56
+ /**
57
+ * Whether this credential may open another listen stream on this worker.
58
+ */
59
+ function canOpenListenStream(request) {
60
+ const id = credentialId(request);
61
+ let open = 0;
62
+ for (const stream of mcpListenStreams) {
63
+ if (stream.mcpSubscription && stream.mcpSubscription.credentialId === id) {
64
+ open++;
65
+ }
66
+ }
67
+ return open < MAX_STREAMS_PER_CREDENTIAL;
68
+ }
69
+
70
+ /**
71
+ * Validates a requested notification filter against what the caller may actually see.
72
+ *
73
+ * @returns {Promise<Object>} the acknowledged filter subset
74
+ */
75
+ async function acceptFilter({ server, request, filter }) {
76
+ const accepted = {};
77
+
78
+ const requested = Array.isArray(filter.resourceSubscriptions) ? filter.resourceSubscriptions.slice(0, MAX_RESOURCE_SUBSCRIPTIONS) : [];
79
+
80
+ const accounts = [...new Set(requested.map(uri => parseAccountUri(uri)).filter(Boolean))];
81
+
82
+ // Independent yes/no checks about separate accounts, so they run concurrently - serialized,
83
+ // a broad subscription would pay one full request pipeline per URI in connect latency. In
84
+ // batches rather than all at once: every check is a full injected request, and one client
85
+ // should not be able to put twenty of those in flight with a single POST.
86
+ const uris = [];
87
+ for (let pos = 0; pos < accounts.length; pos += AUTH_CHECK_CONCURRENCY) {
88
+ const batch = accounts.slice(pos, pos + AUTH_CHECK_CONCURRENCY);
89
+ const admitted = await Promise.all(
90
+ batch.map(async account => {
91
+ const res = await apiInject({ server, request, method: 'get', url: `/v1/account/${encodeURIComponent(account)}` });
92
+ return res.statusCode < 400 ? accountUri(account) : null;
93
+ })
94
+ );
95
+ uris.push(...admitted.filter(Boolean));
96
+ }
97
+ if (uris.length) {
98
+ accepted.resourceSubscriptions = uris;
99
+ }
100
+
101
+ return accepted;
102
+ }
103
+
104
+ /**
105
+ * Opens the SSE response stream for an accepted subscriptions/listen request.
106
+ *
107
+ * @param {Object} opts
108
+ * @param {Object} opts.h - Hapi response toolkit
109
+ * @param {Object} opts.request - the /mcp request, for the credential the stream is counted under
110
+ * @param {*} opts.subscriptionId - the JSON-RPC id of the subscriptions/listen request
111
+ * @param {Object} opts.accepted - the acknowledged filter subset from acceptFilter()
112
+ * @returns {Object} Hapi response
113
+ */
114
+ function openListenStream({ h, request, subscriptionId, accepted }) {
115
+ const { stream, response } = openSseStream(h, {
116
+ registry: mcpListenStreams,
117
+ onOpen: opened =>
118
+ opened.sendMessage({
119
+ jsonrpc: '2.0',
120
+ method: 'notifications/subscriptions/acknowledged',
121
+ params: {
122
+ _meta: { [META_SUBSCRIPTION_ID]: subscriptionId },
123
+ notifications: accepted
124
+ }
125
+ })
126
+ });
127
+
128
+ stream.mcpSubscription = {
129
+ id: subscriptionId,
130
+ credentialId: credentialId(request),
131
+ resourceUris: new Set(accepted.resourceSubscriptions || [])
132
+ };
133
+
134
+ return response;
135
+ }
136
+
137
+ /**
138
+ * Fans one account state-change event out to the listen streams that subscribed to it.
139
+ * Called from the API worker's 'change' message handler, alongside the admin feed fanout.
140
+ */
141
+ function publishAccountChange(data, logger) {
142
+ if (!mcpListenStreams.size || !data || !data.account) {
143
+ return;
144
+ }
145
+
146
+ const uri = accountUri(data.account);
147
+
148
+ for (const stream of mcpListenStreams) {
149
+ const subscription = stream.mcpSubscription;
150
+ if (!subscription || !subscription.resourceUris.has(uri)) {
151
+ continue;
152
+ }
153
+
154
+ try {
155
+ stream.sendMessage({
156
+ jsonrpc: '2.0',
157
+ method: 'notifications/resources/updated',
158
+ params: {
159
+ _meta: { [META_SUBSCRIPTION_ID]: subscription.id },
160
+ uri
161
+ }
162
+ });
163
+ } catch (err) {
164
+ if (logger) {
165
+ logger.warn({ msg: 'Failed to publish MCP resource update', err, account: data.account });
166
+ }
167
+ }
168
+ }
169
+ }
170
+
171
+ module.exports = { acceptFilter, openListenStream, publishAccountChange, canOpenListenStream, MAX_STREAMS_PER_CREDENTIAL, MAX_RESOURCE_SUBSCRIPTIONS };