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
@@ -6,7 +6,17 @@ const config = require('@zone-eu/wild-config');
6
6
  const logger = require('../logger');
7
7
  const { oauth2Apps, oauth2ProviderData } = require('../oauth2-apps');
8
8
 
9
- const { getDuration, getBoolean, resolveCredentials, hasEnvValue, readEnvValue, emitChangeEvent, loadTlsConfig } = require('../tools');
9
+ const {
10
+ getDuration,
11
+ getBoolean,
12
+ resolveCredentials,
13
+ useAuthServerForOAuth2,
14
+ useAuthServerForConnection,
15
+ hasEnvValue,
16
+ readEnvValue,
17
+ emitChangeEvent,
18
+ loadTlsConfig
19
+ } = require('../tools');
10
20
  const { getLocalAddress } = require('../utils/network');
11
21
 
12
22
  const { redis } = require('../db');
@@ -107,7 +117,7 @@ async function metrics(logger, key, method, ...args) {
107
117
  }
108
118
  }
109
119
 
110
- const { ImapFlow } = require('imapflow');
120
+ const { createUpstreamClient } = require('./upstream-client');
111
121
  const { IMAPServer, imapHandler } = require('./imap-core/index.js');
112
122
  const { PassThrough } = require('stream');
113
123
 
@@ -153,6 +163,14 @@ class PassThroughLogger extends PassThrough {
153
163
  // without booting this worker. call() is injected for the Account instance.
154
164
  const authenticateImapProxy = createImapProxyAuthHandler({ call });
155
165
 
166
+ // Tag a credential-loading failure as an IMAP authentication rejection for the proxy client.
167
+ function failImapAuth(err) {
168
+ err.authenticationFailed = true;
169
+ err.serverResponseCode = 'AUTHENTICATIONFAILED';
170
+ err.responseStatus = 'NO';
171
+ return err;
172
+ }
173
+
156
174
  async function onAuth(auth, session) {
157
175
  let account = auth.username;
158
176
 
@@ -166,21 +184,27 @@ async function onAuth(auth, session) {
166
184
  let imapConnectionConfig;
167
185
  if (accountData.oauth2 && accountData.oauth2.auth) {
168
186
  // load OAuth2 tokens
169
- let now = Date.now();
170
- let accessToken;
171
- if (!accountData.oauth2.accessToken || !accountData.oauth2.expires || accountData.oauth2.expires < new Date(now + 30 * 1000)) {
172
- // renew access token
187
+ let imapAuth;
188
+
189
+ if (await useAuthServerForOAuth2(accountData.oauth2, logger, { account, target: 'imap' })) {
190
+ // An external authentication server owns this account's tokens, so ask it for one
191
+ // rather than renewing from a stored refresh token (there is none). The response is
192
+ // already in the { user, accessToken } shape the connection config expects.
173
193
  try {
174
- accountData = await accountObject.renewAccessToken();
175
- accessToken = accountData.oauth2.accessToken;
194
+ imapAuth = await resolveCredentials(account, 'imap');
176
195
  } catch (err) {
177
- err.authenticationFailed = true;
178
- err.serverResponseCode = 'AUTHENTICATIONFAILED';
179
- err.responseStatus = 'NO';
180
- throw err;
196
+ throw failImapAuth(err);
181
197
  }
182
198
  } else {
183
- accessToken = accountData.oauth2.accessToken;
199
+ if (!accountData.oauth2.accessToken || !accountData.oauth2.expires || accountData.oauth2.expires < new Date(Date.now() + 30 * 1000)) {
200
+ // renew access token
201
+ try {
202
+ accountData = await accountObject.renewAccessToken();
203
+ } catch (err) {
204
+ throw failImapAuth(err);
205
+ }
206
+ }
207
+ imapAuth = { user: accountData.oauth2.auth.user, accessToken: accountData.oauth2.accessToken };
184
208
  }
185
209
 
186
210
  const oauth2App = await oauth2Apps.get(accountData.oauth2.provider);
@@ -189,29 +213,18 @@ async function onAuth(auth, session) {
189
213
  }
190
214
  const providerData = oauth2ProviderData(oauth2App.provider, oauth2App.cloud);
191
215
 
192
- imapConnectionConfig = Object.assign(
193
- {
194
- auth: {
195
- user: accountData.oauth2.auth.user,
196
- accessToken
197
- }
198
- },
199
- providerData.imap || {}
200
- );
216
+ imapConnectionConfig = Object.assign({ auth: imapAuth }, providerData.imap || {});
201
217
  } else {
202
218
  // deep copy of imap settings
203
219
  imapConnectionConfig = JSON.parse(JSON.stringify(accountData.imap));
204
220
  }
205
221
 
206
222
  // If authentication server is set then it overrides authentication data
207
- if (imapConnectionConfig.useAuthServer) {
223
+ if (await useAuthServerForConnection(imapConnectionConfig, logger, { account, target: 'imap' })) {
208
224
  try {
209
225
  imapConnectionConfig.auth = await resolveCredentials(account, 'imap');
210
226
  } catch (err) {
211
- err.authenticationFailed = true;
212
- err.serverResponseCode = 'AUTHENTICATIONFAILED';
213
- err.responseStatus = 'NO';
214
- throw err;
227
+ throw failImapAuth(err);
215
228
  }
216
229
  }
217
230
 
@@ -269,7 +282,8 @@ const createProxy = async (options = {}) => {
269
282
  imapConfig.tls.rejectUnauthorized = false;
270
283
  }
271
284
 
272
- let imapClient = new ImapFlow(imapConfig);
285
+ // Carries its own permanent error sink - see lib/imapproxy/upstream-client.js
286
+ let imapClient = createUpstreamClient(imapConfig);
273
287
 
274
288
  await imapClient.connect();
275
289
 
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+
3
+ const { ImapFlow } = require('imapflow');
4
+
5
+ /**
6
+ * Creates the upstream ImapFlow client of a proxied session with a permanent 'error' sink.
7
+ *
8
+ * ImapFlow reports connection failures with a bare `emit('error')`, so an instance left
9
+ * without an 'error' listener turns the next socket failure into an uncaughtException that
10
+ * takes the whole IMAP proxy worker down with it. Two windows are only covered by a sink
11
+ * attached here:
12
+ *
13
+ * - `connect()` resolving and `unbind()` detaching ImapFlow's socket handlers are separated
14
+ * by an await, and a reset landing in between has nowhere else to go. (While `connect()`
15
+ * is still pending ImapFlow rejects the promise instead of emitting, so that part is safe
16
+ * on its own.)
17
+ * - after the handoff the caller wires teardown onto the sockets rather than the client, and
18
+ * `close()` on an already-dead connection can still surface an error on the instance.
19
+ *
20
+ * The sink therefore has to live for as long as the client does - it is attached before
21
+ * `connect()` and never removed.
22
+ *
23
+ * @param {Object} imapConfig - ImapFlow options for the upstream connection
24
+ * @returns {ImapFlow} Client with an error sink attached
25
+ */
26
+ function createUpstreamClient(imapConfig) {
27
+ let imapClient = new ImapFlow(imapConfig);
28
+
29
+ // reads the id off the client so the sink does not keep the config (credentials
30
+ // included) alive through the closure for as long as the connection lives
31
+ imapClient.on('error', err => {
32
+ imapClient.log.warn({ msg: 'Upstream IMAP connection error', cid: imapClient.id, err });
33
+ });
34
+
35
+ return imapClient;
36
+ }
37
+
38
+ module.exports = { createUpstreamClient };
@@ -16,7 +16,7 @@
16
16
  // The caller is expected to also time-box this with withTimeout().
17
17
 
18
18
  const crypto = require('crypto');
19
- const msgpack = require('msgpack5')();
19
+ const msgpack = require('./msgpack');
20
20
 
21
21
  const settings = require('./settings');
22
22
  const { getCounterValues, hasEnvValue, readEnvValue, getBoolean } = require('./tools');
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { redis } = require('./db');
4
- const msgpack = require('msgpack5')();
4
+ const msgpack = require('./msgpack');
5
5
  const logger = require('./logger');
6
6
  const { REDIS_PREFIX } = require('./consts');
7
7
  const settings = require('./settings');
package/lib/msgpack.js ADDED
@@ -0,0 +1,62 @@
1
+ 'use strict';
2
+
3
+ // Wrapper around @msgpack/msgpack that keeps the call-site contract of the deprecated
4
+ // msgpack5 package this codebase used before:
5
+ // - encode() returns a Buffer (call sites chain .toString('base64url'), Buffer.concat and
6
+ // hsetBuffer on it) and omits undefined object properties instead of encoding nil
7
+ // - decode() reads the first value and ignores trailing bytes - graceful-degradation guards
8
+ // for corrupt stored blobs rely on a parseable prefix decoding instead of throwing
9
+ // - decode() returns Buffers for bin values where @msgpack/msgpack yields Uint8Array -
10
+ // call sites use .toString('hex')/.toString('base64') which are Buffer-only
11
+ // The wire format is plain spec msgpack in both directions, so blobs persisted by earlier
12
+ // msgpack5-based releases stay readable and vice versa.
13
+
14
+ const { Encoder, Decoder } = require('@msgpack/msgpack');
15
+
16
+ // shared instances so the per-call codec setup (internal 2KB encode buffer, decoder stack pool)
17
+ // amortizes across calls - decode runs on every API token check and mailbox listing entry.
18
+ // The library guards re-entrancy itself by cloning when an instance is already in use.
19
+ const encoder = new Encoder({ ignoreUndefined: true });
20
+ const decoder = new Decoder();
21
+
22
+ function bufferize(value) {
23
+ if (value instanceof Uint8Array) {
24
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
25
+ }
26
+
27
+ if (Array.isArray(value)) {
28
+ for (let i = 0; i < value.length; i++) {
29
+ value[i] = bufferize(value[i]);
30
+ }
31
+ return value;
32
+ }
33
+
34
+ if (value && typeof value === 'object' && !(value instanceof Date)) {
35
+ for (let key of Object.keys(value)) {
36
+ value[key] = bufferize(value[key]);
37
+ }
38
+ return value;
39
+ }
40
+
41
+ return value;
42
+ }
43
+
44
+ function encode(value) {
45
+ // copy into a standalone Buffer - encodeSharedRef() returns a view over the reused internal buffer
46
+ return Buffer.from(encoder.encodeSharedRef(value));
47
+ }
48
+
49
+ function decode(buf) {
50
+ for (let value of decoder.decodeMulti(buf)) {
51
+ return bufferize(value);
52
+ }
53
+ // empty input yields no values instead of throwing
54
+ throw new Error('Unable to decode msgpack value');
55
+ }
56
+
57
+ // Decodes a byte stream of concatenated msgpack values (append-list hash fields)
58
+ function decodeMulti(buf) {
59
+ return Array.from(decoder.decodeMulti(buf), bufferize);
60
+ }
61
+
62
+ module.exports = { encode, decode, decodeMulti };
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+
3
+ // Maximum size of the encoded payload segment we are willing to decode. Real id_tokens are a few
4
+ // hundred bytes of claims; anything larger is malformed or hostile, and the segment reaches us from a
5
+ // provider response we do not otherwise bound.
6
+ const MAX_PAYLOAD_LENGTH = 16 * 1024;
7
+
8
+ // Decode the claims of a JWT WITHOUT verifying its signature, returning null for anything that does not
9
+ // parse. Never throws - callers treat a null payload as "no claims available" and fall back.
10
+ //
11
+ // Not verifying is deliberate and only safe at the sites that use it: every caller obtained the token
12
+ // from the provider's token endpoint over a direct TLS back-channel POST (lib/oauth/*.js getToken), so
13
+ // authenticity comes from the transport, not from the token. The claims are trustworthy for that reason
14
+ // alone. Do NOT reuse this for a token that arrived through the browser or any other front channel -
15
+ // there the signature is the only thing standing between you and attacker-authored claims.
16
+ function decodeJwtPayload(token) {
17
+ if (!token || typeof token !== 'string') {
18
+ return null;
19
+ }
20
+
21
+ const [, encodedPayload] = token.split('.');
22
+ if (!encodedPayload || encodedPayload.length > MAX_PAYLOAD_LENGTH) {
23
+ return null;
24
+ }
25
+
26
+ try {
27
+ const payload = JSON.parse(Buffer.from(encodedPayload, 'base64url').toString());
28
+ // A JWT payload is a JSON object. Anything else (a bare string, a number, null, an array) is not
29
+ // a claims set, and returning it would hand callers a value that fails on property access.
30
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
31
+ return null;
32
+ }
33
+ return payload;
34
+ } catch (err) {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ module.exports = { decodeJwtPayload, MAX_PAYLOAD_LENGTH };
@@ -0,0 +1,61 @@
1
+ 'use strict';
2
+
3
+ const { isEmail } = require('../utils/is-email');
4
+
5
+ // Resolves the Microsoft account identity from the sources the OAuth2 callback can have. Split out of
6
+ // workers/api.js because this is a TRUST BOUNDARY, and a trust boundary that exists only as an ordering
7
+ // of assignments inside a 300-line switch is one nobody can test or review.
8
+ //
9
+ // The sources are not equal:
10
+ //
11
+ // clientInfo - Microsoft's `client_info` blob. EmailEngine asks for it (lib/oauth/outlook.js sets
12
+ // client_info=1) and it comes back as a query parameter on the FRONT channel, i.e.
13
+ // through the user's browser. It is not signed and nothing verifies it, so whoever
14
+ // drives the callback URL chooses its contents.
15
+ // idTokenPayload - claims from the id_token returned by the token endpoint. Unverified as a token, but
16
+ // fetched over a direct TLS POST (see lib/oauth/decode-jwt-payload.js).
17
+ // profile - the MS Graph /v1.0/me response, also a back-channel request.
18
+ //
19
+ // Callers pass only the sources their branch actually has: the legacy IMAP-scope branch has clientInfo
20
+ // and the id_token, the Graph branch has the profile.
21
+ //
22
+ // `verifiedIdentities` therefore NEVER contains a clientInfo value. It is the only field callers may use
23
+ // to decide whether an authenticated identity satisfies an expected identity. Both the mailbox address
24
+ // and the user principal name are offered, because either can be the stable identity for a tenant and
25
+ // they routinely differ (user@contoso.com vs user@contoso.onmicrosoft.com).
26
+ //
27
+ // `email` prefers a verified value and falls back to clientInfo only when no back-channel source produced
28
+ // one. That fallback exists for OAuth2 apps predating the User.Read scope; it is rarely reached now, since
29
+ // the id_token carries preferred_username whenever `openid profile` is granted. The precedence matters
30
+ // beyond the identity check: accountData.email is persisted, shown in the admin UI, and used as the
31
+ // default From address, so a spoofable value winning there is a bug in its own right.
32
+ //
33
+ // `username` is the credential EmailEngine authenticates with (XOAUTH2), so it is verified-only with no
34
+ // clientInfo fallback. The profile's userPrincipalName is taken as-is rather than filtered as an address,
35
+ // matching the previous behavior - a tenant whose UPN is not email-shaped must still be able to log in.
36
+ function resolveOutlookUserInfo(sources) {
37
+ const { clientInfo, idTokenPayload, profile } = sources || {};
38
+
39
+ // isEmail already rejects non-strings, so these only normalize a miss to null.
40
+ const asEmail = value => isEmail(value) || null;
41
+ const asString = value => (typeof value === 'string' && value ? value : null);
42
+
43
+ const profileUpn = asString(profile && profile.userPrincipalName);
44
+ const idTokenUpn = asEmail(idTokenPayload && idTokenPayload.preferred_username);
45
+
46
+ // One list in preference order does both jobs: membership answers "did the provider return this
47
+ // address", and the first entry is the best address to show. Keeping two orderings in sync by hand
48
+ // would be a silent bug the moment they drifted.
49
+ const verifiedIdentities = [
50
+ ...new Set([asEmail(profile && profile.mail), asEmail(idTokenPayload && idTokenPayload.email), idTokenUpn, asEmail(profileUpn)].filter(Boolean))
51
+ ];
52
+
53
+ return {
54
+ name: asString(idTokenPayload && idTokenPayload.name) || asString(profile && profile.displayName) || asString(clientInfo && clientInfo.name),
55
+ email: verifiedIdentities[0] || asEmail(clientInfo && clientInfo.preferred_username),
56
+ username: idTokenUpn || profileUpn,
57
+ verifiedIdentities
58
+ };
59
+ }
60
+
61
+ module.exports = { resolveOutlookUserInfo };
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+
3
+ // Builds the pending-setup record for a retry after an OAuth2 attempt the user can correct themselves -
4
+ // a consent screen with permissions unchecked, or signing in as an account the setup link is not pinned
5
+ // to. The retry is a fresh single-use setup, so it needs a record of its own.
6
+ //
7
+ // The subtlety is which parts of the rejected attempt to carry over. By the time either failure is
8
+ // detected, the provider branches have already rewritten accountData from whoever actually signed in:
9
+ // `email` holds the authenticated address, `name` may hold their display name, and `oauth2` holds their
10
+ // tokens. Copying that wholesale would let a rejected identity leak into the account the retry creates,
11
+ // while rebuilding from scratch would drop what the caller actually asked for.
12
+ //
13
+ // So the tokens go, and the caller's own intent comes back:
14
+ //
15
+ // oauth2.auth.delegatedUser - names the MAILBOX TO BIND, not a credential. Dropping it silently turns a
16
+ // shared-mailbox setup into a personal one, so the retry would bind the
17
+ // principal's own mailbox while reporting success.
18
+ // email - for a delegated setup this is the shared mailbox, and both delegation
19
+ // paths in the Outlook branch key on it. Overwriting it with the address
20
+ // the user is being steered towards breaks them.
21
+ // name - filled in from the signed-in profile when the caller supplied none, and
22
+ // kept by `name || profile.name` on the retry, so the rejected user's
23
+ // display name would stick to the account and become its From name.
24
+ //
25
+ // `_meta` rides along unchanged: it carries the redirect URL, the expected identity and the single-use
26
+ // form nonce, which is claimed only on success and so is still unspent here.
27
+ function buildRetrySetup(accountData, requestedSetup, provider, accountMeta) {
28
+ const { email, name, delegatedUser } = requestedSetup || {};
29
+
30
+ return Object.assign({}, accountData, {
31
+ oauth2: delegatedUser ? { provider, auth: { delegatedUser } } : { provider },
32
+ email,
33
+ name,
34
+ _meta: accountMeta
35
+ });
36
+ }
37
+
38
+ module.exports = { buildRetrySetup };
@@ -1,9 +1,15 @@
1
1
  'use strict';
2
2
 
3
3
  const { redis } = require('./db');
4
- const msgpack = require('msgpack5')();
4
+ const msgpack = require('./msgpack');
5
5
  const logger = require('./logger');
6
- const { REDIS_PREFIX, TRANSIENT_NETWORK_CODES, GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL, GMAIL_PUBSUB_ACK_DEADLINE_SECONDS } = require('./consts');
6
+ const {
7
+ REDIS_PREFIX,
8
+ TRANSIENT_NETWORK_CODES,
9
+ GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL,
10
+ GMAIL_PUBSUB_ACK_DEADLINE_SECONDS,
11
+ ENCRYPTED_APP_KEYS
12
+ } = require('./consts');
7
13
  const { encrypt, decrypt } = require('./encrypt');
8
14
  const Boom = require('@hapi/boom');
9
15
  const settings = require('./settings');
@@ -704,7 +710,7 @@ class OAuth2AppsHandler {
704
710
  const id = await this.generateId();
705
711
 
706
712
  let encryptedValues = {};
707
- for (let key of ['clientSecret', 'serviceKey', 'accessToken', 'externalAccount']) {
713
+ for (let key of ENCRYPTED_APP_KEYS) {
708
714
  if (data[key]) {
709
715
  encryptedValues[key] = await this.encrypt(data[key]);
710
716
  }
@@ -785,7 +791,7 @@ class OAuth2AppsHandler {
785
791
  let oldPubSubApp = existingData.pubSubApp || null;
786
792
 
787
793
  let encryptedValues = {};
788
- for (let key of ['clientSecret', 'serviceKey', 'accessToken', 'externalAccount']) {
794
+ for (let key of ENCRYPTED_APP_KEYS) {
789
795
  if (data[key]) {
790
796
  encryptedValues[key] = await this.encrypt(data[key]);
791
797
  }