emailengine-app 2.84.2 → 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 (86) hide show
  1. package/.ncurc.js +5 -3
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +33 -0
  6. package/Dockerfile +6 -0
  7. package/README.md +1 -1
  8. package/bin/emailengine.js +434 -408
  9. package/copy-static-files.sh +39 -14
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +16562 -0
  12. package/eslint.config.js +81 -99
  13. package/lib/account.js +36 -5
  14. package/lib/api-reference/format.js +4 -3
  15. package/lib/api-routes/account-routes.js +177 -12
  16. package/lib/api-routes/blocklist-routes.js +23 -2
  17. package/lib/api-routes/delivery-test-routes.js +26 -3
  18. package/lib/api-routes/export-routes.js +28 -2
  19. package/lib/api-routes/gateway-routes.js +28 -2
  20. package/lib/api-routes/mailbox-routes.js +41 -2
  21. package/lib/api-routes/message-routes.js +97 -3
  22. package/lib/api-routes/oauth2-app-routes.js +48 -15
  23. package/lib/api-routes/outbox-routes.js +45 -11
  24. package/lib/api-routes/permission-map.js +12 -1
  25. package/lib/api-routes/settings-routes.js +23 -2
  26. package/lib/api-routes/submit-routes.js +336 -309
  27. package/lib/api-routes/template-routes.js +38 -2
  28. package/lib/api-routes/token-routes.js +142 -96
  29. package/lib/api-routes/webhook-route-routes.js +13 -2
  30. package/lib/bounce-detect.js +397 -205
  31. package/lib/consts.js +5 -4
  32. package/lib/email-client/base-client.js +10 -31
  33. package/lib/email-client/gmail-client.js +9 -11
  34. package/lib/email-client/imap/mailbox.js +3 -19
  35. package/lib/email-client/imap/subconnection.js +1 -1
  36. package/lib/email-client/imap-client.js +1 -1
  37. package/lib/email-client/notification-handler.js +1 -2
  38. package/lib/gateway.js +2 -3
  39. package/lib/hapi-request-logger.js +107 -0
  40. package/lib/imapproxy/imap-core/README.md +6 -5
  41. package/lib/mcp/tools.js +37 -8
  42. package/lib/notify-attachments.js +17 -0
  43. package/lib/oauth/outlook-mailbox.js +35 -0
  44. package/lib/oauth/state.js +24 -0
  45. package/lib/oauth2-apps.js +1 -1
  46. package/lib/pbkdf2-phc.js +1 -1
  47. package/lib/schemas.js +1 -1
  48. package/lib/sso.js +1 -1
  49. package/lib/swagger-options.js +1 -1
  50. package/lib/thread-diagnostics.js +46 -0
  51. package/lib/timezones.js +109 -0
  52. package/lib/token-permission-view.js +3 -3
  53. package/lib/tools.js +40 -10
  54. package/lib/totp.js +2 -5
  55. package/lib/translations.js +1 -2
  56. package/lib/ui-routes/account-routes.js +475 -454
  57. package/lib/ui-routes/account-setup.js +99 -0
  58. package/lib/ui-routes/admin-config-routes.js +88 -10
  59. package/lib/ui-routes/admin-entities-routes.js +91 -7
  60. package/lib/ui-routes/auth-routes.js +90 -38
  61. package/lib/ui-routes/internals-routes.js +5 -0
  62. package/lib/ui-routes/oauth-config-routes.js +124 -82
  63. package/lib/ui-routes/route-helpers.js +19 -3
  64. package/lib/ui-routes/tls-config-routes.js +58 -15
  65. package/lib/utils/back-off.js +82 -0
  66. package/lib/utils/murmurhash3.js +66 -0
  67. package/lib/utils/public-suffix.js +122 -0
  68. package/lib/utils/random-id.js +26 -0
  69. package/lib/utils/version.js +74 -0
  70. package/lib/webhook-routing.js +27 -0
  71. package/lib/webhooks.js +41 -6
  72. package/package.json +27 -29
  73. package/sbom.json +7980 -1
  74. package/server.js +634 -441
  75. package/static/licenses.html +181 -1006
  76. package/translations/messages.pot +62 -63
  77. package/views/config/ai.hbs +1 -1
  78. package/views/config/security.hbs +2 -2
  79. package/views/config/service.hbs +3 -0
  80. package/views/internals/index.hbs +8 -0
  81. package/views/partials/webhook_form.hbs +1 -1
  82. package/views/suppression-lists/index.hbs +1 -1
  83. package/workers/api.js +738 -583
  84. package/workers/export.js +1 -1
  85. package/workers/submit.js +1 -1
  86. package/workers/webhooks.js +16 -32
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');
@@ -40,8 +47,6 @@ const {
40
47
  constantTimeEqual,
41
48
  verifyServiceSignature,
42
49
  SIGNING_PURPOSE,
43
- claimFormNonce,
44
- releaseFormNonce,
45
50
  setAdminSession,
46
51
  isEndedSession
47
52
  } = require('../lib/tools');
@@ -55,7 +60,7 @@ const Boom = require('@hapi/boom');
55
60
  const Cookie = require('@hapi/cookie');
56
61
  const Crumb = require('@hapi/crumb');
57
62
  const Joi = require('joi');
58
- const hapiPino = require('hapi-pino');
63
+ const requestLogger = require('../lib/hapi-request-logger');
59
64
  const Inert = require('@hapi/inert');
60
65
  const Vision = require('@hapi/vision');
61
66
  const Accept = require('@hapi/accept');
@@ -67,6 +72,9 @@ const { registeredPublishers, openChangeStream } = require('../lib/response-stre
67
72
  const { oauth2Apps } = require('../lib/oauth2-apps');
68
73
  const { decodeJwtPayload } = require('../lib/oauth/decode-jwt-payload');
69
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');
70
78
  const { buildRetrySetup } = require('../lib/oauth/retry-setup');
71
79
  const { matchesExpectedIdentity, pendingSetupExpectation, resolveExpectedIdentity } = require('../lib/account/expected-identity');
72
80
 
@@ -370,7 +378,7 @@ async function sendWebhook(account, event, data) {
370
378
  payload.data = data;
371
379
  }
372
380
 
373
- await Webhooks.pushToQueue(event, await Webhooks.formatPayload(event, payload));
381
+ await Webhooks.enqueue(event, payload);
374
382
  }
375
383
 
376
384
  async function onCommand(command) {
@@ -497,13 +505,16 @@ parentPort.on('message', message => {
497
505
  }
498
506
  });
499
507
 
