emailengine-app 2.87.0 → 2.87.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 (71) hide show
  1. package/.ncurc.js +2 -4
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/Dockerfile +3 -4
  5. package/bin/emailengine.js +2 -4
  6. package/bin/healthcheck.js +20 -0
  7. package/data/google-crawlers.json +1 -1
  8. package/data/public_suffix_list.dat +3 -7
  9. package/lib/account/auth-failure-backfill.js +3 -2
  10. package/lib/account/expected-identity.js +2 -2
  11. package/lib/account.js +9 -8
  12. package/lib/api-listener.js +40 -0
  13. package/lib/api-token-auth.js +406 -0
  14. package/lib/autodetect-imap-settings.js +36 -3
  15. package/lib/consts.js +5 -0
  16. package/lib/dbsc/index.js +292 -0
  17. package/lib/dbsc/jwt.js +157 -0
  18. package/lib/dbsc/protocol.js +132 -0
  19. package/lib/dbsc/store.js +136 -0
  20. package/lib/email-client/base-client.js +23 -107
  21. package/lib/email-client/gmail-client.js +7 -4
  22. package/lib/email-client/imap/mailbox.js +89 -96
  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 +4 -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/get-boolean.js +38 -0
  31. package/lib/health-probe.js +71 -0
  32. package/lib/imapproxy/imap-server.js +4 -55
  33. package/lib/net-tos-guard.js +42 -0
  34. package/lib/oauth2-apps.js +2 -1
  35. package/lib/privileged-settings.js +6 -0
  36. package/lib/read-env-value.js +19 -7
  37. package/lib/redis-keys.js +19 -0
  38. package/lib/redis-operations.js +7 -3
  39. package/lib/routes-ui.js +4 -1
  40. package/lib/schemas.js +8 -0
  41. package/lib/security-headers.js +18 -0
  42. package/lib/session-default.js +60 -0
  43. package/lib/settings.js +2 -1
  44. package/lib/stream-encrypt.js +71 -20
  45. package/lib/sub-script.js +8 -2
  46. package/lib/submit-lock.js +84 -0
  47. package/lib/submit-processor.js +283 -0
  48. package/lib/templates.js +6 -3
  49. package/lib/tls/context.js +2 -16
  50. package/lib/tools.js +8 -30
  51. package/lib/ui-routes/admin-config-routes.js +27 -5
  52. package/lib/ui-routes/auth-routes.js +4 -0
  53. package/lib/ui-routes/dbsc-routes.js +43 -0
  54. package/lib/utils/redis-errors.js +44 -0
  55. package/lib/webhook-delivery.js +3 -4
  56. package/lib/worker-rpc-error.js +10 -5
  57. package/lib/worker-rpc.js +138 -0
  58. package/package.json +17 -19
  59. package/sbom.json +370 -1446
  60. package/server.js +6 -5
  61. package/static/css/flyonui.css +2 -2
  62. package/static/licenses.html +253 -1366
  63. package/translations/messages.pot +16 -16
  64. package/views/config/security.hbs +37 -0
  65. package/workers/api.js +61 -467
  66. package/workers/export.js +14 -55
  67. package/workers/imap-proxy.js +5 -18
  68. package/workers/imap.js +27 -49
  69. package/workers/smtp.js +7 -69
  70. package/workers/submit.js +21 -279
  71. 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,16 @@ 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');
90
+ const { setupDbsc, registerDbscExtensions } = require('../lib/dbsc');
93
91
  const { Account } = require('../lib/account');
94
92
  const settings = require('../lib/settings');
95
93
 
@@ -103,7 +101,8 @@ const { registerOpenApiRoute } = require('../lib/openapi');
103
101
  const { getModel: getApiReferenceModel, clearServiceUrlCache } = require('../lib/api-reference');
104
102
 
105
103
  const { createCertHandler } = require('../lib/cert-handler');
