emailengine-app 2.79.1 → 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 (81) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +40 -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 +95 -18
  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 +97 -1
  15. package/lib/api-routes/route-helpers.js +16 -4
  16. package/lib/api-routes/route-metadata.js +24 -4
  17. package/lib/api-routes/submit-routes.js +41 -0
  18. package/lib/api-routes/template-routes.js +7 -0
  19. package/lib/api-routes/token-routes.js +4 -2
  20. package/lib/consts.js +30 -1
  21. package/lib/email-client/base-client.js +102 -117
  22. package/lib/email-client/gmail-client.js +87 -22
  23. package/lib/email-client/imap/mailbox.js +140 -66
  24. package/lib/email-client/outlook-client.js +17 -14
  25. package/lib/enum-descriptions.js +2 -1
  26. package/lib/field-usage.js +17 -1
  27. package/lib/lua/s-list-accounts.lua +5 -2
  28. package/lib/mcp/index.js +29 -0
  29. package/lib/mcp/inject.js +70 -0
  30. package/lib/mcp/json-schema.js +120 -0
  31. package/lib/mcp/listen.js +171 -0
  32. package/lib/mcp/oauth.js +324 -0
  33. package/lib/mcp/protocol.js +489 -0
  34. package/lib/mcp/resources.js +139 -0
  35. package/lib/mcp/tools.js +655 -0
  36. package/lib/openapi/index.js +3 -1
  37. package/lib/response-stream.js +52 -21
  38. package/lib/routes-ui.js +4 -0
  39. package/lib/schemas.js +24 -3
  40. package/lib/token-permission-view.js +104 -8
  41. package/lib/tokens.js +34 -5
  42. package/lib/tools.js +96 -0
  43. package/lib/ui-routes/account-routes.js +43 -1
  44. package/lib/ui-routes/admin-config-routes.js +114 -1
  45. package/lib/ui-routes/admin-entities-routes.js +54 -5
  46. package/lib/ui-routes/auth-routes.js +13 -0
  47. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  48. package/lib/ui-routes/route-helpers.js +116 -1
  49. package/lib/utils/network.js +9 -1
  50. package/lib/web-safe-html.js +61 -0
  51. package/lib/webhooks.js +3 -8
  52. package/package.json +9 -8
  53. package/sbom.json +1 -1
  54. package/scripts/README.md +25 -0
  55. package/scripts/build-icon.js +77 -0
  56. package/static/css/flyonui.css +1 -1
  57. package/static/css/src/app.tailwind.css +98 -0
  58. package/static/emailengine.ico +0 -0
  59. package/static/js/ui.js +465 -1
  60. package/static/licenses.html +42 -22
  61. package/translations/messages.pot +57 -57
  62. package/views/config/mcp.hbs +361 -0
  63. package/views/config/oauth/index.hbs +7 -0
  64. package/views/layout/prompt.hbs +62 -0
  65. package/views/mcp/authorize.hbs +136 -0
  66. package/views/partials/head_assets.hbs +3 -3
  67. package/views/partials/mcp_access_levels.hbs +13 -0
  68. package/views/partials/mcp_account_limit.hbs +14 -0
  69. package/views/partials/mcp_tool_count.hbs +19 -0
  70. package/views/partials/side_menu.hbs +1 -0
  71. package/views/partials/ui/account-picker.hbs +59 -0
  72. package/views/partials/ui/code-block.hbs +26 -0
  73. package/views/partials/ui/menu-item.hbs +5 -0
  74. package/views/partials/ui/radio.hbs +41 -0
  75. package/views/partials/ui/tab.hbs +15 -10
  76. package/views/partials/ui/tabs.hbs +8 -5
  77. package/views/templates/template.hbs +4 -3
  78. package/views/tokens/index.hbs +8 -2
  79. package/views/tokens/new.hbs +514 -243
  80. package/winconf.js +148 -48
  81. package/workers/api.js +198 -48
@@ -10,7 +10,9 @@ const {
10
10
  filterEmptyObjectValues,
11
11
  validUidValidity,
12
12
  mailboxPathHash,
13
- getMailboxStatusKey
13
+ getMailboxStatusKey,
14
+ collectCidReferences,
15
+ cidReferenceRegex
14
16
  } = require('../../tools');
