emailengine-app 2.76.0 → 2.78.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 (165) hide show
  1. package/.github/workflows/release.yaml +24 -19
  2. package/.github/workflows/test.yml +80 -0
  3. package/.ncurc.js +14 -2
  4. package/.release-please-manifest.json +3 -0
  5. package/CHANGELOG.md +54 -0
  6. package/README.md +1 -1
  7. package/bin/emailengine.js +1 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +72 -5
  10. package/lib/account/expected-identity.js +88 -0
  11. package/lib/account.js +75 -26
  12. package/lib/address-strategies.js +18 -0
  13. package/lib/api-reference/code-samples.js +194 -0
  14. package/lib/api-reference/format.js +193 -0
  15. package/lib/api-reference/index.js +222 -0
  16. package/lib/api-reference/model.js +338 -0
  17. package/lib/api-reference/schema-tree.js +366 -0
  18. package/lib/api-routes/account-routes.js +136 -39
  19. package/lib/api-routes/behavior-notes.js +57 -0
  20. package/lib/api-routes/blocklist-routes.js +9 -9
  21. package/lib/api-routes/changes-routes.js +6 -4
  22. package/lib/api-routes/chat-routes.js +3 -3
  23. package/lib/api-routes/delivery-test-routes.js +24 -6
  24. package/lib/api-routes/export-routes.js +14 -12
  25. package/lib/api-routes/gateway-routes.js +11 -11
  26. package/lib/api-routes/license-routes.js +7 -7
  27. package/lib/api-routes/mailbox-routes.js +18 -9
  28. package/lib/api-routes/message-routes.js +55 -35
  29. package/lib/api-routes/oauth2-app-routes.js +22 -16
  30. package/lib/api-routes/outbox-routes.js +7 -7
  31. package/lib/api-routes/pubsub-routes.js +3 -3
  32. package/lib/api-routes/settings-routes.js +10 -9
  33. package/lib/api-routes/stats-routes.js +3 -3
  34. package/lib/api-routes/submit-routes.js +58 -8
  35. package/lib/api-routes/template-routes.js +13 -13
  36. package/lib/api-routes/token-routes.js +15 -10
  37. package/lib/api-routes/webhook-route-routes.js +5 -5
  38. package/lib/append-list.js +3 -14
  39. package/lib/arf-detect.js +23 -1
  40. package/lib/autodetect-imap-settings.js +40 -16
  41. package/lib/base32.js +30 -0
  42. package/lib/bounce-detect.js +182 -62
  43. package/lib/consts.js +7 -0
  44. package/lib/egress-filter.js +89 -8
  45. package/lib/email-client/base-client.js +72 -82
  46. package/lib/email-client/gmail-client.js +3 -3
  47. package/lib/email-client/imap/listing-diff.js +3 -3
  48. package/lib/email-client/imap/mailbox.js +5 -69
  49. package/lib/email-client/imap-client.js +3 -2
  50. package/lib/email-client/message-builder.js +13 -13
  51. package/lib/email-client/outlook-client.js +1 -1
  52. package/lib/enum-descriptions.js +130 -0
  53. package/lib/export.js +1 -1
  54. package/lib/gateway.js +1 -1
  55. package/lib/get-raw-email.js +1 -1
  56. package/lib/imapproxy/imap-core/lib/imap-connection.js +2 -2
  57. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  58. package/lib/imapproxy/imap-server.js +42 -28
  59. package/lib/imapproxy/upstream-client.js +38 -0
  60. package/lib/license-beacon.js +1 -1
  61. package/lib/llm-pre-process.js +1 -1
  62. package/lib/msgpack.js +62 -0
  63. package/lib/oauth/decode-jwt-payload.js +39 -0
  64. package/lib/oauth/outlook-identity.js +61 -0
  65. package/lib/oauth/retry-setup.js +38 -0
  66. package/lib/oauth2-apps.js +10 -4
  67. package/lib/openapi/build-document.js +318 -0
  68. package/lib/openapi/index.js +95 -0
  69. package/lib/openapi/joi-schema.js +523 -0
  70. package/lib/outbox.js +66 -3
  71. package/lib/pre-process.js +1 -1
  72. package/lib/read-env-value.js +37 -0
  73. package/lib/routes-ui.js +5 -1
  74. package/lib/schemas.js +88 -17
  75. package/lib/swagger-options.js +173 -0
  76. package/lib/templates.js +1 -1
  77. package/lib/tokens.js +70 -6
  78. package/lib/tools.js +117 -48
  79. package/lib/totp.js +67 -0
  80. package/lib/ui-routes/account-routes.js +91 -15
  81. package/lib/ui-routes/admin-config-routes.js +2 -7
  82. package/lib/ui-routes/admin-entities-routes.js +3 -0
  83. package/lib/ui-routes/auth-routes.js +6 -24
  84. package/lib/ui-routes/dashboard-routes.js +2 -26
  85. package/lib/ui-routes/reference-routes.js +198 -0
  86. package/lib/ui-routes/route-helpers.js +39 -0
  87. package/lib/utils/is-email.js +34 -0
  88. package/lib/utils/to-camel-case.js +17 -0
  89. package/lib/webhook-egress.js +37 -0
  90. package/lib/webhooks.js +1 -1
  91. package/package.json +27 -31
  92. package/prepare-bundle-deps.sh +28 -0
  93. package/release-please-config.json +11 -0
  94. package/sbom.json +1 -1
  95. package/server.js +11 -3
  96. package/static/css/flyonui.css +1 -1
  97. package/static/css/public.css +3 -0
  98. package/static/css/src/app.tailwind.css +113 -0
  99. package/static/js/app.js +69 -0
  100. package/static/js/ee-client.js +238 -8
  101. package/static/js/reference.js +1021 -0
  102. package/static/js/ui.js +61 -33
  103. package/static/licenses.html +658 -1560
  104. package/translations/README.md +64 -0
  105. package/translations/de.mo +0 -0
  106. package/translations/de.po +164 -120
  107. package/translations/en.po +200 -161
  108. package/translations/et.mo +0 -0
  109. package/translations/et.po +163 -120
  110. package/translations/fr.mo +0 -0
  111. package/translations/fr.po +163 -120
  112. package/translations/ja.mo +0 -0
  113. package/translations/ja.po +163 -120
  114. package/translations/messages.pot +84 -54
  115. package/translations/nl.mo +0 -0
  116. package/translations/nl.po +164 -120
  117. package/translations/pl.mo +0 -0
  118. package/translations/pl.po +163 -120
  119. package/views/account-identity-error.hbs +34 -0
  120. package/views/accounts/edit.hbs +1 -0
  121. package/views/accounts/register/imap.hbs +12 -2
  122. package/views/config/ai.hbs +1 -1
  123. package/views/config/document-store/chat.hbs +5 -5
  124. package/views/config/document-store/index.hbs +2 -2
  125. package/views/config/document-store/pre-processing/index.hbs +1 -1
  126. package/views/config/email-processing.hbs +1 -1
  127. package/views/config/imap-proxy.hbs +1 -1
  128. package/views/config/license.hbs +1 -1
  129. package/views/config/oauth/index.hbs +3 -3
  130. package/views/config/security.hbs +1 -1
  131. package/views/config/smtp.hbs +2 -2
  132. package/views/dashboard.hbs +1 -1
  133. package/views/layout/app.hbs +43 -8
  134. package/views/oauth-scope-error.hbs +1 -1
  135. package/views/partials/oauth_form.hbs +4 -4
  136. package/views/partials/reference/anchor-link.hbs +20 -0
  137. package/views/partials/reference/disclosure.hbs +37 -0
  138. package/views/partials/reference/nav.hbs +120 -0
  139. package/views/partials/reference/operation.hbs +127 -0
  140. package/views/partials/reference/params.hbs +20 -0
  141. package/views/partials/reference/schema-node.hbs +99 -0
  142. package/views/partials/reference/schema.hbs +19 -0
  143. package/views/partials/reference/section-heading.hbs +16 -0
  144. package/views/partials/reference/token-alert.hbs +49 -0
  145. package/views/partials/reference/try-field.hbs +31 -0
  146. package/views/partials/reference/try-it.hbs +78 -0
  147. package/views/partials/side_menu.hbs +1 -1
  148. package/views/partials/ui/badge.hbs +4 -2
  149. package/views/partials/ui/page-header.hbs +1 -1
  150. package/views/partials/ui/search-input.hbs +31 -0
  151. package/views/partials/ui/setting-ref.hbs +1 -1
  152. package/views/partials/ui/stat-card.hbs +4 -2
  153. package/views/partials/ui/tab.hbs +6 -1
  154. package/views/partials/ui/tabs.hbs +2 -2
  155. package/views/reference/index.hbs +76 -0
  156. package/views/reference/redirect.hbs +49 -0
  157. package/views/reference/tag.hbs +28 -0
  158. package/views/reference/token.hbs +49 -0
  159. package/views/tokens/index.hbs +9 -1
  160. package/views/webhooks/index.hbs +3 -3
  161. package/workers/api.js +194 -302
  162. package/workers/imap.js +1 -1
  163. package/workers/submit.js +1 -1
  164. package/workers/webhooks.js +2 -13
  165. package/views/swagger/index.hbs +0 -82
