emailengine-app 2.84.1 → 2.85.0

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 (147) hide show
  1. package/.dockerignore +6 -0
  2. package/.ncurc.js +5 -3
  3. package/.prettierignore +5 -1
  4. package/.prettierrc.js +2 -0
  5. package/.release-please-manifest.json +1 -1
  6. package/CHANGELOG.md +61 -0
  7. package/Dockerfile +8 -2
  8. package/README.md +1 -1
  9. package/bin/emailengine.js +444 -403
  10. package/copy-static-files.sh +39 -14
  11. package/data/google-crawlers.json +1 -1
  12. package/data/public_suffix_list.dat +16562 -0
  13. package/docker-compose.yml +1 -1
  14. package/eslint.config.js +81 -99
  15. package/lib/account/own-account-key.js +42 -0
  16. package/lib/account-assignment.js +1 -33
  17. package/lib/account.js +68 -24
  18. package/lib/add-trackers.js +11 -4
  19. package/lib/api-reference/format.js +4 -3
  20. package/lib/api-routes/account-routes.js +244 -26
  21. package/lib/api-routes/blocklist-routes.js +23 -2
  22. package/lib/api-routes/delivery-test-routes.js +26 -3
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +37 -5
  25. package/lib/api-routes/mailbox-routes.js +41 -2
  26. package/lib/api-routes/message-routes.js +104 -4
  27. package/lib/api-routes/mint-bounds.js +11 -0
  28. package/lib/api-routes/oauth2-app-routes.js +48 -15
  29. package/lib/api-routes/outbox-routes.js +45 -11
  30. package/lib/api-routes/permission-map.js +12 -1
  31. package/lib/api-routes/route-helpers.js +125 -3
  32. package/lib/api-routes/settings-routes.js +23 -2
  33. package/lib/api-routes/submit-routes.js +338 -309
  34. package/lib/api-routes/template-routes.js +38 -2
  35. package/lib/api-routes/token-routes.js +142 -96
  36. package/lib/api-routes/webhook-route-routes.js +13 -2
  37. package/lib/auth-token.js +23 -10
  38. package/lib/bounce-detect.js +414 -210
  39. package/lib/consts.js +39 -4
  40. package/lib/create-imap-client.js +41 -2
  41. package/lib/email-client/base-client.js +30 -41
  42. package/lib/email-client/gmail-client.js +30 -18
  43. package/lib/email-client/imap/mailbox.js +13 -23
  44. package/lib/email-client/imap/response-metrics.js +75 -0
  45. package/lib/email-client/imap/subconnection.js +1 -1
  46. package/lib/email-client/imap-client.js +6 -3
  47. package/lib/email-client/message-builder.js +7 -2
  48. package/lib/email-client/notification-handler.js +1 -2
  49. package/lib/email-client/outlook/graph-api.js +17 -2
  50. package/lib/email-client/outlook-client.js +6 -3
  51. package/lib/email-client/smtp-pool-manager.js +6 -0
  52. package/lib/encrypt.js +9 -0
  53. package/lib/export.js +3 -1
  54. package/lib/gateway.js +2 -3
  55. package/lib/get-raw-email.js +4 -2
  56. package/lib/hapi-request-logger.js +107 -0
  57. package/lib/imap-proxy-auth.js +14 -1
  58. package/lib/imapproxy/imap-core/README.md +6 -5
  59. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  60. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  61. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  62. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  63. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  64. package/lib/mcp/listen.js +10 -1
  65. package/lib/mcp/tools.js +37 -8
  66. package/lib/notify-attachments.js +17 -0
  67. package/lib/oauth/external-account-config.js +3 -1
  68. package/lib/oauth/gmail.js +21 -48
  69. package/lib/oauth/mail-ru.js +5 -38
  70. package/lib/oauth/outlook-mailbox.js +35 -0
  71. package/lib/oauth/outlook.js +26 -44
  72. package/lib/oauth/state.js +24 -0
  73. package/lib/oauth2-apps.js +1 -1
  74. package/lib/pbkdf2-phc.js +19 -2
  75. package/lib/privileged-settings.js +6 -3
  76. package/lib/redis-scan-delete.js +15 -1
  77. package/lib/schemas.js +79 -33
  78. package/lib/settings.js +13 -1
  79. package/lib/smtp-auth.js +23 -0
  80. package/lib/sso.js +1 -1
  81. package/lib/swagger-options.js +1 -1
  82. package/lib/thread-diagnostics.js +46 -0
  83. package/lib/timezones.js +109 -0
  84. package/lib/token-permission-view.js +3 -3
  85. package/lib/tools.js +285 -66
  86. package/lib/totp.js +2 -5
  87. package/lib/translations.js +1 -2
  88. package/lib/ui-routes/account-routes.js +491 -491
  89. package/lib/ui-routes/account-setup.js +99 -0
  90. package/lib/ui-routes/admin-config-routes.js +98 -48
  91. package/lib/ui-routes/admin-entities-routes.js +113 -31
  92. package/lib/ui-routes/auth-routes.js +137 -62
  93. package/lib/ui-routes/connection-security-form.js +74 -0
  94. package/lib/ui-routes/form-lists.js +46 -0
  95. package/lib/ui-routes/internals-routes.js +5 -0
  96. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  97. package/lib/ui-routes/oauth-config-routes.js +133 -100
  98. package/lib/ui-routes/route-helpers.js +19 -3
  99. package/lib/ui-routes/sign-in-helpers.js +59 -0
  100. package/lib/ui-routes/tls-config-routes.js +58 -15
  101. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  102. package/lib/utils/back-off.js +82 -0
  103. package/lib/utils/map-concurrent.js +36 -0
  104. package/lib/utils/murmurhash3.js +66 -0
  105. package/lib/utils/network.js +28 -0
  106. package/lib/utils/provider-id.js +27 -0
  107. package/lib/utils/public-suffix.js +122 -0
  108. package/lib/utils/random-id.js +26 -0
  109. package/lib/utils/require-tls.js +33 -0
  110. package/lib/utils/version.js +74 -0
  111. package/lib/web-safe-html.js +5 -6
  112. package/lib/webhook-penalty.js +75 -0
  113. package/lib/webhook-routing.js +49 -2
  114. package/lib/webhooks.js +41 -6
  115. package/package.json +37 -39
  116. package/sbom.json +7980 -1
  117. package/server.js +659 -455
  118. package/static/js/ace/ace.js +1 -1
  119. package/static/js/ace/mode-handlebars.js +1 -1
  120. package/static/js/ace/mode-html.js +1 -1
  121. package/static/js/ace/mode-javascript.js +1 -1
  122. package/static/js/ace/mode-markdown.js +1 -1
  123. package/static/js/ace/worker-html.js +1 -1
  124. package/static/js/ace/worker-javascript.js +1 -1
  125. package/static/js/ace/worker-json.js +1 -1
  126. package/static/js/ee-client.js +5 -0
  127. package/static/licenses.html +191 -1016
  128. package/translations/messages.pot +70 -71
  129. package/views/account/security.hbs +10 -0
  130. package/views/accounts/account.hbs +11 -11
  131. package/views/accounts/edit.hbs +6 -2
  132. package/views/config/ai.hbs +1 -1
  133. package/views/config/security.hbs +2 -2
  134. package/views/config/service.hbs +3 -0
  135. package/views/internals/index.hbs +8 -0
  136. package/views/partials/gateway_form.hbs +3 -1
  137. package/views/partials/webhook_form.hbs +1 -1
  138. package/views/suppression-lists/index.hbs +1 -1
  139. package/workers/api.js +780 -585
  140. package/workers/export.js +1 -1
  141. package/workers/submit.js +1 -1
  142. package/workers/webhooks.js +54 -34
  143. package/config/test.toml +0 -46
  144. package/install.sh +0 -428
  145. package/setup-production.sh +0 -215
  146. package/systemd/emailengine.service +0 -97
  147. package/systemd/nginx-proxy.conf +0 -77
package/workers/api.js CHANGED
@@ -8,7 +8,14 @@ const logger = require('../lib/logger');
8
8
  const Path = require('path');
9
9
  const Gettext = require('@postalsys/gettext');
10
10
  const { loadTranslations, gt, joiLocales, locales } = require('../lib/translations');
11
- const { accountStateLabel, formatServerState, identityErrorView, workspaceErrorView, isClientError } = require('../lib/ui-routes/route-helpers');
11
+ const {
12
+ accountStateLabel,
13
+ formatServerState,
14
+ identityErrorView,
15
+ workspaceErrorView,
16
+ renderRedirect,
17
+ isClientError
18
+ } = require('../lib/ui-routes/route-helpers');
12
19
  const { boundRouteBinding } = require('../lib/api-routes/account-binding');
13
20
  const util = require('util');
14
21
  const { webhooks: Webhooks } = require('../lib/webhooks');
@@ -39,8 +46,7 @@ const {
39
46
  resolveOAuthErrorStatus,
40
47
  constantTimeEqual,
41
48
  verifyServiceSignature,
42
- claimFormNonce,
43
- releaseFormNonce,
49
+ SIGNING_PURPOSE,
44
50
  setAdminSession,
45
51
  isEndedSession
46
52
  } = require('../lib/tools');
@@ -54,7 +60,7 @@ const Boom = require('@hapi/boom');
54
60
  const Cookie = require('@hapi/cookie');
55
61
  const Crumb = require('@hapi/crumb');
56
62
  const Joi = require('joi');
57
- const hapiPino = require('hapi-pino');
63
+ const requestLogger = require('../lib/hapi-request-logger');
58
64
  const Inert = require('@hapi/inert');
59
65
  const Vision = require('@hapi/vision');
60
66
  const Accept = require('@hapi/accept');
@@ -66,6 +72,9 @@ const { registeredPublishers, openChangeStream } = require('../lib/response-stre
66
72
  const { oauth2Apps } = require('../lib/oauth2-apps');
67
73
  const { decodeJwtPayload } = require('../lib/oauth/decode-jwt-payload');
68
74
  const { resolveOutlookUserInfo } = require('../lib/oauth/outlook-identity');
75
+ const { resolveOutlookMailbox } = require('../lib/oauth/outlook-mailbox');
76
+ const { isValidOAuthState } = require('../lib/oauth/state');
77
+ const { completeAccountSetup } = require('../lib/ui-routes/account-setup');
69
78
  const { buildRetrySetup } = require('../lib/oauth/retry-setup');
70
79
  const { matchesExpectedIdentity, pendingSetupExpectation, resolveExpectedIdentity } = require('../lib/account/expected-identity');
71
80
 
@@ -369,7 +378,7 @@ async function sendWebhook(account, event, data) {
369
378
  payload.data = data;
370
379
  }
371
380
 
372
- await Webhooks.pushToQueue(event, await Webhooks.formatPayload(event, payload));
381
+ await Webhooks.enqueue(event, payload);
373
382
  }
374
383
 
375
384
  async function onCommand(command) {
@@ -496,15 +505,22 @@ parentPort.on('message', message => {
496
505
  }
497
506
  });
498
507
 
