emailengine-app 2.79.1 → 2.79.3

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 (87) hide show
  1. package/.github/workflows/deploy.yml +92 -39
  2. package/.github/workflows/release.yaml +94 -34
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +85 -0
  5. package/bin/emailengine.js +8 -1
  6. package/config/default.toml +6 -0
  7. package/copy-static-files.sh +23 -2
  8. package/data/google-crawlers.json +1 -1
  9. package/lib/account.js +138 -18
  10. package/lib/api-routes/account-routes.js +13 -1
  11. package/lib/api-routes/index.js +12 -0
  12. package/lib/api-routes/mailbox-routes.js +6 -0
  13. package/lib/api-routes/mcp-oauth-routes.js +259 -0
  14. package/lib/api-routes/mcp-routes.js +172 -0
  15. package/lib/api-routes/message-routes.js +125 -4
  16. package/lib/api-routes/outbox-routes.js +7 -0
  17. package/lib/api-routes/permission-map.js +97 -1
  18. package/lib/api-routes/route-helpers.js +16 -4
  19. package/lib/api-routes/route-metadata.js +24 -4
  20. package/lib/api-routes/submit-routes.js +41 -0
  21. package/lib/api-routes/template-routes.js +7 -0
  22. package/lib/api-routes/token-routes.js +4 -2
  23. package/lib/consts.js +30 -1
  24. package/lib/email-client/base-client.js +235 -163
  25. package/lib/email-client/gmail-client.js +99 -22
  26. package/lib/email-client/imap/mailbox.js +140 -66
  27. package/lib/email-client/imap-client.js +74 -68
  28. package/lib/email-client/outlook-client.js +29 -14
  29. package/lib/enum-descriptions.js +2 -1
  30. package/lib/field-usage.js +17 -1
  31. package/lib/logger.js +43 -3
  32. package/lib/lua/s-list-accounts.lua +5 -2
  33. package/lib/mcp/index.js +29 -0
  34. package/lib/mcp/inject.js +70 -0
  35. package/lib/mcp/json-schema.js +120 -0
  36. package/lib/mcp/listen.js +171 -0
  37. package/lib/mcp/oauth.js +324 -0
  38. package/lib/mcp/protocol.js +489 -0
  39. package/lib/mcp/resources.js +139 -0
  40. package/lib/mcp/tools.js +655 -0
  41. package/lib/openapi/index.js +3 -1
  42. package/lib/response-stream.js +52 -21
  43. package/lib/routes-ui.js +4 -0
  44. package/lib/schemas.js +24 -3
  45. package/lib/token-permission-view.js +104 -8
  46. package/lib/tokens.js +34 -5
  47. package/lib/tools.js +96 -0
  48. package/lib/ui-routes/account-routes.js +43 -1
  49. package/lib/ui-routes/admin-config-routes.js +114 -1
  50. package/lib/ui-routes/admin-entities-routes.js +54 -5
  51. package/lib/ui-routes/auth-routes.js +13 -0
  52. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  53. package/lib/ui-routes/route-helpers.js +116 -1
  54. package/lib/utils/network.js +9 -1
  55. package/lib/web-safe-html.js +61 -0
  56. package/lib/webhooks.js +3 -8
  57. package/package.json +15 -14
  58. package/sbom.json +1 -1
  59. package/scripts/README.md +25 -0
  60. package/scripts/build-icon.js +77 -0
  61. package/server.js +21 -9
  62. package/static/css/flyonui.css +1 -1
  63. package/static/css/src/app.tailwind.css +98 -0
  64. package/static/emailengine.ico +0 -0
  65. package/static/js/ui.js +465 -1
  66. package/static/licenses.html +85 -135
  67. package/translations/messages.pot +103 -103
  68. package/views/config/mcp.hbs +361 -0
  69. package/views/config/oauth/index.hbs +7 -0
  70. package/views/layout/prompt.hbs +62 -0
  71. package/views/mcp/authorize.hbs +136 -0
  72. package/views/partials/head_assets.hbs +3 -3
  73. package/views/partials/mcp_access_levels.hbs +13 -0
  74. package/views/partials/mcp_account_limit.hbs +14 -0
  75. package/views/partials/mcp_tool_count.hbs +19 -0
  76. package/views/partials/side_menu.hbs +1 -0
  77. package/views/partials/ui/account-picker.hbs +59 -0
  78. package/views/partials/ui/code-block.hbs +26 -0
  79. package/views/partials/ui/menu-item.hbs +5 -0
  80. package/views/partials/ui/radio.hbs +41 -0
  81. package/views/partials/ui/tab.hbs +15 -10
  82. package/views/partials/ui/tabs.hbs +8 -5
  83. package/views/templates/template.hbs +4 -3
  84. package/views/tokens/index.hbs +8 -2
  85. package/views/tokens/new.hbs +514 -243
  86. package/winconf.js +148 -48
  87. package/workers/api.js +198 -48