package/workers/api.js CHANGED
@@ -8,7 +8,7 @@ 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 } = require('../lib/ui-routes/route-helpers');
11
+ const { accountStateLabel, formatServerState, identityErrorView } = require('../lib/ui-routes/route-helpers');
12
12
  const util = require('util');
13
13
  const { webhooks: Webhooks } = require('../lib/webhooks');
14
14
  const featureFlags = require('../lib/feature-flags');
@@ -57,13 +57,16 @@ const hapiPino = require('hapi-pino');
57
57
  const Inert = require('@hapi/inert');
58
58
  const Vision = require('@hapi/vision');
59
59
  const Accept = require('@hapi/accept');
60
- const HapiSwagger = require('hapi-swagger');
61
60
 
62
61
  const pathlib = require('path');
63
62
 
64
63
  const crypto = require('crypto');
65
64
  const { registeredPublishers, openChangeStream } = require('../lib/response-stream');
66
- const { oauth2Apps, OAUTH_PROVIDERS } = require('../lib/oauth2-apps');
65
+ const { oauth2Apps } = require('../lib/oauth2-apps');
66
+ const { decodeJwtPayload } = require('../lib/oauth/decode-jwt-payload');
67
+ const { resolveOutlookUserInfo } = require('../lib/oauth/outlook-identity');
68
+ const { buildRetrySetup } = require('../lib/oauth/retry-setup');
69
+ const { matchesExpectedIdentity, pendingSetupExpectation, resolveExpectedIdentity } = require('../lib/account/expected-identity');
67
70
 