499
- const init = async () => {
500
- await loadTranslations();
501
-
502
- gt.setLocale((await settings.get('locale')) || 'en');
503
-
504
- registerHandlebarsHelpers(handlebars, { gt });
508
+ // Set by the certificate timer from the startup prechecks (scheduleCertificateReconciler) and read
509
+ // by the onPreResponse extension (registerResponseExtensions)
510
+ let assertPreconditionResult;
505
511
 
512
+ /**
513
+ * Builds the hapi server, with the API TLS context when the API is served over HTTPS
514
+ * @returns {Promise<Object>} The server, the certificate handler, the API TLS context and the
515
+ * SO_REUSEPORT listener (null unless several API workers share the port)
516
+ */
517
+ async function createApiServer() {
506
518
  // Base Hapi options shared by both the default and SO_REUSEPORT binding paths
507
519
  const serverOptions = {
520
+ // hapi's default prints every internal request error to stderr; the request error
521
+ // listener below logs them through pino instead
522
+ debug: false,
523
+
508
524
  state: {
509
525
  strictHeader: false
510
526
  },
@@ -589,8 +605,10 @@ const init = async () => {
589
605
  });
590
606
  }
591
607
 
592
- let assertPreconditionResult;
608
+ return { server, certHandler, apiTlsContext, reusePortListener };
609
+ }
593
610
 
611
+ function decorateApiToolkit(server, certHandler, apiTlsContext) {
594
612
  // A read-only view of the certificate store for routes. Ordering a certificate is the
595
613
  // reconciler's job - it owns the state a page follows, the retry pacing and the listener
596
614
  // reload - and the difference between reading and ordering is one argument
@@ -621,7 +639,9 @@ const init = async () => {
621
639
  enabled: !!API_TLS,
622
640
  active: apiTlsContext ? apiTlsContext.active : null
623
641
  }));
642
+ }
624
643
 
644
+ function registerLocaleExtension(server) {
625
645
  server.ext('onPreAuth', async (request, h) => {
626
646
  const tags = (request.route && request.route.settings && request.route.settings.tags) || [];
627
647
  // Skip if it's a static file route
@@ -696,7 +716,9 @@ const init = async () => {
696
716
 
697
717
  return h.continue;
698
718
  });
719
+ }
699
720
 
721
+ function registerRequestContextExtension(server) {
700
722
  server.ext('onRequest', async (request, h) => {
701
723
  // set default, will be overriden once active language is resolved
702
724
  request.app.gt = gt;
@@ -772,7 +794,9 @@ const init = async () => {
772
794
 
773
795
  return h.continue;
774
796
  });
797
+ }
775
798
 
799
+ function buildOpenApiOptions() {
776
800
  const openApiOptions = {
777
801
  // Spec-shaping options (tag list and order, security scheme, external docs) live in
778
802
  // lib/swagger-options.js so the document can be reproduced outside a running server
@@ -786,6 +810,10 @@ const init = async () => {
786
810
  cors: !!CORS_CONFIG
787
811
  };
788
812
 
813
+ return openApiOptions;
814
+ }
815
+
816
+ function registerApiTokenAuth(server) {
789
817
  server.auth.scheme(API_TOKEN_SCHEME, apiTokenScheme);
790
818
 
791
819
  // Authentication for API calls
@@ -843,6 +871,20 @@ const init = async () => {
843
871
 
844
872
  let isValidSessionToken = await tokens.validateSessionToken(session.sid, token, request.params.account, 900);
845
873
  if (isValidSessionToken) {
874
+ // The credential was minted for a page inside the admin perimeter, so it is
875
+ // held to that perimeter too. The /v1 path it is presented on is not an admin
876
+ // path, so the request-level check above did not apply.
877
+ if (ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length && !matchIp(request.app.ip, ADMIN_ACCESS_ADDRESSES)) {
878
+ logger.warn({
879
+ msg: 'Session token presented from outside the admin address list',
880
+ account: request.params.account,
881
+ remoteAddress: request.app.ip,
882
+ method: request.route.method,
883
+ path: request.route.path
884
+ });
885
+ throw Boom.forbidden('Unauthorized address');
886
+ }
887
+
846
888
  // A session token is bound to the account whose page minted it (checked above,
847
889
  // against request.params.account), but it used to reach every api-tagged route
848
890
  // naming that account - it never met the permission model at all. It lives in
@@ -1148,7 +1190,26 @@ const init = async () => {
1148
1190
  return { isValid: true, credentials: { token }, artifacts: tokenData };
1149
1191
  }
1150
1192
  });
1193
+ }
1151
1194
 
1195
+ // The version an SSO login stamps into its session, so the checks that end a session later can
1196
+ // compare against it. The password logins in lib/ui-routes/auth-routes.js stamp the same field
1197
+ // from the same place; without it a session is refused on the first request after any version
1198
+ // bump, which is a forced re-login rather than a lockout.
1199
+ //
1200
+ // Read by both strategies that accept a session: the cookie strategy below, and the session
1201
+ // token branch of the api-token strategy above - the two credentials the same cookie carries,
1202
+ // and "log out all sessions" has to end both.
1203
+ const sessionPasswordVersion = async () => {
1204
+ const authData = await settings.get('authData');
1205
+ return (authData && authData.passwordVersion) || 0;
1206
+ };
1207
+
1208
+ /**
1209
+ * Registers the cookie plugins and the admin session strategy
1210
+ * @returns {Promise<boolean>} Whether the cookies are marked Secure
1211
+ */
1212
+ async function registerSessionAuth(server) {
1152
1213
  // needed for auth session and flash messages
1153
1214
  await server.register(Cookie);
1154
1215
  await server.register(Bell);
@@ -1166,20 +1227,6 @@ const init = async () => {
1166
1227
  isSecure: secureCookie
1167
1228
  });
1168
1229
 
1169
- // The version an SSO login stamps into its session, so the checks that end a session later can
1170
- // compare against it. The password logins in lib/ui-routes/auth-routes.js stamp the same field
1171
- // from the same place; without it a session is refused on the first request after any version
1172
- // bump, which is a forced re-login rather than a lockout.
1173
- //
1174
- // Read by both strategies that accept a session: the cookie strategy below, and the session
1175
- // token branch of the api-token strategy above - the two credentials the same cookie carries,
1176
- // and "log out all sessions" has to end both. Declared here rather than above because both
1177
- // consumers only call it at request time, which is after this whole function has run.
1178
- const sessionPasswordVersion = async () => {
1179
- const authData = await settings.get('authData');
1180
- return (authData && authData.passwordVersion) || 0;
1181
- };
1182
-
1183
1230
  // Authentication for admin pages
1184
1231
  server.auth.strategy('session', 'cookie', {
1185
1232
  cookie: {
@@ -1276,27 +1323,31 @@ const init = async () => {
1276
1323
  }
1277
1324
  });
1278
1325
 
1279
- // Shared by the SSO strategies. The redirect URL is captured at strategy registration;
1280
- // the validators re-read it from settings so an origin change after startup (which would
1281
- // break the registered callback URL) disables the SSO button instead of failing mid-flow.
1282
- let getServiceRedirectUrl = async () => new URL((await settings.get('serviceUrl')) || `http://${API_HOST}${API_PORT !== 80 ? `:${API_PORT}` : ''}`);
1283
- let serviceOriginUnchanged = async redirectUrl => (await getServiceRedirectUrl()).origin === redirectUrl.origin;
1284
- // A sign-in the IdP denied, or the user cancelled, comes back as an unauthenticated try-mode
1285
- // request. It gets the same flash-and-redirect the allow-list denial in the OIDC handler
1286
- // uses, so the user lands on the login form with a way to try again rather than on the
1287
- // generic error page with bell's raw message. The reason goes to the log only. ?sso_denied=1
1288
- // stops a forced instance from auto-redirecting straight back into the flow.
1289
- let ssoFailureRedirect = async (request, h, method) => {
1290
- request.logger.warn({
1291
- msg: 'SSO login failed',
1292
- method,
1293
- reason: (request.auth.error && request.auth.error.message) || 'unknown',
1294
- remoteAddress: request.app.ip
1295
- });
1296
- await request.flash({ type: 'danger', message: 'Single sign-on failed or was cancelled. Please try again' });
1297
- return h.redirect('/admin/login?sso_denied=1');
1298
- };
1326
+ return secureCookie;
1327
+ }
1328
+
1329
+ // Shared by the SSO strategies. The redirect URL is captured at strategy registration;
1330
+ // the validators re-read it from settings so an origin change after startup (which would
1331
+ // break the registered callback URL) disables the SSO button instead of failing mid-flow.
1332
+ let getServiceRedirectUrl = async () => new URL((await settings.get('serviceUrl')) || `http://${API_HOST}${API_PORT !== 80 ? `:${API_PORT}` : ''}`);
1333
+ let serviceOriginUnchanged = async redirectUrl => (await getServiceRedirectUrl()).origin === redirectUrl.origin;
1334
+ // A sign-in the IdP denied, or the user cancelled, comes back as an unauthenticated try-mode
1335
+ // request. It gets the same flash-and-redirect the allow-list denial in the OIDC handler
1336
+ // uses, so the user lands on the login form with a way to try again rather than on the
1337
+ // generic error page with bell's raw message. The reason goes to the log only. ?sso_denied=1
1338
+ // stops a forced instance from auto-redirecting straight back into the flow.
1339
+ let ssoFailureRedirect = async (request, h, method) => {
1340
+ request.logger.warn({
1341
+ msg: 'SSO login failed',
1342
+ method,
1343
+ reason: (request.auth.error && request.auth.error.message) || 'unknown',
1344
+ remoteAddress: request.app.ip
1345
+ });
1346
+ await request.flash({ type: 'danger', message: 'Single sign-on failed or was cancelled. Please try again' });
1347
+ return h.redirect('/admin/login?sso_denied=1');
1348
+ };
1299
1349
 
1350
+ async function registerOktaAuth(server, secureCookie) {
1300
1351
  if (USE_OKTA_AUTH) {
1301
1352
  let redirectUrl = await getServiceRedirectUrl();
1302
1353
 
@@ -1351,7 +1402,9 @@ const init = async () => {
1351
1402
  }
1352
1403
  });
1353
1404
  }
1405
+ }
1354
1406
 
1407
+ async function registerOidcAuth(server, secureCookie) {
1355
1408
  if (USE_OIDC_AUTH) {
1356
1409
  let redirectUrl = await getServiceRedirectUrl();
1357
1410
 
@@ -1483,7 +1536,9 @@ const init = async () => {
1483
1536
  .catch(err => logger.error({ msg: 'OIDC SSO disabled: discovery retry failed', issuer: sso.OIDC_ISSUER, err }));
1484
1537
  }
1485
1538
  }
1539
+ }
1486
1540
 
1541
+ async function registerServerPlugins(server) {
1487
1542
  if (await settings.isInstanceSecured()) {
1488
1543
  server.auth.default('session');
1489
1544
  }
@@ -1493,19 +1548,37 @@ const init = async () => {
1493
1548
  sessionAuthServer = server;
1494
1549
 
1495
1550
  await server.register({
1496
- plugin: hapiPino,
1551
+ plugin: requestLogger,
1497
1552
  options: {
1498
- instance: logger.child({ component: 'api' }, { redact: consts.REDACTED_LOG_KEYS }),
1499
1553
  // Redact Authorization headers, see https://getpino.io/#/docs/redaction
1500
- redact: consts.REDACTED_LOG_KEYS
1554
+ logger: logger.child({ component: 'api' }, { redact: consts.REDACTED_LOG_KEYS })
1501
1555
  }
1502
1556
  });
1503
1557
 
1504
1558
  await server.register([Inert, Vision]);
1559
+ }
1505
1560
 
1506
- // Position is not load-bearing: the document is generated from the finished route table on the
1507
- // first request, not at registration time
1508
- registerOpenApiRoute(server, openApiOptions);
1561
+ function registerRequestEvents(server) {
1562
+ // An exception thrown by a handler, an extension or a response schema with failAction
1563
+ // 'error' is answered with a bare 500 and reported on the request's error channel. hapi's
1564
+ // own record of it was an unstructured line on stderr (switched off above), and the API
1565
+ // error path only logs what handlers pass to handleError(), not what escapes them
1566
+ server.events.on({ name: 'request', channels: 'error' }, (request, event, tags) => {
1567
+ if (tags.internal && !tags.implementation) {
1568
+ // a 5xx the code raised on purpose: the API error path (handleError) and the web
1569
+ // error page log those themselves, with the request context they have
1570
+ return;
1571
+ }
1572
+ logger.error({
1573
+ msg: 'Request failed with an internal error',
1574
+ component: 'api',
1575
+ method: request.method,
1576
+ path: request.path,
1577
+ route: request.route && request.route.path,
1578
+ tags: Object.keys(tags || {}),
1579
+ err: event.error
1580
+ });
1581
+ });
1509
1582
 
1510
1583
  server.events.on('response', request => {
1511
1584
  const tags = request.route && request.route.settings && request.route.settings.tags;
@@ -1519,7 +1592,9 @@ const init = async () => {
1519
1592
  statusCode: request.response && request.response.statusCode
1520
1593
  });
1521
1594
  });
1595
+ }
1522
1596
 
1597
+ function registerStaticPageRoutes(server) {
1523
1598
  server.route({
1524
1599
  method: 'GET',
1525
1600
  path: '/',
@@ -1640,7 +1715,9 @@ const init = async () => {
1640
1715
  tags: ['static']
1641
1716
  }
1642
1717
  });
1718
+ }
1643
1719
 
1720
+ function registerStaticFilesRoute(server) {
1644
1721
  const staticRoot = pathlib.resolve(__dirname, '..', 'static');
1645
1722
  const staticRootPrefix = staticRoot + pathlib.sep;
1646
1723
 
@@ -1692,7 +1769,9 @@ const init = async () => {
1692
1769
  : undefined
1693
1770
  }
1694
1771
  });
