emailengine-app 2.86.0 → 2.87.1

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 (74) hide show
  1. package/.ncurc.js +2 -4
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +42 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +5 -6
  6. package/README.md +4 -0
  7. package/bin/emailengine.js +2 -4
  8. package/bin/healthcheck.js +20 -0
  9. package/data/google-crawlers.json +1 -1
  10. package/data/public_suffix_list.dat +3 -7
  11. package/lib/account/auth-failure-backfill.js +3 -2
  12. package/lib/account/expected-identity.js +2 -2
  13. package/lib/account.js +101 -39
  14. package/lib/api-listener.js +40 -0
  15. package/lib/api-routes/account-routes.js +14 -7
  16. package/lib/api-routes/submit-routes.js +21 -2
  17. package/lib/api-token-auth.js +406 -0
  18. package/lib/autodetect-imap-settings.js +36 -3
  19. package/lib/consts.js +5 -0
  20. package/lib/email-client/base-client.js +27 -109
  21. package/lib/email-client/gmail-client.js +15 -4
  22. package/lib/email-client/imap/mailbox.js +97 -97
  23. package/lib/email-client/imap/sync-operations.js +13 -6
  24. package/lib/email-client/imap-client.js +28 -7
  25. package/lib/email-client/new-message-steps.js +162 -0
  26. package/lib/email-client/outlook-client.js +10 -2
  27. package/lib/env-setting-overrides.js +6 -2
  28. package/lib/export-worker.js +3 -2
  29. package/lib/export.js +43 -4
  30. package/lib/field-usage.js +1 -1
  31. package/lib/get-boolean.js +38 -0
  32. package/lib/get-raw-email.js +10 -1
  33. package/lib/health-probe.js +71 -0
  34. package/lib/imapproxy/imap-server.js +4 -55
  35. package/lib/net-tos-guard.js +42 -0
  36. package/lib/oauth/gmail.js +54 -29
  37. package/lib/oauth2-apps.js +2 -1
  38. package/lib/otp.js +66 -0
  39. package/lib/read-env-value.js +19 -7
  40. package/lib/redis-keys.js +19 -0
  41. package/lib/redis-operations.js +7 -3
  42. package/lib/schemas.js +62 -2
  43. package/lib/security-headers.js +18 -0
  44. package/lib/session-default.js +50 -0
  45. package/lib/settings.js +2 -1
  46. package/lib/stream-encrypt.js +71 -20
  47. package/lib/sub-script.js +8 -2
  48. package/lib/submit-lock.js +84 -0
  49. package/lib/submit-processor.js +283 -0
  50. package/lib/swagger-options.js +2 -2
  51. package/lib/templates.js +6 -3
  52. package/lib/tls/context.js +2 -16
  53. package/lib/tools.js +8 -30
  54. package/lib/utils/redis-errors.js +44 -0
  55. package/lib/webhook-delivery.js +3 -4
  56. package/lib/webhooks.js +5 -0
  57. package/lib/worker-rpc-error.js +10 -5
  58. package/lib/worker-rpc.js +138 -0
  59. package/package.json +25 -26
  60. package/sbom.json +660 -1736
  61. package/server.js +6 -5
  62. package/static/css/flyonui.css +2 -2
  63. package/static/js/ee-client.js +650 -196
  64. package/static/licenses.html +280 -1393
  65. package/translations/messages.pot +16 -16
  66. package/views/layout/app.hbs +9 -6
  67. package/views/legal.hbs +8 -0
  68. package/workers/api.js +51 -474
  69. package/workers/export.js +14 -55
  70. package/workers/imap-proxy.js +5 -18
  71. package/workers/imap.js +27 -49
  72. package/workers/smtp.js +7 -69
  73. package/workers/submit.js +21 -279
  74. package/workers/webhooks.js +7 -72
package/workers/api.js CHANGED
@@ -16,7 +16,6 @@ const {
16
16
  renderRedirect,
17
17
  isClientError
18
18
  } = require('../lib/ui-routes/route-helpers');
19
- const { boundRouteBinding } = require('../lib/api-routes/account-binding');
20
19
  const util = require('util');
21
20
  const { webhooks: Webhooks } = require('../lib/webhooks');
22
21
  const { lists } = require('../lib/lists');
