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
package/lib/account.js CHANGED
@@ -14,7 +14,8 @@ const {
14
14
  isEmail,
15
15
  resolveDelegatedAccount,
16
16
  escapeRedisGlob,
17
- getMailboxStatusKey
17
+ getMailboxStatusKey,
18
+ cidReferenceRegex
18
19
  } = require('./tools');
19
20
  const { MessageChannel } = require('worker_threads');
20
21
  const { MessagePortReadable } = require('./message-port-stream');
@@ -33,7 +34,7 @@ const Lock = require('ioredfour');
33
34
  const { redis } = require('./db');
34
35
  const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
35
36
  const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY } = require('./consts');
36
- const { messageWebSafeHtml } = require('./web-safe-html');
37
+ const { messageWebSafeHtml, webSafeTextResponse, applyWebSafeHtmlOptions } = require('./web-safe-html');
37
38
  const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
38
39
  const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
39
40
  const { decodeStoredMailboxEntry } = require('./email-client/imap/listing-diff');
@@ -163,6 +164,22 @@ class Account {
163
164
  return !!accountData.smtp;
164
165
  }
165
166
 
167
+ /**
168
+ * Lists accounts, filtered by state and by a substring search.
169
+ *
170
+ * The provider enrichment below is not optional, however little of it a caller reads: it
171
+ * resolves each account's OAuth2 app, and `isApi` falls out of that. getDisplayState() reads
172
+ * `isApi` to decide whether a stored state can be trusted when the run index is behind, so an
173
+ * API account listed without it reports `init` rather than what it is actually doing. A "lean"
174
+ * listing that skipped the loop was tried and reverted for exactly that: it made the cheap
175
+ * fields cheaper and the one field every caller renders wrong.
176
+ *
177
+ * @param {String|Array} state - state filter, 'errors' for every attention state, falsy for all
178
+ * @param {String} query - substring matched against account id, name and address
179
+ * @param {Number} page - zero-based page
180
+ * @param {Number} limit - page size
181
+ * @returns {Promise<Object>} `{ total, pages, page, query, state, accounts }`
182
+ */
166
183
  async listAccounts(state, query, page, limit) {
167
184
  limit = Number(limit) || 20;
168
185
  page = Math.max(Number(page) || 0, 0);
@@ -179,7 +196,19 @@ class Account {
179
196
  }
180
197
  let filterState = Array.isArray(state) ? state.join(',') : state || '*';
181
198
 
182
- let result = await this.redis.sListAccounts(`${REDIS_PREFIX}ia:accounts`, filterState, skip, limit, `${REDIS_PREFIX}`, query);
199
+ // The search is a plain substring match against the lowercased fields, and two things about
200
+ // that were left to the caller to get right:
201
+ //
202
+ // - the needle was passed through as typed, so anything with a capital in it matched
203
+ // nothing at all - on a search box, the account you can see is the one you cannot find.
204
+ // The script folds the needle too, so any caller gets a case-insensitive search; this
205
+ // fold is the one that also covers non-ASCII, which string.lower() leaves alone.
206
+ // - "no search" was spelled `false` by some callers, and ioredis sends that as the string
207
+ // "false", which the script then dutifully searched for. Anything that is not a string
208
+ // is one of those, and means no search.
209
+ let search = typeof query === 'string' ? query.toLowerCase() : '';
210
+
211
+ let result = await this.redis.sListAccounts(`${REDIS_PREFIX}ia:accounts`, filterState, skip, limit, `${REDIS_PREFIX}`, search);
183
212
 
184
213
  let accounts = result[2].map(formatAccountListingResponse).map(this.unserializeAccountData.bind(this));
185
214
  let oauthApps = new Map();
@@ -1018,6 +1047,14 @@ class Account {
1018
1047
  account: this.account,
1019
1048
  state: oldAccountData.state
1020
1049
  });