1772
+ }
1695
1773
 
1774
+ function registerHealthRoute(server) {
1696
1775
  server.route({
1697
1776
  method: 'GET',
1698
1777
  path: '/health',
@@ -1719,13 +1798,15 @@ const init = async () => {
1719
1798
  tags: ['static', 'health']
1720
1799
  }
1721
1800
  });
1801
+ }
1722
1802
 
1803
+ function registerRedirectRoute(server) {
1723
1804
  server.route({
1724
1805
  method: 'GET',
1725
1806
  path: '/redirect',
1726
1807
  async handler(request, h) {
1727
1808
  let data = Buffer.from(request.query.data, 'base64url').toString();
1728
- if (!(await verifyServiceSignature(data, request.query.sig))) {
1809
+ if (!(await verifyServiceSignature(data, request.query.sig, SIGNING_PURPOSE.TRACKING))) {
1729
1810
  let error = Boom.boomify(new Error('Signature validation failed'), { statusCode: 403 });
1730
1811
  throw error;
1731
1812
  }
@@ -1789,13 +1870,15 @@ const init = async () => {
1789
1870
  auth: false
1790
1871
  }
1791
1872
  });
1873
+ }
1792
1874
 
1875
+ function registerOpenTrackingRoute(server) {
1793
1876
  server.route({
1794
1877
  method: 'GET',
1795
1878
  path: '/open.gif',
1796
1879
  async handler(request, h) {
1797
1880
  let data = Buffer.from(request.query.data, 'base64url').toString();
1798
- if (!(await verifyServiceSignature(data, request.query.sig))) {
1881
+ if (!(await verifyServiceSignature(data, request.query.sig, SIGNING_PURPOSE.TRACKING))) {
1799
1882
  let error = Boom.boomify(new Error('Signature validation failed'), { statusCode: 403 });
1800
1883
  throw error;
1801
1884
  }
@@ -1854,7 +1937,9 @@ const init = async () => {
1854
1937
  auth: false
1855
1938
  }
1856
1939
  });
1940
+ }
1857
1941
 
1942
+ function registerUnsubscribeRoute(server) {
1858
1943
  server.route({
1859
1944
  method: 'POST',
1860
1945
  path: '/unsubscribe',
@@ -1873,7 +1958,7 @@ const init = async () => {
1873
1958
 
1874
1959
  // A false result is a forged/bad signature (permanent -> benign); a THROWN error is a
1875
1960
  // transient failure reading the service secret and is intentionally left to surface as 5xx.
1876
- if (!(await verifyServiceSignature(raw, request.query.sig))) {
1961
+ if (!(await verifyServiceSignature(raw, request.query.sig, SIGNING_PURPOSE.UNSUBSCRIBE))) {
1877
1962
  return 'data validation failed';
1878
1963
  }
1879
1964
 
@@ -1972,7 +2057,9 @@ const init = async () => {
1972
2057
  auth: false
1973
2058
  }
1974
2059
  });
2060
+ }
1975
2061
 
2062
+ function registerOutlookNotificationRoute(server) {
1976
2063
  server.route({
1977
2064
  method: 'POST',
1978
2065
  path: '/oauth/msg/notification',
@@ -2075,7 +2162,9 @@ const init = async () => {
2075
2162
  auth: false
2076
2163
  }
2077
2164
  });
2165
+ }
2078
2166
 
2167
+ function registerOutlookLifecycleRoute(server) {
2079
2168
  server.route({
2080
2169
  method: 'POST',
2081
2170
  path: '/oauth/msg/lifecycle',
@@ -2220,587 +2309,608 @@ const init = async () => {
2220
2309
  auth: false
2221
2310
  }
2222
2311
  });
2312
+ }
2223
2313
 
2224
- server.route({
2225
- method: 'GET',
2226
- path: '/oauth',
2227
- async handler(request, h) {
2228
- // The mailbox owner sees these on the public error page, in the same locale as the
2229
- // rest of the setup flow. The pending setup is still unspent at this point (its state
2230
- // entry is claimed only below), so opening the setup link again is a valid retry.
2231
- if (request.query.error === 'access_denied') {
2232
- let error = Boom.badRequest(
2233
- request.app.gt.gettext('The sign-in was cancelled or the requested access was not granted. Open the account setup link again to retry.')
2234
- );
2235
- if (request.query.error_description) {
2236
- error.output.payload.details = [String(request.query.error_description)];
2237
- }
2238
- throw error;
2239
- }
2240
-
2241
- if (request.query.error) {
2242
- throw Boom.badRequest(util.format(request.app.gt.gettext('Sign-in with the email provider failed: %s'), request.query.error));
2243
- }
2314
+ // The OAuth2 callback (GET /oauth). The handler below runs these steps in order; every one that
2315
+ // can end the request either throws or returns the response to send.
2316
+
2317
+ // Refuses a callback that reports a provider error, carries no code or names a malformed state,
2318
+ // before the pending setup is touched
2319
+ function assertOAuthCallbackQuery(request) {
2320
+ // The mailbox owner sees these on the public error page, in the same locale as the
2321
+ // rest of the setup flow. The pending setup is still unspent at this point (its state
2322
+ // entry is claimed only below), so opening the setup link again is a valid retry.
2323
+ if (request.query.error === 'access_denied') {
2324
+ let error = Boom.badRequest(
2325
+ request.app.gt.gettext('The sign-in was cancelled or the requested access was not granted. Open the account setup link again to retry.')
2326
+ );
2327
+ if (request.query.error_description) {
2328
+ error.output.payload.details = [String(request.query.error_description)];
2329
+ }
2330
+ throw error;
2331
+ }
2244
2332
 
2245
- if (!request.query.code) {
2246
- throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: no authorization code was received'));
2247
- }
2333
+ if (request.query.error) {
2334
+ throw Boom.badRequest(util.format(request.app.gt.gettext('Sign-in with the email provider failed: %s'), request.query.error));
2335
+ }
2248
2336
 
2249
- // Validate nonce format: 16 bytes base64url encoded = 21-22 characters
2250
- // Also accept base64 encoding (+, /, =) for backward compatibility with old cached nonces
2251
- if (!/^account:add:[A-Za-z0-9_\-+/]{21,22}={0,2}$/.test(request.query.state)) {
2252
- throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: the request state is not valid'));
2253
- }
2337
+ if (!request.query.code) {
2338
+ throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: no authorization code was received'));
2339
+ }
2254
2340
 
2255
- let [[, accountData]] = await redis.multi().get(`${REDIS_PREFIX}${request.query.state}`).del(`${REDIS_PREFIX}${request.query.state}`).exec();
2256
- if (!accountData) {
2257
- throw Boom.badRequest(
2258
- request.app.gt.gettext('The account setup session has expired or was already used. Open the account setup link again to retry.')
2259
- );
2260
- }
2341
+ if (!isValidOAuthState(request.query.state)) {
2342
+ throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: the request state is not valid'));
2343
+ }
2344
+ }
2261
2345
 
2262
- try {
2263
- accountData = JSON.parse(accountData);
2264
- } catch (E) {
2265
- throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: the stored setup session is not valid'));
2266
- }
2346
+ // Claims the pending setup the state names: the entry is deleted in the same transaction that reads
2347
+ // it, so a setup can be completed only once
2348
+ async function claimOAuthSetup(request) {
2349
+ let [[, accountData]] = await redis.multi().get(`${REDIS_PREFIX}${request.query.state}`).del(`${REDIS_PREFIX}${request.query.state}`).exec();
2350
+ if (!accountData) {
2351
+ throw Boom.badRequest(request.app.gt.gettext('The account setup session has expired or was already used. Open the account setup link again to retry.'));
2352
+ }
2267
2353
 
2268
- if (!accountData.account) {
2269
- accountData.account = null;
2270
- }
2354
+ try {
2355
+ accountData = JSON.parse(accountData);
2356
+ } catch (E) {
2357
+ throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: the stored setup session is not valid'));
2358
+ }
2271
2359
 
2272
- const accountMeta = accountData._meta || {};
2273
- delete accountData._meta;
2360
+ if (!accountData.account) {
2361
+ accountData.account = null;
2362
+ }
2274
2363
 
2275
- const redirectUrl = accountMeta.redirectUrl;
2364
+ return accountData;
2365
+ }
2276
2366
 
2277
- const provider = accountData.oauth2.provider;
2367
+ // Hands the user back to the provider after a failure they can correct themselves, as a fresh
2368
+ // single-use setup. The token-bearing oauth2 object is dropped so the retry starts clean, and
2369
+ // _meta rides along so the redirect URL, the expected identity and the form nonce all survive
2370
+ // it - that nonce is claimed only on success, so it is still unspent here.
2371
+ async function startOAuthRetry(flow, loginHint, prompt) {
2372
+ const { accountData, requestedSetup, provider, accountMeta, oAuth2Client } = flow;
2278
2373
 
2279
- // What the caller originally asked for, captured before the provider branches below rewrite
2280
- // accountData from whoever signed in. A retry has to start from this rather than from the
2281
- // rejected attempt: `email` may name a shared mailbox to bind (and is otherwise overwritten
2282
- // with the authenticated address), `name` gets filled in from the rejected user's profile when
2283
- // the caller supplied none, and `oauth2.auth.delegatedUser` names the mailbox rather than a
2284
- // credential, so it must survive while the tokens do not.
2285
- const requestedSetup = {
2286
- email: accountData.email,
2287
- name: accountData.name,
2288
- delegatedUser: accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser
2289
- };
2374
+ const reAuthState = `account:add:${crypto.randomBytes(NONCE_BYTES).toString('base64url')}`;
2375
+ const reAuthAccountData = buildRetrySetup(accountData, requestedSetup, provider, accountMeta);
2290
2376
 
2291
- const oauth2App = await oauth2Apps.get(provider);
2292
- if (!oauth2App) {
2293
- let error = Boom.boomify(new Error('Missing or disabled OAuth2 app'), { statusCode: 404 });
2294
- throw error;
2295
- }
2377
+ await redis.set(`${REDIS_PREFIX}${reAuthState}`, JSON.stringify(reAuthAccountData), 'EX', Math.floor(MAX_FORM_TTL / 1000));
2296
2378
 
2297
- // The code exchange, the profile lookups and any revoke already speak for the account being
2298
- // set up, so they leave through its route (its own proxy, if the setup named one)
2299
- const oAuth2Client = await oauth2Apps.getClient(oauth2App.id, { route: await getAccountHttpRoute(redis, accountData) });
2379
+ // The address to steer the user towards rides on the authorize URL only - persisting it
2380
+ // would overwrite a shared mailbox with the principal that is signing in to reach it.
2381
+ return oAuth2Client.generateAuthUrl({ state: reAuthState, email: loginHint, prompt });
2382
+ }
2300
2383
 
2301
- // have to use HTML redirect, otherwise samesite=strict cookies are not passed on
2302
- const renderRedirect = httpRedirectUrl =>
2303
- h.view(
2304
- 'redirect',
2305
- {
2306
- pageTitleFull: request.app.gt.gettext('Email Account Setup'),
2307
- httpRedirectUrl
2308
- },
2309
- {
2310
- layout: 'public'
2311
- }
2312
- );
2384
+ async function gmailMissingScopesView(flow, r, grantedScopes) {
2385
+ const { request, h, oAuth2Client, accountData } = flow;
2313
2386
 
2314
- // Hands the user back to the provider after a failure they can correct themselves, as a fresh
2315
- // single-use setup. The token-bearing oauth2 object is dropped so the retry starts clean, and
2316
- // _meta rides along so the redirect URL, the expected identity and the form nonce all survive
2317
- // it - that nonce is claimed only on success, so it is still unspent here.
2318
- const startOAuthRetry = async (loginHint, prompt) => {
2319
- const reAuthState = `account:add:${crypto.randomBytes(NONCE_BYTES).toString('base64url')}`;
2320
- const reAuthAccountData = buildRetrySetup(accountData, requestedSetup, provider, accountMeta);
2387
+ // Check if user deselected required scopes in Google's granular consent
2388
+ const requiredFunctionalScopes = oAuth2Client.scopes.filter(s => !OPENID_SCOPES.includes(s));
2389
+ const missingScopes = requiredFunctionalScopes.filter(s => !grantedScopes.includes(s));
2321
2390
 
2322
- await redis.set(`${REDIS_PREFIX}${reAuthState}`, JSON.stringify(reAuthAccountData), 'EX', Math.floor(MAX_FORM_TTL / 1000));
2391
+ if (missingScopes.length > 0) {
2392
+ request.logger.warn({
2393
+ msg: 'OAuth2 grant missing required scopes',
2394
+ requested: requiredFunctionalScopes,
2395
+ granted: grantedScopes,
2396
+ missing: missingScopes
2397
+ });
2323
2398
 
2324
- // The address to steer the user towards rides on the authorize URL only - persisting it
2325
- // would overwrite a shared mailbox with the principal that is signing in to reach it.
2326
- return oAuth2Client.generateAuthUrl({ state: reAuthState, email: loginHint, prompt });
2327
- };
2399
+ // Best-effort revocation of the partial token
2400
+ oAuth2Client.revokeToken(r.refresh_token || r.access_token).catch(err => {
2401
+ request.logger.warn({ msg: 'Failed to revoke partial OAuth2 token', err });
2402
+ });
2328
2403
 
2329
- // Addresses the provider itself returned over a back channel, the only values allowed to
2330
- // satisfy an expected identity (see lib/account/expected-identity.js). Every provider case
2331
- // fills this in; one that does not leaves it empty, and an empty list fails the check closed.
2332
- const providerIdentities = [];
2333
-
2334
- // The Workspace or Cloud organization domain the provider reported, for an application
2335
- // restricted to Google Workspace accounts. Only the Gmail case fills it in; the
2336
- // restriction is a Google setting and no other provider has the notion.
2337
- let workspaceDomain = null;
2338
-
2339
- // The token to revoke if the setup is rejected after the code was already exchanged, set by
2340
- // each provider case because the token response is scoped to the switch. Prefer the refresh
2341
- // token: revoking either invalidates the grant, but the access token may already be expired.
2342
- let grantToken;
2343
-
2344
- // `app.provider` is for example "gmail", `provider` is oauth2 app id
2345
- switch (oauth2App.provider) {
2346
- case 'gmail': {
2347
- const r = await oAuth2Client.getToken(request.query.code);
2348
- if (!r || !r.access_token) {
2349
- let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
2350
- throw error;
2351
- }
2404
+ const retryUrl = await startOAuthRetry(flow, accountData.email);
2352
2405
 
2353
- const grantedScopes = r.scope ? r.scope.split(/\s+/) : [];
2406
+ const missingScopesList = missingScopes.map(formatScopeDescription);
2354
2407
 
2355
- request.logger.info({ msg: 'OAuth token received', grantedScopes, hasIdToken: !!r.id_token });
2408
+ return h.view(
2409
+ 'oauth-scope-error',
2410
+ {
2411
+ pageTitleFull: request.app.gt.gettext('Email Account Setup'),
2412
+ templateLocale: request.app.locale,
2413
+ retryUrl,
2414
+ missingScopesList
2415
+ },
2416
+ {
2417
+ layout: 'public'
2418
+ }
2419
+ );
2420
+ }
2421
+ }
2356
2422
 
2357
- // Check if user deselected required scopes in Google's granular consent
2358
- const requiredFunctionalScopes = oAuth2Client.scopes.filter(s => !OPENID_SCOPES.includes(s));
2359
- const missingScopes = requiredFunctionalScopes.filter(s => !grantedScopes.includes(s));
2423
+ async function resolveGmailUserEmail(flow, r, grantedScopes) {
2424
+ const { request, oAuth2Client } = flow;
2360
2425
 
2361
- if (missingScopes.length > 0) {
2362
- request.logger.warn({
2363
- msg: 'OAuth2 grant missing required scopes',
2364
- requested: requiredFunctionalScopes,
2365
- granted: grantedScopes,
2366
- missing: missingScopes
2367
- });
2426
+ let profileRes;
2427
+ let userEmail;
2428
+ let userName;
2368
2429
 
2369
- // Best-effort revocation of the partial token
2370
- oAuth2Client.revokeToken(r.refresh_token || r.access_token).catch(err => {
2371
- request.logger.warn({ msg: 'Failed to revoke partial OAuth2 token', err });
2372
- });
2430
+ // With OpenID Connect scopes (openid, email, profile), the ID token contains user info
2431
+ // This works for all account types including send-only accounts
2432
+ const idTokenPayload = decodeJwtPayload(r.id_token);
2433
+ if (r.id_token && !idTokenPayload) {
2434
+ request.logger.warn({ msg: 'Failed to decode Gmail ID token' });
2435
+ }
2436
+ if (idTokenPayload && typeof idTokenPayload.email === 'string' && isEmail(idTokenPayload.email)) {
2437
+ userEmail = idTokenPayload.email;
2438
+ userName = idTokenPayload.name || null;
2439
+ request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
2440
+ }
2373
2441
 
2374
- const retryUrl = await startOAuthRetry(accountData.email);
2442
+ // Back channel, so this is the claim the restriction can actually be enforced on;
2443
+ // the hd argument on the authorization URL only filters the chooser Google shows
2444
+ const workspaceDomain = workspaceDomainOf(idTokenPayload);
2445
+
2446
+ // If ID token didn't provide email, fall back to Gmail API profile endpoint
2447
+ // This should rarely happen since we now request openid/email/profile scopes
2448
+ if (!userEmail) {
2449
+ // Check if we have scopes that allow accessing the profile endpoint
2450
+ const hasProfileScope =
2451
+ grantedScopes.includes('https://mail.google.com/') ||
2452
+ grantedScopes.includes('https://www.googleapis.com/auth/gmail.readonly') ||
2453
+ grantedScopes.includes('https://www.googleapis.com/auth/gmail.modify') ||
2454
+ grantedScopes.includes('https://www.googleapis.com/auth/gmail.metadata');
2455
+
2456
+ if (hasProfileScope) {
2457
+ try {
2458
+ request.logger.debug({ msg: 'Attempting Gmail profile endpoint as fallback' });
2459
+ profileRes = await oAuth2Client.request(r.access_token, 'https://gmail.googleapis.com/gmail/v1/users/me/profile');
2460
+ if (profileRes && profileRes.emailAddress) {
2461
+ userEmail = profileRes.emailAddress;
2462
+ }
2463
+ } catch (err) {
2464
+ request.logger.error({ msg: 'Failed to fetch user info from Gmail API', err });
2465
+ let response = err.oauthRequest && err.oauthRequest.response;
2466
+ if (response && response.error) {
2467
+ let message;
2468
+ if (/Gmail API has not been used in project/.test(response.error.message)) {
2469
+ message =
2470
+ 'Can not perform requests against Gmail API as the project has not been enabled. If you are the admin, check notifications on the dashboard.';
2471
+ } else {
2472
+ message = response.error.message;
2473
+ }
2375
2474
 
2376
- const missingScopesList = missingScopes.map(formatScopeDescription);
2475
+ let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
2476
+ throw error;
2477
+ }
2478
+ throw err;
2479
+ }
2480
+ }
2481
+ }
2377
2482
 
2378
- return h.view(
2379
- 'oauth-scope-error',
2380
- {
2381
- pageTitleFull: request.app.gt.gettext('Email Account Setup'),
2382
- templateLocale: request.app.locale,
2383
- retryUrl,
2384
- missingScopesList
2385
- },
2386
- {
2387
- layout: 'public'
2388
- }
2389
- );
2390
- }
2483
+ return { profileRes, userEmail, workspaceDomain };
2484
+ }
2391
2485
 
2392
- let profileRes;
2393
- let userEmail;
2394
- let userName;
2486
+ async function completeGmailCallback(flow) {
2487
+ const { request, oAuth2Client, oauth2App, provider, accountData, providerIdentities } = flow;
2395
2488
 
2396
- // With OpenID Connect scopes (openid, email, profile), the ID token contains user info
2397
- // This works for all account types including send-only accounts
2398
- const idTokenPayload = decodeJwtPayload(r.id_token);
2399
- if (r.id_token && !idTokenPayload) {
2400
- request.logger.warn({ msg: 'Failed to decode Gmail ID token' });
2401
- }
2402
- if (idTokenPayload && typeof idTokenPayload.email === 'string' && isEmail(idTokenPayload.email)) {
2403
- userEmail = idTokenPayload.email;
2404
- userName = idTokenPayload.name || null;
2405
- request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
2406
- }
2489
+ const r = await oAuth2Client.getToken(request.query.code);
2490
+ if (!r || !r.access_token) {
2491
+ let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
2492
+ throw error;
2493
+ }
2407
2494
 
2408
- // Back channel, so this is the claim the restriction can actually be enforced on;
2409
- // the hd argument on the authorization URL only filters the chooser Google shows
2410
- workspaceDomain = workspaceDomainOf(idTokenPayload);
2411
-
2412
- // If ID token didn't provide email, fall back to Gmail API profile endpoint
2413
- // This should rarely happen since we now request openid/email/profile scopes
2414
- if (!userEmail) {
2415
- // Check if we have scopes that allow accessing the profile endpoint
2416
- const hasProfileScope =
2417
- grantedScopes.includes('https://mail.google.com/') ||
2418
- grantedScopes.includes('https://www.googleapis.com/auth/gmail.readonly') ||
2419
- grantedScopes.includes('https://www.googleapis.com/auth/gmail.modify') ||
2420
- grantedScopes.includes('https://www.googleapis.com/auth/gmail.metadata');
2421
-
2422
- if (hasProfileScope) {
2423
- try {
2424
- request.logger.debug({ msg: 'Attempting Gmail profile endpoint as fallback' });
2425
- profileRes = await oAuth2Client.request(r.access_token, 'https://gmail.googleapis.com/gmail/v1/users/me/profile');
2426
- if (profileRes && profileRes.emailAddress) {
2427
- userEmail = profileRes.emailAddress;
2428
- }
2429
- } catch (err) {
2430
- request.logger.error({ msg: 'Failed to fetch user info from Gmail API', err });
2431
- let response = err.oauthRequest && err.oauthRequest.response;
2432
- if (response && response.error) {
2433
- let message;
2434
- if (/Gmail API has not been used in project/.test(response.error.message)) {
2435
- message =
2436
- 'Can not perform requests against Gmail API as the project has not been enabled. If you are the admin, check notifications on the dashboard.';
2437
- } else {
2438
- message = response.error.message;
2439
- }
2440
-
2441
- let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
2442
- throw error;
2443
- }
2444
- throw err;
2445
- }
2446
- }
2447
- }
2495
+ const grantedScopes = r.scope ? r.scope.split(/\s+/) : [];
2448
2496
 
2449
- if (!userEmail) {
2450
- let error = Boom.boomify(new Error(`Oauth failed: failed to retrieve account email address`), { statusCode: 400 });
2451
- throw error;
2452
- }
2497
+ request.logger.info({ msg: 'OAuth token received', grantedScopes, hasIdToken: !!r.id_token });
2453
2498
 
2454
- // Back-channel only: either the id_token from the token endpoint or the Gmail profile
2455
- // API response, never a value that travelled through the browser.
2456
- providerIdentities.push(userEmail);
2457
- grantToken = r.refresh_token || r.access_token;
2499
+ const scopeErrorView = await gmailMissingScopesView(flow, r, grantedScopes);
2500
+ if (scopeErrorView) {
2501
+ return { view: scopeErrorView };
2502
+ }
2458
2503
 
2459
- accountData.email = isEmail(userEmail) ? userEmail : accountData.email;
2504
+ const { profileRes, userEmail, workspaceDomain } = await resolveGmailUserEmail(flow, r, grantedScopes);
2460
2505
 
2461
- const defaultScopes = (oauth2App.baseScopes && GMAIL_SCOPES[oauth2App.baseScopes]) || GMAIL_SCOPES.imap;
2506
+ if (!userEmail) {
2507
+ let error = Boom.boomify(new Error(`Oauth failed: failed to retrieve account email address`), { statusCode: 400 });
2508
+ throw error;
2509
+ }
2462
2510
 
2463
- accountData.oauth2 = Object.assign(
2464
- accountData.oauth2 || {},
2465
- {
2466
- provider,
2467
- accessToken: r.access_token,
2468
- refreshToken: r.refresh_token,
2469
- expires: new Date(Date.now() + r.expires_in * 1000),
2470
- scope: grantedScopes.length ? grantedScopes : defaultScopes,
2471
- tokenType: r.token_type
2472
- },
2473
- {
2474
- auth: {
2475
- user: userEmail
2476
- }
2477
- }
2478
- );
2511
+ // Back-channel only: either the id_token from the token endpoint or the Gmail profile
2512
+ // API response, never a value that travelled through the browser.
2513
+ providerIdentities.push(userEmail);
2479
2514
 
2480
- accountData.googleHistoryId = profileRes ? Number(profileRes.historyId) || null : null;
2515
+ accountData.email = isEmail(userEmail) ? userEmail : accountData.email;
2481
2516
 
2482
- request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: userEmail, provider: oauth2App.provider });
2483
- break;
2484
- }
2517
+ const defaultScopes = (oauth2App.baseScopes && GMAIL_SCOPES[oauth2App.baseScopes]) || GMAIL_SCOPES.imap;
2485
2518
 
2486
- case 'outlook': {
2487
- const r = await oAuth2Client.getToken(request.query.code);
2488
- if (!r || !r.access_token) {
2489
- let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
2490
- throw error;
2491
- }
2519
+ accountData.oauth2 = Object.assign(
2520
+ accountData.oauth2 || {},
2521
+ {
2522
+ provider,
2523
+ accessToken: r.access_token,
2524
+ refreshToken: r.refresh_token,
2525
+ expires: new Date(Date.now() + r.expires_in * 1000),
2526
+ scope: grantedScopes.length ? grantedScopes : defaultScopes,
2527
+ tokenType: r.token_type
2528
+ },
2529
+ {
2530
+ auth: {
2531
+ user: userEmail
2532
+ }
2533
+ }
2534
+ );
2492
2535
 
2493
- let userInfo;
2494
-
2495
- if (!oauth2App.baseScopes || oauth2App.baseScopes === 'imap') {
2496
- // Read account info from the id_token, falling back to the client_info GET argument.
2497
- // The fallback is needed because previously EmailEngine did not request for the
2498
- // User.Read scope - but client_info arrives through the browser, so it is a display
2499
- // fallback only and never counts as identity evidence. See lib/oauth/outlook-identity.js.
2500
-
2501
- let clientInfo = false;
2502
- if (request.query.client_info) {
2503
- try {
2504
- clientInfo = JSON.parse(Buffer.from(request.query.client_info, 'base64url').toString());
2505
- } catch (err) {
2506
- // Base64-shaped but not JSON. It is an optional display hint, so log and continue
2507
- // rather than failing the whole setup on a value we do not trust anyway.
2508
- request.logger.warn({ msg: 'Failed to decode Outlook client_info argument', err });
2509
- }
2510
- }
2536
+ accountData.googleHistoryId = profileRes ? Number(profileRes.historyId) || null : null;
2511
2537
 
2512
- const idTokenPayload = decodeJwtPayload(r.id_token);
2513
- if (r.id_token && !idTokenPayload) {
2514
- request.logger.warn({ msg: 'Failed to decode Outlook ID token' });
2515
- }
2538
+ request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: userEmail, provider: oauth2App.provider });
2516
2539
 
2517
- userInfo = resolveOutlookUserInfo({ clientInfo, idTokenPayload });
2518
- } else {
2519
- // Request profile info from API
2520
-
2521
- let profileRes;
2522
- try {
2523
- profileRes = await oAuth2Client.request(r.access_token, `${oAuth2Client.apiBase}/v1.0/me`);
2524
- } catch (err) {
2525
- let response = err.oauthRequest && err.oauthRequest.response;
2526
- if (response && response.error) {
2527
- let message = response.error.message;
2528
- let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
2529
- throw error;
2530
- }
2531
- throw err;
2532
- }
2540
+ return { grantToken: r.refresh_token || r.access_token, workspaceDomain };
2541
+ }
2533
2542
 
2534
- userInfo = resolveOutlookUserInfo({ profile: profileRes });
2543
+ async function resolveOutlookCallbackUser(flow, r) {
2544
+ const { request, oAuth2Client, oauth2App } = flow;
2535
2545
 
2536
- request.logger.info({
2537
- msg: 'User profile returned by MS Graph API',
2538
- user: userInfo.email,
2539
- provider: oauth2App.provider
2540
- });
2541
- }
2546
+ let userInfo;
2542
2547
 
2543
- const authData = {
2544
- user: userInfo.username || userInfo.email
2545
- };
2548
+ if (!oauth2App.baseScopes || oauth2App.baseScopes === 'imap') {
2549
+ // Read account info from the id_token, falling back to the client_info GET argument.
2550
+ // The fallback is needed because previously EmailEngine did not request for the
2551
+ // User.Read scope - but client_info arrives through the browser, so it is a display
2552
+ // fallback only and never counts as identity evidence. See lib/oauth/outlook-identity.js.
2546
2553
 
2547
- if (!authData.user) {
2548
- let error = Boom.boomify(new Error(`Oauth failed: failed to retrieve account email address`), { statusCode: 400 });
2549
- throw error;
2550
- }
2554
+ let clientInfo = false;
2555
+ if (request.query.client_info) {
2556
+ try {
2557
+ clientInfo = JSON.parse(Buffer.from(request.query.client_info, 'base64url').toString());
2558
+ } catch (err) {
2559
+ // Base64-shaped but not JSON. It is an optional display hint, so log and continue
2560
+ // rather than failing the whole setup on a value we do not trust anyway.
2561
+ request.logger.warn({ msg: 'Failed to decode Outlook client_info argument', err });
2562
+ }
2563
+ }
2551
2564
 
2552
- // Only the back-channel addresses, so a forged client_info cannot satisfy an expectation.
2553
- providerIdentities.push(...userInfo.verifiedIdentities);
2554
- grantToken = r.refresh_token || r.access_token;
2565
+ const idTokenPayload = decodeJwtPayload(r.id_token);
2566
+ if (r.id_token && !idTokenPayload) {
2567
+ request.logger.warn({ msg: 'Failed to decode Outlook ID token' });
2568
+ }
2555
2569
 
2556
- if (accountData.oauth2 && accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser) {
2557
- // Delegated user (shared mailbox) specified in oauth2.auth.delegatedUser
2558
- authData.delegatedUser = accountData.oauth2.auth.delegatedUser;
2559
- // Ensure email is set to the delegated user if not already provided
2560
- if (!accountData.email) {
2561
- accountData.email = accountData.oauth2.auth.delegatedUser;
2562
- }
2563
- } else if (accountData.delegated && accountData.email && accountData.email !== userInfo.email) {
2564
- // Legacy: Shared mailbox specified via delegated flag
2565
- authData.delegatedUser = accountData.email;
2566
- } else {
2567
- // Not a delegated account, use the authenticated user's email
2568
- accountData.email = userInfo.email;
2569
- }
2570
+ userInfo = resolveOutlookUserInfo({ clientInfo, idTokenPayload });
2571
+ } else {
2572
+ // Request profile info from API
2570
2573
 
2571
- accountData.name = accountData.name || userInfo.name || '';
2574
+ let profileRes;
2575
+ try {
2576
+ profileRes = await oAuth2Client.request(r.access_token, `${oAuth2Client.apiBase}/v1.0/me`);
2577
+ } catch (err) {
2578
+ let response = err.oauthRequest && err.oauthRequest.response;
2579
+ if (response && response.error) {
2580
+ let message = response.error.message;
2581
+ let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
2582
+ throw error;
2583
+ }
2584
+ throw err;
2585
+ }
2572
2586
 
2573
- accountData.oauth2 = Object.assign(
2574
- accountData.oauth2 || {},
2575
- {
2576
- provider,
2577
- accessToken: r.access_token,
2578
- refreshToken: r.refresh_token,
2579
- expires: new Date(Date.now() + r.expires_in * 1000),
2580
- scope: r.scope ? r.scope.split(/\s+/) : oAuth2Client.scopes,
2581
- tokenType: r.token_type
2582
- },
2583
- {
2584
- auth: authData
2585
- }
2586
- );
2587
+ userInfo = resolveOutlookUserInfo({ profile: profileRes });
2587
2588
 
2588
- request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: userInfo.email, provider: oauth2App.provider });
2589
- break;
2590
- }
2589
+ request.logger.info({
2590
+ msg: 'User profile returned by MS Graph API',
2591
+ user: userInfo.email,
2592
+ provider: oauth2App.provider
2593
+ });
2594
+ }
2591
2595
 
2592
- case 'mailRu': {
2593
- const r = await oAuth2Client.getToken(request.query.code);
2594
- if (!r || !r.access_token) {
2595
- let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
2596
- throw error;
2597
- }
2596
+ return userInfo;
2597
+ }
2598
2598
 
2599
- let profileRes;
2600
- try {
2601
- profileRes = await oAuth2Client.request(r.access_token, 'https://oauth.mail.ru/userinfo');
2602
- } catch (err) {
2603
- let response = err.oauthRequest && err.oauthRequest.response;
2604
- if (response && response.error) {
2605
- let message = response.error.message;
2606
- let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
2607
- throw error;
2608
- }
2609
- throw err;
2610
- }
2599
+ async function completeOutlookCallback(flow) {
2600
+ const { request, oAuth2Client, oauth2App, provider, accountData, providerIdentities } = flow;
2611
2601
 
2612
- if (!profileRes || !profileRes || !profileRes.email) {
2613
- let error = Boom.boomify(new Error(`Oauth failed: failed to retrieve account email address`), { statusCode: 400 });
2614
- throw error;
2615
- }
2602
+ const r = await oAuth2Client.getToken(request.query.code);
2603
+ if (!r || !r.access_token) {
2604
+ let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
2605
+ throw error;
2606
+ }
2616
2607
 
2617
- // Back-channel only: the Mail.ru userinfo endpoint response.
2618
- providerIdentities.push(profileRes.email);
2619
- grantToken = r.refresh_token || r.access_token;
2608
+ const userInfo = await resolveOutlookCallbackUser(flow, r);
2620
2609
 
2621
- accountData.name = accountData.name || profileRes.name || '';
2622
- accountData.email = isEmail(profileRes.email) ? profileRes.email : accountData.email;
2610
+ const authData = {
2611
+ user: userInfo.username || userInfo.email
2612
+ };
2623
2613
 
2624
- accountData.oauth2 = Object.assign(
2625
- accountData.oauth2 || {},
2626
- {
2627
- provider,
2628
- accessToken: r.access_token,
2629
- refreshToken: r.refresh_token,
2630
- expires: new Date(Date.now() + r.expires_in * 1000),
2631
- scope: r.scope ? r.scope.split(/\s+/) : MAIL_RU_SCOPES,
2632
- tokenType: r.token_type
2633
- },
2634
- {
2635
- auth: {
2636
- user: profileRes.email
2637
- }
2638
- }
2639
- );
2614
+ if (!authData.user) {
2615
+ let error = Boom.boomify(new Error(`Oauth failed: failed to retrieve account email address`), { statusCode: 400 });
2616
+ throw error;
2617
+ }
2640
2618
 
2641
- request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: profileRes.email, provider: oauth2App.provider });
2642
- break;
2643
- }
2619
+ // Only the back-channel addresses, so a forged client_info cannot satisfy an expectation.
2620
+ providerIdentities.push(...userInfo.verifiedIdentities);
2644
2621
 
2645
- default: {
2646
- throw new Error('Unknown OAuth2 provider');
2647
- }
2648
- }
2622
+ // A shared mailbox, named either way, or the signed-in user's own
2623
+ const mailbox = resolveOutlookMailbox(accountData, userInfo);
2624
+ accountData.email = mailbox.email;
2625
+ if (mailbox.delegatedUser) {
2626
+ authData.delegatedUser = mailbox.delegatedUser;
2627
+ }
2649
2628
 
2650
- // Expected identity check. Runs before the nonce claim and before create(), so a rejected
2651
- // setup neither consumes the signed link nor overwrites the credentials already on the
2652
- // account. The expectation can come from the signed form blob or from the account itself -
2653
- // persisting it is what makes the constraint outlive the link that introduced it, and it is
2654
- // why a later link issued without expectedEmail cannot quietly drop the pin.
2655
- const expectedEmail = await resolveExpectedIdentity(redis, {
2656
- account: accountData.account,
2657
- blobExpectation: pendingSetupExpectation(accountData, accountMeta)
2658
- });
2629
+ accountData.name = accountData.name || userInfo.name || '';
2630
+
2631
+ accountData.oauth2 = Object.assign(
2632
+ accountData.oauth2 || {},
2633
+ {
2634
+ provider,
2635
+ accessToken: r.access_token,
2636
+ refreshToken: r.refresh_token,
2637
+ expires: new Date(Date.now() + r.expires_in * 1000),
2638
+ scope: r.scope ? r.scope.split(/\s+/) : oAuth2Client.scopes,
2639
+ tokenType: r.token_type
2640
+ },
2641
+ {
2642
+ auth: authData
2643
+ }
2644
+ );
2659
2645
 
2660
- // "Accept only Google Workspace accounts" used to be advisory: generateAuthUrl() sets hd=*,
2661
- // which filters the account chooser Google shows and nothing else, so a link assembled
2662
- // without that argument - or a user who switches account inside the chooser - completed the
2663
- // setup with a consumer account. The hosted-domain claim of the ID token is checked here
2664
- // instead, and a token that names no domain is refused rather than trusted: for the Gmail
2665
- // provider the OpenID scopes are always requested (GmailOauth's constructor adds them), so
2666
- // a missing claim means the account has no Workspace domain, not that the claim was never
2667
- // asked for.
2668
- if (oauth2App.googleWorkspaceAccounts && oauth2App.provider === 'gmail' && !workspaceDomain) {
2669
- request.logger.warn({
2670
- msg: 'OAuth2 sign-in used a personal account for a Workspace-only application',
2671
- account: accountData.account,
2672
- provider: oauth2App.provider
2673
- });
2646
+ request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: userInfo.email, provider: oauth2App.provider });
2674
2647
 
2675
- // The code was already exchanged, so we are holding a grant we will never use. Best
2676
- // effort, and the same duck-typing guard as the identity mismatch below.
2677
- if (grantToken && typeof oAuth2Client.revokeToken === 'function') {
2678
- try {
2679
- await oAuth2Client.revokeToken(grantToken);
2680
- } catch (err) {
2681
- request.logger.warn({ msg: 'Failed to revoke the OAuth2 grant after a Workspace check', err });
2682
- }
2683
- }
2648
+ return { grantToken: r.refresh_token || r.access_token };
2649
+ }
2684
2650
 