68
71
  const handlebars = require('handlebars');
69
72
  const AuthBearer = require('hapi-auth-bearer-token');
@@ -79,6 +82,9 @@ const { getESClient, documentStoreFeatureEnabled } = require('../lib/document-st
79
82
  const sso = require('../lib/sso');
80
83
 
81
84
  const routesUi = require('../lib/routes-ui');
85
+ const specOptions = require('../lib/swagger-options');
86
+ const { registerOpenApiRoute } = require('../lib/openapi');
87
+ const { getModel: getApiReferenceModel, clearServiceUrlCache } = require('../lib/api-reference');
82
88
 
83
89
  const { encrypt, decrypt } = require('../lib/encrypt');
84
90
  const { Certs } = require('@postalsys/certs');
@@ -105,23 +111,15 @@ const {
105
111
  const registerApiRoutes = require('../lib/api-routes');
106
112
  const bullBoardRoutes = require('../lib/api-routes/bull-board-routes');
107
113
 
108
- const { imapSchema, smtpSchema, oauth2Schema, accountIdSchema, headerTimeoutSchema } = require('../lib/schemas');
109
-
110
- const OAuth2ProviderSchema = Joi.string()
111
- .valid(...Object.keys(OAUTH_PROVIDERS))
112
- .required()
113
- .example('gmail')
114
- .description('OAuth2 provider')
115
- .label('OAuth2Provider');
116
-
117
- const AccountTypeSchema = Joi.string()
118
- .valid(...['imap'].concat(Object.keys(OAUTH_PROVIDERS)).concat(['oauth2', 'delegated', 'sending', 'invalid']))
119
- .example('outlook')
120
- .description(
121
- 'Account type: "imap" for IMAP accounts, an OAuth2 provider name for OAuth2 accounts, "oauth2" when the OAuth2 application is missing, "delegated" for delegated accounts, "sending" for send-only accounts, "invalid" when delegation cannot be resolved'
122
- )
123
- .required()
124
- .label('AccountType');
114
+ const {
115
+ imapSchema,
116
+ smtpSchema,
117
+ oauth2Schema,
118
+ accountIdSchema,
119
+ apiHeadersSchema,
120
+ oauth2ProviderSchema: OAuth2ProviderSchema,
121
+ accountTypeSchema: AccountTypeSchema
122
+ } = require('../lib/schemas');
125
123
 
126
124
  const SUPPORTED_LOCALES = locales.map(locale => locale.locale);
127
125
 
@@ -439,6 +437,8 @@ parentPort.on('message', message => {
439
437
  if (message && message.cmd === 'settings') {
440
438
  // Keep this worker's in-memory HTTP proxy agent in sync when proxy settings change
441
439
  maybeReloadHttpProxyAgent(message.data);
440
+ // ...and the API reference's memoized serviceUrl, which its code samples embed
441
+ clearServiceUrlCache();
442
442
  }
443
443
  });
444
444
 
@@ -560,9 +560,7 @@ const init = async () => {
560
560
  language: 'en' // Default language
561
561
  }
562
562
  },
563
- headers: Joi.object({
564
- 'x-ee-timeout': headerTimeoutSchema
565
- }).unknown()
563
+ headers: apiHeadersSchema
566
564
  }
567
565
  }
568
566
  };
@@ -837,184 +835,17 @@ const init = async () => {
837
835
  return h.continue;
838
836
  });
839
837
 