500
- const init = async () => {
501
- await loadTranslations();
502
-
503
- gt.setLocale((await settings.get('locale')) || 'en');
504
-
505
- 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;
506
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() {
507
518
  // Base Hapi options shared by both the default and SO_REUSEPORT binding paths
508
519
  const serverOptions = {
509
520
  // hapi's default prints every internal request error to stderr; the request error
@@ -594,8 +605,10 @@ const init = async () => {
594
605
  });
595
606
  }
596
607
 
597
- let assertPreconditionResult;
608
+ return { server, certHandler, apiTlsContext, reusePortListener };
609
+ }
598
610
 
611
+ function decorateApiToolkit(server, certHandler, apiTlsContext) {
599
612
  // A read-only view of the certificate store for routes. Ordering a certificate is the
600
613
  // reconciler's job - it owns the state a page follows, the retry pacing and the listener
601
614
  // reload - and the difference between reading and ordering is one argument
@@ -626,7 +639,9 @@ const init = async () => {
626
639
  enabled: !!API_TLS,
627
640
  active: apiTlsContext ? apiTlsContext.active : null
628
641
  }));
642
+ }
629
643
 
644
+ function registerLocaleExtension(server) {
630
645
  server.ext('onPreAuth', async (request, h) => {
631
646
  const tags = (request.route && request.route.settings && request.route.settings.tags) || [];
632
647
  // Skip if it's a static file route
@@ -701,7 +716,9 @@ const init = async () => {
701
716
 
702
717
  return h.continue;
703
718
  });
719
+ }
704
720
 
721
+ function registerRequestContextExtension(server) {
705
722
  server.ext('onRequest', async (request, h) => {
706
723
  // set default, will be overriden once active language is resolved
707
724
  request.app.gt = gt;
@@ -777,7 +794,9 @@ const init = async () => {
777
794
 
778
795
  return h.continue;
779
796
  });
797
+ }
780
798
 
799
+ function buildOpenApiOptions() {
781
800
  const openApiOptions = {
782
801
  // Spec-shaping options (tag list and order, security scheme, external docs) live in
783
802
  // lib/swagger-options.js so the document can be reproduced outside a running server
@@ -791,6 +810,10 @@ const init = async () => {
791
810
  cors: !!CORS_CONFIG
792
811
  };
793
812
 
813
+ return openApiOptions;
814
+ }
815
+
816
+ function registerApiTokenAuth(server) {
794
817
  server.auth.scheme(API_TOKEN_SCHEME, apiTokenScheme);
795
818
 
796
819
  // Authentication for API calls
@@ -1167,7 +1190,26 @@ const init = async () => {
1167
1190
  return { isValid: true, credentials: { token }, artifacts: tokenData };
1168
1191
  }
1169
1192
  });
1193
+ }
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
+ };
1170
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) {
1171
1213
  // needed for auth session and flash messages
1172
1214
  await server.register(Cookie);
1173
1215
  await server.register(Bell);
@@ -1185,20 +1227,6 @@ const init = async () => {
1185
1227
  isSecure: secureCookie
1186
1228
  });
1187
1229
 
1188
- // The version an SSO login stamps into its session, so the checks that end a session later can
1189
- // compare against it. The password logins in lib/ui-routes/auth-routes.js stamp the same field
1190
- // from the same place; without it a session is refused on the first request after any version
1191
- // bump, which is a forced re-login rather than a lockout.
1192
- //
1193
- // Read by both strategies that accept a session: the cookie strategy below, and the session
1194
- // token branch of the api-token strategy above - the two credentials the same cookie carries,
1195
- // and "log out all sessions" has to end both. Declared here rather than above because both
1196
- // consumers only call it at request time, which is after this whole function has run.
1197
- const sessionPasswordVersion = async () => {
1198
- const authData = await settings.get('authData');
1199
- return (authData && authData.passwordVersion) || 0;
1200
- };
1201
-
1202
1230
  // Authentication for admin pages
1203
1231
  server.auth.strategy('session', 'cookie', {
1204
1232
  cookie: {
@@ -1295,27 +1323,31 @@ const init = async () => {
1295
1323
  }
1296
1324
  });
1297
1325
 
1298
- // Shared by the SSO strategies. The redirect URL is captured at strategy registration;
1299
- // the validators re-read it from settings so an origin change after startup (which would
1300
- // break the registered callback URL) disables the SSO button instead of failing mid-flow.
1301
- let getServiceRedirectUrl = async () => new URL((await settings.get('serviceUrl')) || `http://${API_HOST}${API_PORT !== 80 ? `:${API_PORT}` : ''}`);
1302
- let serviceOriginUnchanged = async redirectUrl => (await getServiceRedirectUrl()).origin === redirectUrl.origin;
1303
- // A sign-in the IdP denied, or the user cancelled, comes back as an unauthenticated try-mode
1304
- // request. It gets the same flash-and-redirect the allow-list denial in the OIDC handler
1305
- // uses, so the user lands on the login form with a way to try again rather than on the
1306
- // generic error page with bell's raw message. The reason goes to the log only. ?sso_denied=1
1307
- // stops a forced instance from auto-redirecting straight back into the flow.
1308
- let ssoFailureRedirect = async (request, h, method) => {
1309
- request.logger.warn({
1310
- msg: 'SSO login failed',
1311
- method,
1312
- reason: (request.auth.error && request.auth.error.message) || 'unknown',
1313
- remoteAddress: request.app.ip
1314
- });
1315
- await request.flash({ type: 'danger', message: 'Single sign-on failed or was cancelled. Please try again' });
1316
- return h.redirect('/admin/login?sso_denied=1');
1317
- };
1326
+ return secureCookie;
1327
+ }
1318
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
+ };
1349
+
1350
+ async function registerOktaAuth(server, secureCookie) {
1319
1351
  if (USE_OKTA_AUTH) {
1320
1352
  let redirectUrl = await getServiceRedirectUrl();
1321
1353
 
@@ -1370,7 +1402,9 @@ const init = async () => {
1370
1402
  }
1371
1403
  });
1372
1404
  }
1405
+ }
1373
1406
 
1407
+ async function registerOidcAuth(server, secureCookie) {
1374
1408
  if (USE_OIDC_AUTH) {
1375
1409
  let redirectUrl = await getServiceRedirectUrl();
1376
1410
 
@@ -1502,7 +1536,9 @@ const init = async () => {
1502
1536
  .catch(err => logger.error({ msg: 'OIDC SSO disabled: discovery retry failed', issuer: sso.OIDC_ISSUER, err }));
1503
1537
  }
1504
1538
  }
1539
+ }
1505
1540
 