2685
- // select_account for the same reason as the identity mismatch: they are signed in to the
2686
- // account that just failed, and without it Google would hand back the same one
2687
- const retryUrl = await startOAuthRetry(accountData.email, 'select_account consent');
2651
+ async function completeMailRuCallback(flow) {
2652
+ const { request, oAuth2Client, oauth2App, provider, accountData, providerIdentities } = flow;
2688
2653
 
2689
- return workspaceErrorView(request, h, { actualEmail: providerIdentities[0], retryUrl });
2690
- }
2654
+ const r = await oAuth2Client.getToken(request.query.code);
2655
+ if (!r || !r.access_token) {
2656
+ let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
2657
+ throw error;
2658
+ }
2691
2659
 
2692
- if (expectedEmail && !matchesExpectedIdentity(expectedEmail, providerIdentities)) {
2693
- // Neither address is logged: the expectation and the authenticated identity both belong to
2694
- // the end user, and this line is the one record of a failed attempt. Note the provider
2695
- // identity was already logged by the "Provisioned OAuth2 tokens" line above.
2696
- request.logger.warn({
2697
- msg: 'OAuth2 identity did not match the expected email address',
2698
- account: accountData.account,
2699
- provider: oauth2App.provider
2700
- });
2660
+ let profileRes;
2661
+ try {
2662
+ profileRes = await oAuth2Client.request(r.access_token, 'https://oauth.mail.ru/userinfo');
2663
+ } catch (err) {
2664
+ let response = err.oauthRequest && err.oauthRequest.response;
2665
+ if (response && response.error) {
2666
+ let message = response.error.message;
2667
+ let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
2668
+ throw error;
2669
+ }
2670
+ throw err;
2671
+ }
2701
2672
 
2702
- // The code was already exchanged, so we are holding a refresh token we will never use.
2703
- // Best effort, and the same duck-typing guard Account.delete({ revoke }) uses: only
2704
- // GmailOauth implements revokeToken, and a rejected setup must not become a 500.
2705
- if (grantToken && typeof oAuth2Client.revokeToken === 'function') {
2706
- try {
2707
- await oAuth2Client.revokeToken(grantToken);
2708
- } catch (err) {
2709
- request.logger.warn({ msg: 'Failed to revoke the OAuth2 grant after an identity mismatch', err });
2710
- }
2711
- }
2673
+ if (!profileRes || !profileRes || !profileRes.email) {
2674
+ let error = Boom.boomify(new Error(`Oauth failed: failed to retrieve account email address`), { statusCode: 400 });
2675
+ throw error;
2676
+ }
2712
2677
 
2713
- // Stop here with a way back rather than redirecting to the calling application: signing in
2714
- // as the wrong account is a correctable mistake, and the hosted flow only ever redirects on
2715
- // success. Hint the address they were supposed to use, and force the account picker:
2716
- // they are already signed in to the one that just failed, so without select_account Google
2717
- // would hand back the same account and the retry would loop. Microsoft always shows the
2718
- // picker and Mail.ru ignores the hint, so this only changes Google's behavior.
2719
- const retryUrl = await startOAuthRetry(expectedEmail, 'select_account consent');
2720
-
2721
- return identityErrorView(request, h, {
2722
- expectedEmail,
2723
- // The primary address the provider reported. Microsoft can return both a mailbox
2724
- // address and a user principal name, and either would have satisfied the pin, so
2725
- // naming the first is enough to show which account actually signed in.
2726
- actualEmail: providerIdentities[0],
2727
- retryUrl
2728
- });
2678
+ // Back-channel only: the Mail.ru userinfo endpoint response.
2679
+ providerIdentities.push(profileRes.email);
2680
+
2681
+ accountData.name = accountData.name || profileRes.name || '';
2682
+ accountData.email = isEmail(profileRes.email) ? profileRes.email : accountData.email;
2683
+
2684
+ accountData.oauth2 = Object.assign(
2685
+ accountData.oauth2 || {},
2686
+ {
2687
+ provider,
2688
+ accessToken: r.access_token,
2689
+ refreshToken: r.refresh_token,
2690
+ expires: new Date(Date.now() + r.expires_in * 1000),
2691
+ scope: r.scope ? r.scope.split(/\s+/) : MAIL_RU_SCOPES,
2692
+ tokenType: r.token_type
2693
+ },
2694
+ {
2695
+ auth: {
2696
+ user: profileRes.email
2729
2697
  }
2698
+ }
2699
+ );
2730
2700
 
2731
- if (expectedEmail) {
2732
- // Pin the account so every later setup is checked, including one driven by a link that
2733
- // carries no expectation of its own.
2734
- accountData.expectedEmail = expectedEmail;
2735
- }
2701
+ request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: profileRes.email, provider: oauth2App.provider });
2736
2702
 