840
- const swaggerOptions = {
841
- swaggerUI: true,
842
- jsonPath: '/swagger.json',
843
- swaggerUIPath: '/admin/swagger/resources/',
844
-
845
- OAS: 'v3.0',
846
-
847
- expanded: 'list',
848
- sortEndpoints: 'method',
849
- sortTags: 'unsorted',
850
-
851
- tryItOutEnabled: true,
852
-
853
- templates: Path.join(__dirname, '..', 'views', 'swagger', 'ui'),
854
-
855
- grouping: 'tags',
856
-
857
- info: {
858
- title: 'EmailEngine API',
859
- version: packageData.version,
860
-
861
- description: `EmailEngine provides a RESTful API for managing email accounts, sending messages, and processing email data across multiple providers.
862
-
863
- <h3>Authentication</h3>
864
- All API requests require authentication using an Access Token. You can generate and manage your tokens from the <a href="/admin/tokens" target="_parent"><strong>Access Tokens</strong></a> page.
865
-
866
- Include your token in requests using one of these methods:
867
- - Query parameter: <code>?access_token=YOUR_TOKEN</code>
868
- - Authorization header: <code>Authorization: Bearer YOUR_TOKEN</code>
869
-
870
- <h3>Request Processing</h3>
871
-
872
- <strong>Sequential Processing:</strong> Requests to the same email account are processed sequentially to maintain data consistency. Multiple simultaneous requests will be queued.
873
-
874
- <strong>Timeouts:</strong> Long-running operations may cause queued requests to timeout. Configure appropriate timeout values using the <code>X-EE-Timeout</code> header (in milliseconds).
875
-
876
- <h3>Getting Started</h3>
877
- 1. <a href="/admin/tokens" target="_parent">Generate an Access Token</a>
878
- 2. <a href="/admin/accounts" target="_parent">Add an email account</a>
879
- 3. Start making API requests using the endpoints below`,
838
+ const openApiOptions = {
839
+ // Spec-shaping options (tag list and order, security scheme, external docs) live in
840
+ // lib/swagger-options.js so the document can be reproduced outside a running server
841
+ ...specOptions,
880
842
 
881
- contact: {
882
- name: 'EmailEngine Support',
883
- url: 'https://learn.emailengine.app/docs/support',
884
- email: 'support@emailengine.app'
885
- },
886
-
887
- license: {
888
- name: 'EmailEngine License',
889
- url: 'https://emailengine.dev/LICENSE_EMAILENGINE.txt'
890
- }
891
- },
892
-
893
- externalDocs: {
894
- description: 'EmailEngine Documentation',
895
- url: 'https://learn.emailengine.app/'
896
- },
897
-
898
- securityDefinitions: {
899
- bearerAuth: {
900
- type: 'http',
901
- scheme: 'bearer',
902
- bearerFormat: 'JWT',
903
- description: 'Enter your access token'
904
- }
905
- },
906
-
907
- security: [{ bearerAuth: [] }],
908
-
909
- definitionPrefix: 'useLabel',
910
-
911
- cors: !!CORS_CONFIG,
912
- cache: {
913
- expiresIn: 7 * 24 * 60 * 60 * 1000
914
- },
915
-
916
- tags: [
917
- {
918
- name: 'Account',
919
- description: 'Manage email accounts, including IMAP/SMTP configuration, OAuth2 authentication, and account health monitoring'
920
- },
921
- {
922
- name: 'Mailbox',
923
- description: 'List, create, modify, and manage mailbox folders. Retrieve folder statistics and special-use designations'
924
- },
925
- {
926
- name: 'Message',
927
- description: 'Search, retrieve, update, and delete email messages. Manage flags, labels, and message content'
928
- },
929
- {
930
- name: 'Submit',
931
- description:
932
- 'Send emails with attachments, reply to threads, forward messages, and upload to folders. Supports both immediate and scheduled sending',
933
- externalDocs: {
934
- description: 'Sending Emails Documentation',
935
- url: 'https://learn.emailengine.app/docs/sending'
936
- }
937
- },
938
- {
939
- name: 'Outbox',
940
- description: 'Monitor and manage the email sending queue. View pending messages, retry failed deliveries, and track sending progress'
941
- },
942
- {
943
- name: 'Delivery Test',
944
- description: 'Test email deliverability and authentication. Verify SPF, DKIM signatures, DMARC alignment, and analyze potential delivery issues'
945
- },
946
- {
947
- name: 'Access Tokens',
948
- description: 'Create and manage API access tokens with customizable permissions, IP restrictions, and rate limits'
949
- },
950
- {
951
- name: 'Settings',
952
- description: 'Configure EmailEngine runtime settings including webhooks, tracking, AI features, and email processing options'
953
- },
954
- {
955
- name: 'Templates',
956
- description: 'Create and manage reusable email templates with variable substitution, HTML/text content, and attachments',
957
- externalDocs: {
958
- description: 'Email Templates Documentation',
959
- url: 'https://learn.emailengine.app/docs/sending/templates'
960
- }
961
- },
962
- {
963
- name: 'Logs',
964
- description: 'Access system and account-level logs for debugging, monitoring, and audit purposes'
965
- },
966
- {
967
- name: 'Stats',
968
- description: 'Retrieve usage statistics, performance metrics, and account activity data',
969
- externalDocs: {
970
- description: 'Monitoring and Analytics',
971
- url: 'https://learn.emailengine.app/docs/advanced/monitoring'
972
- }
973
- },
974
- {
975
- name: 'License',
976
- description: 'Manage EmailEngine licensing, view license status, and handle license-related operations'
977
- },
978
- {
979
- name: 'Webhooks',
980
- description: 'Configure webhook endpoints, manage event subscriptions, and monitor webhook delivery status',
981
- externalDocs: {
982
- description: 'Webhooks Guide',
983
- url: 'https://learn.emailengine.app/docs/webhooks/overview'
984
- }
985
- },
986
- {
987
- name: 'OAuth2 Applications',
988
- description: 'Configure OAuth2 applications for Gmail, Outlook, and other providers. Manage client credentials and authentication flows',
989
- externalDocs: {
990
- description: 'OAuth2 Configuration Guide',
991
- url: 'https://learn.emailengine.app/docs/configuration/oauth2-configuration'
992
- }
993
- },
994
- {
995
- name: 'SMTP Gateway',
996
- description: 'Configure and manage the built-in SMTP server for receiving emails and integrating with external systems'
997
- },
998
- {
999
- name: 'Blocklists',
1000
- description: 'Manage email address blocklists to prevent sending to specific recipients or domains'
1001
- },
1002
- {
1003
- name: 'Multi Message Actions',
1004
- description: 'Perform bulk operations on multiple messages simultaneously, such as marking as read, moving, or deleting'
1005
- },
1006
- {
1007
- name: 'Export (Beta)',
1008
- description:
1009
- 'Bulk export messages from email accounts. This feature is in beta and the API may change in future releases. Export files are encrypted at rest when a service secret is configured.'
1010
- }
1011
- ],
843
+ // The running version is the only part of `info` this worker owns - the rest is static
844
+ // and lives with the other document metadata in lib/swagger-options.js, so the tests
845
+ // see the same values a real instance serves
846
+ info: Object.assign({}, specOptions.info, { version: packageData.version }),
1012
847
 
1013
- // Custom vendor extensions for additional metadata
1014
- 'x-logo': {
1015
- url: 'https://emailengine.dev/static/logo.png',
1016
- altText: 'EmailEngine Logo'
1017
- }
848
+ cors: !!CORS_CONFIG
1018
849
  };
1019
850
 
1020
851
  await server.register(AuthBearer);
@@ -1485,14 +1316,11 @@ Include your token in requests using one of these methods:
1485
1316
  }