1541
+ async function registerServerPlugins(server) {
1506
1542
  if (await settings.isInstanceSecured()) {
1507
1543
  server.auth.default('session');
1508
1544
  }
@@ -1512,20 +1548,17 @@ const init = async () => {
1512
1548
  sessionAuthServer = server;
1513
1549
 
1514
1550
  await server.register({
1515
- plugin: hapiPino,
1551
+ plugin: requestLogger,
1516
1552
  options: {
1517
- instance: logger.child({ component: 'api' }, { redact: consts.REDACTED_LOG_KEYS }),
1518
1553
  // Redact Authorization headers, see https://getpino.io/#/docs/redaction
1519
- redact: consts.REDACTED_LOG_KEYS
1554
+ logger: logger.child({ component: 'api' }, { redact: consts.REDACTED_LOG_KEYS })
1520
1555
  }
1521
1556
  });
1522
1557
 
1523
1558
  await server.register([Inert, Vision]);
1559
+ }
1524
1560
 
1525
- // Position is not load-bearing: the document is generated from the finished route table on the
1526
- // first request, not at registration time
1527
- registerOpenApiRoute(server, openApiOptions);
1528
-
1561
+ function registerRequestEvents(server) {
1529
1562
  // An exception thrown by a handler, an extension or a response schema with failAction
1530
1563
  // 'error' is answered with a bare 500 and reported on the request's error channel. hapi's
1531
1564
  // own record of it was an unstructured line on stderr (switched off above), and the API
@@ -1559,7 +1592,9 @@ const init = async () => {
1559
1592
  statusCode: request.response && request.response.statusCode
1560
1593
  });
1561
1594
  });
1595
+ }
1562
1596
 
1597
+ function registerStaticPageRoutes(server) {
1563
1598
  server.route({
1564
1599
  method: 'GET',
1565
1600
  path: '/',
@@ -1680,7 +1715,9 @@ const init = async () => {
1680
1715
  tags: ['static']
1681
1716
  }
1682
1717
  });
1718
+ }
1683
1719
 
1720
+ function registerStaticFilesRoute(server) {
1684
1721
  const staticRoot = pathlib.resolve(__dirname, '..', 'static');
1685
1722
  const staticRootPrefix = staticRoot + pathlib.sep;
1686
1723
 
@@ -1732,7 +1769,9 @@ const init = async () => {
1732
1769
  : undefined
1733
1770
  }
1734
1771
  });
1772
+ }
1735
1773
 
1774
+ function registerHealthRoute(server) {
1736
1775
  server.route({
1737
1776
  method: 'GET',
1738
1777
  path: '/health',
@@ -1759,7 +1798,9 @@ const init = async () => {
1759
1798
  tags: ['static', 'health']
1760
1799
  }
1761
1800
  });
1801
+ }
1762
1802
 
1803
+ function registerRedirectRoute(server) {
1763
1804
  server.route({
1764
1805
  method: 'GET',
1765
1806
  path: '/redirect',
@@ -1829,7 +1870,9 @@ const init = async () => {
1829
1870
  auth: false
1830
1871
  }
1831
1872
  });
1873
+ }
1832
1874
 
1875
+ function registerOpenTrackingRoute(server) {
1833
1876
  server.route({
1834
1877
  method: 'GET',
1835
1878
  path: '/open.gif',
@@ -1894,7 +1937,9 @@ const init = async () => {
1894
1937
  auth: false
1895
1938
  }
1896
1939
  });
1940
+ }
1897
1941
 
1942
+ function registerUnsubscribeRoute(server) {
1898
1943
  server.route({
1899
1944
  method: 'POST',
1900
1945
  path: '/unsubscribe',
@@ -2012,7 +2057,9 @@ const init = async () => {
2012
2057
  auth: false
2013
2058
  }
2014
2059
  });
2060
+ }
2015
2061
 
2062
+ function registerOutlookNotificationRoute(server) {
2016
2063
  server.route({
2017
2064
  method: 'POST',
2018
2065
  path: '/oauth/msg/notification',
@@ -2115,7 +2162,9 @@ const init = async () => {
2115
2162
  auth: false
2116
2163
  }
2117
2164
  });
2165
+ }
2118
2166
 
2167
+ function registerOutlookLifecycleRoute(server) {
2119
2168
  server.route({
2120
2169
  method: 'POST',
2121
2170
  path: '/oauth/msg/lifecycle',
@@ -2260,587 +2309,608 @@ const init = async () => {
2260
2309
  auth: false
2261
2310
  }
2262
2311
  });
2312
+ }
2263
2313
 
2264
- server.route({
2265
- method: 'GET',
2266
- path: '/oauth',
2267
- async handler(request, h) {
2268
- // The mailbox owner sees these on the public error page, in the same locale as the
2269
- // rest of the setup flow. The pending setup is still unspent at this point (its state
2270
- // entry is claimed only below), so opening the setup link again is a valid retry.
2271
- if (request.query.error === 'access_denied') {
2272
- let error = Boom.badRequest(
2273
- request.app.gt.gettext('The sign-in was cancelled or the requested access was not granted. Open the account setup link again to retry.')
2274
- );
2275
- if (request.query.error_description) {
2276
- error.output.payload.details = [String(request.query.error_description)];
2277
- }
2278
- throw error;
2279
- }
2280
-
2281
- if (request.query.error) {
2282
- throw Boom.badRequest(util.format(request.app.gt.gettext('Sign-in with the email provider failed: %s'), request.query.error));
2283
- }
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
+ }
2284
2332
 
2285
- if (!request.query.code) {
2286
- throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: no authorization code was received'));
2287
- }
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
+ }
2288
2336
 
2289
- // Validate nonce format: 16 bytes base64url encoded = 21-22 characters
2290
- // Also accept base64 encoding (+, /, =) for backward compatibility with old cached nonces
2291
- if (!/^account:add:[A-Za-z0-9_\-+/]{21,22}={0,2}$/.test(request.query.state)) {
2292
- throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: the request state is not valid'));
2293
- }
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
+ }
2294
2340
 
2295
- let [[, accountData]] = await redis.multi().get(`${REDIS_PREFIX}${request.query.state}`).del(`${REDIS_PREFIX}${request.query.state}`).exec();
2296
- if (!accountData) {
2297
- throw Boom.badRequest(
2298
- request.app.gt.gettext('The account setup session has expired or was already used. Open the account setup link again to retry.')
2299
- );
2300
- }
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
+ }
2301
2345
 
2302
- try {
2303
- accountData = JSON.parse(accountData);
2304
- } catch (E) {
2305
- throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: the stored setup session is not valid'));
2306
- }
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
+ }
2307
2353
 
2308
- if (!accountData.account) {
2309
- accountData.account = null;
2310
- }
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
+ }
2311
2359
 
2312
- const accountMeta = accountData._meta || {};
2313
- delete accountData._meta;
2360
+ if (!accountData.account) {
2361
+ accountData.account = null;
2362
+ }
2314
2363
 
2315
- const redirectUrl = accountMeta.redirectUrl;
2364
+ return accountData;
2365
+ }
2316
2366
 
2317
- 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;
2318
2373
 