2737
- if ('delegated' in accountData) {
2738
- // remove artefacts
2739
- delete accountData.delegated;
2740
- }
2703
+ return { grantToken: r.refresh_token || r.access_token };
2704
+ }
2741
2705
 
2742
- let accountObject = new Account({
2743
- redis,
2744
- call,
2745
- secret: await getSecret(),
2746
- timeout: request.headers['x-ee-timeout']
2747
- });
2706
+ // Exchanges the authorization code with the app's provider type (flow.oauth2App.provider, for example
2707
+ // "gmail") and fills in accountData and providerIdentities from what the provider returned. Resolves
2708
+ // to `{ view }` when the setup has to stop on a page of its own, otherwise to:
2709
+ // grantToken - the token to revoke if the setup is rejected after the exchange. The refresh
2710
+ // token is preferred: revoking either invalidates the grant, but the access token
2711
+ // may already be expired.
2712
+ // workspaceDomain - the Workspace or Cloud organization domain, for an application restricted to
2713
+ // Google Workspace accounts. Only the Gmail provider reports one; the restriction
2714
+ // is a Google setting and no other provider has the notion.
2715
+ async function exchangeOAuthCode(flow) {
2716
+ switch (flow.oauth2App.provider) {
2717
+ case 'gmail':
2718
+ return await completeGmailCallback(flow);
2719
+
2720
+ case 'outlook':
2721
+ return await completeOutlookCallback(flow);
2722
+
2723
+ case 'mailRu':
2724
+ return await completeMailRuCallback(flow);
2725
+
2726
+ default: {
2727
+ throw new Error('Unknown OAuth2 provider');
2728
+ }
2729
+ }
2730
+ }
2748
2731
 
