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
package/workers/api.js CHANGED
@@ -41,7 +41,8 @@ const {
41
41
  verifyServiceSignature,
42
42
  claimFormNonce,
43
43
  releaseFormNonce,
44
- setAdminSession
44
+ setAdminSession,
45
+ isEndedSession
45
46
  } = require('../lib/tools');
46
47
  const { matchIp, resolveClientIp, detectAutomatedRequest } = require('../lib/utils/network');
47
48
 
@@ -72,8 +73,11 @@ const handlebars = require('handlebars');
72
73
  const AuthBearer = require('hapi-auth-bearer-token');
73
74
  const tokens = require('../lib/tokens');
74
75
  const tokenPermissions = require('../lib/token-permissions');
76
+ const { mcpFeatureEnabled } = require('../lib/mcp');
77
+ const mcpListen = require('../lib/mcp/listen');
75
78
  const tokenAuditLog = require('../lib/token-audit-log');
76
- const { routeGrant } = require('../lib/api-routes/permission-map');
79
+ const { routeGrant, surfaceAdmits, sessionTokenAdmits } = require('../lib/api-routes/permission-map');
80
+ const { mcpOptions } = require('../lib/api-routes/route-metadata');
77
81
 
78
82
  const { redis, documentsQueue } = require('../lib/db');
79
83
  const { Account } = require('../lib/account');
@@ -240,7 +244,12 @@ const CORS_CONFIG = !CORS_ORIGINS
240
244
  )
241
245
  ) || ['*']
242
246
  ),
243
- additionalHeaders: ['X-EE-Timeout'],
247
+ // The MCP entries are what lets a browser-based MCP client reach /mcp at all: the
248
+ // modern revision mirrors the method and tool name into routing headers and carries
249
+ // the protocol version in one, so a preflight lists all four and Hapi rejects it
250
+ // unless they are allowed here (lib/mcp/protocol.js isAllowedOrigin admits the origin,
251
+ // this admits the headers).
252
+ additionalHeaders: ['X-EE-Timeout', 'MCP-Protocol-Version', 'Mcp-Method', 'Mcp-Name', 'Mcp-Session-Id'],
244
253
  additionalExposedHeaders: ['Accept'],
245
254
  preflightStatusCode: 204,
246
255
  maxAge:
@@ -439,6 +448,9 @@ parentPort.on('message', message => {
439
448
 
440
449
  if (message && message.cmd === 'change') {
441
450
  publishChangeEvent(message);
451
+ // The MCP subscriptions/listen streams ride the same fanout as the admin change feed,
452
+ // but frame the event as a JSON-RPC notification, so they keep their own registry
453
+ mcpListen.publishAccountChange(message, logger);
442
454
  }
443
455
 
444
456
  if (message && message.cmd === 'settings') {
@@ -801,8 +813,12 @@ const init = async () => {
801
813
  request.setUrl(`${url.pathname}${url.search}`);
802
814
  }
803
815
 
804
- // make license info available for the request
805
- request.app.licenseInfo = await call({ cmd: 'license', timeout: request.headers['x-ee-timeout'] });
816
+ // make license info available for the request. An MCP-dispatched inject seeds it from
817
+ // the outer request (lib/mcp/inject.js), so the IPC round trip is not paid twice for
818
+ // one answer that cannot differ within a request.
819
+ if (!request.app.licenseInfo) {
820
+ request.app.licenseInfo = await call({ cmd: 'license', timeout: request.headers['x-ee-timeout'] });
821
+ }
806
822
 
807
823
  // flash notifications
808
824
  request.flash = async message => await flash(redis, request, message);
@@ -871,27 +887,70 @@ const init = async () => {
871
887
  };
872
888
  }
873
889
 
874
- let scope = false;
890
+ // Every scope a route names admits a token that holds it. Single-scope routes behave
891
+ // exactly as before; the MCP endpoint is the one route naming two (`scope:api` and
892
+ // `scope:mcp`), so both kinds of credential can open it.
875
893
  let tags = (request.route && request.route.settings && request.route.settings.tags) || [];
876
- if (tags.includes('api')) {
877
- scope = 'api';
878
- } else {
879
- for (let tag of tags) {
880
- if (/^scope:/.test(tag)) {
881
- scope = tag.substr('scope:'.length);
882
- }
894
+ let scopes = tags.filter(tag => tag === 'api' || /^scope:/.test(tag)).map(tag => tag.replace(/^scope:/, ''));
895
+
896
+ // The MCP endpoint (lib/api-routes/mcp-routes.js) is a protocol multiplexer with no
897
+ // operation of its own: every tools/call becomes an injected API request that runs
898
+ // this whole strategy again against the route it actually targets. Several checks
899
+ // below defer to that inner request, and each says so where it does.
900
+ const mcpEndpoint = !!mcpOptions(request.route).endpoint;
901
+
902
+ // Session tokens are refused at the MCP door rather than half-admitted: a session
903
+ // credential carries no bearer token the injected inner requests could forward, so
904
+ // it could initialize and list tools but every tools/call would die on an inner 401.
905
+ if (token.startsWith('sess_') && scopes.includes('api') && !mcpEndpoint) {
906
+ // seems like a session token
907
+ const session = (request.state && request.state.ee) || {};
908
+
909
+ // "Log out all sessions" has to reach this credential too. The session strategy's
910
+ // own passwordVersion check never runs here - an API request authenticates with
911
+ // this strategy and only reads the cookie for its `sid` - and validateSessionToken()
912
+ // slides the token's TTL on every use, so a cookie-plus-token pair left behind on a
913
+ // device the operator no longer controls stayed usable indefinitely after the click
914
+ // that was supposed to end every session. Same predicate as the session strategy,
915
+ // including its "only when a local password exists" condition, so a session stamped
916
+ // before this shipped is not force-expired.
917
+ if (isEndedSession(await sessionPasswordVersion(), session)) {
918
+ logger.warn({
919
+ msg: 'Session token presented for an ended session',
920
+ account: request.params.account,
921
+ method: request.route.method,
922
+ path: request.route.path
923
+ });
924
+ throw Boom.unauthorized('Session has ended');
883
925
  }
884
- }
885
926
 
886
- if (token.startsWith('sess_') && scope === 'api') {
887
- // seems like a session token
888
- let isValidSessionToken = await tokens.validateSessionToken(
889
- request.state && request.state.ee && request.state.ee.sid,
890
- token,
891
- request.params.account,
892
- 900
893
- );
927
+ let isValidSessionToken = await tokens.validateSessionToken(session.sid, token, request.params.account, 900);
894
928
  if (isValidSessionToken) {
929
+ // A session token is bound to the account whose page minted it (checked above,
930
+ // against request.params.account), but it used to reach every api-tagged route
931
+ // naming that account - it never met the permission model at all. It lives in
932
+ // the page HTML where any script on the page can read it, which the HttpOnly
933
+ // session cookie does not, so it must not be the wider of the two credentials:
934
+ // SESSION_TOKEN_GRANTS is what the browser actually calls, and everything else
935
+ // - the account edit that rewrites a webhook target, the route that hands out
936
+ // the account's provider access token - is refused here.
937
+ if (!sessionTokenAdmits(routeGrant(request.route), { account: request.params.account })) {
938
+ logger.warn({
939
+ msg: 'Session token used outside the message browser grants',
940
+ account: request.params.account,
941
+ method: request.route.method,
942
+ path: request.route.path
943
+ });
944
+ throw Boom.forbidden('Unauthorized permission');
945
+ }
946
+
947
+ // The credential is bounded by a grant list rather than by a permissions
948
+ // record, so anything that keys off "is this token narrowed" cannot see it -
949
+ // assertNoNetworkOverride() is the one that matters, since `send/submit` is
950
+ // admitted above and a submit payload's `proxy` decides where the session
951
+ // carrying the account's SMTP credential connects.
952
+ request.app.sessionToken = true;
953
+
895
954
  return {
896
955
  isValid: true,
897
956
  credentials: {},
@@ -902,7 +961,10 @@ const init = async () => {
902
961
 
903
962
  let tokenData;
904
963
  try {
905
- tokenData = await tokens.get(token, false, { log: true, remoteAddress: request.app.ip });
964
+ // The last-use record is skipped on MCP-dispatched injects: the outer /mcp
965
+ // request just wrote the same credential's entry, and the second write would
966
+ // only repeat it
967
+ tokenData = await tokens.get(token, false, { log: !request.app.mcpInternal, remoteAddress: request.app.ip });
906
968
  } catch (err) {
907
969
  return {
908
970
  isValid: false,
@@ -947,20 +1009,35 @@ const init = async () => {
947
1009
  account: (request.params && request.params.account) || queryAccount || tokenData.account || null
948
1010
  };
949
1011
 
950
- if (scope && tokenData.scopes && !tokenData.scopes.includes(scope) && !tokenData.scopes.includes('*')) {
1012
+ // `mcp` is a surface scope like `smtp`: it admits exactly the API operations the MCP
1013
+ // tool set wraps (surfaceAdmits over SURFACE_GRANTS.mcp), and only on requests the
1014
+ // MCP endpoint dispatched itself - request.app.mcpInternal is set by
1015
+ // lib/mcp/inject.js and cannot be set from the network, so an mcp-scoped token
1016
+ // presented to plain REST is refused here like any other missing scope.
1017
+ const mcpSurfaceAdmits =
1018
+ scopes.includes('api') && tokenData.scopes && tokenData.scopes.includes('mcp') && !!request.app.mcpInternal && surfaceAdmits('mcp', grant);
1019
+
1020
+ const hasRequiredScope =
1021
+ !scopes.length ||
1022
+ !tokenData.scopes ||
1023
+ tokenData.scopes.includes('*') ||
1024
+ tokenData.scopes.some(entry => scopes.includes(entry)) ||
1025
+ mcpSurfaceAdmits;
1026
+
1027
+ if (!hasRequiredScope) {
951
1028
  // failed scope validation
952
1029
  logger.warn({
953
1030
  msg: 'Trying to use invalid scope for a token',
954
1031
  tokenAccount: tokenData.account,
955
1032
  tokenId: tokenData.id,
956
- requestedScope: scope,
1033
+ requestedScope: scopes.join(', '),
957
1034
  tokenScopes: tokenData.scopes
958
1035
  });
959
1036
 
960
1037
  tokenAuditLog.denied(auditEntry, 'scope');
961
1038
 
962
1039
  let error = Boom.forbidden('Unauthorized scope');
963
- error.output.payload.requestedScope = scope;
1040
+ error.output.payload.requestedScope = scopes.join(', ');
964
1041
  throw error;
965
1042
  }
966
1043
 
@@ -973,7 +1050,10 @@ const init = async () => {
973
1050
  //
974
1051
  // Only subtracts: a token with no `permissions` field takes the allowed path, which is
975
1052
  // every token issued before this shipped.
976
- const permissionCheck = tokenPermissions.check({ tokenData, operation: grant });
1053
+ // The MCP door defers this check: its own routeGrant() resolves to no group on
1054
+ // purpose, and the operation a narrowed token must hold a grant for is the injected
1055
+ // inner request, which re-runs this strategy with the real route.
1056
+ const permissionCheck = mcpEndpoint ? { allowed: true } : tokenPermissions.check({ tokenData, operation: grant });
977
1057
  if (!permissionCheck.allowed) {
978
1058
  logger.warn({
979
1059
  msg: 'Token permissions do not allow this operation',
@@ -994,7 +1074,13 @@ const init = async () => {
994
1074
  throw error;
995
1075
  }
996
1076
 
997
- if (tokenData.account) {
1077
+ if (tokenData.account && mcpEndpoint) {
1078
+ // The door names no account, so the binding cannot be checked here; it is
1079
+ // enforced on every injected inner request, which does name one. Parked on the
1080
+ // request so the MCP layer can seed resources/list and the agent instructions
1081
+ // for a bound credential.
1082
+ request.app.mcpBoundAccount = tokenData.account;
1083
+ } else if (tokenData.account) {
998
1084
  // account token
999
1085
 
1000
1086
  let accountIdSource;
@@ -1094,7 +1180,11 @@ const init = async () => {
1094
1180
  throw error;
1095
1181
  }
1096
1182
 
1097
- if (tokenData.restrictions.rateLimit) {
1183
+ // Skipped on MCP-dispatched injects like the last-use record above: the outer
1184
+ // /mcp request already spent one unit of this token's budget at the door, and
1185
+ // counting the inner request too silently halved every restricted token's
1186
+ // effective limit over MCP.
1187
+ if (tokenData.restrictions.rateLimit && !request.app.mcpInternal) {
1098
1188
  let rateLimit = await checkRateLimit(
1099
1189
  `api:${tokenData.id}`,
1100
1190
  1,
@@ -1128,7 +1218,14 @@ const init = async () => {
1128
1218
  // payload validation and the handler, so a call recorded here can still end in a 400 or
1129
1219
  // a 404. That is the right boundary for a credential trail - it answers what the token
1130
1220
  // was permitted to attempt.
1131
- tokenAuditLog.allowed(auditEntry);
1221
+ //
1222
+ // Except at the MCP door, where "allowed" describes no operation at all (the permission
1223
+ // check above was deferred): every tool call writes its own row as the injected API
1224
+ // request it becomes, and a second content-free row per call would halve the capped
1225
+ // audit retention for MCP traffic. Denials at the door are still recorded above.
1226
+ if (!mcpEndpoint) {
1227
+ tokenAuditLog.allowed(auditEntry);
1228
+ }
1132
1229
 
1133
1230
  return { isValid: true, credentials: { token }, artifacts: tokenData };
1134
1231
  }
@@ -1156,6 +1253,20 @@ const init = async () => {
1156
1253
  path: '/'
1157
1254
  });
1158
1255
 
1256
+ // The version an SSO login stamps into its session, so the checks that end a session later can
1257
+ // compare against it. The password logins in lib/ui-routes/auth-routes.js stamp the same field
1258
+ // from the same place; without it a session is refused on the first request after any version
1259
+ // bump, which is a forced re-login rather than a lockout.
1260
+ //
1261
+ // Read by both strategies that accept a session: the cookie strategy below, and the session
1262
+ // token branch of the api-token strategy above - the two credentials the same cookie carries,
1263
+ // and "log out all sessions" has to end both. Declared here rather than above because both
1264
+ // consumers only call it at request time, which is after this whole function has run.
1265
+ const sessionPasswordVersion = async () => {
1266
+ const authData = await settings.get('authData');
1267
+ return (authData && authData.passwordVersion) || 0;
1268
+ };
1269
+
1159
1270
  // Authentication for admin pages
1160
1271
  server.auth.strategy('session', 'cookie', {
1161
1272
  cookie: {
@@ -1169,6 +1280,23 @@ const init = async () => {
1169
1280
  redirectTo: '/admin/login',
1170
1281
 
1171
1282
  async validate(request, session) {
1283
+ const authData = await settings.get('authData');
1284
+
1285
+ // "Log out all sessions" and a password change both bump authData.passwordVersion, and
1286
+ // a session stamped with an older one is over. Checked before the provider switch
1287
+ // because it is true of every session: the SSO branch used to return before reaching
1288
+ // it, so an SSO session outlived the click that was supposed to end every session.
1289
+ // Only reachable when a local password exists at all, which is also the only case
1290
+ // where this strategy is installed (isInstanceSecured() is `!!authData`).
1291
+ //
1292
+ // This ends the admin session. The browse page's `sess_` API token rides the same
1293
+ // cookie and never reaches this strategy, so it applies the same predicate for itself
1294
+ // in the api-token strategy above - neither check covers the other.
1295
+ if (isEndedSession((authData && authData.passwordVersion) || 0, session)) {
1296
+ // force logout
1297
+ return { isValid: false };
1298
+ }
1299
+
1172
1300
  switch (session.provider) {
1173
1301
  case 'okta':
1174
1302
  case 'oidc': {
@@ -1203,16 +1331,10 @@ const init = async () => {
1203
1331
  }
1204
1332
  }
1205
1333
 
1206
- const authData = await settings.get('authData');
1207
1334
  if (!authData) {
1208
1335
  return { isValid: true, credentials: { enabled: false } };
1209
1336
  }
1210
1337
 
1211
- if (authData.passwordVersion && authData.passwordVersion !== session.passwordVersion) {
1212
- // force logout
1213
- return { isValid: false };
1214
- }
1215
-
1216
1338
  const account = authData.user === session.user;
1217
1339
 
1218
1340
  if (!account) {
@@ -1275,9 +1397,9 @@ const init = async () => {
1275
1397
  server.route({
1276
1398
  method: ['GET', 'POST'],
1277
1399
  path: '/admin/login/okta',
1278
- handler(request, h) {
1400
+ async handler(request, h) {
1279
1401
  assertSsoAuthenticated(request);
1280
- setAdminSession(request, request.auth.credentials);
1402
+ setAdminSession(request, Object.assign({}, request.auth.credentials, { passwordVersion: await sessionPasswordVersion() }));
1281
1403
  let oktaUser = request.auth.credentials && request.auth.credentials.profile && request.auth.credentials.profile.username;
1282
1404
  request.logger.info({ msg: 'Admin login successful', user: oktaUser || 'unknown', method: 'okta', remoteAddress: request.app.ip });
1283
1405
  return h.redirect('/admin');
@@ -1365,6 +1487,7 @@ const init = async () => {
1365
1487
  // `ee` cookie past the ~4KB browser limit and cause a silent login loop.
1366
1488
  // Group names are kept so the per-request authorization re-check works;
1367
1489
  // the id_token is kept only as the logout id_token_hint (RP-initiated logout).
1490
+ const passwordVersion = await sessionPasswordVersion();
1368
1491
  setAdminSession(request, {
1369
1492
  provider: 'oidc',
1370
1493
  profile: {
@@ -1377,6 +1500,7 @@ const init = async () => {
1377
1500
  emailVerified: profile.emailVerified,
1378
1501
  groups: profile.groups
1379
1502
  },
1503
+ passwordVersion,
1380
1504
  idToken: (request.auth.artifacts && request.auth.artifacts.id_token) || null
1381
1505
  });
1382
1506
 
@@ -1490,6 +1614,16 @@ const init = async () => {
1490
1614
  }
1491
1615
  });
1492
1616
 
1617
+ // The dependency inventory. Unlike the licence texts and the favicon next to it this is not
1618
+ // public content: it names every package and version the instance runs, which is the first
1619
+ // thing worth having when looking for a way in. An operator or an auditor asking for it holds a
1620
+ // token; nobody else has business reading it.
1621
+ //
1622
+ // `scope:api` rather than a scope of its own, and no `api` tag: the tag is what selects a route
1623
+ // into /swagger.json, and this is a file download rather than an API operation. The route names
1624
+ // no account, so an account-bound token is refused by the binding check, and it is in no
1625
+ // permission group, so a narrowed token is refused as unclassified - both correct for a
1626
+ // instance-wide inventory.
1493
1627
  server.route({
1494
1628
  method: 'GET',
1495
1629
  path: '/sbom.json',
@@ -1497,8 +1631,11 @@ const init = async () => {
1497
1631
  file: { path: pathlib.join(__dirname, '..', 'sbom.json'), confine: false }
1498
1632
  },
1499
1633
  options: {
1500
- auth: false,
1501
- tags: ['static']
1634
+ tags: ['static', 'scope:api'],
1635
+ auth: {
1636
+ strategy: 'api-token',
1637
+ mode: 'required'
1638
+ }
1502
1639
  }
1503
1640
  });
1504
1641
 
@@ -2697,6 +2834,7 @@ const init = async () => {
2697
2834
  MAX_BODY_SIZE,
2698
2835
  MAX_PAYLOAD_TIMEOUT,
2699
2836
  documentStoreFeatureEnabled,
2837
+ mcpFeatureEnabled,
2700
2838
  oauth2Schema,
2701
2839
  imapSchema,
2702
2840
  smtpSchema,
@@ -3010,7 +3148,13 @@ const init = async () => {
3010
3148
  .code(error.output.statusCode);
3011
3149
  }
3012
3150
 
3013
- if (request.errorInfo && request.route && request.route.settings && request.route.settings.tags && request.route.settings.tags.includes('api')) {
3151
+ const routeTags = (request.route && request.route.settings && request.route.settings.tags) || [];
3152
+
3153
+ // `external` covers the MCP endpoint and its OAuth routes: machine-facing surfaces whose
3154
+ // clients expect JSON errors, never the admin HTML error page
3155
+ const wantsJsonError = routeTags.includes('api') || routeTags.includes('external');
3156
+
3157
+ if (request.errorInfo && wantsJsonError) {
3014
3158
  // JSON response for API requests
3015
3159
 
3016
3160
  let res = h.response(request.errorInfo);
@@ -3023,10 +3167,7 @@ const init = async () => {
3023
3167
  return res.code(request.errorInfo.statusCode || 500);
3024
3168
  }
3025
3169
 
3026
- const tags = (request.route && request.route.settings && request.route.settings.tags) || [];
3027
- const isApiRoute = tags.includes('api') || tags.includes('test');
3028
-
3029
- if (isApiRoute) {
3170
+ if (wantsJsonError || routeTags.includes('test')) {
3030
3171
  // API path
3031
3172
  return h.response(request.errorInfo).code(request.errorInfo.statusCode || 500);
3032
3173
  }
@@ -3131,15 +3272,24 @@ const init = async () => {
3131
3272
  // An IP allowlist is only as trustworthy as the address it matches against. If the deployment
3132
3273
  // takes the client address from X-Forwarded-For but does not say which peers may set it, any
3133
3274
  // client that can reach this port can present whatever address the allowlist expects.
3275
+ //
3276
+ // Fired on the configuration rather than on the admin allowlist alone: per-token
3277
+ // `restrictions.addresses` reads the same resolved address and is just as spoofable, and those
3278
+ // live on individual token records rather than in a startup value, so there is nothing to test
3279
+ // for here - an instance in this state cannot rely on either control.
3280
+ //
3134
3281
  // Length-checked, not just null-checked: readEnvList returns [] for a variable that is present
3135
3282
  // but empty (an unset shell interpolation, an empty secret), which is truthy. resolveClientIp
3136
3283
  // treats that as no proxies configured, so the warning has to agree or it goes quiet in
3137
3284
  // exactly the deployment it exists to warn.
3138
- if (ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length && !API_PROXY_ADDRESSES?.length && (await settings.get('enableApiProxy'))) {
3285
+ if (!API_PROXY_ADDRESSES?.length && (await settings.get('enableApiProxy'))) {
3139
3286
  logger.warn({
3140
- msg: 'Admin IP allowlist is spoofable because X-Forwarded-For is trusted from any peer. Set EENGINE_API_PROXY_ADDRESSES to the addresses of your proxies, or disable the API proxy setting.',
3287
+ msg:
3288
+ 'X-Forwarded-For is trusted from any peer, so the resolved client address is caller-controlled. ' +
3289
+ 'The admin IP allowlist and per-token restrictions.addresses cannot be relied on in this configuration. ' +
3290
+ 'Set EENGINE_API_PROXY_ADDRESSES to the addresses of your proxies, or disable the API proxy setting.',
3141
3291
  component: 'api',
3142
- allowedAddresses: ADMIN_ACCESS_ADDRESSES
3292
+ allowedAddresses: ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length ? ADMIN_ACCESS_ADDRESSES : null
3143
3293
  });
3144
3294
  }
3145
3295