2319
- // What the caller originally asked for, captured before the provider branches below rewrite
2320
- // accountData from whoever signed in. A retry has to start from this rather than from the
2321
- // rejected attempt: `email` may name a shared mailbox to bind (and is otherwise overwritten
2322
- // with the authenticated address), `name` gets filled in from the rejected user's profile when
2323
- // the caller supplied none, and `oauth2.auth.delegatedUser` names the mailbox rather than a
2324
- // credential, so it must survive while the tokens do not.
2325
- const requestedSetup = {
2326
- email: accountData.email,
2327
- name: accountData.name,
2328
- delegatedUser: accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser
2329
- };
2374
+ const reAuthState = `account:add:${crypto.randomBytes(NONCE_BYTES).toString('base64url')}`;
2375
+ const reAuthAccountData = buildRetrySetup(accountData, requestedSetup, provider, accountMeta);
2330
2376
 
2331
- const oauth2App = await oauth2Apps.get(provider);
2332
- if (!oauth2App) {
2333
- let error = Boom.boomify(new Error('Missing or disabled OAuth2 app'), { statusCode: 404 });
2334
- throw error;
2335
- }
2377
+ await redis.set(`${REDIS_PREFIX}${reAuthState}`, JSON.stringify(reAuthAccountData), 'EX', Math.floor(MAX_FORM_TTL / 1000));
2336
2378
 
2337
- // The code exchange, the profile lookups and any revoke already speak for the account being
2338
- // set up, so they leave through its route (its own proxy, if the setup named one)
2339
- 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
+ }
2340
2383
 
2341
- // have to use HTML redirect, otherwise samesite=strict cookies are not passed on
2342
- const renderRedirect = httpRedirectUrl =>
2343
- h.view(
2344
- 'redirect',
2345
- {
2346
- pageTitleFull: request.app.gt.gettext('Email Account Setup'),
2347
- httpRedirectUrl
2348
- },
2349
- {
2350
- layout: 'public'
2351
- }
2352
- );
2384
+ async function gmailMissingScopesView(flow, r, grantedScopes) {
2385
+ const { request, h, oAuth2Client, accountData } = flow;
2353
2386
 
2354
- // Hands the user back to the provider after a failure they can correct themselves, as a fresh
2355
- // single-use setup. The token-bearing oauth2 object is dropped so the retry starts clean, and
2356
- // _meta rides along so the redirect URL, the expected identity and the form nonce all survive
2357
- // it - that nonce is claimed only on success, so it is still unspent here.
2358
- const startOAuthRetry = async (loginHint, prompt) => {
2359
- const reAuthState = `account:add:${crypto.randomBytes(NONCE_BYTES).toString('base64url')}`;
2360
- 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));
2361
2390
 
2362
- 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
+ });
2363
2398
 
2364
- // The address to steer the user towards rides on the authorize URL only - persisting it
2365
- // would overwrite a shared mailbox with the principal that is signing in to reach it.
2366
- return oAuth2Client.generateAuthUrl({ state: reAuthState, email: loginHint, prompt });
2367
- };
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
+ });
2368
2403
 
2369
- // Addresses the provider itself returned over a back channel, the only values allowed to
2370
- // satisfy an expected identity (see lib/account/expected-identity.js). Every provider case
2371
- // fills this in; one that does not leaves it empty, and an empty list fails the check closed.
2372
- const providerIdentities = [];
2373
-
2374
- // The Workspace or Cloud organization domain the provider reported, for an application
2375
- // restricted to Google Workspace accounts. Only the Gmail case fills it in; the
2376
- // restriction is a Google setting and no other provider has the notion.
2377
- let workspaceDomain = null;
2378
-
2379
- // The token to revoke if the setup is rejected after the code was already exchanged, set by
2380
- // each provider case because the token response is scoped to the switch. Prefer the refresh
2381
- // token: revoking either invalidates the grant, but the access token may already be expired.
2382
- let grantToken;
2383
-
2384
- // `app.provider` is for example "gmail", `provider` is oauth2 app id
2385
- switch (oauth2App.provider) {
2386
- case 'gmail': {
2387
- const r = await oAuth2Client.getToken(request.query.code);
2388
- if (!r || !r.access_token) {
2389
- let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
2390
- throw error;
2391
- }
2404
+ const retryUrl = await startOAuthRetry(flow, accountData.email);
2392
2405
 
2393
- const grantedScopes = r.scope ? r.scope.split(/\s+/) : [];
2406
+ const missingScopesList = missingScopes.map(formatScopeDescription);
2394
2407
 
2395
- 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
+ }
2396
2422
 
2397
- // Check if user deselected required scopes in Google's granular consent
2398
- const requiredFunctionalScopes = oAuth2Client.scopes.filter(s => !OPENID_SCOPES.includes(s));
2399
- const missingScopes = requiredFunctionalScopes.filter(s => !grantedScopes.includes(s));
2423
+ async function resolveGmailUserEmail(flow, r, grantedScopes) {
2424
+ const { request, oAuth2Client } = flow;
2400
2425
 
2401
- if (missingScopes.length > 0) {
2402
- request.logger.warn({
2403
- msg: 'OAuth2 grant missing required scopes',
2404
- requested: requiredFunctionalScopes,
2405
- granted: grantedScopes,
2406
- missing: missingScopes
2407
- });
2426
+ let profileRes;
2427
+ let userEmail;
2428
+ let userName;
2408
2429
 
2409
- // Best-effort revocation of the partial token
2410
- oAuth2Client.revokeToken(r.refresh_token || r.access_token).catch(err => {
2411
- request.logger.warn({ msg: 'Failed to revoke partial OAuth2 token', err });
2412
- });
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
+ }
2413
2441
 
2414
- 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
+ }
2415
2474
 
2416
- 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
+ }
2417
2482
 
2418
- return h.view(
2419
- 'oauth-scope-error',
2420
- {
2421
- pageTitleFull: request.app.gt.gettext('Email Account Setup'),
2422
- templateLocale: request.app.locale,
2423
- retryUrl,
2424
- missingScopesList
2425
- },
2426
- {
2427
- layout: 'public'
2428
- }
2429
- );
2430
- }
2483
+ return { profileRes, userEmail, workspaceDomain };
2484
+ }
2431
2485
 
2432
- let profileRes;
2433
- let userEmail;
2434
- let userName;
2486
+ async function completeGmailCallback(flow) {
2487
+ const { request, oAuth2Client, oauth2App, provider, accountData, providerIdentities } = flow;
2435
2488
 
2436
- // With OpenID Connect scopes (openid, email, profile), the ID token contains user info
2437
- // This works for all account types including send-only accounts
2438
- const idTokenPayload = decodeJwtPayload(r.id_token);
2439
- if (r.id_token && !idTokenPayload) {
2440
- request.logger.warn({ msg: 'Failed to decode Gmail ID token' });
2441
- }
2442
- if (idTokenPayload && typeof idTokenPayload.email === 'string' && isEmail(idTokenPayload.email)) {
2443
- userEmail = idTokenPayload.email;
2444
- userName = idTokenPayload.name || null;
2445
- request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
2446
- }
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
+ }
2447
2494
 