1486
1317
  });
1487
1318
 
1488
- await server.register([
1489
- Inert,
1490
- Vision,
1491
- {
1492
- plugin: HapiSwagger,
1493
- options: swaggerOptions
1494
- }
1495
- ]);
1319
+ await server.register([Inert, Vision]);
1320
+
1321
+ // Position is not load-bearing: the document is generated from the finished route table on the
1322
+ // first request, not at registration time
1323
+ registerOpenApiRoute(server, openApiOptions);
1496
1324
 
1497
1325
  server.events.on('response', request => {
1498
1326
  const tags = request.route && request.route.settings && request.route.settings.tags;
@@ -2232,6 +2060,18 @@ Include your token in requests using one of these methods:
2232
2060
 
2233
2061
  const provider = accountData.oauth2.provider;
2234
2062
 
2063
+ // What the caller originally asked for, captured before the provider branches below rewrite
2064
+ // accountData from whoever signed in. A retry has to start from this rather than from the
2065
+ // rejected attempt: `email` may name a shared mailbox to bind (and is otherwise overwritten
2066
+ // with the authenticated address), `name` gets filled in from the rejected user's profile when
2067
+ // the caller supplied none, and `oauth2.auth.delegatedUser` names the mailbox rather than a
2068
+ // credential, so it must survive while the tokens do not.
2069
+ const requestedSetup = {
2070
+ email: accountData.email,
2071
+ name: accountData.name,
2072
+ delegatedUser: accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser
2073
+ };
2074
+
2235
2075
  const oauth2App = await oauth2Apps.get(provider);
2236
2076
  if (!oauth2App) {
2237
2077
  let error = Boom.boomify(new Error('Missing or disabled OAuth2 app'), { statusCode: 404 });
@@ -2240,6 +2080,44 @@ Include your token in requests using one of these methods:
2240
2080
 
2241
2081
  const oAuth2Client = await oauth2Apps.getClient(oauth2App.id);
2242
2082
 
2083
+ // have to use HTML redirect, otherwise samesite=strict cookies are not passed on
2084
+ const renderRedirect = httpRedirectUrl =>
2085
+ h.view(
2086
+ 'redirect',
2087
+ {
2088
+ pageTitleFull: request.app.gt.gettext('Email Account Setup'),
2089
+ httpRedirectUrl
2090
+ },
2091
+ {
2092
+ layout: 'public'
2093
+ }
2094
+ );
2095
+
2096
+ // Hands the user back to the provider after a failure they can correct themselves, as a fresh
2097
+ // single-use setup. The token-bearing oauth2 object is dropped so the retry starts clean, and
2098
+ // _meta rides along so the redirect URL, the expected identity and the form nonce all survive
2099
+ // it - that nonce is claimed only on success, so it is still unspent here.
2100
+ const startOAuthRetry = async (loginHint, prompt) => {
2101
+ const reAuthState = `account:add:${crypto.randomBytes(NONCE_BYTES).toString('base64url')}`;
2102
+ const reAuthAccountData = buildRetrySetup(accountData, requestedSetup, provider, accountMeta);
2103
+
2104
+ await redis.set(`${REDIS_PREFIX}${reAuthState}`, JSON.stringify(reAuthAccountData), 'EX', Math.floor(MAX_FORM_TTL / 1000));
2105
+
2106
+ // The address to steer the user towards rides on the authorize URL only - persisting it
2107
+ // would overwrite a shared mailbox with the principal that is signing in to reach it.
2108
+ return oAuth2Client.generateAuthUrl({ state: reAuthState, email: loginHint, prompt });
2109
+ };
2110
+
2111
+ // Addresses the provider itself returned over a back channel, the only values allowed to
2112
+ // satisfy an expected identity (see lib/account/expected-identity.js). Every provider case
2113
+ // fills this in; one that does not leaves it empty, and an empty list fails the check closed.
2114
+ const providerIdentities = [];
2115
+
2116
+ // The token to revoke if the setup is rejected after the code was already exchanged, set by
2117
+ // each provider case because the token response is scoped to the switch. Prefer the refresh
2118
+ // token: revoking either invalidates the grant, but the access token may already be expired.
2119
+ let grantToken;
2120
+
2243
2121
  // `app.provider` is for example "gmail", `provider` is oauth2 app id
2244
2122
  switch (oauth2App.provider) {
2245
2123
  case 'gmail': {
@@ -2270,19 +2148,7 @@ Include your token in requests using one of these methods:
2270
2148
  request.logger.error({ msg: 'Failed to revoke partial OAuth2 token', err });
2271
2149
  });
2272
2150
 
2273
- const reAuthNonce = crypto.randomBytes(NONCE_BYTES).toString('base64url');
2274
- const reAuthState = `account:add:${reAuthNonce}`;
2275
- const reAuthAccountData = Object.assign({}, accountData, {
2276
- oauth2: { provider },
2277
- _meta: accountMeta
2278
- });
2279
-
2280
- await redis.set(`${REDIS_PREFIX}${reAuthState}`, JSON.stringify(reAuthAccountData), 'EX', Math.floor(MAX_FORM_TTL / 1000));
2281
-
2282
- const reAuthUrl = oAuth2Client.generateAuthUrl({
2283
- state: reAuthState,
2284
- email: accountData.email
2285
- });
2151
+ const retryUrl = await startOAuthRetry(accountData.email);
2286
2152
 
2287
2153
  const missingScopesList = missingScopes.map(formatScopeDescription);
2288
2154
 
@@ -2291,7 +2157,7 @@ Include your token in requests using one of these methods:
2291
2157
  {
2292
2158
  pageTitleFull: request.app.gt.gettext('Email Account Setup'),
2293
2159
  templateLocale: request.app.locale,
2294
- reAuthUrl,
2160
+ retryUrl,
2295
2161
  missingScopesList
2296
2162
  },
2297
2163
  {
@@ -2306,20 +2172,14 @@ Include your token in requests using one of these methods:
2306
2172
 
2307
2173
  // With OpenID Connect scopes (openid, email, profile), the ID token contains user info
2308
2174
  // This works for all account types including send-only accounts
2309
- if (r.id_token && typeof r.id_token === 'string') {
2310
- let [, encodedValue] = r.id_token.split('.');
2311
- if (encodedValue) {
2312
- try {
2313
- let decodedValue = JSON.parse(Buffer.from(encodedValue, 'base64url').toString());
2314
- if (decodedValue && typeof decodedValue.email === 'string' && isEmail(decodedValue.email)) {
2315
- userEmail = decodedValue.email;
2316
- userName = decodedValue.name || null;
2317
- request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
2318
- }
2319
- } catch (err) {
2320
- request.logger.error({ msg: 'Failed to decode Gmail ID token', err });
2321
- }
2322
- }
2175
+ const idTokenPayload = decodeJwtPayload(r.id_token);
2176
+ if (r.id_token && !idTokenPayload) {
2177
+ request.logger.error({ msg: 'Failed to decode Gmail ID token' });
2178
+ }
2179
+ if (idTokenPayload && typeof idTokenPayload.email === 'string' && isEmail(idTokenPayload.email)) {
2180
+ userEmail = idTokenPayload.email;
2181
+ userName = idTokenPayload.name || null;
2182
+ request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
2323
2183
  }
2324
2184
 
2325
2185
  // If ID token didn't provide email, fall back to Gmail API profile endpoint
@@ -2364,6 +2224,11 @@ Include your token in requests using one of these methods:
2364
2224
  throw error;
2365
2225
  }
2366
2226
 
2227
+ // Back-channel only: either the id_token from the token endpoint or the Gmail profile
2228
+ // API response, never a value that travelled through the browser.
2229
+ providerIdentities.push(userEmail);
2230
+ grantToken = r.refresh_token || r.access_token;
2231
+
2367
2232
  accountData.email = isEmail(userEmail) ? userEmail : accountData.email;
2368
2233
 
2369
2234
  const defaultScopes = (oauth2App.baseScopes && GMAIL_SCOPES[oauth2App.baseScopes]) || GMAIL_SCOPES.imap;
@@ -2398,43 +2263,31 @@ Include your token in requests using one of these methods:
2398
2263
  throw error;
2399
2264
  }
2400
2265
 
2401
- let userInfo = {};
2266
+ let userInfo;
2402
2267
 
2403
2268
  if (!oauth2App.baseScopes || oauth2App.baseScopes === 'imap') {
2404
- // Read account info from GET arguments
2405
- // This is needed because previously EmailEngine did not request for the User.Read scope
2406
-
2407
- let clientInfo = request.query.client_info ? JSON.parse(Buffer.from(request.query.client_info, 'base64url').toString()) : false;
2269
+ // Read account info from the id_token, falling back to the client_info GET argument.
2270
+ // The fallback is needed because previously EmailEngine did not request for the
2271
+ // User.Read scope - but client_info arrives through the browser, so it is a display
2272
+ // fallback only and never counts as identity evidence. See lib/oauth/outlook-identity.js.
2408
2273
 
2409
- if (clientInfo && typeof clientInfo.name === 'string') {
2410
- userInfo.name = clientInfo.name;
2274
+ let clientInfo = false;
2275
+ if (request.query.client_info) {
2276
+ try {
2277
+ clientInfo = JSON.parse(Buffer.from(request.query.client_info, 'base64url').toString());
2278
+ } catch (err) {
2279
+ // Base64-shaped but not JSON. It is an optional display hint, so log and continue
2280
+ // rather than failing the whole setup on a value we do not trust anyway.
2281
+ request.logger.warn({ msg: 'Failed to decode Outlook client_info argument', err });
2282
+ }
2411
2283
  }
2412
2284
 
2413
- if (clientInfo && clientInfo.preferred_username && isEmail(clientInfo.preferred_username)) {
2414
- userInfo.email = clientInfo.preferred_username;
2285
+ const idTokenPayload = decodeJwtPayload(r.id_token);
2286
+ if (r.id_token && !idTokenPayload) {
2287
+ request.logger.error({ msg: 'Failed to decode JWT payload' });
2415
2288
  }
2416
2289
 
2417
- if (r.id_token && typeof r.id_token === 'string') {
2418
- let [, encodedValue] = r.id_token.split('.');
2419
- if (encodedValue) {
2420
- try {
2421
- let decodedValue = JSON.parse(Buffer.from(encodedValue, 'base64url').toString());
2422
- if (decodedValue && typeof decodedValue.name === 'string') {
2423
- userInfo.name = decodedValue.name;
2424
- }
2425
-
2426
- if (decodedValue && typeof decodedValue.email === 'string' && isEmail(decodedValue.email)) {
2427
- userInfo.email = decodedValue.email;
2428
- }
2429
-
2430
- if (decodedValue && typeof decodedValue.preferred_username === 'string' && isEmail(decodedValue.preferred_username)) {
2431
- userInfo.username = decodedValue.preferred_username;
2432
- }
2433
- } catch (err) {
2434
- request.logger.error({ msg: 'Failed to decode JWT payload', err, encodedValue });
2435
- }
2436
- }
2437
- }
2290
+ userInfo = resolveOutlookUserInfo({ clientInfo, idTokenPayload });
2438
2291
  } else {
2439
2292
  // Request profile info from API
2440
2293
 
@@ -2451,28 +2304,14 @@ Include your token in requests using one of these methods:
2451
2304
  throw err;
2452
2305
  }
2453
2306
 
2307
+ userInfo = resolveOutlookUserInfo({ profile: profileRes });
2308
+
2454
2309
  request.logger.info({
2455
2310
  msg: 'User profile returned by MS Graph API',
2456
2311
  user: userInfo.email,
2457
2312
  provider: oauth2App.provider,
2458
2313
  profile: profileRes
2459
2314
  });
2460
-
2461
- if (profileRes.displayName) {
2462
- userInfo.name = profileRes.displayName;
2463
- }
2464
-
2465
- if (profileRes.mail) {
2466
- userInfo.email = profileRes.mail;
2467
- }
2468
-
2469
- if (profileRes.userPrincipalName) {
2470
- userInfo.username = profileRes.userPrincipalName;
2471
- }
2472
- }
2473
-
2474
- if (!userInfo.email && userInfo.username && isEmail(userInfo.username)) {
2475
- userInfo.email = userInfo.username;
2476
2315
  }
2477
2316
 
2478
2317
  const authData = {
@@ -2484,6 +2323,10 @@ Include your token in requests using one of these methods:
2484
2323
  throw error;
2485
2324
  }
2486
2325
 
2326
+ // Only the back-channel addresses, so a forged client_info cannot satisfy an expectation.
2327
+ providerIdentities.push(...userInfo.verifiedIdentities);
2328
+ grantToken = r.refresh_token || r.access_token;
2329
+
2487
2330
  if (accountData.oauth2 && accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser) {
2488
2331
  // Delegated user (shared mailbox) specified in oauth2.auth.delegatedUser
2489
2332
  authData.delegatedUser = accountData.oauth2.auth.delegatedUser;
@@ -2545,6 +2388,10 @@ Include your token in requests using one of these methods:
2545
2388
  throw error;
2546
2389
  }
2547
2390
 
2391
+ // Back-channel only: the Mail.ru userinfo endpoint response.
2392
+ providerIdentities.push(profileRes.email);
2393
+ grantToken = r.refresh_token || r.access_token;
2394
+
2548
2395
  accountData.name = accountData.name || profileRes.name || '';
2549
2396
  accountData.email = isEmail(profileRes.email) ? profileRes.email : accountData.email;
2550
2397
 
@@ -2574,6 +2421,61 @@ Include your token in requests using one of these methods:
2574
2421
  }
2575
2422
  }
2576
2423
 
2424
+ // Expected identity check. Runs before the nonce claim and before create(), so a rejected
2425
+ // setup neither consumes the signed link nor overwrites the credentials already on the
2426
+ // account. The expectation can come from the signed form blob or from the account itself -
2427
+ // persisting it is what makes the constraint outlive the link that introduced it, and it is
2428
+ // why a later link issued without expectedEmail cannot quietly drop the pin.
2429
+ const expectedEmail = await resolveExpectedIdentity(redis, {
2430
+ account: accountData.account,
2431
+ blobExpectation: pendingSetupExpectation(accountData, accountMeta)
2432
+ });
2433
+
2434
+ if (expectedEmail && !matchesExpectedIdentity(expectedEmail, providerIdentities)) {
2435
+ // Neither address is logged: the expectation and the authenticated identity both belong to
2436
+ // the end user, and this line is the one record of a failed attempt. Note the provider
2437
+ // identity was already logged by the "Provisioned OAuth2 tokens" line above.
2438
+ request.logger.warn({
2439
+ msg: 'OAuth2 identity did not match the expected email address',
2440
+ account: accountData.account,
2441
+ provider: oauth2App.provider
2442
+ });
2443
+
2444
+ // The code was already exchanged, so we are holding a refresh token we will never use.
2445
+ // Best effort, and the same duck-typing guard Account.delete({ revoke }) uses: only
2446
+ // GmailOauth implements revokeToken, and a rejected setup must not become a 500.
2447
+ if (grantToken && typeof oAuth2Client.revokeToken === 'function') {
2448
+ try {
2449
+ await oAuth2Client.revokeToken(grantToken);
2450
+ } catch (err) {
2451
+ request.logger.error({ msg: 'Failed to revoke the OAuth2 grant after an identity mismatch', err });
2452
+ }
2453
+ }
2454
+
2455
+ // Stop here with a way back rather than redirecting to the calling application: signing in
2456
+ // as the wrong account is a correctable mistake, and the hosted flow only ever redirects on
2457
+ // success. Hint the address they were supposed to use, and force the account picker:
2458
+ // they are already signed in to the one that just failed, so without select_account Google
2459
+ // would hand back the same account and the retry would loop. Microsoft always shows the
2460
+ // picker and Mail.ru ignores the hint, so this only changes Google's behavior.
2461
+ const retryUrl = await startOAuthRetry(expectedEmail, 'select_account consent');
2462
+
2463
+ return identityErrorView(request, h, {
2464
+ expectedEmail,
2465
+ // The primary address the provider reported. Microsoft can return both a mailbox
2466
+ // address and a user principal name, and either would have satisfied the pin, so
2467
+ // naming the first is enough to show which account actually signed in.
2468
+ actualEmail: providerIdentities[0],
2469
+ retryUrl
2470
+ });
2471
+ }
2472
+
2473
+ if (expectedEmail) {
2474
+ // Pin the account so every later setup is checked, including one driven by a link that
2475
+ // carries no expectation of its own.
2476
+ accountData.expectedEmail = expectedEmail;
2477
+ }
2478
+
2577
2479
  if ('delegated' in accountData) {
2578
2480
  // remove artefacts
2579
2481
  delete accountData.delegated;
@@ -2639,17 +2541,7 @@ Include your token in requests using one of these methods:
2639
2541
  httpRedirectUrl = `/admin/accounts/${result.account}`;
2640
2542
  }
2641
2543
 
2642
- // have to use HTML redirect, otherwise samesite=strict cookies are not passed on
2643
- return h.view(
2644
- 'redirect',
2645
- {
2646
- pageTitleFull: request.app.gt.gettext('Email Account Setup'),
2647
- httpRedirectUrl
2648
- },
2649
- {
2650
- layout: 'public'
2651
- }
2652
- );
2544
+ return renderRedirect(httpRedirectUrl);
2653
2545
  },
2654
2546
  options: {
2655
2547
  description: 'OAuth2 response endpoint',
@@ -2680,7 +2572,9 @@ Include your token in requests using one of these methods:
2680
2572
  .description('OAuth2 scopes'),
2681
2573
  client_info: Joi.string()
2682
2574
  .empty('')
2683
- .max(1024 * 1024)
2575
+ // A few hundred bytes of JSON in practice. Bounded tightly because this is an
2576
+ // unauthenticated route and the value is JSON.parse-d.
2577
+ .max(4 * 1024)
2684
2578
  .base64({ urlSafe: true, paddingRequired: false })
2685
2579
  .description('Outlook client info'),
2686
2580
  error: Joi.string()
@@ -3166,18 +3060,16 @@ Include your token in requests using one of these methods:
3166
3060
  });
3167
3061
  }
3168
3062
 
3169
- // trigger a request to cache swagger.json
3063
+ // Warm the swagger.json cache, and with it the /admin/reference render model - which
3064
+ // reads the same document back and costs ~12ms to build. Doing both here keeps that
3065
+ // work off the first visitor's request.
3170
3066
  setImmediate(() => {
3171
- server
3172
- .inject({
3173
- method: 'get',
3174
- url: '/swagger.json'
3175
- })
3176
- .then(res => {
3177
- logger.debug({ msg: 'Triggered swagger caching request', statusCode: res.statusCode });
3067
+ getApiReferenceModel(server)
3068
+ .then(model => {
3069
+ logger.debug({ msg: 'Built the API reference model', operations: model.operationCount });
3178
3070
  })
3179
3071
  .catch(err => {
3180
- logger.debug({ msg: 'Failed to trigger swagger caching request', err });
3072
+ logger.debug({ msg: 'Failed to build the API reference model', err });
3181
3073
  });
3182
3074
  });
3183
3075