@@ -415,19 +415,18 @@ class IMAPClient extends BaseClient {
415
415
  await commandClient.connect();
416
416
  commandClient.log.info({ msg: 'Command channel connected', cid: commandCid, channel: 'command', account: this.account });
417
417
  } catch (err) {
418
- if (this.connections.delete(commandClient)) {
419
- await this.redis.hSetExists(this.getAccountKey(), 'connections', this.connections.size.toString());
420
- }
418
+ // untrackConnection() swallows its own Redis failure, so the connect error is
419
+ // what the caller sees - a hiccup while updating the count must not replace it
420
+ await this.untrackConnection(commandClient);
421
421
  commandClient.log.warn({ msg: 'Failed to connect command client', cid: commandCid, channel: 'command', account: this.account, err });
422
422
  throw err;
423
423
  }
424
424
 
425
- // Clean up when connection closes
425
+ // Clean up when connection closes. EventEmitter never observes what an async listener
426
+ // returns, so nothing in this body may escape - see the primary connection's handler
426
427
  commandClient.on('close', async () => {
427
428
  try {
428
- if (this.connections.delete(commandClient)) {
429
- await this.redis.hSetExists(this.getAccountKey(), 'connections', this.connections.size.toString());
430
- }
429
+ await this.untrackConnection(commandClient);
431
430
  commandClient.log.info({ msg: 'Connection closed', cid: commandCid, channel: 'command', account: this.account });
432
431
  } catch (err) {
433
432
  this.logger.error({ msg: 'Error in command client close handler', cid: commandCid, account: this.account, err });
@@ -1663,81 +1662,88 @@ class IMAPClient extends BaseClient {
1663
1662
  metricsMeta({}, this.logger, 'imapBytesReceived', 'inc', imapStats.received);
1664
1663
  });
1665
1664
 
1666
- // Handle connection close events
1665
+ // Handle connection close events. EventEmitter never observes what an async
1666
+ // listener returns, so anything that escapes this body becomes an unhandled
1667
+ // rejection and takes the whole worker down. The steps below carry their own
1668
+ // catches; this outer one is what keeps that true for an await added outside them.
1667
1669
  imapClient.on('close', async () => {
1668
- await this.untrackConnection(imapClient);
1669
- imapClient?.log.info({ msg: 'Connection closed', type: 'imapClient', account: this.account, disabled: imapClient.disabled });
1670
+ try {
1671
+ await this.untrackConnection(imapClient);
1672
+ imapClient?.log.info({ msg: 'Connection closed', type: 'imapClient', account: this.account, disabled: imapClient.disabled });
1670
1673
 
1671
- // Update state on unexpected disconnect
1672
- if (['init', 'connecting', 'syncing', 'connected'].includes(this.state)) {
1673
- this.state = 'disconnected';
1674
- try {
1675
- await this.setStateVal();
1676
- await emitChangeEvent(this.logger, this.account, 'state', this.state);
1677
- } catch (err) {
1678
- this.logger.error({ msg: 'Failed to update state on connection close', account: this.account, err });
1674
+ // Update state on unexpected disconnect
1675
+ if (['init', 'connecting', 'syncing', 'connected'].includes(this.state)) {
1676
+ this.state = 'disconnected';
1677
+ try {
1678
+ await this.setStateVal();
1679
+ await emitChangeEvent(this.logger, this.account, 'state', this.state);
1680
+ } catch (err) {
1681
+ this.logger.error({ msg: 'Failed to update state on connection close', account: this.account, err });
1682
+ }
1679
1683
  }
1680
- }
1681
1684
 
1682
- try {
1683
- // Handle cleanup for all mailboxes
1684
- for (let [, mailbox] of this.mailboxes) {
1685
- if (mailbox.syncing) {
1686
- try {
1687
- // set failure flag
1688
- await this.redis.hSetNew(
1689
- this.getAccountKey(),
1690
- 'syncError',
1691
- JSON.stringify({
1692
- path: mailbox.path,
1693
- time: new Date().toISOString(),
1694
- error: {
1695
- error: 'Connection closed unexpectedly'
1696
- }
1697
- })
1698
- );
1699
- } catch (err) {
1700
- // ignore
1685
+ try {
1686
+ // Handle cleanup for all mailboxes
1687
+ for (let [, mailbox] of this.mailboxes) {
1688
+ if (mailbox.syncing) {
1689
+ try {
1690
+ // set failure flag
1691
+ await this.redis.hSetNew(
1692
+ this.getAccountKey(),
1693
+ 'syncError',
1694
+ JSON.stringify({
1695
+ path: mailbox.path,
1696
+ time: new Date().toISOString(),
1697
+ error: {
1698
+ error: 'Connection closed unexpectedly'
1699
+ }
1700
+ })
1701
+ );
1702
+ } catch (err) {
1703
+ // ignore
1704
+ }
1701
1705
  }
1702
- }
1703
1706
 
1704
- if (mailbox.selected) {
1705
- // should be at most one though
1706
- await mailbox.onClose();
1707
+ if (mailbox.selected) {
1708
+ // should be at most one though
1709
+ await mailbox.onClose();
1710
+ }
1707
1711
  }
1712
+ } catch (err) {
1713
+ imapClient.log.error({ msg: 'Connection close error', err });
1708
1714
  }
1709
- } catch (err) {
1710
- imapClient.log.error({ msg: 'Connection close error', err });
1711
- }
1712
1715
 
1713
- try {
1714
- // Attempt reconnection if this was an unexpected close
1715
- if (!imapClient.disabled && imapClient === this.imapClient && !this._connecting) {
1716
- if (this.validateConnectionAge(imapClient)) {
1717
- // A proven-stable connection dropped - reconnect right away
1718
- if (!this.reconnectTimer) {
1719
- imapClient.log.debug({ msg: 'Requesting reconnection due to unexpected close', type: 'imapClient', account: this.account });
1720
- await this.reconnect();
1716
+ try {
1717
+ // Attempt reconnection if this was an unexpected close
1718
+ if (!imapClient.disabled && imapClient === this.imapClient && !this._connecting) {
1719
+ if (this.validateConnectionAge(imapClient)) {
1720
+ // A proven-stable connection dropped - reconnect right away
1721
+ if (!this.reconnectTimer) {
1722
+ imapClient.log.debug({ msg: 'Requesting reconnection due to unexpected close', type: 'imapClient', account: this.account });
1723
+ await this.reconnect();
1724
+ }
1725
+ } else {
1726
+ // The connection died soon after it was set up. An
1727
+ // immediate retry against a server that drops
1728
+ // connections right after setup turns into an
1729
+ // unthrottled login loop (the setup itself
1730
+ // "succeeds", so the sync-reset backoffs never
1731
+ // grow), so schedule the reconnect with a growing
1732
+ // delay instead
1733
+ this.scheduleReconnect(this.closeReconnectBackoff, 'Throttling reconnection of a short-lived connection');
1721
1734
  }
1722
- } else {
1723
- // The connection died soon after it was set up. An
1724
- // immediate retry against a server that drops
1725
- // connections right after setup turns into an
1726
- // unthrottled login loop (the setup itself
1727
- // "succeeds", so the sync-reset backoffs never
1728
- // grow), so schedule the reconnect with a growing
1729
- // delay instead
1730
- this.scheduleReconnect(this.closeReconnectBackoff, 'Throttling reconnection of a short-lived connection');
1731
1735
  }
1736
+ } catch (err) {
1737
+ // This is the only path that re-arms the connection after an unexpected close.
1738
+ // If it throws, nothing else reconnects the account, so it stays offline until
1739
+ // the worker restarts - never demote this below error.
1740
+ imapClient.log.error({ msg: 'Reconnection error', account: this.account, err });
1732
1741
  }
1733
1742
  } catch (err) {
1734
- // This is the only path that re-arms the connection after an unexpected close.
1735
- // If it throws, nothing else reconnects the account, so it stays offline until
1736
- // the worker restarts - never demote this below error.
1737
- imapClient.log.error({ msg: 'Reconnection error', account: this.account, err });
1743
+ this.logger.error({ msg: 'Failed to process connection close', account: this.account, err });
1744
+ } finally {
1745
+ imapClient = null;
1738
1746
  }
1739
-
1740
- imapClient = null;
1741
1747
  });
1742
1748
 
1743
1749
  try {
@@ -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');
@@ -238,6 +238,18 @@ class OutlookClient extends BaseClient {
238
238
  await this.setStateVal();
239
239
 
240
240
  await this.getAccount();
241
+
242
+ // The auth-failure safety net switches an account off by setting `imap.disabled`, and
243
+ // an API-backed account reaches it the same way an IMAP one does - its failures run
244
+ // through the same setErrorState(). Checked before any credential work, because the
245
+ // work that keeps failing for these accounts is the token refresh below.
246
+ if (await this.isSyncDisabled()) {
247
+ this.logger.info({ msg: 'Skipped connection setup', account: this.account, reason: 'disabled' });
248
+ this.state = 'unset';
249
+ await this.setStateVal();
250
+ return;
251
+ }
252
+
241
253
  await this.getClient(true);
242
254
  await this.prepareDelegatedAccount();
243
255
 
@@ -1603,11 +1615,7 @@ class OutlookClient extends BaseClient {
1603
1615
  async getMessage(emailId, options) {
1604
1616
  options = options || {};
1605
1617
 
1606
- if (options.webSafeHtml) {
1607
- options.textType = '*';
1608
- options.embedAttachedImages = true;
1609
- options.preProcessHtml = true;
1610
- }
1618
+ applyWebSafeHtmlOptions(options);
1611
1619
 
1612
1620
  await this.prepare();
1613
1621
 
@@ -1737,6 +1745,7 @@ class OutlookClient extends BaseClient {
1737
1745
  extended: true,
1738
1746
  path,
1739
1747
  textType: options.textType,
1748
+ maxBytes: options.maxBytes,
1740
1749
  showPath: options.showPath
1741
1750
  });
1742
1751
 
@@ -1762,11 +1771,12 @@ class OutlookClient extends BaseClient {
1762
1771
  // Embed attached images as data URLs
1763
1772
  if (options.embedAttachedImages && formattedMessage.text?.html && formattedMessage.attachments) {
1764
1773
  let attachmentMap = new Map();
1774
+ let cidReferences = collectCidReferences(formattedMessage.text.html);
1765
1775
 
1766
1776
  // Collect all referenced inline attachments
1767
1777
  for (let attachment of formattedMessage.attachments) {
1768
1778
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
1769
- if (contentId && !attachmentMap.has(contentId) && formattedMessage.text.html.indexOf(`cid:${contentId}`) >= 0) {
1779
+ if (contentId && !attachmentMap.has(contentId) && cidReferences.has(contentId)) {
1770
1780
  attachmentMap.set(contentId, {
1771
1781
  attachment,
1772
1782
  content: await this.getAttachmentContent(attachment.id, {
@@ -1777,7 +1787,7 @@ class OutlookClient extends BaseClient {
1777
1787
  }
1778
1788
 
1779
1789
  // Replace cid: references with data URLs
1780
- formattedMessage.text.html = formattedMessage.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1790
+ formattedMessage.text.html = formattedMessage.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1781
1791
  if (attachmentMap.has(cidMatch)) {
1782
1792
  let { content } = attachmentMap.get(cidMatch);
1783
1793
  if (content.content) {
@@ -1965,6 +1975,7 @@ class OutlookClient extends BaseClient {
1965
1975
  extended: true,
1966
1976
  path,
1967
1977
  textType: options.textType,
1978
+ maxBytes: options.maxBytes,
1968
1979
  showPath: options.showPath
1969
1980
  });
1970
1981
 
@@ -2104,7 +2115,7 @@ class OutlookClient extends BaseClient {
2104
2115
  }
2105
2116
  }
2106
2117
 
2107
- response.hasMore = false;
2118
+ response.hasMore = truncateTextContents(response, options.maxBytes);
2108
2119
 
2109
2120
  return response;
2110
2121
  }
@@ -2208,6 +2219,7 @@ class OutlookClient extends BaseClient {
2208
2219
  case 'attachments': {
2209
2220
  messageUploadObj.attachments = [];
2210
2221
  let attachmentCounter = 0;
2222
+ let cidReferences = collectCidReferences(emailObject.html);
2211
2223
  for (let attachment of emailObject.attachments || []) {
2212
2224
  let attachmentEntry = {
2213
2225
  '@odata.type': '#microsoft.graph.fileAttachment'
@@ -2225,7 +2237,7 @@ class OutlookClient extends BaseClient {
2225
2237
  if (attachment.cid) {
2226
2238
  // make sure that cid links to not use <content-id> format, otherwise this will be replaced
2227
2239
  attachmentEntry.contentId = attachment.cid.replace(/^[\s<]*|[\s>]*$/g, '');
2228
- if (emailObject.html?.indexOf(attachmentEntry.contentId) >= 0) {
2240
+ if (cidReferences.has(attachmentEntry.contentId)) {
2229
2241
  attachmentEntry.isInline = true;
2230
2242
  emailObject.html.replace(new RegExp(`cid:<${attachment.cid}>`, 'g'), `cid:${attachment.cid}`);
2231
2243
  }
@@ -3714,7 +3726,7 @@ class OutlookClient extends BaseClient {
3714
3726
  * Handles all message properties and attachments
3715
3727
  */
3716
3728
  formatMessage(messageData, options) {
3717
- let { extended, path, textType, showPath, minimalFields } = options || {};
3729
+ let { extended, path, textType, maxBytes, showPath, minimalFields } = options || {};
3718
3730
 
3719
3731
  let date = messageData.receivedDateTime ? new Date(messageData.receivedDateTime) : undefined;
3720
3732
  if (date?.toString() === 'Invalid Date') {
@@ -3784,6 +3796,8 @@ class OutlookClient extends BaseClient {
3784
3796
  }
3785
3797
  }
3786
3798
 
3799
+ const textHasMore = truncateTextContents(textContents, maxBytes);
3800
+
3787
3801
  let message = {
3788
3802
  id: messageData.id,
3789
3803
 
@@ -3822,7 +3836,7 @@ class OutlookClient extends BaseClient {
3822
3836
  encodedSize: encodedTextSize,
3823
3837
  plain: textContents?.plain?.toString(),
3824
3838
  html: textContents?.html?.toString(),
3825
- hasMore: textContents?.plain || textContents?.html ? false : undefined
3839
+ hasMore: textContents?.plain || textContents?.html ? textHasMore : undefined
3826
3840
  },
3827
3841
 
3828
3842
  preview: messageData.bodyPreview
@@ -3835,6 +3849,7 @@ class OutlookClient extends BaseClient {
3835
3849
 
3836
3850
  // Process attachments
3837
3851
  if (messageData.attachments?.length) {
3852
+ let cidReferences = collectCidReferences(message.text.html);
3838
3853
  message.attachments = messageData.attachments.map(entry => {
3839
3854
  const attachment = {
3840
3855
  // Encode both message ID and attachment ID for later retrieval
@@ -3852,7 +3867,7 @@ class OutlookClient extends BaseClient {
3852
3867
  // Normalize content ID format
3853
3868
  attachment.contentId = entry.contentId.replace(/^<*/, '<').replace(/>*$/, '>');
3854
3869
  // Check if attachment is embedded in HTML
3855
- if (textContents?.html?.indexOf(`cid:${attachment.contentId.replace(/^[\s<]*|[\s>]*$/g, '')}`) >= 0) {
3870
+ if (cidReferences.has(attachment.contentId.replace(/^[\s<]*|[\s>]*$/g, ''))) {
3856
3871
  attachment.embedded = true;
3857
3872
  }
3858
3873
  }
@@ -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' +
package/lib/logger.js CHANGED
@@ -59,6 +59,14 @@ const FATAL_EXIT_CODES = {
59
59
  unhandledRejection: 2
60
60
  };
61
61
 
62
+ // How long the process stays alive after a fatal error before the exit lands. This is not the
63
+ // error-tracking delivery window - lib/sentry.js installs notifyError and flushNotifications
64
+ // together, so whenever there is a report to deliver its own Sentry.flush() promise already
65
+ // covers it. What this covers is Node's: a handler that arrives a microtask after a rejection was
66
+ // reported raises 'rejectionHandled' a turn later, and without a timer the exit beats it (see the
67
+ // listener at the bottom of this file). Tune it against event-loop turns, not network latency.
68
+ const FATAL_EXIT_GRACE = 10;
69
+
62
70
  // An error that reaches the global handlers leaves the process in an unknown state,
63
71
  // so the process must always exit. If error tracking is enabled, report the error
64
72
  // first and allow a short flush window for the delivery. The report is tagged with
@@ -70,11 +78,17 @@ function fatalShutdown(handler, err) {
70
78
  logger.notifyError(err, { level: 'fatal', tags: { handler } });
71
79
  }
72
80
 
73
- let exit = () => process.exit(FATAL_EXIT_CODES[handler]);
81
+ // The exit is always taken a timer turn later, never straight off the flush promise. Node
82
+ // decides a rejection went unhandled at the end of the tick it settled in and only emits
83
+ // 'rejectionHandled' once a handler turns up after that, so exiting from a resolved flush's
84
+ // microtask races the event away - and it did, on exactly the installations that have error
85
+ // tracking switched on and therefore report the most crashes.
86
+ let exit = () => setTimeout(() => process.exit(FATAL_EXIT_CODES[handler]), FATAL_EXIT_GRACE);
87
+
74
88
  if (logger.flushNotifications) {
75
89
  logger.flushNotifications().then(exit, exit);
76
90
  } else {
77
- setTimeout(exit, 10);
91
+ exit();
78
92
  }
79
93
  }
80
94
 
@@ -88,14 +102,40 @@ process.on('uncaughtException', err => {
88
102
  fatalShutdown('uncaughtException', err);
89
103
  });
90
104
 
91
- process.on('unhandledRejection', err => {
105
+ // Promises that already reached the handler below, so a late handler can be recognised. Weak
106
+ // keys, because the entry is only ever looked up from the promise Node hands back.
107
+ const reportedRejections = new WeakMap();
108
+
109
+ process.on('unhandledRejection', (err, promise) => {
92
110
  logger.fatal({
93
111
  msg: 'unhandledRejection',
94
112
  _msg: 'unhandledRejection',
95
113
  err
96
114
  });
97
115
 
116
+ reportedRejections.set(promise, Date.now());
117
+
98
118
  fatalShutdown('unhandledRejection', err);
99
119
  });
100
120
 
121
+ // Node decides a rejection is unhandled at the end of the tick it settled in, so a handler that
122
+ // arrives one microtask late still counts as unhandled. Such a handler fires 'rejectionHandled'
123
+ // afterwards, and fatalShutdown() always leaves FATAL_EXIT_GRACE before the exit lands, so the
124
+ // event has time to arrive. The worker still dies either way - a rejection that escaped is a bug
125
+ // wherever it came from - but this line is the difference between a genuinely missing catch and a
126
+ // handler that lost a race, which is otherwise impossible to tell apart from a crash log.
127
+ process.on('rejectionHandled', promise => {
128
+ let reportedAt = reportedRejections.get(promise);
129
+ if (!reportedAt) {
130
+ return;
131
+ }
132
+ reportedRejections.delete(promise);
133
+
134
+ logger.fatal({
135
+ msg: 'unhandledRejection was handled after it was reported',
136
+ _msg: 'unhandledRejection was handled after it was reported',
137
+ delay: Date.now() - reportedAt
138
+ });
139
+ });
140
+
101
141
  module.exports = logger;
@@ -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 };