15
17
  const msgpack = require('../../msgpack');
16
18
  const he = require('he');
@@ -68,6 +70,115 @@ function phantomStatusKey(status) {
68
70
  return `${status.uidValidity || ''}:${status.uidNext || 0}:${status.messages || 0}`;
69
71
  }
70
72
 
73
+ /**
74
+ * Headers the notification path needs for its own processing, whatever the notifyHeaders
75
+ * setting asks for. They travel in the one BODY.PEEK[HEADER.FIELDS (...)] section that path
76
+ * already requests, and are filtered back down before anything is published: processNew()
77
+ * narrows the exposed set to what the caller asked for, and Webhooks.formatPayload() drops
78
+ * the block entirely unless notifyHeaders names something.
79
+ */
80
+ const NOTIFICATION_HEADERS = [
81
+ // Auto-reply detection
82
+ 'x-autoreply',
83
+ 'x-autorespond',
84
+ 'auto-submitted',
85
+ 'precedence',
86
+
87
+ // Threading
88
+ 'in-reply-to',
89
+ 'references',
90
+
91
+ // Bounce and complaint detection
92
+ 'content-type',
93
+
94
+ // Fallback for an ENVELOPE that carries no usable address. Lark Mail omits the address
95
+ // fields outright, and any server can mis-parse a malformed header into a display name
96
+ // with no address - see preferAddressList()
97
+ 'from',
98
+ 'to',
99
+ 'cc',
100
+ 'bcc'
101
+ ];
102
+
103
+ /**
104
+ * Builds the header field list for a notification fetch.
105
+ *
106
+ * @param {String[]|Boolean} configuredHeaders - Headers the notifyHeaders setting asks for
107
+ * @returns {String[]} Header names to request from the server
108
+ */
109
+ function notificationHeaderFields(configuredHeaders) {
110
+ let fetchHeaders = new Set(Array.isArray(configuredHeaders) ? configuredHeaders : []);
111
+
112
+ for (let key of NOTIFICATION_HEADERS) {
113
+ fetchHeaders.add(key);
114
+ }
115
+
116
+ return Array.from(fetchHeaders);
117
+ }
118
+
119
+ /**
120
+ * Parses a raw address header into the address objects the API exposes.
121
+ *
122
+ * @param {String[]} values - Raw header values for one address field
123
+ * @returns {Object[]|undefined} Parsed addresses, or undefined if none could be read
124
+ */
125
+ function parseAddressHeader(values) {
126
+ if (!values?.length) {
127
+ return undefined;
128
+ }
129
+
130
+ try {
131
+ let addressList = addressparser(values)
132
+ .filter(address => !!address.address)
133
+ .map(address => {
134
+ let name = address.name;
135
+ try {
136
+ name = libmime.decodeWords(name);
137
+ } catch (err) {
138
+ // keep the undecoded name
139
+ }
140
+ return { name, address: address.address };
141
+ });
142
+
143
+ return addressList.length ? addressList : undefined;
144
+ } catch (err) {
145
+ // a header we cannot read is worth no more than one that is not there
146
+ return undefined;
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Picks the address list to expose for a header, preferring the server's ENVELOPE.
152
+ *
153
+ * An ENVELOPE list can come back holding no usable address at all: RFC 9051 7.5.2 group
154
+ * markers carry a group name and nothing else, and a server that failed to parse a
155
+ * malformed header reports the wreckage the same way, as a display name with an empty
156
+ * address. The raw header is the better answer in that case, because addressparser sees
157
+ * the original value and can still recover the recipient. Falling back on emptiness alone
158
+ * was not enough - the broken list is not empty, just useless.
159
+ *
160
+ * The header is parsed only when the ENVELOPE turns out to be unusable, which is rare.
161
+ * Parsing all four address fields up front would be work discarded on every message.
162
+ *
163
+ * @param {Object[]} envelopeList - Address list from the IMAP ENVELOPE
164
+ * @param {Object} headers - Decoded message headers, if any were fetched
165
+ * @param {String} key - Header name to fall back to
166
+ * @returns {Object[]|undefined} The list to expose, or undefined if neither source has one
167
+ */
168
+ function preferAddressList(envelopeList, headers, key) {
169
+ if (envelopeList?.some(entry => entry.address)) {
170
+ return envelopeList;
171
+ }
172
+
173
+ let headerList = parseAddressHeader(headers?.[key]);
174
+ if (headerList?.length) {
175
+ return headerList;
176
+ }
177
+
178
+ // Nothing usable anywhere - keep the ENVELOPE entries so a group name still shows up
179
+ return envelopeList?.length ? envelopeList : undefined;
180
+ }
181
+
71
182
  /**
72
183
  * Represents a single IMAP mailbox/folder and handles all operations on it
73
184
  */
@@ -1298,6 +1409,7 @@ class Mailbox {
1298
1409
  // Fetch inline attachments referenced in HTML
1299
1410
  if (messageInfo.attachments?.length && messageInfo.text?.html) {
1300
1411
  // fetch inline attachments
1412
+ let cidReferences = collectCidReferences(messageInfo.text.html);
1301
1413
  for (let attachment of messageInfo.attachments || []) {
1302
1414
  if (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE) {
1303
1415
  // skip large attachments
@@ -1305,7 +1417,7 @@ class Mailbox {
1305
1417
  }
1306
1418
 
1307
1419
  // Check if attachment is referenced by Content-ID in HTML
1308
- if (!attachment.content && attachment.contentId && messageInfo.text.html.indexOf(`cid:${attachment.contentId.replace(/^<|>$/g, '')}`) >= 0) {
1420
+ if (!attachment.content && attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
1309
1421
  try {
1310
1422
  let buf = Buffer.from(attachment.id, 'base64url');
1311
1423
  let part = buf.subarray(8).toString();
@@ -1585,11 +1697,12 @@ class Mailbox {
1585
1697
  if (messageInfo.text.html && messageInfo.attachments) {
1586
1698
  let attachmentList = new Map();
1587
1699
  let partList = [];
1700
+ let cidReferences = collectCidReferences(messageInfo.text.html);
1588
1701
 
1589
1702
  // Collect CID-referenced attachments
1590
1703
  for (let attachment of messageInfo.attachments || []) {
1591
1704
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
1592
- if (contentId && messageInfo.text.html.indexOf(contentId) >= 0) {
1705
+ if (contentId && cidReferences.has(contentId)) {
1593
1706
  attachmentList.set(contentId, {
1594
1707
  attachment,
1595
1708
  content: attachment.content || null
@@ -1635,7 +1748,7 @@ class Mailbox {
1635
1748
  }
1636
1749
 
1637
1750
  // Replace CID references with data URIs
1638
- messageInfo.text.html = messageInfo.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1751
+ messageInfo.text.html = messageInfo.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1639
1752
  if (attachmentList.has(cidMatch)) {
1640
1753
  let { attachment, content } = attachmentList.get(cidMatch);
1641
1754
  if (content) {
@@ -1777,39 +1890,13 @@ class Mailbox {
1777
1890
  isDraft = true;
1778
1891
  }
1779
1892
 
1893
+ // The address fields fall back to these when the ENVELOPE carries no usable address,
1894
+ // which Lark Mail does by omitting them and any server can do by mis-parsing a
1895
+ // malformed header. See preferAddressList(). Normally only the ENVELOPE is used, and
1896
+ // a message listing fetches no headers at all
1780
1897
  let headers;
1781
-
1782
- // This section is needed for Lark Mail as some address fields might be missing
1783
- // from the ENVELOPE section, so fall back to the header instead.
1784
- // Normally, these headers are not fetched from the server and only ENVELOPE is used
1785
- let parsedAddresses = {};
1786
1898
  if (messageData.headers) {
1787
1899
  headers = decodeHeaders(messageData.headers.toString().trim());
1788
- for (let key of ['from', 'to', 'cc', 'bcc']) {
1789
- if (headers[key]?.length) {
1790
- try {
1791
- const addressList = addressparser(headers[key])
1792
- .filter(address => !!address.address)
1793
- .map(address => {
1794
- let name = address.name;
1795
- try {
1796
- name = libmime.decodeWords(name);
1797
- } catch (err) {
1798
- // ignore
1799
- }
1800
- return {
1801
- name,
1802
- address: address.address
1803
- };
1804
- });
1805
- if (addressList?.length) {
1806
- parsedAddresses[key] = addressList;
1807
- }
1808
- } catch (err) {
1809
- // just ignore
1810
- }
1811
- }
1812
- }
1813
1900
  }
1814
1901
 
1815
1902
  // Build message info object
@@ -1835,16 +1922,16 @@ class Mailbox {
1835
1922
 
1836
1923
  size: messageData.size || undefined,
1837
1924
  subject: envelope.subject || undefined,
1838
- // Prefer envelope from, fall back to parsed header
1839
- from: envelope.from?.[0] ? envelope.from[0] : parsedAddresses.from?.[0] || undefined,
1925
+ // Prefer the ENVELOPE, fall back to the raw header when it holds no usable address
1926
+ from: preferAddressList(envelope.from, headers, 'from')?.[0] || undefined,
1840
1927
 
1841
1928
  replyTo: envelope.replyTo && envelope.replyTo.length ? envelope.replyTo : undefined,
1842
1929
  sender: extended && envelope.sender && envelope.sender[0] ? envelope.sender[0] : undefined,
1843
1930
 
1844
- to: envelope.to?.length ? envelope.to : parsedAddresses.to || undefined,
1845
- cc: envelope.cc?.length ? envelope.cc : parsedAddresses.cc || undefined,
1931
+ to: preferAddressList(envelope.to, headers, 'to'),
1932
+ cc: preferAddressList(envelope.cc, headers, 'cc'),
1846
1933
 
1847
- bcc: extended && envelope.bcc && envelope.bcc.length ? envelope.bcc : undefined,
1934
+ bcc: extended ? preferAddressList(envelope.bcc, headers, 'bcc') : undefined,
1848
1935
 
1849
1936
  attachments: attachments && attachments.length ? attachments : undefined,
1850
1937
  messageId: (envelope.messageId && envelope.messageId.toString().trim()) || undefined,
@@ -2080,31 +2167,10 @@ class Mailbox {
2080
2167
  messageFetchOptions.headers = notifyHeaders.includes('*') || documentStoreEnabled ? true : notifyHeaders.length ? notifyHeaders : false;
2081
2168
  }
2082
2169
 
2083
- // Also request autoresponse headers
2170
+ // Also request the headers this path needs for its own processing. Skipped when the
2171
+ // setting already asks for every header, since there is nothing left to add
2084
2172
  if (messageFetchOptions.headers !== true) {
2085
- let fetchHeaders = new Set(messageFetchOptions.headers || []);
2086
-
2087
- // Auto-reply detection headers
2088
- fetchHeaders.add('x-autoreply');
2089
- fetchHeaders.add('x-autorespond');
2090
- fetchHeaders.add('auto-submitted');
2091
- fetchHeaders.add('precedence');
2092
-
2093
- // Threading headers
2094
- fetchHeaders.add('in-reply-to');
2095
- fetchHeaders.add('references');
2096
-
2097
- // Content type for bounce/complaint detection
2098
- fetchHeaders.add('content-type');
2099
-
2100
- if (this.isLarkSuite) {
2101
- // Add address headers as a fallback for unreliable ENVELOPE
2102
- fetchHeaders.add('from');
2103
- fetchHeaders.add('to');
2104
- fetchHeaders.add('cc');
2105
- }
2106
-
2107
- messageFetchOptions.fetchHeaders = Array.from(fetchHeaders);
2173
+ messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers);
2108
2174
  }
2109
2175
 
2110
2176
  // Peek-then-remove: read entries without removing so that connection errors
@@ -2620,11 +2686,12 @@ class Mailbox {
2620
2686
  if (options.embedAttachedImages && messageInfo.text && messageInfo.text.html && messageInfo.attachments) {
2621
2687
  let attachmentList = new Map();
2622
2688
  let partList = [];
2689
+ let cidReferences = collectCidReferences(messageInfo.text.html);
2623
2690
 
2624
2691
  // Find images referenced by CID
2625
2692
  for (let attachment of messageInfo.attachments || []) {
2626
2693
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
2627
- if (contentId && messageInfo.text.html.indexOf(contentId) >= 0) {
2694
+ if (contentId && cidReferences.has(contentId)) {
2628
2695
  attachmentList.set(contentId, { attachment, content: null });
2629
2696
 
2630
2697
  let buf = Buffer.from(attachment.id, 'base64url');
@@ -2659,7 +2726,7 @@ class Mailbox {
2659
2726
  }
2660
2727
 
2661
2728
  // Replace CID references with data URIs
2662
- messageInfo.text.html = messageInfo.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
2729
+ messageInfo.text.html = messageInfo.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
2663
2730
  if (attachmentList.has(cidMatch)) {
2664
2731
  let { attachment } = attachmentList.get(cidMatch);
2665
2732
  if (attachment.content) {
@@ -3135,7 +3202,12 @@ class Mailbox {
3135
3202
  labels: true
3136
3203
  };
3137
3204
 
3138
- // LarkSuite specific handling - ensure address headers are fetched
3205
+ // LarkSuite specific handling - ensure address headers are fetched.
3206
+ // This stays provider-gated, unlike the notification path: a listing fetches no
3207
+ // headers at all otherwise, so asking for them here adds a BODY.PEEK section to
3208
+ // every message of every page. Lark needs it because its ENVELOPE omits addresses
3209
+ // outright; for everyone else a mis-parsed header still yields a display name, and
3210
+ // paying for it on every listing is not worth the rare recovery.
3139
3211
  if (this.isLarkSuite) {
3140
3212
  if (!fields.headers && fields.headers !== true) {
3141
3213
  fields.headers = [];
@@ -3403,3 +3475,5 @@ class Mailbox {
3403
3475
  }
3404
3476
 
3405
3477
  module.exports.Mailbox = Mailbox;
3478
+ // Exported for tests: publishSyncedEvents() cannot be driven without a live connection
3479
+ module.exports.notificationHeaderFields = notificationHeaderFields;
@@ -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');
@@ -1603,11 +1603,7 @@ class OutlookClient extends BaseClient {
1603
1603
  async getMessage(emailId, options) {
1604
1604
  options = options || {};
1605
1605
 
1606
- if (options.webSafeHtml) {
1607
- options.textType = '*';
1608
- options.embedAttachedImages = true;
1609
- options.preProcessHtml = true;
1610
- }
1606
+ applyWebSafeHtmlOptions(options);
1611
1607
 
1612
1608
  await this.prepare();
1613
1609
 
@@ -1737,6 +1733,7 @@ class OutlookClient extends BaseClient {
1737
1733
  extended: true,
1738
1734
  path,
1739
1735
  textType: options.textType,
1736
+ maxBytes: options.maxBytes,
1740
1737
  showPath: options.showPath
1741
1738
  });
1742
1739
 
@@ -1762,11 +1759,12 @@ class OutlookClient extends BaseClient {
1762
1759
  // Embed attached images as data URLs
1763
1760
  if (options.embedAttachedImages && formattedMessage.text?.html && formattedMessage.attachments) {
1764
1761
  let attachmentMap = new Map();
1762
+ let cidReferences = collectCidReferences(formattedMessage.text.html);
1765
1763
 
1766
1764
  // Collect all referenced inline attachments
1767
1765
  for (let attachment of formattedMessage.attachments) {
1768
1766
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
1769
- if (contentId && !attachmentMap.has(contentId) && formattedMessage.text.html.indexOf(`cid:${contentId}`) >= 0) {
1767
+ if (contentId && !attachmentMap.has(contentId) && cidReferences.has(contentId)) {
1770
1768
  attachmentMap.set(contentId, {
1771
1769
  attachment,
1772
1770
  content: await this.getAttachmentContent(attachment.id, {
@@ -1777,7 +1775,7 @@ class OutlookClient extends BaseClient {
1777
1775
  }
1778
1776
 
1779
1777
  // Replace cid: references with data URLs
1780
- formattedMessage.text.html = formattedMessage.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1778
+ formattedMessage.text.html = formattedMessage.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1781
1779
  if (attachmentMap.has(cidMatch)) {
1782
1780
  let { content } = attachmentMap.get(cidMatch);
1783
1781
  if (content.content) {
@@ -1965,6 +1963,7 @@ class OutlookClient extends BaseClient {
1965
1963
  extended: true,
1966
1964
  path,
1967
1965
  textType: options.textType,
1966
+ maxBytes: options.maxBytes,
1968
1967
  showPath: options.showPath
1969
1968
  });
1970
1969
 
@@ -2104,7 +2103,7 @@ class OutlookClient extends BaseClient {
2104
2103
  }
2105
2104
  }
2106
2105
 
2107
- response.hasMore = false;
2106
+ response.hasMore = truncateTextContents(response, options.maxBytes);
2108
2107
 
2109
2108
  return response;
2110
2109
  }
@@ -2208,6 +2207,7 @@ class OutlookClient extends BaseClient {
2208
2207
  case 'attachments': {
2209
2208
  messageUploadObj.attachments = [];
2210
2209
  let attachmentCounter = 0;
2210
+ let cidReferences = collectCidReferences(emailObject.html);
2211
2211
  for (let attachment of emailObject.attachments || []) {
2212
2212
  let attachmentEntry = {
2213
2213
  '@odata.type': '#microsoft.graph.fileAttachment'
@@ -2225,7 +2225,7 @@ class OutlookClient extends BaseClient {
2225
2225
  if (attachment.cid) {
2226
2226
  // make sure that cid links to not use <content-id> format, otherwise this will be replaced
2227
2227
  attachmentEntry.contentId = attachment.cid.replace(/^[\s<]*|[\s>]*$/g, '');
2228
- if (emailObject.html?.indexOf(attachmentEntry.contentId) >= 0) {
2228
+ if (cidReferences.has(attachmentEntry.contentId)) {
2229
2229
  attachmentEntry.isInline = true;
2230
2230
  emailObject.html.replace(new RegExp(`cid:<${attachment.cid}>`, 'g'), `cid:${attachment.cid}`);
2231
2231
  }
@@ -3714,7 +3714,7 @@ class OutlookClient extends BaseClient {
3714
3714
  * Handles all message properties and attachments
3715
3715
  */
3716
3716
  formatMessage(messageData, options) {
3717
- let { extended, path, textType, showPath, minimalFields } = options || {};
3717
+ let { extended, path, textType, maxBytes, showPath, minimalFields } = options || {};
3718
3718
 
3719
3719
  let date = messageData.receivedDateTime ? new Date(messageData.receivedDateTime) : undefined;
3720
3720
  if (date?.toString() === 'Invalid Date') {
@@ -3784,6 +3784,8 @@ class OutlookClient extends BaseClient {
3784
3784
  }
3785
3785
  }
3786
3786
 
3787
+ const textHasMore = truncateTextContents(textContents, maxBytes);
3788
+
3787
3789
  let message = {
3788
3790
  id: messageData.id,
3789
3791
 
@@ -3822,7 +3824,7 @@ class OutlookClient extends BaseClient {
3822
3824
  encodedSize: encodedTextSize,
3823
3825
  plain: textContents?.plain?.toString(),
3824
3826
  html: textContents?.html?.toString(),
3825
- hasMore: textContents?.plain || textContents?.html ? false : undefined
3827
+ hasMore: textContents?.plain || textContents?.html ? textHasMore : undefined
3826
3828
  },
3827
3829
 
3828
3830
  preview: messageData.bodyPreview
@@ -3835,6 +3837,7 @@ class OutlookClient extends BaseClient {
3835
3837
 
3836
3838
  // Process attachments
3837
3839
  if (messageData.attachments?.length) {
3840
+ let cidReferences = collectCidReferences(message.text.html);
3838
3841
  message.attachments = messageData.attachments.map(entry => {
3839
3842
  const attachment = {
3840
3843
  // Encode both message ID and attachment ID for later retrieval
@@ -3852,7 +3855,7 @@ class OutlookClient extends BaseClient {
3852
3855
  // Normalize content ID format
3853
3856
  attachment.contentId = entry.contentId.replace(/^<*/, '<').replace(/>*$/, '>');
3854
3857
  // Check if attachment is embedded in HTML
3855
- if (textContents?.html?.indexOf(`cid:${attachment.contentId.replace(/^[\s<]*|[\s>]*$/g, '')}`) >= 0) {
3858
+ if (cidReferences.has(attachment.contentId.replace(/^[\s<]*|[\s>]*$/g, ''))) {
3856
3859
  attachment.embedded = true;
3857
3860
  }
3858
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' +
@@ -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 };