106
- const { createTlsContext, applyTlsContext, apiTlsConfig } = require('../lib/tls/context');
104
+ const { createTlsContext, applyTlsContext } = require('../lib/tls/context');
105
+ const { apiPort, apiHost, apiTlsConfig } = require('../lib/api-listener');
107
106
  const { reconcileCertificates, requestProvisioning } = require('../lib/tls/provision');
108
107
  const { buildCertificateStatus } = require('../lib/tls/status');
109
108
 
@@ -125,7 +124,15 @@ const {
125
124
  } = consts;
126
125
 
127
126
  const registerApiRoutes = require('../lib/api-routes');
128
- const { securityHeadersExt, attachSecurityContext, isAdminPath, isMachineRoute, isSecureOrigin, CSP_MODES } = require('../lib/security-headers');
127
+ const {
128
+ securityHeadersExt,
129
+ attachSecurityContext,
130
+ isAdminPath,
131
+ isMachineRoute,
132
+ acceptsSession,
133
+ isSecureOrigin,
134
+ CSP_MODES
135
+ } = require('../lib/security-headers');
129
136
  const { deprecationExt } = require('../lib/deprecations');
130
137
  const { errorCodeExt } = require('../lib/api-error-codes');
131
138
  const { apiCallDuration } = require('../lib/request-timing');
@@ -206,12 +213,11 @@ const oidcAllowGroups = sso.parseGroupList(sso.OIDC_ALLOWED_GROUPS);
206
213
  const EENGINE_TIMEOUT = getDuration(readEnvValue('EENGINE_TIMEOUT') || config.service.commandTimeout) || DEFAULT_EENGINE_TIMEOUT;
207
214
  const MAX_ATTACHMENT_SIZE = getByteSize(readEnvValue('EENGINE_MAX_SIZE') || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
208
215
 
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;
216
+ const API_PORT = apiPort(config.api);
217
+ const API_HOST = apiHost(config.api);
212
218
 
213
219
  // Either an object (TLS enabled) or `false` (TLS disabled)
214
- const API_TLS = apiTlsConfig();
220
+ const API_TLS = apiTlsConfig(config.api);
215
221
 
216
222
  // Merge TLS settings from config params and environment
217
223
  loadTlsConfig(API_TLS, 'EENGINE_API_TLS_');
@@ -303,42 +309,9 @@ logger.info({
303
309
 
304
310
  const TRACKER_IMAGE = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');
305
311
 
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
- }
312
+ const { createRpcClient, respond, isCall } = require('../lib/worker-rpc');
313
+ const rpc = createRpcClient({ port: parentPort, defaultTimeout: EENGINE_TIMEOUT, timeoutTag: 'T2' });
314
+ const call = rpc.call;
342
315
 
343
316
  async function checkRateLimit(key, count, allowed, windowSize) {
344
317
  return await call({ cmd: 'rate-limit', key, count, allowed, windowSize });
@@ -466,47 +439,12 @@ let sessionAuthServer = null;
466
439
  let refreshApiTls = null;
467
440
 
468
441
  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
- }
442
+ if (rpc.handleResponse(message)) {
443
+ return;
490
444
  }
491
445
 
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
- });
446
+ if (isCall(message)) {
447
+ return respond(parentPort, message, onCommand, { logger });
510
448
  }
511
449
 
