emailengine-app 2.79.0 → 2.79.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +79 -0
  3. package/bin/emailengine.js +8 -1
  4. package/config/default.toml +6 -0
  5. package/data/google-crawlers.json +1 -1
  6. package/lib/account.js +137 -19
  7. package/lib/api-routes/account-routes.js +13 -1
  8. package/lib/api-routes/index.js +12 -0
  9. package/lib/api-routes/mailbox-routes.js +6 -0
  10. package/lib/api-routes/mcp-oauth-routes.js +259 -0
  11. package/lib/api-routes/mcp-routes.js +172 -0
  12. package/lib/api-routes/message-routes.js +125 -4
  13. package/lib/api-routes/outbox-routes.js +7 -0
  14. package/lib/api-routes/permission-map.js +101 -1
  15. package/lib/api-routes/route-helpers.js +87 -4
  16. package/lib/api-routes/route-metadata.js +24 -4
  17. package/lib/api-routes/settings-routes.js +37 -14
  18. package/lib/api-routes/submit-routes.js +41 -0
  19. package/lib/api-routes/template-routes.js +7 -0
  20. package/lib/api-routes/token-routes.js +292 -122
  21. package/lib/arf-detect.js +17 -4
  22. package/lib/bounce-detect.js +28 -17
  23. package/lib/consts.js +36 -1
  24. package/lib/db.js +6 -0
  25. package/lib/email-client/base-client.js +102 -117
  26. package/lib/email-client/gmail-client.js +91 -29
  27. package/lib/email-client/imap/mailbox.js +175 -101
  28. package/lib/email-client/imap-client.js +49 -2
  29. package/lib/email-client/outlook-client.js +20 -24
  30. package/lib/enum-descriptions.js +2 -1
  31. package/lib/field-usage.js +17 -1
  32. package/lib/lua/h-set-new-mark.lua +36 -0
  33. package/lib/lua/s-list-accounts.lua +5 -2
  34. package/lib/mcp/index.js +29 -0
  35. package/lib/mcp/inject.js +70 -0
  36. package/lib/mcp/json-schema.js +120 -0
  37. package/lib/mcp/listen.js +171 -0
  38. package/lib/mcp/oauth.js +324 -0
  39. package/lib/mcp/protocol.js +489 -0
  40. package/lib/mcp/resources.js +139 -0
  41. package/lib/mcp/tools.js +655 -0
  42. package/lib/message-port-stream.js +84 -1
  43. package/lib/oauth2-apps.js +84 -15
  44. package/lib/openapi/build-document.js +5 -1
  45. package/lib/openapi/index.js +3 -1
  46. package/lib/response-stream.js +52 -21
  47. package/lib/routes-ui.js +4 -0
  48. package/lib/schemas.js +26 -5
  49. package/lib/settings.js +23 -9
  50. package/lib/token-audit-log.js +32 -9
  51. package/lib/token-permission-view.js +104 -8
  52. package/lib/tokens.js +194 -68
  53. package/lib/tools.js +96 -0
  54. package/lib/ui-routes/account-routes.js +55 -6
  55. package/lib/ui-routes/admin-config-routes.js +114 -1
  56. package/lib/ui-routes/admin-entities-routes.js +103 -19
  57. package/lib/ui-routes/auth-routes.js +13 -0
  58. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  59. package/lib/ui-routes/oauth-config-routes.js +7 -7
  60. package/lib/ui-routes/route-helpers.js +143 -1
  61. package/lib/ui-routes/suppression-list-routes.js +14 -9
  62. package/lib/utils/decode-headers.js +42 -0
  63. package/lib/utils/header-map.js +48 -0
  64. package/lib/utils/network.js +9 -1
  65. package/lib/utils/unsafe-key.js +59 -0
  66. package/lib/web-safe-html.js +61 -0
  67. package/lib/webhook-routing.js +6 -2
  68. package/lib/webhooks.js +31 -8
  69. package/package.json +9 -8
  70. package/sbom.json +1 -1
  71. package/scripts/README.md +25 -0
  72. package/scripts/build-icon.js +77 -0
  73. package/server.js +39 -17
  74. package/static/css/flyonui.css +1 -1
  75. package/static/css/src/app.tailwind.css +98 -0
  76. package/static/emailengine.ico +0 -0
  77. package/static/js/ui.js +465 -1
  78. package/static/licenses.html +42 -22
  79. package/translations/messages.pot +57 -57
  80. package/views/accounts/account.hbs +8 -8
  81. package/views/accounts/browse.hbs +1 -1
  82. package/views/accounts/edit.hbs +2 -2
  83. package/views/config/mcp.hbs +361 -0
  84. package/views/config/oauth/index.hbs +7 -0
  85. package/views/gateways/edit.hbs +1 -1
  86. package/views/gateways/gateway.hbs +2 -2
  87. package/views/gateways/index.hbs +7 -7
  88. package/views/layout/prompt.hbs +62 -0
  89. package/views/mcp/authorize.hbs +136 -0
  90. package/views/partials/accounts_table.hbs +7 -7
  91. package/views/partials/head_assets.hbs +3 -3
  92. package/views/partials/mcp_access_levels.hbs +13 -0
  93. package/views/partials/mcp_account_limit.hbs +14 -0
  94. package/views/partials/mcp_tool_count.hbs +19 -0
  95. package/views/partials/side_menu.hbs +1 -0
  96. package/views/partials/ui/account-picker.hbs +59 -0
  97. package/views/partials/ui/code-block.hbs +26 -0
  98. package/views/partials/ui/menu-item.hbs +5 -0
  99. package/views/partials/ui/radio.hbs +41 -0
  100. package/views/partials/ui/tab.hbs +15 -10
  101. package/views/partials/ui/tabs.hbs +8 -5
  102. package/views/suppression-lists/list.hbs +1 -1
  103. package/views/templates/index.hbs +2 -2
  104. package/views/templates/template.hbs +5 -4
  105. package/views/tokens/index.hbs +30 -4
  106. package/views/tokens/new.hbs +517 -239
  107. package/winconf.js +148 -48
  108. package/workers/api.js +239 -95
  109. package/workers/imap.js +65 -72
  110. package/workers/webhooks.js +21 -1
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') {
@@ -481,6 +493,11 @@ const init = async () => {
481
493
  // keep using "danger" etc.
482
494
  handlebars.registerHelper('eeColor', value => (value === 'danger' ? 'error' : value || 'neutral'));
483
495
 
496
+ // Percent-encode a value for interpolation into a URL path segment. Handlebars escapes for
497
+ // HTML, which leaves "#", "/", "?" and "%" untouched - and an account ID is free text, so
498
+ // href="/admin/accounts/{{account}}" resolves somewhere else entirely for an ID carrying one.
499
+ handlebars.registerHelper('urlpart', value => encodeURIComponent(value === null || value === undefined ? '' : value));
500
+
484
501
  // Join string fragments in subexpressions, e.g. building composed partial
485
502
  // hash values: text=(concat "Up to " (formatInteger n locale) " lines")
486
503
  handlebars.registerHelper('concat', (...args) => args.slice(0, -1).join(''));
@@ -796,8 +813,12 @@ const init = async () => {
796
813
  request.setUrl(`${url.pathname}${url.search}`);
797
814
  }
798
815
 
799
- // make license info available for the request
800
- 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
+ }
801
822
 