2749
- // Claim the single-use nonce BEFORE create (SET NX), mirroring the IMAP arm in
2750
- // lib/ui-routes/account-routes.js, so one signed link cannot be double-spent across the two
2751
- // arms (initiate OAuth -> submit the same blob to /accounts/new/imap/server -> complete this
2752
- // callback) and a replayed callback cannot create a second account.
2753
- //
2754
- // Backward-compat, BY DESIGN: this only engages when accountMeta.n is present. Legacy /
2755
- // pre-upgrade re-auth blobs carry no nonce (accountMeta.n is undefined), so the claim is
2756
- // skipped and those links keep working - the OAuth entry (accountFormHandler) intentionally
2757
- // does NOT require a nonce for exactly that reason.
2758
- // claimFormNonce/releaseFormNonce (lib/tools.js) are the same primitives the IMAP arm uses, so
2759
- // the double-spend semantics stay in one place.
2760
- let nonceClaimed = false;
2761
- if (accountMeta.n) {
2762
- let claimed;
2763
- try {
2764
- claimed = await claimFormNonce(redis, accountMeta.n, accountMeta.t);
2765
- } catch (err) {
2766
- // A Redis failure is not a consumed nonce - surface a retryable error rather than
2767
- // misreporting a valid setup URL as invalid.
2768
- request.logger.error({ msg: 'Failed to claim nonce for an account form request', err });
2769
- throw Boom.boomify(new Error('Temporary error, please try again'), { statusCode: 500 });
2770
- }
2771
- if (!claimed) {
2772
- // The nonce key already exists: this signed URL was already used.
2773
- throw Boom.boomify(new Error('Invalid or expired account setup URL'), { statusCode: 403 });
2774
- }
2775
- nonceClaimed = true;
2776
- }
2732
+ // The Workspace restriction and the expected identity, both checked after the code exchange.
2733
+ // Answers the error page with a way back when the setup has to be refused
2734
+ async function rejectOAuthIdentity(flow, { grantToken, workspaceDomain }, expectedEmail) {
2735
+ const { request, h, accountData, oauth2App, oAuth2Client, providerIdentities } = flow;
2777
2736
 
2778
- let result;
2737
+ // The code was already exchanged, so a refused setup leaves us holding a grant we will never
2738
+ // use. Best effort, and the same duck-typing guard Account.delete({ revoke }) uses: only
2739
+ // GmailOauth implements revokeToken, and a rejected setup must not become a 500.
2740
+ const revokeUnusedGrant = async failureMessage => {
2741
+ if (grantToken && typeof oAuth2Client.revokeToken === 'function') {
2779
2742
  try {
2780
- result = await accountObject.create(accountData);
2743
+ await oAuth2Client.revokeToken(grantToken);
2781
2744
  } catch (err) {
2782
- // Release the nonce so the user can retry (same accepted residual as the IMAP arm: if
2783
- // Redis also fails here the nonce stays consumed for its TTL and a fresh link is needed -
2784
- // the price of claim-before-create being atomic).
2785
- if (nonceClaimed) {
2786
- await releaseFormNonce(redis, accountMeta.n, request.logger);
2787
- }
2788
- throw err;
2745
+ request.logger.warn({ msg: failureMessage, err });
2789
2746
  }
2747
+ }
2748
+ };
2790
2749
 
2791
- let httpRedirectUrl;
2792
- if (redirectUrl) {
2793
- let serviceUrl = await settings.get('serviceUrl');
2794
- let url = new URL(redirectUrl, serviceUrl);
2795
- url.searchParams.set('account', result.account);
2796
- url.searchParams.set('state', result.state);
2797
- httpRedirectUrl = url.href;
2798
- } else {
2799
- httpRedirectUrl = `/admin/accounts/${result.account}`;
2800
- }
2750
+ // "Accept only Google Workspace accounts" used to be advisory: generateAuthUrl() sets hd=*,
2751
+ // which filters the account chooser Google shows and nothing else, so a link assembled
2752
+ // without that argument - or a user who switches account inside the chooser - completed the
2753
+ // setup with a consumer account. The hosted-domain claim of the ID token is checked here
2754
+ // instead, and a token that names no domain is refused rather than trusted: for the Gmail
2755
+ // provider the OpenID scopes are always requested (GmailOauth's constructor adds them), so
2756
+ // a missing claim means the account has no Workspace domain, not that the claim was never
2757
+ // asked for.
2758
+ if (oauth2App.googleWorkspaceAccounts && oauth2App.provider === 'gmail' && !workspaceDomain) {
2759
+ request.logger.warn({
2760
+ msg: 'OAuth2 sign-in used a personal account for a Workspace-only application',
2761
+ account: accountData.account,
2762
+ provider: oauth2App.provider
2763
+ });
2801
2764
 
2802
- return renderRedirect(httpRedirectUrl);
2803
- },
2765
+ await revokeUnusedGrant('Failed to revoke the OAuth2 grant after a Workspace check');
2766
+
2767
+ // select_account for the same reason as the identity mismatch: they are signed in to the
2768
+ // account that just failed, and without it Google would hand back the same one
2769
+ const retryUrl = await startOAuthRetry(flow, accountData.email, 'select_account consent');
2770
+
2771
+ return workspaceErrorView(request, h, { actualEmail: providerIdentities[0], retryUrl });
2772
+ }
2773
+
2774
+ if (expectedEmail && !matchesExpectedIdentity(expectedEmail, providerIdentities)) {
2775
+ // Neither address is logged: the expectation and the authenticated identity both belong to
2776
+ // the end user, and this line is the one record of a failed attempt. Note the provider
2777
+ // identity was already logged by the provider's "Provisioned OAuth2 tokens" line in exchangeOAuthCode().
2778
+ request.logger.warn({
2779
+ msg: 'OAuth2 identity did not match the expected email address',
2780
+ account: accountData.account,
2781
+ provider: oauth2App.provider
2782
+ });
2783
+
2784
+ await revokeUnusedGrant('Failed to revoke the OAuth2 grant after an identity mismatch');
2785
+
2786
+ // Stop here with a way back rather than redirecting to the calling application: signing in
2787
+ // as the wrong account is a correctable mistake, and the hosted flow only ever redirects on
2788
+ // success. Hint the address they were supposed to use, and force the account picker:
2789
+ // they are already signed in to the one that just failed, so without select_account Google
2790
+ // would hand back the same account and the retry would loop. Microsoft always shows the
2791
+ // picker and Mail.ru ignores the hint, so this only changes Google's behavior.
2792
+ const retryUrl = await startOAuthRetry(flow, expectedEmail, 'select_account consent');
2793
+
2794
+ return identityErrorView(request, h, {
2795
+ expectedEmail,
2796
+ // The primary address the provider reported. Microsoft can return both a mailbox
2797
+ // address and a user principal name, and either would have satisfied the pin, so
2798
+ // naming the first is enough to show which account actually signed in.
2799
+ actualEmail: providerIdentities[0],
2800
+ retryUrl
2801
+ });
2802
+ }
2803
+ }
2804
+
2805
+ async function handleOAuthCallback(request, h) {
2806
+ assertOAuthCallbackQuery(request);
2807
+
2808
+ const accountData = await claimOAuthSetup(request);
2809
+
2810
+ const accountMeta = accountData._meta || {};
2811
+ delete accountData._meta;
2812
+
2813
+ const redirectUrl = accountMeta.redirectUrl;
2814
+
2815
+ const provider = accountData.oauth2.provider;
2816
+
2817
+ // What the caller originally asked for, captured before the provider branches below rewrite
2818
+ // accountData from whoever signed in. A retry has to start from this rather than from the
2819
+ // rejected attempt: `email` may name a shared mailbox to bind (and is otherwise overwritten
2820
+ // with the authenticated address), `name` gets filled in from the rejected user's profile when
2821
+ // the caller supplied none, and `oauth2.auth.delegatedUser` names the mailbox rather than a
2822
+ // credential, so it must survive while the tokens do not.
2823
+ const requestedSetup = {
2824
+ email: accountData.email,
2825
+ name: accountData.name,
2826
+ delegatedUser: accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser
2827
+ };
2828
+
2829
+ const oauth2App = await oauth2Apps.get(provider);
2830
+ if (!oauth2App) {
2831
+ let error = Boom.boomify(new Error('Missing or disabled OAuth2 app'), { statusCode: 404 });
2832
+ throw error;
2833
+ }
2834
+
2835
+ // The code exchange, the profile lookups and any revoke already speak for the account being
2836
+ // set up, so they leave through its route (its own proxy, if the setup named one)
2837
+ const oAuth2Client = await oauth2Apps.getClient(oauth2App.id, { route: await getAccountHttpRoute(redis, accountData) });
2838
+
2839
+ // What the provider steps below read, and the values they fill in
2840
+ const flow = {
2841
+ request,
2842
+ h,
2843
+ accountData,
2844
+ accountMeta,
2845
+ requestedSetup,
2846
+ provider,
2847
+ oauth2App,
2848
+ oAuth2Client,
2849
+
2850
+ // Addresses the provider itself returned over a back channel, the only values allowed to
2851
+ // satisfy an expected identity (see lib/account/expected-identity.js). Every provider case
2852
+ // fills this in; one that does not leaves it empty, and an empty list fails the check closed.
2853
+ providerIdentities: []
2854
+ };
2855
+
2856
+ const exchange = await exchangeOAuthCode(flow);
2857
+ if (exchange.view) {
2858
+ return exchange.view;
2859
+ }
2860
+
2861
+ // Expected identity check. Runs before the nonce claim and before create(), so a rejected
2862
+ // setup neither consumes the signed link nor overwrites the credentials already on the
2863
+ // account. The expectation can come from the signed form blob or from the account itself -
2864
+ // persisting it is what makes the constraint outlive the link that introduced it, and it is
2865
+ // why a later link issued without expectedEmail cannot quietly drop the pin.
2866
+ const expectedEmail = await resolveExpectedIdentity(redis, {
2867
+ account: accountData.account,
2868
+ blobExpectation: pendingSetupExpectation(accountData, accountMeta)
2869
+ });
2870
+
2871
+ const identityView = await rejectOAuthIdentity(flow, exchange, expectedEmail);
2872
+ if (identityView) {
2873
+ return identityView;
2874
+ }
2875
+
2876
+ if (expectedEmail) {
2877
+ // Pin the account so every later setup is checked, including one driven by a link that
2878
+ // carries no expectation of its own.
2879
+ accountData.expectedEmail = expectedEmail;
2880
+ }
2881
+
2882
+ if ('delegated' in accountData) {
2883
+ // remove artefacts
2884
+ delete accountData.delegated;
2885
+ }
2886
+
2887
+ const accountObject = new Account({
2888
+ redis,
2889
+ call,
2890
+ secret: await getSecret(),
2891
+ timeout: request.headers['x-ee-timeout']
2892
+ });
2893
+
2894
+ // The nonce claim spans both arms, so one signed link cannot be spent on each (start OAuth2,
2895
+ // submit the same blob to /accounts/new/imap/server, then complete this callback) and a
2896
+ // replayed callback cannot create a second account. Only a link that carries a nonce is
2897
+ // claimed: re-auth links issued before nonces existed carry none, and the OAuth2 entry
2898
+ // (accountFormHandler) deliberately does not require one so that they keep working.
2899
+ const httpRedirectUrl = await completeAccountSetup(request, {
2900
+ accountObject,
2901
+ accountData,
2902
+ nonce: accountMeta.n ? { n: accountMeta.n, t: accountMeta.t } : null,
2903
+ redirectUrl
2904
+ });
2905
+
2906
+ return renderRedirect(request, h, httpRedirectUrl);
2907
+ }
2908
+
2909
+ function registerOAuthCallbackRoute(server) {
2910
+ server.route({
2911
+ method: 'GET',
2912
+ path: '/oauth',
2913
+ handler: handleOAuthCallback,
2804
2914
  options: {
2805
2915
  description: 'OAuth2 response endpoint',
2806
2916
 
@@ -2846,28 +2956,9 @@ const init = async () => {
2846
2956
  auth: false
2847
2957
  }
2848
2958
  });
2959
+ }
2849
2960
 
2850
- // setup every /v1 route module (wiring lives in lib/api-routes/index.js so the route table
2851
- // can be captured without booting this worker - see test/api-routes-table-test.js)
2852
- await registerApiRoutes({
2853
- server,
2854
- call,
2855
- notify,
2856
- metrics,
2857
- CORS_CONFIG,
2858
- FLAG_SORT_ORDER,
2859
- SMTP_TEST_HOST,
2860
- MAX_ATTACHMENT_SIZE,
2861
- MAX_BODY_SIZE,
2862
- MAX_PAYLOAD_TIMEOUT,
2863
- mcpFeatureEnabled,
2864
- oauth2Schema,
2865
- imapSchema,
2866
- smtpSchema,
2867
- AccountTypeSchema,
2868
- OAuth2ProviderSchema
2869
- });
2870
-
2961
+ async function registerCsrfProtection(server, secureCookie) {
2871
2962
  // Web UI routes
2872
2963
 
2873
2964
  await server.register({
@@ -2889,7 +2980,9 @@ const init = async () => {
2889
2980
  }
2890
2981
  }
2891
2982
  });
2983
+ }
2892
2984
 