2448
- // Back channel, so this is the claim the restriction can actually be enforced on;
2449
- // the hd argument on the authorization URL only filters the chooser Google shows
2450
- workspaceDomain = workspaceDomainOf(idTokenPayload);
2451
-
2452
- // If ID token didn't provide email, fall back to Gmail API profile endpoint
2453
- // This should rarely happen since we now request openid/email/profile scopes
2454
- if (!userEmail) {
2455
- // Check if we have scopes that allow accessing the profile endpoint
2456
- const hasProfileScope =
2457
- grantedScopes.includes('https://mail.google.com/') ||
2458
- grantedScopes.includes('https://www.googleapis.com/auth/gmail.readonly') ||
2459
- grantedScopes.includes('https://www.googleapis.com/auth/gmail.modify') ||
2460
- grantedScopes.includes('https://www.googleapis.com/auth/gmail.metadata');
2461
-
2462
- if (hasProfileScope) {
2463
- try {
2464
- request.logger.debug({ msg: 'Attempting Gmail profile endpoint as fallback' });
2465
- profileRes = await oAuth2Client.request(r.access_token, 'https://gmail.googleapis.com/gmail/v1/users/me/profile');
2466
- if (profileRes && profileRes.emailAddress) {
2467
- userEmail = profileRes.emailAddress;
2468
- }
2469
- } catch (err) {
2470
- request.logger.error({ msg: 'Failed to fetch user info from Gmail API', err });
2471
- let response = err.oauthRequest && err.oauthRequest.response;
2472
- if (response && response.error) {
2473
- let message;
2474
- if (/Gmail API has not been used in project/.test(response.error.message)) {
2475
- message =
2476
- 'Can not perform requests against Gmail API as the project has not been enabled. If you are the admin, check notifications on the dashboard.';
2477
- } else {
2478
- message = response.error.message;
2479
- }
2480
-
2481
- let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
2482
- throw error;
2483
- }
2484
- throw err;
2485
- }
2486
- }
2487
- }
2495
+ const grantedScopes = r.scope ? r.scope.split(/\s+/) : [];
2488
2496
 
2489
- if (!userEmail) {
2490
- let error = Boom.boomify(new Error(`Oauth failed: failed to retrieve account email address`), { statusCode: 400 });
2491
- throw error;
2492
- }
2497
+ request.logger.info({ msg: 'OAuth token received', grantedScopes, hasIdToken: !!r.id_token });
2493
2498
 
2494
- // Back-channel only: either the id_token from the token endpoint or the Gmail profile
2495
- // API response, never a value that travelled through the browser.
2496
- providerIdentities.push(userEmail);
2497
- grantToken = r.refresh_token || r.access_token;
2499
+ const scopeErrorView = await gmailMissingScopesView(flow, r, grantedScopes);
2500
+ if (scopeErrorView) {
2501
+ return { view: scopeErrorView };
2502
+ }
2498
2503
 
2499
- accountData.email = isEmail(userEmail) ? userEmail : accountData.email;
2504
+ const { profileRes, userEmail, workspaceDomain } = await resolveGmailUserEmail(flow, r, grantedScopes);
2500
2505
 
2501
- 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
+ }
2502
2510
 
2503
- accountData.oauth2 = Object.assign(
2504
- accountData.oauth2 || {},
2505
- {
2506
- provider,
2507
- accessToken: r.access_token,
2508
- refreshToken: r.refresh_token,
2509
- expires: new Date(Date.now() + r.expires_in * 1000),
2510
- scope: grantedScopes.length ? grantedScopes : defaultScopes,
2511
- tokenType: r.token_type
2512
- },
2513
- {
2514
- auth: {
2515
- user: userEmail
2516
- }
2517
- }
2518
- );
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);
2519
2514
 
2520
- accountData.googleHistoryId = profileRes ? Number(profileRes.historyId) || null : null;
2515
+ accountData.email = isEmail(userEmail) ? userEmail : accountData.email;
2521
2516
 
2522
- request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: userEmail, provider: oauth2App.provider });
2523
- break;
2524
- }
2517
+ const defaultScopes = (oauth2App.baseScopes && GMAIL_SCOPES[oauth2App.baseScopes]) || GMAIL_SCOPES.imap;
2525
2518
 
2526
- case 'outlook': {
2527
- const r = await oAuth2Client.getToken(request.query.code);
2528
- if (!r || !r.access_token) {
2529
- let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
2530
- throw error;
2531
- }
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
+ );
2532
2535
 
2533
- let userInfo;
2534
-
2535
- if (!oauth2App.baseScopes || oauth2App.baseScopes === 'imap') {
2536
- // Read account info from the id_token, falling back to the client_info GET argument.
2537
- // The fallback is needed because previously EmailEngine did not request for the
2538
- // User.Read scope - but client_info arrives through the browser, so it is a display
2539
- // fallback only and never counts as identity evidence. See lib/oauth/outlook-identity.js.
2540
-
2541
- let clientInfo = false;
2542
- if (request.query.client_info) {
2543
- try {
2544
- clientInfo = JSON.parse(Buffer.from(request.query.client_info, 'base64url').toString());
2545
- } catch (err) {
2546
- // Base64-shaped but not JSON. It is an optional display hint, so log and continue
2547
- // rather than failing the whole setup on a value we do not trust anyway.
2548
- request.logger.warn({ msg: 'Failed to decode Outlook client_info argument', err });
2549
- }
2550
- }
2536
+ accountData.googleHistoryId = profileRes ? Number(profileRes.historyId) || null : null;
2551
2537
 
2552
- const idTokenPayload = decodeJwtPayload(r.id_token);
2553
- if (r.id_token && !idTokenPayload) {
2554
- request.logger.warn({ msg: 'Failed to decode Outlook ID token' });
2555
- }
2538
+ request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: userEmail, provider: oauth2App.provider });
2556
2539
 
2557
- userInfo = resolveOutlookUserInfo({ clientInfo, idTokenPayload });
2558
- } else {
2559
- // Request profile info from API
2560
-
2561
- let profileRes;
2562
- try {
2563
- profileRes = await oAuth2Client.request(r.access_token, `${oAuth2Client.apiBase}/v1.0/me`);
2564
- } catch (err) {
2565
- let response = err.oauthRequest && err.oauthRequest.response;
2566
- if (response && response.error) {
2567
- let message = response.error.message;
2568
- let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
2569
- throw error;
2570
- }
2571
- throw err;
2572
- }
2540
+ return { grantToken: r.refresh_token || r.access_token, workspaceDomain };
2541
+ }
2573
2542
 