802
823
  // flash notifications
803
824
  request.flash = async message => await flash(redis, request, message);
@@ -866,27 +887,70 @@ const init = async () => {
866
887
  };
867
888
  }
868
889
 
869
- 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.
870
893
  let tags = (request.route && request.route.settings && request.route.settings.tags) || [];
871
- if (tags.includes('api')) {
872
- scope = 'api';
873
- } else {
874
- for (let tag of tags) {
875
- if (/^scope:/.test(tag)) {
876
- scope = tag.substr('scope:'.length);
877
- }
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');
878
925
  }
879
- }
880
926
 
881
- if (token.startsWith('sess_') && scope === 'api') {
882
- // seems like a session token
883
- let isValidSessionToken = await tokens.validateSessionToken(
884
- request.state && request.state.ee && request.state.ee.sid,
885
- token,
886
- request.params.account,
887
- 900
888
- );
927
+ let isValidSessionToken = await tokens.validateSessionToken(session.sid, token, request.params.account, 900);
889
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
+
890
954
  return {
891
955
  isValid: true,
892
956
  credentials: {},
@@ -897,7 +961,10 @@ const init = async () => {
897
961
 
898
962
  let tokenData;
899
963
  try {
900
- 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 });
901
968
  } catch (err) {
902
969
  return {
903
970
  isValid: false,
@@ -942,20 +1009,35 @@ const init = async () => {
942
1009
  account: (request.params && request.params.account) || queryAccount || tokenData.account || null
943
1010
  };
944
1011
 
945
- 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) {
946
1028
  // failed scope validation
947
1029
  logger.warn({
948
1030
  msg: 'Trying to use invalid scope for a token',
949
1031
  tokenAccount: tokenData.account,
950
1032
  tokenId: tokenData.id,
951
- requestedScope: scope,
1033
+ requestedScope: scopes.join(', '),
952
1034
  tokenScopes: tokenData.scopes
953
1035
  });
954
1036
 
955
1037
  tokenAuditLog.denied(auditEntry, 'scope');
956
1038
 
957
1039
  let error = Boom.forbidden('Unauthorized scope');
958
- error.output.payload.requestedScope = scope;
1040
+ error.output.payload.requestedScope = scopes.join(', ');
959
1041
  throw error;
960
1042
  }
961
1043
 
@@ -968,7 +1050,10 @@ const init = async () => {
968
1050
  //
969
1051
  // Only subtracts: a token with no `permissions` field takes the allowed path, which is
970
1052
  // every token issued before this shipped.
971
- 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 });
972
1057
  if (!permissionCheck.allowed) {
973
1058
  logger.warn({
974
1059
  msg: 'Token permissions do not allow this operation',
@@ -989,7 +1074,13 @@ const init = async () => {
989
1074
  throw error;
990
1075
  }
991
1076
 
992
- 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) {
993
1084
  // account token
994
1085
 
995
1086
  let accountIdSource;
@@ -999,8 +1090,7 @@ const init = async () => {
999
1090
  // The two listings that take the account as a query argument. `/v1/tokens` is
1000
1091
  // here because it replaced GET /v1/tokens/account/{account}, which carried the
1001
1092
  // account in the path and so reached a bound token's own tokens through the
1002
- // default branch below - the replacement had nothing reading the argument, so
1003
- // the capability disappeared with no alias and no error a caller could act on.
1093
+ // default branch below - as its deprecated alias registration still does.
1004
1094
  // Both stay under the same rule as everything else: the argument has to name the
1005
1095
  // token's own account, and omitting it still refuses, because a bound credential
1006
1096
  // must not enumerate the instance.
@@ -1090,7 +1180,11 @@ const init = async () => {
1090
1180
  throw error;
1091
1181
  }
1092
1182
 
1093
- 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) {
1094
1188
  let rateLimit = await checkRateLimit(
1095
1189
  `api:${tokenData.id}`,
1096
1190
  1,
@@ -1124,7 +1218,14 @@ const init = async () => {
1124
1218
  // payload validation and the handler, so a call recorded here can still end in a 400 or
1125
1219
  // a 404. That is the right boundary for a credential trail - it answers what the token
1126
1220
  // was permitted to attempt.
1127
- 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
+ }
1128
1229
 
1129
1230
  return { isValid: true, credentials: { token }, artifacts: tokenData };
1130
1231
  }
@@ -1152,6 +1253,20 @@ const init = async () => {
1152
1253
  path: '/'
1153
1254
  });
1154
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
+
1155
1270
  // Authentication for admin pages
1156
1271
  server.auth.strategy('session', 'cookie', {
1157
1272
  cookie: {
@@ -1165,6 +1280,23 @@ const init = async () => {
1165
1280
  redirectTo: '/admin/login',
1166
1281
 
1167
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
+
1168
1300
  switch (session.provider) {
1169
1301
  case 'okta':
1170
1302
  case 'oidc': {
@@ -1199,16 +1331,10 @@ const init = async () => {
1199
1331
  }
1200
1332
  }
1201
1333
 
1202
- const authData = await settings.get('authData');
1203
1334
  if (!authData) {
1204
1335
  return { isValid: true, credentials: { enabled: false } };
1205
1336
  }
1206
1337
 
1207
- if (authData.passwordVersion && authData.passwordVersion !== session.passwordVersion) {
1208
- // force logout
1209
- return { isValid: false };
1210
- }
1211
-
1212
1338
  const account = authData.user === session.user;
1213
1339
 
1214
1340
  if (!account) {
@@ -1271,9 +1397,9 @@ const init = async () => {
1271
1397
  server.route({
1272
1398
  method: ['GET', 'POST'],
1273
1399
  path: '/admin/login/okta',
1274
- handler(request, h) {
1400
+ async handler(request, h) {
1275
1401
  assertSsoAuthenticated(request);
1276
- setAdminSession(request, request.auth.credentials);
1402
+ setAdminSession(request, Object.assign({}, request.auth.credentials, { passwordVersion: await sessionPasswordVersion() }));
1277
1403
  let oktaUser = request.auth.credentials && request.auth.credentials.profile && request.auth.credentials.profile.username;
1278
1404
  request.logger.info({ msg: 'Admin login successful', user: oktaUser || 'unknown', method: 'okta', remoteAddress: request.app.ip });
1279
1405
  return h.redirect('/admin');
@@ -1361,6 +1487,7 @@ const init = async () => {
1361
1487
  // `ee` cookie past the ~4KB browser limit and cause a silent login loop.
1362
1488
  // Group names are kept so the per-request authorization re-check works;
1363
1489
  // the id_token is kept only as the logout id_token_hint (RP-initiated logout).
1490
+ const passwordVersion = await sessionPasswordVersion();
1364
1491
  setAdminSession(request, {
1365
1492
  provider: 'oidc',
1366
1493
  profile: {
@@ -1373,6 +1500,7 @@ const init = async () => {
1373
1500
  emailVerified: profile.emailVerified,
1374
1501
  groups: profile.groups
1375
1502
  },
1503
+ passwordVersion,
1376
1504
  idToken: (request.auth.artifacts && request.auth.artifacts.id_token) || null
1377
1505
  });
1378
1506
 
@@ -1486,6 +1614,16 @@ const init = async () => {
1486
1614
  }
1487
1615
  });
1488
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.
1489
1627
  server.route({
1490
1628
  method: 'GET',
1491
1629
  path: '/sbom.json',
@@ -1493,8 +1631,11 @@ const init = async () => {
1493
1631
  file: { path: pathlib.join(__dirname, '..', 'sbom.json'), confine: false }
1494
1632
  },
1495
1633
  options: {
1496
- auth: false,
1497
- tags: ['static']
1634
+ tags: ['static', 'scope:api'],
1635
+ auth: {
1636
+ strategy: 'api-token',
1637
+ mode: 'required'
1638
+ }
1498
1639
  }
1499
1640
  });
1500
1641
 
@@ -2693,6 +2834,7 @@ const init = async () => {
2693
2834
  MAX_BODY_SIZE,
2694
2835
  MAX_PAYLOAD_TIMEOUT,
2695
2836
  documentStoreFeatureEnabled,
2837
+ mcpFeatureEnabled,
2696
2838
  oauth2Schema,
2697
2839
  imapSchema,
2698
2840
  smtpSchema,
@@ -2739,13 +2881,37 @@ const init = async () => {
2739
2881
  isCached: false,
2740
2882
 
2741
2883
  async context(request) {
2742
- const pendingMessages = await flash(redis, request);
2884
+ // The three reads are independent, and this runs on every admin page render. The
2885
+ // OAuth2 auth flags are best-effort - a failure to read them must not take the page
2886
+ // down with it.
2887
+ const [pendingMessages, settingsValues, oauthAuthFlags] = await Promise.all([
2888
+ flash(redis, request),
2889
+ settings.getMulti(
2890
+ 'upgrade',
2891
+ 'subexp',
2892
+ 'webhookErrorFlag',
2893
+ 'webhooksEnabled',
2894
+ 'disableTokens',
2895
+ 'tract',
2896
+ 'templateHeader',
2897
+ 'templateHtmlHead',
2898
+ 'documentStoreEnabled',
2899
+ 'serviceUrl',
2900
+ 'language',
2901
+ 'locale',
2902
+ 'timezone',
2903
+ 'pageBrandName',
2904
+ 'notificationBaseUrl'
2905
+ ),
2906
+ oauth2Apps.listAuthFlags().catch(err => {
2907
+ logger.error({ msg: 'Failed to list OAuth2 app auth flags', err });
2908
+ return [];
2909
+ })
2910
+ ]);
2911
+
2743
2912
  const {
2744
2913
  upgrade: upgradeInfo,
2745
2914
  subexp,
2746
- outlookAuthFlag,
2747
- gmailAuthFlag,
2748
- gmailServiceAuthFlag,
2749
2915
  webhookErrorFlag,
2750
2916
  webhooksEnabled,
2751
2917
  disableTokens,
@@ -2759,26 +2925,7 @@ const init = async () => {
2759
2925
  timezone,
2760
2926
  pageBrandName,
2761
2927
  notificationBaseUrl
2762
- } = await settings.getMulti(
2763
- 'upgrade',
2764
- 'subexp',
2765
- 'outlookAuthFlag',
2766
- 'gmailAuthFlag',
2767
- 'gmailServiceAuthFlag',
2768
- 'webhookErrorFlag',
2769
- 'webhooksEnabled',
2770
- 'disableTokens',
2771
- 'tract',
2772
- 'templateHeader',
2773
- 'templateHtmlHead',
2774
- 'documentStoreEnabled',
2775
- 'serviceUrl',
2776
- 'language',
2777
- 'locale',
2778
- 'timezone',
2779
- 'pageBrandName',
2780
- 'notificationBaseUrl'
2781
- );
2928
+ } = settingsValues;
2782
2929
 
2783
2930
  let systemAlerts = [];
2784
2931
  let authData;
@@ -2852,30 +2999,15 @@ const init = async () => {
2852
2999
  });
2853
3000
  }
2854
3001
 
2855
- if (outlookAuthFlag && outlookAuthFlag.message) {
3002
+ // OAuth2 apps whose token requests are being refused (setFlag() writes the failure
3003
+ // into app meta). Shown on every admin page: the accounts on such an app sit
3004
+ // disconnected until the operator acts, so the OAuth config page alone is not enough.
3005
+ for (let { app, authFlag } of oauthAuthFlags) {
2856
3006
  systemAlerts.push({
2857
- url: outlookAuthFlag.url || '/admin/config/oauth/app/outlook',
3007
+ url: authFlag.url || `/admin/config/oauth/app/${encodeURIComponent(app)}`,
2858
3008
  level: 'danger',
2859
3009
  icon: 'icon-[tabler--lock-open]',
2860
- message: outlookAuthFlag.message
2861
- });
2862
- }
2863
-
2864
- if (gmailAuthFlag && gmailAuthFlag.message) {
2865
- systemAlerts.push({
2866
- url: gmailAuthFlag.url || '/admin/config/oauth/app/gmail',
2867
- level: 'danger',
2868
- icon: 'icon-[tabler--lock-open]',
2869
- message: gmailAuthFlag.message
2870
- });
2871
- }
2872
-
2873
- if (gmailServiceAuthFlag && gmailServiceAuthFlag.message) {
2874
- systemAlerts.push({
2875
- url: gmailServiceAuthFlag.url || '/admin/config/oauth/app/gmailService',
2876
- level: 'danger',
2877
- icon: 'icon-[tabler--lock-open]',
2878
- message: gmailServiceAuthFlag.message
3010
+ message: authFlag.message
2879
3011
  });
2880
3012
  }
2881
3013
 
@@ -3016,7 +3148,13 @@ const init = async () => {
3016
3148
  .code(error.output.statusCode);
3017
3149
  }
3018
3150
 
3019
- 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) {
3020
3158
  // JSON response for API requests
3021
3159
 
3022
3160
  let res = h.response(request.errorInfo);
@@ -3029,10 +3167,7 @@ const init = async () => {
3029
3167
  return res.code(request.errorInfo.statusCode || 500);
3030
3168
  }
3031
3169
 
3032
- const tags = (request.route && request.route.settings && request.route.settings.tags) || [];
3033
- const isApiRoute = tags.includes('api') || tags.includes('test');
3034
-
3035
- if (isApiRoute) {
3170
+ if (wantsJsonError || routeTags.includes('test')) {
3036
3171
  // API path
3037
3172
  return h.response(request.errorInfo).code(request.errorInfo.statusCode || 500);
3038
3173
  }
@@ -3137,15 +3272,24 @@ const init = async () => {
3137
3272
  // An IP allowlist is only as trustworthy as the address it matches against. If the deployment
3138
3273
  // takes the client address from X-Forwarded-For but does not say which peers may set it, any
3139
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
+ //
3140
3281
  // Length-checked, not just null-checked: readEnvList returns [] for a variable that is present
3141
3282
  // but empty (an unset shell interpolation, an empty secret), which is truthy. resolveClientIp
3142
3283
  // treats that as no proxies configured, so the warning has to agree or it goes quiet in
3143
3284
  // exactly the deployment it exists to warn.
3144
- 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'))) {
3145
3286
  logger.warn({
3146
- 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.',
3147
3291
  component: 'api',
3148
- allowedAddresses: ADMIN_ACCESS_ADDRESSES
3292
+ allowedAddresses: ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length ? ADMIN_ACCESS_ADDRESSES : null
3149
3293
  });
3150
3294
  }
3151
3295