512
450
  if (message && message.cmd === 'change') {
@@ -753,7 +691,16 @@ function registerRequestContextExtension(server) {
753
691
 
754
692
  // Both settings are needed on every request and neither depends on the other, so they are
755
693
  // read in a single HMGET rather than two serialized round trips
756
- let { enableApiProxy, disableTokens, serviceUrl } = await settings.getMulti('enableApiProxy', 'disableTokens', 'serviceUrl');
694
+ let { enableApiProxy, disableTokens, serviceUrl, dbscEnabled } = await settings.getMulti(
695
+ 'enableApiProxy',
696
+ 'disableTokens',
697
+ 'serviceUrl',
698
+ 'dbscEnabled'
699
+ );
700
+
701
+ // Device-bound admin sessions only work on an https origin, which is what serviceUrl says
702
+ // the admin UI is reached on (the same signal that marks the cookies Secure)
703
+ request.app.dbscEnabled = !!dbscEnabled && isSecureOrigin(serviceUrl);
757
704
 
758
705
  // Before anything can render a view (the allowlist refusal below does), so the nonce
759
706
  // the template stamps on its scripts is the one the response header carries
@@ -847,376 +794,16 @@ function registerApiTokenAuth(server) {
847
794
  // Authentication for API calls
848
795
  server.auth.strategy('api-token', API_TOKEN_SCHEME, {
849
796
  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
- }
797
+ validate: createApiTokenValidator({
798
+ settings,
799
+ tokens,
800
+ tokenAuditLog,
801
+ redis,
802
+ checkRateLimit,
803
+ sessionPasswordVersion,
804
+ adminAccessAddresses: ADMIN_ACCESS_ADDRESSES,
805
+ logger
806
+ })
1220
807
  });
1221
808
  }
1222
809
 
@@ -1255,11 +842,13 @@ async function registerSessionAuth(server) {
1255
842
  isSecure: secureCookie
1256
843
  });
1257
844
 
845
+ const cookiePassword = await settings.get('cookiePassword');
846
+
1258
847
  // Authentication for admin pages
1259
848
  server.auth.strategy('session', 'cookie', {
1260
849
  cookie: {
1261
850
  name: 'ee',
1262
- password: await settings.get('cookiePassword'),
851
+ password: cookiePassword,
1263
852
  isSecure: secureCookie,
1264
853
  path: '/',
1265
854
  isSameSite: 'Lax'
@@ -1329,13 +918,8 @@ async function registerSessionAuth(server) {
1329
918
  return { isValid: false };
1330
919
  }
1331
920
 
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
- ) {
921
+ // unless it is a login or TOTP (or public) page, require TOTP code
922
+ if (session.requireTotp && !TOTP_EXEMPT_PATHS.includes(request.route && request.route.path)) {
1339
923
  request.requireTotp = true;
1340
924
  }
1341
925
 
@@ -1351,6 +935,9 @@ async function registerSessionAuth(server) {
1351
935
  }
1352
936
  });
1353
937
 
938
+ // Device-bound sessions ride on the same cookie settings (lib/dbsc)
939
+ setupDbsc(server, { redis, logger, secure: secureCookie, password: cookiePassword });
940
+
1354
941
  return secureCookie;
1355
942
  }
1356
943
 
@@ -1572,8 +1159,10 @@ async function registerServerPlugins(server) {
1572
1159
  }
1573
1160
 
1574
1161
  // 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)
1162
+ // through the settings dispatcher (see the authData branch there), and a password written with no
1163
+ // broadcast (the CLI) is noticed by the first request that would use the default
1576
1164
  sessionAuthServer = server;
1165
+ requireSessionOnceSecured({ server, isInstanceSecured: () => settings.isInstanceSecured(), logger });
1577
1166
 
1578
1167
  await server.register({
1579
1168
  plugin: requestLogger,
@@ -3041,7 +2630,9 @@ async function registerCsrfProtection(server, secureCookie) {
3041
2630
  skip: (request /*, h*/) => {
3042
2631
  let tags = (request.route && request.route.settings && request.route.settings.tags) || [];
3043
2632
 
3044
- if (isMachineRoute(tags)) {
2633
+ // A machine client holds no crumb, but a route that also takes the session cookie is
2634
+ // reachable from a browser and keeps the check whatever its tags say
2635
+ if (isMachineRoute(tags) && !acceptsSession(request.route.settings.auth)) {
3045
2636
  return true;
3046
2637
  }
3047
2638
 
@@ -3642,6 +3233,9 @@ const init = async () => {
3642
3233
 
3643
3234
  registerTotpExtension(server);
3644
3235
 
3236
+ // After the TOTP step and the error pages, see registerDbscExtensions()
3237
+ registerDbscExtensions(server);
3238
+
3645
3239
  registerChangesRoute(server);
3646
3240
 
3647
3241
  // setup web UI