@@ -36,7 +35,6 @@ const {
36
35
  isEmail,
37
36
  getWorkerCount,
38
37
  runPrechecks,
39
- matcher,
40
38
  readEnvValue,
41
39
  readEnvList,
42
40
  threadStats,
@@ -80,16 +78,15 @@ const { matchesExpectedIdentity, pendingSetupExpectation, resolveExpectedIdentit
80
78
 
81
79
  const handlebars = require('handlebars');
82
80
  const { apiTokenScheme, SCHEME_NAME: API_TOKEN_SCHEME } = require('../lib/api-token-scheme');
81
+ const { createApiTokenValidator } = require('../lib/api-token-auth');
83
82
  const tokens = require('../lib/tokens');
84
- const tokenPermissions = require('../lib/token-permissions');
85
83
  const { mcpFeatureEnabled } = require('../lib/mcp');
86
84
  const mcpListen = require('../lib/mcp/listen');
87
85
  const tokenAuditLog = require('../lib/token-audit-log');
88
- const { routeGrant, perRequestSurfaceAdmits, sessionTokenAdmits } = require('../lib/api-routes/permission-map');
89
- const { mcpOptions } = require('../lib/api-routes/route-metadata');
90
86
 
91
87
  const { redis } = require('../lib/db');
92
88
  const { createHealthChecks } = require('../lib/health');
89
+ const { requireSessionOnceSecured, TOTP_EXEMPT_PATHS } = require('../lib/session-default');
93
90
  const { Account } = require('../lib/account');
94
91
  const settings = require('../lib/settings');
95
92
 
@@ -103,7 +100,8 @@ const { registerOpenApiRoute } = require('../lib/openapi');
103
100
  const { getModel: getApiReferenceModel, clearServiceUrlCache } = require('../lib/api-reference');
104
101
 
105
102
  const { createCertHandler } = require('../lib/cert-handler');
106
- const { createTlsContext, applyTlsContext, apiTlsConfig } = require('../lib/tls/context');
103
+ const { createTlsContext, applyTlsContext } = require('../lib/tls/context');
104
+ const { apiPort, apiHost, apiTlsConfig } = require('../lib/api-listener');
107
105
  const { reconcileCertificates, requestProvisioning } = require('../lib/tls/provision');
108
106
  const { buildCertificateStatus } = require('../lib/tls/status');
109
107
 
@@ -125,7 +123,15 @@ const {
125
123
  } = consts;
126
124
 
127
125
  const registerApiRoutes = require('../lib/api-routes');
128
- const { securityHeadersExt, attachSecurityContext, isAdminPath, isMachineRoute, isSecureOrigin, CSP_MODES } = require('../lib/security-headers');
126
+ const {
127
+ securityHeadersExt,
128
+ attachSecurityContext,
129
+ isAdminPath,
130
+ isMachineRoute,
131
+ acceptsSession,
132
+ isSecureOrigin,
133
+ CSP_MODES
134
+ } = require('../lib/security-headers');
129
135
  const { deprecationExt } = require('../lib/deprecations');
130
136
  const { errorCodeExt } = require('../lib/api-error-codes');
131
137
  const { apiCallDuration } = require('../lib/request-timing');
@@ -206,12 +212,11 @@ const oidcAllowGroups = sso.parseGroupList(sso.OIDC_ALLOWED_GROUPS);
206
212
  const EENGINE_TIMEOUT = getDuration(readEnvValue('EENGINE_TIMEOUT') || config.service.commandTimeout) || DEFAULT_EENGINE_TIMEOUT;
207
213
  const MAX_ATTACHMENT_SIZE = getByteSize(readEnvValue('EENGINE_MAX_SIZE') || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
208
214
 
209
- const API_PORT =
210
- (hasEnvValue('EENGINE_PORT') && Number(readEnvValue('EENGINE_PORT'))) || (hasEnvValue('PORT') && Number(readEnvValue('PORT'))) || config.api.port;
211
- const API_HOST = readEnvValue('EENGINE_HOST') || config.api.host;
215
+ const API_PORT = apiPort(config.api);
216
+ const API_HOST = apiHost(config.api);
212
217
 
213
218
  // Either an object (TLS enabled) or `false` (TLS disabled)
214
- const API_TLS = apiTlsConfig();
219
+ const API_TLS = apiTlsConfig(config.api);
215
220
 
216
221
  // Merge TLS settings from config params and environment
217
222
  loadTlsConfig(API_TLS, 'EENGINE_API_TLS_');
@@ -303,42 +308,9 @@ logger.info({
303
308
 
304
309
  const TRACKER_IMAGE = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');
305
310
 
306
- let callQueue = new Map();
307
- let mids = 0;
308
-
309
- async function call(message, transferList) {
310
- return new Promise((resolve, reject) => {
311
- let mid = `${Date.now()}:${++mids}`;
312
-
313
- let ttl = Math.max(message.timeout || 0, EENGINE_TIMEOUT || 0);
314
-
315
- let timer = setTimeout(() => {
316
- let err = new Error('Timeout waiting for command response [T2]');
317
- err.statusCode = 504;
318
- err.code = 'Timeout';
319
- err.ttl = ttl;
320
- callQueue.delete(mid);
321
- reject(err);
322
- }, ttl);
323
-
324
- callQueue.set(mid, { resolve, reject, timer });
325
-
326
- try {
327
- parentPort.postMessage(
328
- {
329
- cmd: 'call',
330
- mid,
331
- message
332
- },
333
- transferList
334
- );
335
- } catch (err) {
336
- clearTimeout(timer);
337
- callQueue.delete(mid);
338
- return reject(err);
339
- }
340
- });
341
- }
311
+ const { createRpcClient, respond, isCall } = require('../lib/worker-rpc');
312
+ const rpc = createRpcClient({ port: parentPort, defaultTimeout: EENGINE_TIMEOUT, timeoutTag: 'T2' });
313
+ const call = rpc.call;
342
314
 
343
315
  async function checkRateLimit(key, count, allowed, windowSize) {
344
316
  return await call({ cmd: 'rate-limit', key, count, allowed, windowSize });
@@ -466,47 +438,12 @@ let sessionAuthServer = null;
466
438
  let refreshApiTls = null;
467
439
 
468
440
  parentPort.on('message', message => {
469
- if (message && message.cmd === 'resp' && message.mid && callQueue.has(message.mid)) {
470
- let { resolve, reject, timer } = callQueue.get(message.mid);
471
- clearTimeout(timer);
472
- callQueue.delete(message.mid);
473
-
474
- if (message.error) {
475
- let err = new Error(message.error);
476
- if (message.code) {
477
- err.code = message.code;
478
- }
479
- if (message.statusCode) {
480
- err.statusCode = message.statusCode;
481
- }
482
- if (message.info) {
483
- err.info = message.info;
484
- }
485
-
486
- return reject(err);
487
- } else {
488
- return resolve(message.response);
489
- }
441
+ if (rpc.handleResponse(message)) {
442
+ return;
490
443
  }
491
444
 
492
- if (message && message.cmd === 'call' && message.mid) {
493
- return onCommand(message.message)
494
- .then(response => {
495
- parentPort.postMessage({
496
- cmd: 'resp',
497
- mid: message.mid,
498
- response
499
- });
500
- })
501
- .catch(err => {
502
- parentPort.postMessage({
503
- cmd: 'resp',
504
- mid: message.mid,
505
- error: err.message,
506
- code: err.code,
507
- statusCode: err.statusCode
508
- });
509
- });
445
+ if (isCall(message)) {
446
+ return respond(parentPort, message, onCommand, { logger });
510
447
  }
511
448
 
512
449
  if (message && message.cmd === 'change') {
@@ -847,376 +784,16 @@ function registerApiTokenAuth(server) {
847
784
  // Authentication for API calls
848
785
  server.auth.strategy('api-token', API_TOKEN_SCHEME, {
849
786
  allowQueryToken: true, // optional, false by default
850
- validate: async (request, token /*, h*/) => {
851
- let disableTokens = await settings.get('disableTokens');
852
- if (disableTokens && (!token || token === 'preauth')) {
853
- // tokens checks are disabled, allow all if token is not set.
854
- // `preauth` marks a caller that presented NO credential at all - routes that hand
855
- // out lasting privilege have to be able to tell that apart from a real token.
856
- return {
857
- isValid: true,
858
- credentials: { preauth: true },
859
- artifacts: {}
860
- };
861
- }
862
-
863
- // Every scope a route names admits a token that holds it. Single-scope routes behave
864
- // exactly as before; the MCP endpoint is the one route naming two (`scope:api` and
865
- // `scope:mcp`), so both kinds of credential can open it.
866
- let tags = (request.route && request.route.settings && request.route.settings.tags) || [];
867
- let scopes = tags.filter(tag => tag === 'api' || /^scope:/.test(tag)).map(tag => tag.replace(/^scope:/, ''));
868
-
869
- // The MCP endpoint (lib/api-routes/mcp-routes.js) is a protocol multiplexer with no
870
- // operation of its own: every tools/call becomes an injected API request that runs
871
- // this whole strategy again against the route it actually targets. Several checks
872
- // below defer to that inner request, and each says so where it does.
873
- const mcpEndpoint = !!mcpOptions(request.route).endpoint;
874
-
875
- // Session tokens are refused at the MCP door rather than half-admitted: a session
876
- // credential carries no bearer token the injected inner requests could forward, so
877
- // it could initialize and list tools but every tools/call would die on an inner 401.
878
- if (token.startsWith('sess_') && scopes.includes('api') && !mcpEndpoint) {
879
- // seems like a session token
880
- const session = (request.state && request.state.ee) || {};
881
-
882
- // "Log out all sessions" has to reach this credential too. The session strategy's
883
- // own passwordVersion check never runs here - an API request authenticates with
884
- // this strategy and only reads the cookie for its `sid` - and validateSessionToken()
885
- // slides the token's TTL on every use, so a cookie-plus-token pair left behind on a
886
- // device the operator no longer controls stayed usable indefinitely after the click
887
- // that was supposed to end every session. Same predicate as the session strategy,
888
- // including its "only when a local password exists" condition, so a session stamped
889
- // before this shipped is not force-expired.
890
- if (isEndedSession(await sessionPasswordVersion(), session)) {
891
- logger.warn({
892
- msg: 'Session token presented for an ended session',
893
- account: request.params.account,
894
- method: request.route.method,
895
- path: request.route.path
896
- });
897
- throw Boom.unauthorized('Session has ended');
898
- }
899
-
900
- let isValidSessionToken = await tokens.validateSessionToken(session.sid, token, request.params.account, 900);
901
- if (isValidSessionToken) {
902
- // The credential was minted for a page inside the admin perimeter, so it is
903
- // held to that perimeter too. The /v1 path it is presented on is not an admin
904
- // path, so the request-level check above did not apply.
905
- if (ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length && !matchIp(request.app.ip, ADMIN_ACCESS_ADDRESSES)) {
906
- logger.warn({
907
- msg: 'Session token presented from outside the admin address list',
908
- account: request.params.account,
909
- remoteAddress: request.app.ip,
910
- method: request.route.method,
911
- path: request.route.path
912
- });
913
- throw Boom.forbidden('Unauthorized address');
914
- }
915
-
916
- // A session token is bound to the account whose page minted it (checked above,
917
- // against request.params.account), but it used to reach every api-tagged route
918
- // naming that account - it never met the permission model at all. It lives in
919
- // the page HTML where any script on the page can read it, which the HttpOnly
920
- // session cookie does not, so it must not be the wider of the two credentials:
921
- // SESSION_TOKEN_GRANTS is what the browser actually calls, and everything else
922
- // - the account edit that rewrites a webhook target, the route that hands out
923
- // the account's provider access token - is refused here.
924
- if (!sessionTokenAdmits(routeGrant(request.route), { account: request.params.account })) {
925
- logger.warn({
926
- msg: 'Session token used outside the message browser grants',
927
- account: request.params.account,
928
- method: request.route.method,
929
- path: request.route.path
930
- });
931
- throw Boom.forbidden('Unauthorized permission');
932
- }
933
-
934
- // The credential is bounded by a grant list rather than by a permissions
935
- // record, so anything that keys off "is this token narrowed" cannot see it -
936
- // assertNoNetworkOverride() is the one that matters, since `send/submit` is
937
- // admitted above and a submit payload's `proxy` decides where the session
938
- // carrying the account's SMTP credential connects.
939
- request.app.sessionToken = true;
940
-
941
- return {
942
- isValid: true,
943
- credentials: {},
944
- artifacts: {}
945
- };
946
- }
947
- }
948
-
949
- let tokenData;
950
- try {
951
- // The last-use record is skipped on MCP-dispatched injects: the outer /mcp
952
- // request just wrote the same credential's entry, and the second write would
953
- // only repeat it
954
- tokenData = await tokens.get(token, false, { log: !request.app.mcpInternal, remoteAddress: request.app.ip });
955
- } catch (err) {
956
- // A thrown Boom reaches the client the way the scope and permission refusals
957
- // below do (the api-token scheme does not catch it), so the reason travels as a
958
- // machine-readable code - UnknownToken, ExpiredToken, InvalidToken - while the
959
- // message stays the generic one the scheme itself would have sent. The scheme
960
- // name keeps the WWW-Authenticate header the plugin's own refusal carries.
961
- let error = Boom.unauthorized('Bad token', 'Bearer');
962
- if (err.code) {
963
- error.output.payload.code = err.code;
964
- }
965
- throw error;
966
- }
967
-
968
- // Bind the token hash (id) to the request logger so it is included in the per-request
969
- // log entry, allowing API requests to be correlated to the token that made them.
970
- if (request.logger && typeof request.logger.setBindings === 'function') {
971
- request.logger.setBindings({ tokenId: tokenData.id, tokenAccount: tokenData.account || null });
972
- }
973
-
974
- const grant = routeGrant(request.route);
975
-
976
- // This strategy runs before route validation, so `request.query` is whatever the client
977
- // sent: a repeated `?account=` arrives as an array. Only a string can name an account,
978
- // and this value is persisted into the audit log, so anything else is not one.
979
- const queryAccount = request.query && typeof request.query.account === 'string' ? request.query.account : null;
980
-
981
- // Shared by every audit entry below, so an allow and a deny describe the same request.
982
- // Built before the first check that can refuse: a rejection is the strongest signal of
983
- // credential misuse there is, and a trail that only held the calls that succeeded would
984
- // be silent about exactly the ones worth looking at.
985
- const auditEntry = {
986
- tokenId: tokenData.id,
987
- ip: request.app.ip,
988
- method: request.route.method,
989
- path: request.route.path,
990
- action: grant.action,
991
- group: grant.group,
992
- // The account the REQUEST addressed, which is not always the one in the path: the
993
- // routes that take it as a query argument are the ones a bound token gets refused
994
- // on, and falling straight through to the token's own account recorded a
995
- // cross-account attempt against the account it was entitled to reach - the opposite
996
- // of what the entry exists to show. The token's account is still the answer for the
997
- // routes that name no account at all.
998
- //
999
- // The refusals below log this field rather than re-deriving it, so the application
1000
- // log and the audit row cannot disagree about which account a denial concerned.
1001
- account: (request.params && request.params.account) || queryAccount || tokenData.account || null
1002
- };
1003
-
1004
- // `mcp` and `mcp-manage` are surface scopes like `smtp`: each admits exactly the API
1005
- // operations its half of the MCP tool set wraps (perRequestSurfaceAdmits over
1006
- // SURFACE_GRANTS), and only on requests the MCP endpoint dispatched itself -
1007
- // request.app.mcpInternal is set by lib/mcp/inject.js and cannot be set from the
1008
- // network, so an mcp-scoped token presented to plain REST is refused here like any
1009
- // other missing scope.
1010
- const mcpSurfaceAdmits = scopes.includes('api') && !!request.app.mcpInternal && perRequestSurfaceAdmits(tokenData.scopes, grant);
1011
-
1012
- const hasRequiredScope =
1013
- !scopes.length ||
1014
- !tokenData.scopes ||
1015
- tokenData.scopes.includes('*') ||
1016
- tokenData.scopes.some(entry => scopes.includes(entry)) ||
1017
- mcpSurfaceAdmits;
1018
-
1019
- if (!hasRequiredScope) {
1020
- // failed scope validation
1021
- logger.warn({
1022
- msg: 'Trying to use invalid scope for a token',
1023
- tokenAccount: tokenData.account,
1024
- tokenId: tokenData.id,
1025
- requestedScope: scopes.join(', '),
1026
- tokenScopes: tokenData.scopes
1027
- });
1028
-
1029
- tokenAuditLog.denied(auditEntry, 'scope');
1030
-
1031
- let error = Boom.forbidden('Unauthorized scope');
1032
- error.output.payload.requestedScope = scopes.join(', ');
1033
- throw error;
1034
- }
1035
-
1036
- // Narrowing below the scope. Runs after the scope check and before the account binding,
1037
- // so the order is: token resolved, scope, permissions, account, restrictions.
1038
- //
1039
- // Before the account switch on purpose - that switch reads the account from the query or
1040
- // from a Redis membership check for the three /v1/templates special cases, and none of
1041
- // that should happen for a request the permissions already refuse.
1042
- //
1043
- // Only subtracts: a token with no `permissions` field takes the allowed path, which is
1044
- // every token issued before this shipped.
1045
- // The MCP door defers this check: its own routeGrant() resolves to no group on
1046
- // purpose, and the operation a narrowed token must hold a grant for is the injected
1047
- // inner request, which re-runs this strategy with the real route.
1048
- const permissionCheck = mcpEndpoint ? { allowed: true } : tokenPermissions.check({ tokenData, operation: grant });
1049
- if (!permissionCheck.allowed) {
1050
- logger.warn({
1051
- msg: 'Token permissions do not allow this operation',
1052
- tokenAccount: tokenData.account,
1053
- tokenId: tokenData.id,
1054
- account: auditEntry.account,
1055
- reason: permissionCheck.reason,
1056
- required: permissionCheck.required
1057
- });
1058
-
1059
- let error = Boom.forbidden('Unauthorized permission');
1060
- // Mirrors how the scope failure above attaches requestedScope: an agent that gets a
1061
- // 403 needs to know WHICH grant it lacked, not just that it lacked one.
1062
- // A refused call is the interesting record, so it is logged before the throw
1063
- tokenAuditLog.denied(auditEntry, permissionCheck.reason);
1064
-
1065
- error.output.payload.requiredPermission = permissionCheck.required;
1066
- throw error;
1067
- }
1068
-
1069
- if (tokenData.account && mcpEndpoint) {
1070
- // The door names no account, so the binding cannot be checked here; it is
1071
- // enforced on every injected inner request, which does name one. Parked on the
1072
- // request so the MCP layer can seed resources/list and the agent instructions
1073
- // for a bound credential.
1074
- request.app.mcpBoundAccount = tokenData.account;
1075
- } else if (tokenData.account) {
1076
- // account token
1077
-
1078
- let accountIdSource;
1079
-
1080
- // Routes that carry an account component somewhere other than their URL params, named
1081
- // by lib/api-routes/account-binding.js. The table is shared with the MCP tool registry,
1082
- // which has to advertise exactly the tools a bound credential can actually call; the
1083
- // resolution of each kind stays here, where the request is.
1084
- switch (boundRouteBinding(request.method, request.route.path)) {
1085
- case 'query':
1086
- // `/v1/tokens` is in the table because it replaced
1087
- // GET /v1/tokens/account/{account}, which carried the account in the path and so
1088
- // reached a bound token's own tokens through the default branch below - as its
1089
- // deprecated alias registration still does. Both stay under the same rule as
1090
- // everything else: the argument has to name the token's own account, and
1091
- // omitting it still refuses, because a bound credential must not enumerate the
1092
- // instance.
1093
- accountIdSource = queryAccount;
1094
- break;
1095
-
1096
- case 'record': {
1097
- let isAccountTemplate =
1098
- request.params.template && (await redis.sismember(`${REDIS_PREFIX}tpl:${tokenData.account}:i`, request.params.template));
1099
- if (isAccountTemplate) {
1100
- accountIdSource = tokenData.account;
1101
- }
1102
- break;
1103
- }
1104
-
1105
- case 'token':
1106
- request.app.enforceAccount = tokenData.account;
1107
- accountIdSource = tokenData.account;
1108
- break;
1109
-
1110
- default:
1111
- accountIdSource = request.params && request.params.account;
1112
- break;
1113
- }
1114
-
1115
- if (accountIdSource !== tokenData.account) {
1116
- logger.warn({
1117
- msg: 'Trying to use invalid account for a token',
1118
- tokenAccount: tokenData.account,
1119
- tokenId: tokenData.id,
1120
- account: auditEntry.account
1121
- });
1122
-
1123
- tokenAuditLog.denied(auditEntry, 'account');
1124
-
1125
- let error = Boom.forbidden('Unauthorized account');
1126
- throw error;
1127
- }
1128
- }
1129
-
1130
- if (tokenData.restrictions) {
1131
- if (tokenData.restrictions.addresses && !matchIp(request.app.ip, tokenData.restrictions.addresses)) {
1132
- logger.warn({
1133
- msg: 'Trying to use invalid IP for a token',
1134
- tokenAccount: tokenData.account,
1135
- tokenId: tokenData.id,
1136
- account: auditEntry.account,
1137
- remoteAddress: request.app.ip,
1138
- addressAllowlist: tokenData.restrictions.addresses
1139
- });
1140
-
1141
- tokenAuditLog.denied(auditEntry, 'address');
1142
-
1143
- let error = Boom.forbidden('Unauthorized address');
1144
- error.output.payload.remoteAddress = request.app.ip;
1145
- throw error;
1146
- }
1147
-
1148
- if (
1149
- tokenData.restrictions.referrers &&
1150
- tokenData.restrictions.referrers.length &&
1151
- !matcher(tokenData.restrictions.referrers, request.headers.referer)
1152
- ) {
1153
- logger.warn({
1154
- msg: 'Trying to use invalid referer for a token',
1155
- tokenAccount: tokenData.account,
1156
- tokenId: tokenData.id,
1157
- account: auditEntry.account,
1158
- referer: request.headers.referer,
1159
- referrerAllowlist: tokenData.restrictions.referrers
1160
- });
1161
-
1162
- tokenAuditLog.denied(auditEntry, 'referrer');
1163
-
1164
- let error = Boom.forbidden('Unauthorized referrer');
1165
- throw error;
1166
- }
1167
-
1168
- // Skipped on MCP-dispatched injects like the last-use record above: the outer
1169
- // /mcp request already spent one unit of this token's budget at the door, and
1170
- // counting the inner request too silently halved every restricted token's
1171
- // effective limit over MCP.
1172
- if (tokenData.restrictions.rateLimit && !request.app.mcpInternal) {
1173
- let rateLimit = await checkRateLimit(
1174
- `api:${tokenData.id}`,
1175
- 1,
1176
- tokenData.restrictions.rateLimit.maxRequests,
1177
- tokenData.restrictions.rateLimit.timeWindow
1178
- );
1179
-
1180
- if (!rateLimit.success) {
1181
- logger.warn({ msg: 'Rate limited', token: tokenData.id, rateLimit });
1182
- tokenAuditLog.denied(auditEntry, 'rateLimit');
1183
-
1184
- let error = Boom.tooManyRequests('Rate limit exceeded');
1185
- error.output.payload.ttl = Math.ceil(rateLimit.ttl);
1186
- error.output.headers = {
1187
- 'X-RateLimit-Limit': rateLimit.allowed,
1188
- 'X-RateLimit-Reset': Math.ceil(rateLimit.ttl),
1189
- // The conventional header for a 429, so a generic HTTP client backs
1190
- // off without knowing about the ttl field in the body
1191
- 'Retry-After': Math.ceil(rateLimit.ttl)
1192
- };
1193
- throw error;
1194
- } else {
1195
- request.app.rateLimitHeaders = {
1196
- 'X-RateLimit-Limit': rateLimit.allowed,
1197
- 'X-RateLimit-Reset': Math.ceil(rateLimit.ttl),
1198
- 'X-RateLimit-Remaining': rateLimit.allowed - rateLimit.count
1199
- };
1200
- }
1201
- }
1202
- }
1203
-
1204
- // The one point every accepted token request passes. "allowed" means the credential was
1205
- // accepted, not that the request succeeded: this runs in the auth strategy, before
1206
- // payload validation and the handler, so a call recorded here can still end in a 400 or
1207
- // a 404. That is the right boundary for a credential trail - it answers what the token
1208
- // was permitted to attempt.
1209
- //
1210
- // Except at the MCP door, where "allowed" describes no operation at all (the permission
1211
- // check above was deferred): every tool call writes its own row as the injected API
1212
- // request it becomes, and a second content-free row per call would halve the capped
1213
- // audit retention for MCP traffic. Denials at the door are still recorded above.
1214
- if (!mcpEndpoint) {
1215
- tokenAuditLog.allowed(auditEntry);
1216
- }
1217
-
1218
- return { isValid: true, credentials: { token }, artifacts: tokenData };
1219
- }
787
+ validate: createApiTokenValidator({
788
+ settings,
789
+ tokens,
790
+ tokenAuditLog,
791
+ redis,
792
+ checkRateLimit,
793
+ sessionPasswordVersion,
794
+ adminAccessAddresses: ADMIN_ACCESS_ADDRESSES,
795
+ logger
796
+ })
1220
797
  });
1221
798
  }
1222
799
 
@@ -1329,13 +906,8 @@ async function registerSessionAuth(server) {
1329
906
  return { isValid: false };
1330
907
  }
1331
908
 
1332
- // unless it is a login or TOPT (or public) page, require TOTP code
1333
- if (
1334
- session.requireTotp &&
1335
- !['/{any*}', '/admin/totp', '/admin/login', '/admin/passkey/auth/options', '/admin/passkey/auth/verify'].includes(
1336
- request.route && request.route.path
1337
- )
1338
- ) {
909
+ // unless it is a login or TOTP (or public) page, require TOTP code
910
+ if (session.requireTotp && !TOTP_EXEMPT_PATHS.includes(request.route && request.route.path)) {
1339
911
  request.requireTotp = true;
1340
912
  }
1341
913
 
@@ -1572,8 +1144,10 @@ async function registerServerPlugins(server) {
1572
1144
  }
1573
1145
 
1574
1146
  // From here on a first password set on another API worker switches the session strategy on
1575
- // through the settings dispatcher (see the authData branch there)
1147
+ // through the settings dispatcher (see the authData branch there), and a password written with no
1148
+ // broadcast (the CLI) is noticed by the first request that would use the default
1576
1149
  sessionAuthServer = server;
1150
+ requireSessionOnceSecured({ server, isInstanceSecured: () => settings.isInstanceSecured(), logger });
1577
1151
 
1578
1152
  await server.register({
1579
1153
  plugin: requestLogger,
@@ -2464,9 +2038,11 @@ async function gmailMissingScopesView(flow, r, grantedScopes) {
2464
2038
  missing: missingScopes
2465
2039
  });
2466
2040
 
2467
- // Best-effort revocation of the partial token
2468
- oAuth2Client.revokeToken(r.refresh_token || r.access_token).catch(err => {
2469
- request.logger.warn({ msg: 'Failed to revoke partial OAuth2 token', err });
2041
+ // Best-effort revocation of the partial token. revokeToken() never throws, it reports
2042
+ oAuth2Client.revokeToken(r.refresh_token || r.access_token).then(revocation => {
2043
+ if (!revocation.revoked) {
2044
+ request.logger.warn({ msg: 'Failed to revoke partial OAuth2 token', revocation });
2045
+ }
2470
2046
  });
2471
2047
 
2472
2048
  const retryUrl = await startOAuthRetry(flow, accountData.email);
@@ -2803,14 +2379,13 @@ async function rejectOAuthIdentity(flow, { grantToken, workspaceDomain }, expect
2803
2379
  const { request, h, accountData, oauth2App, oAuth2Client, providerIdentities } = flow;
2804
2380
 
2805
2381
  // The code was already exchanged, so a refused setup leaves us holding a grant we will never
2806
- // use. Best effort, and the same duck-typing guard Account.delete({ revoke }) uses: only
2807
- // GmailOauth implements revokeToken, and a rejected setup must not become a 500.
2382
+ // use. Best effort, and the same duck-typing guard Account.findRevocableGrant() uses: only
2383
+ // GmailOauth implements revokeToken, which reports a failure rather than throwing it.
2808
2384
  const revokeUnusedGrant = async failureMessage => {
2809
2385
  if (grantToken && typeof oAuth2Client.revokeToken === 'function') {
2810
- try {
2811
- await oAuth2Client.revokeToken(grantToken);
2812
- } catch (err) {
2813
- request.logger.warn({ msg: failureMessage, err });
2386
+ const revocation = await oAuth2Client.revokeToken(grantToken);
2387
+ if (!revocation.revoked) {
2388
+ request.logger.warn({ msg: failureMessage, revocation });
2814
2389
  }
2815
2390
  }
2816
2391
  };
@@ -3040,7 +2615,9 @@ async function registerCsrfProtection(server, secureCookie) {
3040
2615
  skip: (request /*, h*/) => {
3041
2616
  let tags = (request.route && request.route.settings && request.route.settings.tags) || [];
3042
2617
 
3043
- if (isMachineRoute(tags)) {
2618
+ // A machine client holds no crumb, but a route that also takes the session cookie is
2619
+ // reachable from a browser and keeps the check whatever its tags say
2620
+ if (isMachineRoute(tags) && !acceptsSession(request.route.settings.auth)) {
3044
2621
  return true;
3045
2622
  }
3046
2623