2574
- userInfo = resolveOutlookUserInfo({ profile: profileRes });
2543
+ async function resolveOutlookCallbackUser(flow, r) {
2544
+ const { request, oAuth2Client, oauth2App } = flow;
2575
2545
 
2576
- request.logger.info({
2577
- msg: 'User profile returned by MS Graph API',
2578
- user: userInfo.email,
2579
- provider: oauth2App.provider
2580
- });
2581
- }
2546
+ let userInfo;
2582
2547
 
2583
- const authData = {
2584
- user: userInfo.username || userInfo.email
2585
- };
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.
2586
2553
 
2587
- if (!authData.user) {
2588
- let error = Boom.boomify(new Error(`Oauth failed: failed to retrieve account email address`), { statusCode: 400 });
2589
- throw error;
2590
- }
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
+ }
2591
2564
 
2592
- // Only the back-channel addresses, so a forged client_info cannot satisfy an expectation.
2593
- providerIdentities.push(...userInfo.verifiedIdentities);
2594
- 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
+ }
2595
2569
 
2596
- if (accountData.oauth2 && accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser) {
2597
- // Delegated user (shared mailbox) specified in oauth2.auth.delegatedUser
2598
- authData.delegatedUser = accountData.oauth2.auth.delegatedUser;
2599
- // Ensure email is set to the delegated user if not already provided
2600
- if (!accountData.email) {
2601
- accountData.email = accountData.oauth2.auth.delegatedUser;
2602
- }
2603
- } else if (accountData.delegated && accountData.email && accountData.email !== userInfo.email) {
2604
- // Legacy: Shared mailbox specified via delegated flag
2605
- authData.delegatedUser = accountData.email;
2606
- } else {
2607
- // Not a delegated account, use the authenticated user's email
2608
- accountData.email = userInfo.email;
2609
- }
2570
+ userInfo = resolveOutlookUserInfo({ clientInfo, idTokenPayload });
2571
+ } else {
2572
+ // Request profile info from API
2610
2573
 
2611
- 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
+ }
2612
2586
 
2613
- accountData.oauth2 = Object.assign(
2614
- accountData.oauth2 || {},
2615
- {
2616
- provider,
2617
- accessToken: r.access_token,
2618
- refreshToken: r.refresh_token,
2619
- expires: new Date(Date.now() + r.expires_in * 1000),
2620
- scope: r.scope ? r.scope.split(/\s+/) : oAuth2Client.scopes,
2621
- tokenType: r.token_type
2622
- },
2623
- {
2624
- auth: authData
2625
- }
2626
- );
2587
+ userInfo = resolveOutlookUserInfo({ profile: profileRes });
2627
2588
 
2628
- request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: userInfo.email, provider: oauth2App.provider });
2629
- break;
2630
- }
2589
+ request.logger.info({
2590
+ msg: 'User profile returned by MS Graph API',
2591
+ user: userInfo.email,
2592
+ provider: oauth2App.provider
2593
+ });
2594
+ }
2631
2595
 
2632
- case 'mailRu': {
2633
- const r = await oAuth2Client.getToken(request.query.code);
2634
- if (!r || !r.access_token) {
2635
- let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
2636
- throw error;
2637
- }
2596
+ return userInfo;
2597
+ }
2638
2598
 
2639
- let profileRes;
2640
- try {
2641
- profileRes = await oAuth2Client.request(r.access_token, 'https://oauth.mail.ru/userinfo');
2642
- } catch (err) {
2643
- let response = err.oauthRequest && err.oauthRequest.response;
2644
- if (response && response.error) {
2645
- let message = response.error.message;
2646
- let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
2647
- throw error;
2648
- }
2649
- throw err;
2650
- }
2599
+ async function completeOutlookCallback(flow) {
2600
+ const { request, oAuth2Client, oauth2App, provider, accountData, providerIdentities } = flow;
2651
2601
 
2652
- if (!profileRes || !profileRes || !profileRes.email) {
2653
- let error = Boom.boomify(new Error(`Oauth failed: failed to retrieve account email address`), { statusCode: 400 });
2654
- throw error;
2655
- }
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
+ }
2656
2607
 
2657
- // Back-channel only: the Mail.ru userinfo endpoint response.
2658
- providerIdentities.push(profileRes.email);
2659
- grantToken = r.refresh_token || r.access_token;
2608
+ const userInfo = await resolveOutlookCallbackUser(flow, r);
2660
2609
 
2661
- accountData.name = accountData.name || profileRes.name || '';
2662
- accountData.email = isEmail(profileRes.email) ? profileRes.email : accountData.email;
2610
+ const authData = {
2611
+ user: userInfo.username || userInfo.email
2612
+ };
2663
2613
 
2664
- accountData.oauth2 = Object.assign(
2665
- accountData.oauth2 || {},
2666
- {
2667
- provider,
2668
- accessToken: r.access_token,
2669
- refreshToken: r.refresh_token,
2670
- expires: new Date(Date.now() + r.expires_in * 1000),
2671
- scope: r.scope ? r.scope.split(/\s+/) : MAIL_RU_SCOPES,
2672
- tokenType: r.token_type
2673
- },
2674
- {
2675
- auth: {
2676
- user: profileRes.email
2677
- }
2678
- }
2679
- );
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
+ }
2680
2618
 
2681
- request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: profileRes.email, provider: oauth2App.provider });
2682
- break;
2683
- }
2619
+ // Only the back-channel addresses, so a forged client_info cannot satisfy an expectation.
2620
+ providerIdentities.push(...userInfo.verifiedIdentities);
2684
2621
 
2685
- default: {
2686
- throw new Error('Unknown OAuth2 provider');
2687
- }
2688
- }
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
+ }
2689
2628
 
2690
- // Expected identity check. Runs before the nonce claim and before create(), so a rejected
2691
- // setup neither consumes the signed link nor overwrites the credentials already on the
2692
- // account. The expectation can come from the signed form blob or from the account itself -
2693
- // persisting it is what makes the constraint outlive the link that introduced it, and it is
2694
- // why a later link issued without expectedEmail cannot quietly drop the pin.
2695
- const expectedEmail = await resolveExpectedIdentity(redis, {
2696
- account: accountData.account,
2697
- blobExpectation: pendingSetupExpectation(accountData, accountMeta)
2698
- });
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
+ );
2699
2645
 