2985
+ function registerViews(server) {
2893
2986
  server.views({
2894
2987
  engines: {
2895
2988
  hbs: handlebars
@@ -3145,7 +3238,9 @@ const init = async () => {
3145
3238
  };
3146
3239
  }
3147
3240
  });
3241
+ }
3148
3242
 
3243
+ function registerResponseExtensions(server) {
3149
3244
  const preResponse = async (request, h) => {
3150
3245
  let response = request.response;
3151
3246
 
@@ -3232,7 +3327,9 @@ const init = async () => {
3232
3327
  // After preResponse on purpose: it replaces an error response with the rendered error page
3233
3328
  // or a JSON body, and the headers have to land on whatever is actually sent
3234
3329
  server.ext('onPreResponse', securityHeadersExt({ cspMode: CSP_MODE }));
3330
+ }
3235
3331
 
3332
+ function registerTotpExtension(server) {
3236
3333
  server.ext('onPostAuth', async (request, h) => {
3237
3334
  if (request.requireTotp) {
3238
3335
  // The password step is done and only the second factor is missing, so the session
@@ -3249,7 +3346,9 @@ const init = async () => {
3249
3346
  }
3250
3347
  return h.continue;
3251
3348
  });
3349
+ }
3252
3350
 
3351
+ function registerChangesRoute(server) {
3253
3352
  server.route({
3254
3353
  method: 'GET',
3255
3354
  path: '/admin/changes',
@@ -3258,10 +3357,9 @@ const init = async () => {
3258
3357
  // helper so the two can not drift apart on framing or on stream cleanup.
3259
3358
  handler: openChangeStream
3260
3359
  });
3360
+ }
3261
3361
 
3262
- // setup web UI
3263
- routesUi(server, call);
3264
-
3362
+ function registerMetricsRoute(server) {
3265
3363
  server.route({
3266
3364
  method: 'GET',
3267
3365
  path: '/metrics',
@@ -3279,7 +3377,9 @@ const init = async () => {
3279
3377
  }
3280
3378
  }
3281
3379
  });
3380
+ }
3282
3381
 
3382
+ function registerNotFoundRoute(server) {
3283
3383
  server.route({
3284
3384
  method: '*',
3285
3385
  path: '/{any*}',
@@ -3287,7 +3387,9 @@ const init = async () => {
3287
3387
  throw Boom.notFound(request.app.gt.gettext('Requested page not found')); // 404
3288
3388
  }
3289
3389
  });
3390
+ }
3290
3391
 
3392
+ async function startApiListener(server, reusePortListener) {
3291
3393
  await server.start();
3292
3394
 
3293
3395
  if (USE_REUSE_PORT) {
@@ -3318,7 +3420,9 @@ const init = async () => {
3318
3420
  }
3319
3421
  });
3320
3422
  }
3423
+ }
3321
3424
 
3425
+ async function warnUntrustedForwardedFor() {
3322
3426
  // An IP allowlist is only as trustworthy as the address it matches against. If the deployment
3323
3427
  // takes the client address from X-Forwarded-For but does not say which peers may set it, any
3324
3428
  // client that can reach this port can present whatever address the allowlist expects.
@@ -3342,7 +3446,9 @@ const init = async () => {
3342
3446
  allowedAddresses: ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length ? ADMIN_ACCESS_ADDRESSES : null
3343
3447
  });
3344
3448
  }