1050
+
1051
+ // A reconnect cannot resume an account that the auth-failure safety net has switched
1052
+ // off, so lift that first. For a password account the operator clears the flag by
1053
+ // saving new IMAP settings, but an OAuth2 account has no IMAP settings to save - the
1054
+ // re-authorization IS the fix, and without this the account would stay off until
1055
+ // somebody hand-edited it through the API.
1056
+ await this.clearAuthFailureDisable();
1057
+
1021
1058
  if (typeof this.call === 'function') {
1022
1059
  try {
1023
1060
  await this.call({
@@ -1060,6 +1097,41 @@ class Account {
1060
1097
  return id;
1061
1098
  }
1062
1099
 
1100
+ /**
1101
+ * Re-enables an account that setErrorState() switched off after a run of authentication
1102
+ * failures. Called when fresh credentials arrive for an account in an error state.
1103
+ *
1104
+ * Reads the stored value rather than trusting the copy loaded before the update, because the
1105
+ * same update may have rewritten the `imap` field.
1106
+ *
1107
+ * @returns {Promise<Boolean>} True when a disable flag was actually lifted
1108
+ */
1109
+ async clearAuthFailureDisable() {
1110
+ let imapInfo = await this.redis.hget(this.getAccountKey(), 'imap');
1111
+ if (!imapInfo) {
1112
+ return false;
1113
+ }
1114
+
1115
+ let imapData;
1116
+ try {
1117
+ imapData = JSON.parse(imapInfo);
1118
+ } catch (err) {
1119
+ this.logger.error({ msg: 'Failed parsing IMAP data', account: this.account, err });
1120
+ return false;
1121
+ }
1122
+
1123
+ if (!imapData || !imapData.disabled) {
1124
+ return false;
1125
+ }
1126
+
1127
+ imapData.disabled = false;
1128
+ await this.redis.hset(this.getAccountKey(), 'imap', JSON.stringify(imapData));
1129
+
1130
+ this.logger.info({ msg: 'Re-enabled IMAP for account after re-authorization', account: this.account });
1131
+
1132
+ return true;
1133
+ }
1134
+
1063
1135
  async create(accountData) {
1064
1136
  this.account = accountData.account;
1065
1137
  if (this.account === null) {
@@ -1730,6 +1802,13 @@ class Account {
1730
1802
  }
1731
1803
 
1732
1804
  async getText(text, options) {
1805
+ if (options.webSafeHtml) {
1806
+ // Both bodies are needed to build the web-safe rendering: the generator falls back to
1807
+ // the plaintext part when the message carries no HTML one, and the thread-collapse
1808
+ // analysis reads whichever of the two the extractor picks.
1809
+ options = Object.assign({}, options, { textType: '*' });
1810
+ }
1811
+
1733
1812
  if (options.documentStore && (await isDocumentStoreEnabled())) {
1734
1813
  await this.loadAccountData(this.account, false);
1735
1814
 
@@ -1764,7 +1843,7 @@ class Account {
1764
1843
  }
1765
1844
  }
1766
1845
 
1767
- return response;
1846
+ return this.textResponse(response, options);
1768
1847
  }
1769
1848
 
1770
1849
  await this.loadAccountData(this.account, true);
@@ -1778,15 +1857,17 @@ class Account {
1778
1857
  });
1779
1858
 
1780
1859
  // IMAP backend returns false for unknown messages and folders
1781
- return this.assertMessageFound(textData);
1860
+ return this.textResponse(this.assertMessageFound(textData), options);
1861
+ }
1862
+
1863
+ // The one exit of getText(), so the document-store branch and the live one cannot answer a
1864
+ // webSafeHtml request differently
1865
+ async textResponse(textData, options) {
1866
+ return options.webSafeHtml ? webSafeTextResponse(textData) : textData;
1782
1867
  }
1783
1868
 
1784
1869
  async getMessage(message, options) {
1785
- if (options.webSafeHtml) {
1786
- options.textType = '*';
1787
- options.embedAttachedImages = true;
1788
- options.preProcessHtml = true;
1789
- }
1870
+ applyWebSafeHtmlOptions(options);
1790
1871
 
1791
1872
  if (options.documentStore && (await isDocumentStoreEnabled())) {
1792
1873
  await this.loadAccountData(this.account, false);
@@ -1854,15 +1935,28 @@ class Account {
1854
1935
  }
1855
1936
 
1856
1937
  if (options.embedAttachedImages && messageData.text && messageData.text.html && messageData.attachments && messageData.attachments.length) {
1857
- let attachmentsToDownload = [];
1938
+ // map both content id forms (bare and <bracketed>) to the first attachment carrying them,
1939
+ // so the passes below cost one lookup per reference instead of a scan of all attachments
1940
+ let attachmentsByContentId = new Map();
1941
+ for (let attachment of messageData.attachments) {
1942
+ if (!attachment.contentId) {
1943
+ continue;
1944
+ }
1945
+ for (let key of [attachment.contentId, attachment.contentId.replace(/^<(.*)>$/, '$1')]) {
1946
+ if (!attachmentsByContentId.has(key)) {
1947
+ attachmentsByContentId.set(key, attachment);
1948
+ }
1949
+ }
1950
+ }
1858
1951
 
1859
1952
  // first pass, find attachments to inline
1860
- messageData.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1861
- let attachment = messageData.attachments.find(attachment => [`<${cidMatch}>`, cidMatch].includes(attachment.contentId));
1953
+ let attachmentsToDownload = new Set();
1954
+ for (let match of messageData.text.html.matchAll(cidReferenceRegex())) {
1955
+ let attachment = attachmentsByContentId.get(match[1]);
1862
1956
  if (attachment && !attachment.content) {
1863
- attachmentsToDownload.push(attachment);
1957
+ attachmentsToDownload.add(attachment);
1864
1958
  }
1865
- });
1959
+ }
1866
1960
 
1867
1961
  // download large inline attachments not stored in ES
1868
1962
  for (let attachment of attachmentsToDownload) {
@@ -1885,8 +1979,8 @@ class Account {
1885
1979
  }
1886
1980
 
1887
1981
  // second pass, replace placeholders with inline attachments
1888
- messageData.text.html = messageData.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1889
- let attachment = messageData.attachments.find(attachment => [`<${cidMatch}>`, cidMatch].includes(attachment.contentId));
1982
+ messageData.text.html = messageData.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1983
+ let attachment = attachmentsByContentId.get(cidMatch);
1890
1984
  if (attachment && attachment.content) {
1891
1985
  return `data:${attachment.contentType || 'application/octet-stream'};base64,${attachment.content}`;
1892
1986
  }
@@ -3042,4 +3136,30 @@ async function accountsExist(redis, accounts) {
3042
3136
  return new Map(accounts.map((account, i) => [account, values[i] === 1]));
3043
3137
  }
3044
3138
 
3045
- module.exports = { Account, accountExists, accountsExist };
3139
+ /**
3140
+ * The display fields of one account, without loading or decrypting anything.
3141
+ *
3142
+ * What a form that already holds an account id needs in order to show it back as something a
3143
+ * person recognises: a name, an address and a connection state. loadAccountData() answers the same
3144
+ * question by reading and decrypting the whole record, which is a lot of work for three strings on
3145
+ * a page that is not about that account.
3146
+ *
3147
+ * @param {Object} redis - Redis client
3148
+ * @param {String} account - Account ID
3149
+ * @returns {Promise<Object|null>} `{ account, name, email, state }`, or null when no such account exists
3150
+ */
3151
+ async function accountSummary(redis, account) {
3152
+ if (!account) {
3153
+ return null;
3154
+ }
3155
+
3156
+ // `account` is the existence marker (see accountExists); the rest are optional on a record
3157
+ let [exists, name, email, state] = await redis.hmget(`${REDIS_PREFIX}iad:${account}`, 'account', 'name', 'email', 'state');
3158
+ if (!exists) {
3159
+ return null;
3160
+ }
3161
+
3162
+ return { account, name: name || '', email: email || '', state: state || 'init' };
3163
+ }
3164
+
3165
+ module.exports = { Account, accountExists, accountsExist, accountSummary };
@@ -32,7 +32,7 @@ const {
32
32
  ENUM_DESCRIPTIONS
33
33
  } = require('../schemas');
34
34
 
35
- const { REDIS_PREFIX, MAX_FORM_TTL, NONCE_BYTES } = require('../consts');
35
+ const { REDIS_PREFIX, MAX_FORM_TTL, NONCE_BYTES, MCP_MAX_PAGE_SIZE } = require('../consts');
36
36
  const BEHAVIOR = require('./behavior-notes');
37
37
  const { IMPACT } = require('./operation-impact');
38
38
  const { FIELD_USAGE } = require('../field-usage');
@@ -798,6 +798,13 @@ async function init(args) {
798
798
  tags: ['api', 'Account'],
799
799
 
800
800
  plugins: {
801
+ mcp: {
802
+ name: 'list_accounts',
803
+ title: 'List accounts',
804
+ description:
805
+ 'List the email accounts on this instance, paged. Use the returned account id as the account argument of the other tools. Check the state field: only connected accounts can be read.',
806
+ bounds: { pageSize: MCP_MAX_PAGE_SIZE }
807
+ },
801
808
  openapi: {
802
809
  responses: apiResponses('Returns a page of accounts with their connection states.', 400, 401, 403, 429, 500)
803
810
  }
@@ -1045,6 +1052,11 @@ async function init(args) {
1045
1052
  tags: ['api', 'Account'],
1046
1053
 
1047
1054
  plugins: {
1055
+ mcp: {
1056
+ name: 'get_account',
1057
+ title: 'Get account',
1058
+ description: 'Get one account: its display name, email address, connection state and sync status. Credentials are masked.'
1059
+ },
1048
1060
  openapi: {
1049
1061
  'x-ee-behavior': [BEHAVIOR.NO_QUOTA_ON_API_ACCOUNTS],
1050
1062
  responses: apiResponses('Returns the account configuration, connection state and sync status.', 400, 401, 403, 404, 429, 500)
@@ -31,6 +31,8 @@ const deliveryTestRoutes = require('./delivery-test-routes');
31
31
  const blocklistRoutes = require('./blocklist-routes');
32
32
  const submitRoutes = require('./submit-routes');
33
33
  const changesRoutes = require('./changes-routes');
34
+ const mcpRoutes = require('./mcp-routes');
35
+ const mcpOauthRoutes = require('./mcp-oauth-routes');
34
36
 
35
37
  /**
36
38
  * Registers every /v1 route module on the supplied Hapi server.
@@ -48,6 +50,7 @@ const changesRoutes = require('./changes-routes');
48
50
  * @param {Number} args.MAX_BODY_SIZE
49
51
  * @param {Number} args.MAX_PAYLOAD_TIMEOUT
50
52
  * @param {Boolean} args.documentStoreFeatureEnabled - gate for the deprecated Document Store
53
+ * @param {Boolean} args.mcpFeatureEnabled - gate for the MCP endpoint
51
54
  * @param {Object} args.oauth2Schema
52
55
  * @param {Object} args.imapSchema
53
56
  * @param {Object} args.smtpSchema
@@ -68,6 +71,7 @@ async function registerApiRoutes(args) {
68
71
  MAX_BODY_SIZE,
69
72
  MAX_PAYLOAD_TIMEOUT,
70
73
  documentStoreFeatureEnabled,
74
+ mcpFeatureEnabled,
71
75
  oauth2Schema,
72
76
  imapSchema,
73
77
  smtpSchema,
@@ -155,6 +159,14 @@ async function registerApiRoutes(args) {
155
159
 
156
160
  // setup the account state change stream (SSE)
157
161
  await changesRoutes({ server, CORS_CONFIG });
162
+
163
+ // setup the MCP endpoint and its OAuth discovery/registration/token routes (only when the
164
+ // deployment gate is on; the OAuth routes additionally answer 404 until the mcpOAuthEnabled
165
+ // setting is turned on)
166
+ if (mcpFeatureEnabled) {
167
+ await mcpRoutes({ server, CORS_CONFIG, MAX_BODY_SIZE, MAX_PAYLOAD_TIMEOUT });
168
+ await mcpOauthRoutes({ server });
169
+ }
158
170
  }
159
171
 
160
172
  module.exports = registerApiRoutes;
@@ -79,6 +79,12 @@ async function init(args) {
79
79
  tags: ['api', 'Mailbox'],
80
80
 
81
81
  plugins: {
82
+ mcp: {
83
+ name: 'list_mailboxes',
84
+ title: 'List mailboxes',
85
+ description:
86
+ 'List the folders of an account with message counts and special-use roles (Inbox, Sent, Trash and so on). Folder paths from here are what list_messages, search_messages and move_message take.'
87
+ },
82
88
  openapi: {
83
89
  responses: apiResponses(
84
90
  'Returns the account folder tree, including special-use designations and message counts.',
@@ -0,0 +1,259 @@
1
+ 'use strict';
2
+
3
+ // The public half of the MCP OAuth flow: discovery metadata (RFC 9728 protected resource
4
+ // metadata and RFC 8414 authorization server metadata), open dynamic client registration
5
+ // (RFC 7591), and the token endpoint. The consent page - the only part with a human in it -
6
+ // lives on the admin surface (lib/ui-routes/mcp-consent-routes.js).
7
+ //
8
+ // Everything here is unauthenticated by design and rate limited per IP: registration mints
9
+ // nothing but a client id that only an admin's consent can turn into a credential, and the
10
+ // token endpoint redeems single-use PKCE-bound codes. Every route answers 404 while the flow
11
+ // is unavailable (MCP disabled, the mcpOAuthEnabled setting off, or no serviceUrl to anchor
12
+ // the canonical origin on).
13
+ //
14
+ // CORS is wide open on these routes on purpose, independent of the instance's CORS setting:
15
+ // browser-based MCP clients fetch the metadata and call the token endpoint cross-origin, and
16
+ // none of these endpoints reads a cookie or serves per-user state.
17
+
18
+ const Boom = require('@hapi/boom');
19
+ const Joi = require('joi');
20
+
21
+ const { checkRateLimit } = require('../rate-limit');
22
+ const { oauthOrigin, mcpResource, registerClient, redeemAuthorizationCode, MAX_REDIRECT_URIS } = require('../mcp/oauth');
23
+
24
+ const OPEN_CORS = { origin: ['*'] };
25
+
26
+ // One OAuth-style error shape for every failure on these routes (RFC 6749 5.2)
27
+ function oauthErrorResponse(h, statusCode, error, description) {
28
+ return h.response({ error, error_description: description }).code(statusCode);
29
+ }
30
+
31
+ // Registration and token requests are unauthenticated writes, so both get a per-IP budget that
32
+ // no working client comes near: a real flow registers once and redeems one code. Checked before
33
+ // any other Redis work in the handlers, so an abusive caller costs one Redis op per request.
34
+ // lib/rate-limit directly rather than the h.checkRateLimit toolkit decoration on purpose: the
35
+ // decoration routes through a main-thread RPC, the library call is one Redis round trip, and
36
+ // both count in the same Redis buckets.
37
+ async function assertRateLimit(request, bucket, allowed) {
38
+ const limit = await checkRateLimit(`mcp:oauth:${bucket}:${request.app.ip}`, 1, allowed, 3600);
39
+ if (!limit.success) {
40
+ const ttl = Math.ceil(limit.ttl);
41
+ const err = Boom.tooManyRequests('Rate limit exceeded');
42
+ err.output.payload.ttl = ttl;
43
+ // The conventional header for a 429, so a generic HTTP client backs off without
44
+ // knowing about the ttl field in the body
45
+ err.output.headers['Retry-After'] = ttl;
46
+ throw err;
47
+ }
48
+ }
49
+
50
+ async function init(args) {
51
+ const { server } = args;
52
+
53
+ // Sends OAuth discovery at MCP clients that authenticate with nothing or with an unusable
54
+ // token: the WWW-Authenticate pointer at the protected resource metadata is how a client
55
+ // finds the authorization server (RFC 9728). Header-only, so token-authenticated clients
56
+ // never notice it.
57
+ server.ext('onPreResponse', async (request, h) => {
58
+ const response = request.response;
59
+
60
+ if (request.path !== '/mcp' || !response.isBoom || response.output.statusCode !== 401) {
61
+ return h.continue;
62
+ }
63
+
64
+ const origin = await oauthOrigin();
65
+ if (origin) {
66
+ // The exact capitalized key Boom used for the strategy's own challenge: the worker's
67
+ // preResponse extension rebuilds bearer 401s from output.headers['WWW-Authenticate'],
68
+ // so writing any other key would be dropped in the rebuild. The strategy's challenge
69
+ // params (error="...") are kept - a client debugging a bad token needs both.
70
+ const pointer = `resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"`;
71
+ const existing = response.output.headers['WWW-Authenticate'];
72
+ response.output.headers['WWW-Authenticate'] =
73
+ typeof existing === 'string' && /^Bearer\s+\S/.test(existing) ? `${existing}, ${pointer}` : `Bearer ${pointer}`;
74
+ }
75
+
76
+ return h.continue;
77
+ });
78
+
79
+ // RFC 9728: served both at the path-suffixed location clients derive from the resource URI
80
+ // (/mcp) and at the root for clients that use the bare origin as the resource identifier
81
+ server.route({
82
+ method: 'GET',
83
+ path: '/.well-known/oauth-protected-resource/{suffix?}',
84
+
85
+ async handler(request) {
86
+ if (request.params.suffix && request.params.suffix !== 'mcp') {
87
+ throw Boom.notFound();
88
+ }
89
+
90
+ const origin = await oauthOrigin();
91
+ if (!origin) {
92
+ throw Boom.notFound();
93
+ }
94
+
95
+ return {
96
+ resource: mcpResource(origin),
97
+ authorization_servers: [origin],
98
+ scopes_supported: ['mcp'],
99
+ bearer_methods_supported: ['header'],
100
+ resource_name: 'EmailEngine MCP'
101
+ };
102
+ },
103
+
104
+ options: {
105
+ description: 'MCP OAuth protected resource metadata',
106
+ tags: ['external'],
107
+ auth: false,
108
+ cors: OPEN_CORS
109
+ }
110
+ });
111
+
112
+ server.route({
113
+ method: 'GET',
114
+ path: '/.well-known/oauth-authorization-server',
115
+
116
+ async handler() {
117
+ const origin = await oauthOrigin();
118
+ if (!origin) {
119
+ throw Boom.notFound();
120
+ }
121
+
122
+ return {
123
+ issuer: origin,
124
+ authorization_endpoint: `${origin}/admin/mcp/authorize`,
125
+ token_endpoint: `${origin}/mcp/oauth/token`,
126
+ registration_endpoint: `${origin}/mcp/oauth/register`,
127
+ response_types_supported: ['code'],
128
+ grant_types_supported: ['authorization_code'],
129
+ code_challenge_methods_supported: ['S256'],
130
+ token_endpoint_auth_methods_supported: ['none'],
131
+ scopes_supported: ['mcp'],
132
+ authorization_response_iss_parameter_supported: true
133
+ };
134
+ },
135
+
136
+ options: {
137
+ description: 'MCP OAuth authorization server metadata',
138
+ tags: ['external'],
139
+ auth: false,
140
+ cors: OPEN_CORS
141
+ }
142
+ });
143
+
144
+ server.route({
145
+ method: 'POST',
146
+ path: '/mcp/oauth/register',
147
+
148
+ async handler(request, h) {
149
+ await assertRateLimit(request, 'register', 20);
150
+
151
+ if (!(await oauthOrigin())) {
152
+ throw Boom.notFound();
153
+ }
154
+
155
+ try {
156
+ const client = await registerClient({
157
+ redirectUris: request.payload.redirect_uris,
158
+ clientName: request.payload.client_name
159
+ });
160
+ return h.response(client).code(201);
161
+ } catch (err) {
162
+ if (err.oauthError) {
163
+ return oauthErrorResponse(h, 400, err.oauthError, err.message);
164
+ }
165
+ throw err;
166
+ }
167
+ },
168
+
169
+ options: {
170
+ description: 'MCP OAuth dynamic client registration',
171
+ tags: ['external'],
172
+ auth: false,
173
+ cors: OPEN_CORS,
174
+
175
+ payload: {
176
+ maxBytes: 64 * 1024,
177
+ allow: ['application/json']
178
+ },
179
+
180
+ validate: {
181
+ payload: Joi.object({
182
+ redirect_uris: Joi.array().items(Joi.string().max(2048)).min(1).max(MAX_REDIRECT_URIS).required(),
183
+ client_name: Joi.string().max(1024),
184
+ token_endpoint_auth_method: Joi.string().valid('none'),
185
+ grant_types: Joi.array().items(Joi.string().max(64)).max(10),
186
+ response_types: Joi.array().items(Joi.string().max(64)).max(10),
187
+ scope: Joi.string().max(1024)
188
+ }).unknown(true),
189
+
190
+ failAction: (request, h, err) =>
191
+ oauthErrorResponse(h, 400, 'invalid_client_metadata', (err && err.message) || 'Invalid client metadata').takeover()
192
+ }
193
+ }
194
+ });
195
+
196
+ server.route({
197
+ method: 'POST',
198
+ path: '/mcp/oauth/token',
199
+
200
+ async handler(request, h) {
201
+ await assertRateLimit(request, 'token', 60);
202
+
203
+ const origin = await oauthOrigin();
204
+ if (!origin) {
205
+ throw Boom.notFound();
206
+ }
207
+
208
+ if (request.payload.grant_type !== 'authorization_code') {
209
+ return oauthErrorResponse(h, 400, 'unsupported_grant_type', 'Only authorization_code is supported');
210
+ }
211
+
212
+ try {
213
+ const tokenResponse = await redeemAuthorizationCode({
214
+ code: request.payload.code,
215
+ clientId: request.payload.client_id,
216
+ redirectUri: request.payload.redirect_uri,
217
+ codeVerifier: request.payload.code_verifier,
218
+ resource: request.payload.resource,
219
+ origin,
220
+ ip: request.app.ip
221
+ });
222
+
223
+ return h.response(tokenResponse).header('Cache-Control', 'no-store').header('Pragma', 'no-cache');
224
+ } catch (err) {
225
+ if (err.oauthError) {
226
+ return oauthErrorResponse(h, 400, err.oauthError, err.message);
227
+ }
228
+ throw err;
229
+ }
230
+ },
231
+
232
+ options: {
233
+ description: 'MCP OAuth token endpoint',
234
+ tags: ['external'],
235
+ auth: false,
236
+ cors: OPEN_CORS,
237
+
238
+ payload: {
239
+ maxBytes: 64 * 1024,
240
+ allow: ['application/x-www-form-urlencoded', 'application/json']
241
+ },
242
+
243
+ validate: {
244
+ payload: Joi.object({
245
+ grant_type: Joi.string().max(64).required(),
246
+ code: Joi.string().max(256),
247
+ client_id: Joi.string().max(256),
248
+ redirect_uri: Joi.string().max(2048),
249
+ code_verifier: Joi.string().max(256),
250
+ resource: Joi.string().max(2048)
251
+ }).unknown(true),
252
+
253
+ failAction: (request, h, err) => oauthErrorResponse(h, 400, 'invalid_request', (err && err.message) || 'Invalid request').takeover()
254
+ }
255
+ }
256
+ });
257
+ }
258
+
259
+ module.exports = init;