2700
- // "Accept only Google Workspace accounts" used to be advisory: generateAuthUrl() sets hd=*,
2701
- // which filters the account chooser Google shows and nothing else, so a link assembled
2702
- // without that argument - or a user who switches account inside the chooser - completed the
2703
- // setup with a consumer account. The hosted-domain claim of the ID token is checked here
2704
- // instead, and a token that names no domain is refused rather than trusted: for the Gmail
2705
- // provider the OpenID scopes are always requested (GmailOauth's constructor adds them), so
2706
- // a missing claim means the account has no Workspace domain, not that the claim was never
2707
- // asked for.
2708
- if (oauth2App.googleWorkspaceAccounts && oauth2App.provider === 'gmail' && !workspaceDomain) {
2709
- request.logger.warn({
2710
- msg: 'OAuth2 sign-in used a personal account for a Workspace-only application',
2711
- account: accountData.account,
2712
- provider: oauth2App.provider
2713
- });
2646
+ request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: userInfo.email, provider: oauth2App.provider });
2714
2647
 
2715
- // The code was already exchanged, so we are holding a grant we will never use. Best
2716
- // effort, and the same duck-typing guard as the identity mismatch below.
2717
- if (grantToken && typeof oAuth2Client.revokeToken === 'function') {
2718
- try {
2719
- await oAuth2Client.revokeToken(grantToken);
2720
- } catch (err) {
2721
- request.logger.warn({ msg: 'Failed to revoke the OAuth2 grant after a Workspace check', err });
2722
- }
2723
- }
2648
+ return { grantToken: r.refresh_token || r.access_token };
2649
+ }
2724
2650
 
2725
- // select_account for the same reason as the identity mismatch: they are signed in to the
2726
- // account that just failed, and without it Google would hand back the same one
2727
- const retryUrl = await startOAuthRetry(accountData.email, 'select_account consent');
2651
+ async function completeMailRuCallback(flow) {
2652
+ const { request, oAuth2Client, oauth2App, provider, accountData, providerIdentities } = flow;
2728
2653
 
2729
- return workspaceErrorView(request, h, { actualEmail: providerIdentities[0], retryUrl });
2730
- }
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
+ }
2731
2659
 
2732
- if (expectedEmail && !matchesExpectedIdentity(expectedEmail, providerIdentities)) {
2733
- // Neither address is logged: the expectation and the authenticated identity both belong to
2734
- // the end user, and this line is the one record of a failed attempt. Note the provider
2735
- // identity was already logged by the "Provisioned OAuth2 tokens" line above.
2736
- request.logger.warn({
2737
- msg: 'OAuth2 identity did not match the expected email address',
2738
- account: accountData.account,
2739
- provider: oauth2App.provider
2740
- });
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
+ }
2741
2672
 
2742
- // The code was already exchanged, so we are holding a refresh token we will never use.
2743
- // Best effort, and the same duck-typing guard Account.delete({ revoke }) uses: only
2744
- // GmailOauth implements revokeToken, and a rejected setup must not become a 500.
2745
- if (grantToken && typeof oAuth2Client.revokeToken === 'function') {
2746
- try {
2747
- await oAuth2Client.revokeToken(grantToken);
2748
- } catch (err) {
2749
- request.logger.warn({ msg: 'Failed to revoke the OAuth2 grant after an identity mismatch', err });
2750
- }
2751
- }
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
+ }
2752
2677
 
2753
- // Stop here with a way back rather than redirecting to the calling application: signing in
2754
- // as the wrong account is a correctable mistake, and the hosted flow only ever redirects on
2755
- // success. Hint the address they were supposed to use, and force the account picker:
2756
- // they are already signed in to the one that just failed, so without select_account Google
2757
- // would hand back the same account and the retry would loop. Microsoft always shows the
2758
- // picker and Mail.ru ignores the hint, so this only changes Google's behavior.
2759
- const retryUrl = await startOAuthRetry(expectedEmail, 'select_account consent');
2760
-
2761
- return identityErrorView(request, h, {
2762
- expectedEmail,
2763
- // The primary address the provider reported. Microsoft can return both a mailbox
2764
- // address and a user principal name, and either would have satisfied the pin, so
2765
- // naming the first is enough to show which account actually signed in.
2766
- actualEmail: providerIdentities[0],
2767
- retryUrl
2768
- });
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
2769
2697
  }
2698
+ }
2699
+ );
2770
2700
 
2771
- if (expectedEmail) {
2772
- // Pin the account so every later setup is checked, including one driven by a link that
2773
- // carries no expectation of its own.
2774
- accountData.expectedEmail = expectedEmail;
2775
- }
2701
+ request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: profileRes.email, provider: oauth2App.provider });
2776
2702
 
2777
- if ('delegated' in accountData) {
2778
- // remove artefacts
2779
- delete accountData.delegated;
2780
- }
2703
+ return { grantToken: r.refresh_token || r.access_token };
2704
+ }
2781
2705
 
2782
- let accountObject = new Account({
2783
- redis,
2784
- call,
2785
- secret: await getSecret(),
2786
- timeout: request.headers['x-ee-timeout']
2787
- });
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
+ }
2788
2731
 
2789
- // Claim the single-use nonce BEFORE create (SET NX), mirroring the IMAP arm in
2790
- // lib/ui-routes/account-routes.js, so one signed link cannot be double-spent across the two
2791
- // arms (initiate OAuth -> submit the same blob to /accounts/new/imap/server -> complete this
2792
- // callback) and a replayed callback cannot create a second account.
2793
- //
2794
- // Backward-compat, BY DESIGN: this only engages when accountMeta.n is present. Legacy /
2795
- // pre-upgrade re-auth blobs carry no nonce (accountMeta.n is undefined), so the claim is
2796
- // skipped and those links keep working - the OAuth entry (accountFormHandler) intentionally
2797
- // does NOT require a nonce for exactly that reason.
2798
- // claimFormNonce/releaseFormNonce (lib/tools.js) are the same primitives the IMAP arm uses, so
2799
- // the double-spend semantics stay in one place.
2800
- let nonceClaimed = false;
2801
- if (accountMeta.n) {
2802
- let claimed;
2803
- try {
2804
- claimed = await claimFormNonce(redis, accountMeta.n, accountMeta.t);
2805
- } catch (err) {
2806
- // A Redis failure is not a consumed nonce - surface a retryable error rather than
2807
- // misreporting a valid setup URL as invalid.
2808
- request.logger.error({ msg: 'Failed to claim nonce for an account form request', err });
2809
- throw Boom.boomify(new Error('Temporary error, please try again'), { statusCode: 500 });
2810
- }
2811
- if (!claimed) {
2812
- // The nonce key already exists: this signed URL was already used.
2813
- throw Boom.boomify(new Error('Invalid or expired account setup URL'), { statusCode: 403 });
2814
- }
2815
- nonceClaimed = true;
2816
- }
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;
2817
2736
 
2818
- 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') {
2819
2742
  try {
2820
- result = await accountObject.create(accountData);
2743
+ await oAuth2Client.revokeToken(grantToken);
2821
2744
  } catch (err) {
2822
- // Release the nonce so the user can retry (same accepted residual as the IMAP arm: if
2823
- // Redis also fails here the nonce stays consumed for its TTL and a fresh link is needed -
2824
- // the price of claim-before-create being atomic).
2825
- if (nonceClaimed) {
2826
- await releaseFormNonce(redis, accountMeta.n, request.logger);
2827
- }
2828
- throw err;
2745
+ request.logger.warn({ msg: failureMessage, err });
2829
2746
  }