3449
+ }
3345
3450
 
3451
+ function warmApiReference(server) {
3346
3452
  // Warm the swagger.json cache, and with it the /admin/reference render model - which
3347
3453
  // reads the same document back and costs ~12ms to build. Doing both here keeps that
3348
3454
  // work off the first visitor's request.
@@ -3355,7 +3461,9 @@ const init = async () => {
3355
3461
  logger.debug({ msg: 'Failed to build the API reference model', err });
3356
3462
  });
3357
3463
  });
3464
+ }
3358
3465
 
3466
+ function scheduleCertificateReconciler(certHandler) {
3359
3467
  // Keep the configured hostnames supplied with certificates.
3360
3468
  //
3361
3469
  // This used to be a renewal timer and nothing else: it read the certificate for the service
@@ -3387,6 +3495,93 @@ const init = async () => {
3387
3495
 
3388
3496
  handler().catch(err => logger.error({ msg: 'Failed to run certificate handler', err }));
3389
3497
  }, TLS_RENEW_CHECK_INTERVAL).unref();
3498
+ }
3499
+
3500
+ const init = async () => {
3501
+ await loadTranslations();
3502
+
3503
+ gt.setLocale((await settings.get('locale')) || 'en');
3504
+
3505
+ registerHandlebarsHelpers(handlebars, { gt });
3506
+
3507
+ const { server, certHandler, apiTlsContext, reusePortListener } = await createApiServer();
3508
+
3509
+ decorateApiToolkit(server, certHandler, apiTlsContext);
3510
+
3511
+ registerLocaleExtension(server);
3512
+ registerRequestContextExtension(server);
3513
+
3514
+ const openApiOptions = buildOpenApiOptions();
3515
+
3516
+ registerApiTokenAuth(server);
3517
+
3518
+ const secureCookie = await registerSessionAuth(server);
3519
+
3520
+ await registerOktaAuth(server, secureCookie);
3521
+ await registerOidcAuth(server, secureCookie);
3522
+
3523
+ await registerServerPlugins(server);
3524
+
3525
+ // Position is not load-bearing: the document is generated from the finished route table on the
3526
+ // first request, not at registration time
3527
+ registerOpenApiRoute(server, openApiOptions);
3528
+
3529
+ registerRequestEvents(server);
3530
+
3531
+ registerStaticPageRoutes(server);
3532
+ registerStaticFilesRoute(server);
3533
+ registerHealthRoute(server);
3534
+ registerRedirectRoute(server);
3535
+ registerOpenTrackingRoute(server);
3536
+ registerUnsubscribeRoute(server);
3537
+ registerOutlookNotificationRoute(server);
3538
+ registerOutlookLifecycleRoute(server);
3539
+ registerOAuthCallbackRoute(server);
3540
+
3541
+ // setup every /v1 route module (wiring lives in lib/api-routes/index.js so the route table
3542
+ // can be captured without booting this worker - see test/api-routes-table-test.js)
3543
+ await registerApiRoutes({
3544
+ server,
3545
+ call,
3546
+ notify,
3547
+ metrics,
3548
+ CORS_CONFIG,
3549
+ FLAG_SORT_ORDER,
3550
+ SMTP_TEST_HOST,
3551
+ MAX_ATTACHMENT_SIZE,
3552
+ MAX_BODY_SIZE,
3553
+ MAX_PAYLOAD_TIMEOUT,
3554
+ mcpFeatureEnabled,
3555
+ oauth2Schema,
3556
+ imapSchema,
3557
+ smtpSchema,
3558
+ AccountTypeSchema,
3559
+ OAuth2ProviderSchema
3560
+ });
3561
+
3562
+ await registerCsrfProtection(server, secureCookie);
3563
+
3564
+ registerViews(server);
3565
+
3566
+ registerResponseExtensions(server);
3567
+
3568
+ registerTotpExtension(server);
3569
+
3570
+ registerChangesRoute(server);
3571
+
3572
+ // setup web UI
3573
+ routesUi(server, call);
3574
+
3575
+ registerMetricsRoute(server);
3576
+ registerNotFoundRoute(server);
3577
+
3578
+ await startApiListener(server, reusePortListener);
3579
+
3580
+ await warnUntrustedForwardedFor();
3581
+
3582
+ warmApiReference(server);
3583
+
3584
+ scheduleCertificateReconciler(certHandler);
3390
3585
  };
3391
3586
 
3392
3587
  // dynamic imports first, use a wrapper function or eslint parser will crash