2747
+ }
2748
+ };
2830
2749
 
2831
- let httpRedirectUrl;
2832
- if (redirectUrl) {
2833
- let serviceUrl = await settings.get('serviceUrl');
2834
- let url = new URL(redirectUrl, serviceUrl);
2835
- url.searchParams.set('account', result.account);
2836
- url.searchParams.set('state', result.state);
2837
- httpRedirectUrl = url.href;
2838
- } else {
2839
- httpRedirectUrl = `/admin/accounts/${result.account}`;
2840
- }
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
+ });
2841
2764
 
2842
- return renderRedirect(httpRedirectUrl);
2843
- },
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,
2844
2914
  options: {
2845
2915
  description: 'OAuth2 response endpoint',
2846
2916
 
@@ -2886,28 +2956,9 @@ const init = async () => {
2886
2956
  auth: false
2887
2957
  }
2888
2958
  });
2959
+ }
2889
2960
 
2890
- // setup every /v1 route module (wiring lives in lib/api-routes/index.js so the route table
2891
- // can be captured without booting this worker - see test/api-routes-table-test.js)
2892
- await registerApiRoutes({
2893
- server,
2894
- call,
2895
- notify,
2896
- metrics,
2897
- CORS_CONFIG,
2898
- FLAG_SORT_ORDER,
2899
- SMTP_TEST_HOST,
2900
- MAX_ATTACHMENT_SIZE,
2901
- MAX_BODY_SIZE,
2902
- MAX_PAYLOAD_TIMEOUT,
2903
- mcpFeatureEnabled,
2904
- oauth2Schema,
2905
- imapSchema,
2906
- smtpSchema,
2907
- AccountTypeSchema,
2908
- OAuth2ProviderSchema
2909
- });
2910
-
2961
+ async function registerCsrfProtection(server, secureCookie) {
2911
2962
  // Web UI routes
2912
2963
 
2913
2964
  await server.register({
@@ -2929,7 +2980,9 @@ const init = async () => {
2929
2980
  }
2930
2981
  }
2931
2982
  });
2983
+ }
2932
2984
 
2985
+ function registerViews(server) {
2933
2986
  server.views({
2934
2987
  engines: {
2935
2988
  hbs: handlebars
@@ -3185,7 +3238,9 @@ const init = async () => {
3185
3238
  };
3186
3239
  }
3187
3240
  });
3241
+ }
3188
3242
 
3243
+ function registerResponseExtensions(server) {
3189
3244
  const preResponse = async (request, h) => {
3190
3245
  let response = request.response;
3191
3246
 
@@ -3272,7 +3327,9 @@ const init = async () => {
3272
3327
  // After preResponse on purpose: it replaces an error response with the rendered error page
3273
3328
  // or a JSON body, and the headers have to land on whatever is actually sent
3274
3329
  server.ext('onPreResponse', securityHeadersExt({ cspMode: CSP_MODE }));
3330
+ }
3275
3331
 
3332
+ function registerTotpExtension(server) {
3276
3333
  server.ext('onPostAuth', async (request, h) => {
3277
3334
  if (request.requireTotp) {
3278
3335
  // The password step is done and only the second factor is missing, so the session
@@ -3289,7 +3346,9 @@ const init = async () => {
3289
3346
  }
3290
3347
  return h.continue;
3291
3348
  });
3349
+ }
3292
3350
 
3351
+ function registerChangesRoute(server) {
3293
3352
  server.route({
3294
3353
  method: 'GET',
3295
3354
  path: '/admin/changes',
@@ -3298,10 +3357,9 @@ const init = async () => {
3298
3357
  // helper so the two can not drift apart on framing or on stream cleanup.
3299
3358
  handler: openChangeStream
3300
3359
  });
3360
+ }
3301
3361
 
3302
- // setup web UI
3303
- routesUi(server, call);
3304
-
3362
+ function registerMetricsRoute(server) {
3305
3363
  server.route({
3306
3364
  method: 'GET',
3307
3365
  path: '/metrics',
@@ -3319,7 +3377,9 @@ const init = async () => {
3319
3377
  }
3320
3378
  }
3321
3379
  });
3380
+ }
3322
3381
 
3382
+ function registerNotFoundRoute(server) {
3323
3383
  server.route({
3324
3384
  method: '*',
3325
3385
  path: '/{any*}',
@@ -3327,7 +3387,9 @@ const init = async () => {
3327
3387
  throw Boom.notFound(request.app.gt.gettext('Requested page not found')); // 404
3328
3388
  }
3329
3389
  });
3390
+ }
3330
3391
 
3392
+ async function startApiListener(server, reusePortListener) {
3331
3393
  await server.start();
3332
3394
 
3333
3395
  if (USE_REUSE_PORT) {
@@ -3358,7 +3420,9 @@ const init = async () => {
3358
3420
  }
3359
3421
  });
3360
3422
  }
3423
+ }
3361
3424
 
3425
+ async function warnUntrustedForwardedFor() {
3362
3426
  // An IP allowlist is only as trustworthy as the address it matches against. If the deployment
3363
3427
  // takes the client address from X-Forwarded-For but does not say which peers may set it, any
3364
3428
  // client that can reach this port can present whatever address the allowlist expects.
@@ -3382,7 +3446,9 @@ const init = async () => {
3382
3446
  allowedAddresses: ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length ? ADMIN_ACCESS_ADDRESSES : null
3383
3447
  });
3384
3448
  }
3449
+ }
3385
3450
 
3451
+ function warmApiReference(server) {
3386
3452
  // Warm the swagger.json cache, and with it the /admin/reference render model - which
3387
3453
  // reads the same document back and costs ~12ms to build. Doing both here keeps that
3388
3454
  // work off the first visitor's request.
@@ -3395,7 +3461,9 @@ const init = async () => {
3395
3461
  logger.debug({ msg: 'Failed to build the API reference model', err });
3396
3462
  });
3397
3463
  });
3464
+ }
3398
3465
 
3466
+ function scheduleCertificateReconciler(certHandler) {
3399
3467
  // Keep the configured hostnames supplied with certificates.
3400
3468
  //
3401
3469
  // This used to be a renewal timer and nothing else: it read the certificate for the service
@@ -3427,6 +3495,93 @@ const init = async () => {
3427
3495
 
3428
3496
  handler().catch(err => logger.error({ msg: 'Failed to run certificate handler', err }));
3429
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);
3430
3585
  };
3431
3586
 
3432
3587
  // dynamic imports first, use a wrapper function or eslint parser will crash