emailengine-app 2.82.2 → 2.83.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 (55) hide show
  1. package/.ncurc.js +8 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +18 -0
  4. package/data/google-crawlers.json +1 -1
  5. package/lib/account.js +16 -3
  6. package/lib/api-routes/account-routes.js +8 -6
  7. package/lib/api-routes/blocklist-routes.js +4 -4
  8. package/lib/api-routes/oauth2-app-routes.js +5 -2
  9. package/lib/api-routes/route-helpers.js +28 -0
  10. package/lib/api-routes/submit-routes.js +6 -5
  11. package/lib/bounce-detect.js +4 -2
  12. package/lib/egress-filter.js +8 -3
  13. package/lib/email-client/gmail-client.js +3 -1
  14. package/lib/email-client/imap-client.js +2 -1
  15. package/lib/email-client/outlook-client.js +11 -2
  16. package/lib/enum-descriptions.js +3 -1
  17. package/lib/imapproxy/imap-core/README.md +1 -0
  18. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +11 -1
  19. package/lib/imapproxy/proxy-handoff.js +6 -3
  20. package/lib/imapproxy/response-error.js +14 -1
  21. package/lib/oauth/gcp-metadata.js +222 -0
  22. package/lib/oauth/gmail.js +115 -20
  23. package/lib/oauth/mail-ru.js +10 -4
  24. package/lib/oauth/outlook.js +11 -4
  25. package/lib/oauth/token-fetch.js +4 -2
  26. package/lib/oauth/verify-app.js +120 -32
  27. package/lib/oauth2-apps.js +46 -12
  28. package/lib/schemas.js +60 -18
  29. package/lib/tools.js +52 -2
  30. package/lib/ui-routes/admin-entities-routes.js +2 -2
  31. package/lib/ui-routes/auth-routes.js +4 -1
  32. package/lib/ui-routes/gmail-service-auth.js +64 -0
  33. package/lib/ui-routes/oauth-config-routes.js +8 -16
  34. package/lib/ui-routes/suppression-list-routes.js +2 -2
  35. package/lib/utils/network.js +29 -0
  36. package/lib/webhook-request.js +12 -4
  37. package/lib/webhook-routing.js +34 -11
  38. package/package.json +11 -11
  39. package/sbom.json +1 -1
  40. package/server.js +8 -2
  41. package/static/css/flyonui.css +1 -1
  42. package/static/js/app.js +2 -1
  43. package/static/js/ui.js +6 -1
  44. package/static/licenses.html +18 -28
  45. package/translations/messages.pot +73 -73
  46. package/views/accounts/edit.hbs +1 -1
  47. package/views/config/imap-proxy.hbs +1 -1
  48. package/views/config/network.hbs +7 -5
  49. package/views/config/oauth/app.hbs +2 -0
  50. package/views/config/smtp.hbs +1 -1
  51. package/views/config/tls.hbs +2 -2
  52. package/views/config/webhooks.hbs +1 -1
  53. package/views/partials/oauth_form.hbs +116 -27
  54. package/workers/api.js +4 -2
  55. package/workers/webhooks.js +18 -7
@@ -0,0 +1,222 @@
1
+ 'use strict';
2
+
3
+ // The Google Cloud metadata server: the credentials of the service account attached to the
4
+ // Compute Engine VM, GKE pod (Workload Identity) or Cloud Run service EmailEngine runs on. Used by
5
+ // the `metadataServer` authentication method of a Cloud Pub/Sub app, which stores no secret at all.
6
+ //
7
+ // The host is fixed in code and can only be moved from the environment. It is deliberately not an
8
+ // application or settings field: these requests bypass the HTTP proxy and the webhook egress policy
9
+ // (the metadata server is reachable only from this host, and 169.254.169.254 is exactly what the
10
+ // default egress policy blocks), and the verify report echoes what came back. A host that an API
11
+ // token with `oauth2` or `settings` write could choose would turn that into a probe of the
12
+ // instance's own network. The environment belongs to whoever deployed the instance, who already
13
+ // holds the encryption secret and the Redis URL. Only the host moves: the paths, the
14
+ // `Metadata-Flavor` header and the http scheme are fixed, so this never becomes a general fetcher.
15
+ //
16
+ // No dependency on lib/tools.js on purpose: that module opens Redis on require, and this one has
17
+ // to stay testable as a pure helper.
18
+
19
+ const timers = require('timers/promises');
20
+ const { fetch: undiciFetch, Agent } = require('undici');
21
+ const packageData = require('../../package.json');
22
+ const { makeError } = require('./external-account-config');
23
+
24
+ // Google recommends the DNS name over 169.254.169.254, and it fails safer: it resolves only on
25
+ // Google Cloud, so on any other host the request ends at once with ENOTFOUND, instead of waiting
26
+ // out a connect timeout or reaching another cloud's instance metadata service at the same address
27
+ const DEFAULT_METADATA_HOST = 'metadata.google.internal';
28
+
29
+ // EmailEngine's own name first; GCE_METADATA_HOST is what every Google client library reads, so an
30
+ // existing emulator or metadata proxy setup keeps working without a second variable
31
+ const METADATA_HOST_ENV_KEYS = ['EENGINE_GCP_METADATA_HOST', 'GCE_METADATA_HOST'];
32
+
33
+ const TOKEN_PATH = '/computeMetadata/v1/instance/service-accounts/default/token';
34
+ const EMAIL_PATH = '/computeMetadata/v1/instance/service-accounts/default/email';
35
+ const PROJECT_ID_PATH = '/computeMetadata/v1/project/project-id';
36
+
37
+ // Required on every request, and sent back by the metadata server on its answers. Checking the
38
+ // answer is what tells the Google metadata server from something else listening at the address
39
+ const FLAVOR_HEADER = 'Metadata-Flavor';
40
+ const FLAVOR_VALUE = 'Google';
41
+
42
+ const REQUEST_TIMEOUT = 10 * 1000;
43
+
44
+ // Google documents sub-second 503 answers during host maintenance, so one quick retry covers them
45
+ const MAINTENANCE_RETRY_DELAY = 500;
46
+
47
+ // Upper bound on response text kept on an error, which the verify report can surface
48
+ const MAX_RESPONSE_TEXT = 512;
49
+
50
+ const USER_AGENT = `${packageData.name}/${packageData.version} (+${packageData.homepage})`;
51
+
52
+ // Never the shared proxy dispatcher: a proxy cannot reach the metadata server, and the request
53
+ // would hand it the access token that comes back
54
+ const metadataAgent = new Agent({
55
+ connectTimeout: 3 * 1000,
56
+ headersTimeout: REQUEST_TIMEOUT,
57
+ bodyTimeout: REQUEST_TIMEOUT
58
+ });
59
+
60
+ /**
61
+ * Resolves the origin the metadata server is reached at.
62
+ *
63
+ * An override takes `host`, `host:port` or `http://host[:port]`. Anything else (https, a path, a
64
+ * query, credentials) is refused rather than replaced by the default: an override that is quietly
65
+ * ignored sends a test setup to the real metadata server, which is the worse way to fail.
66
+ *
67
+ * @param {Object} [env=process.env] - environment to read
68
+ * @returns {string} the origin, e.g. `http://metadata.google.internal`
69
+ */
70
+ function resolveMetadataOrigin(env) {
71
+ env = env || process.env;
72
+
73
+ for (let key of METADATA_HOST_ENV_KEYS) {
74
+ let raw = (env[key] || '').toString().trim();
75
+ if (!raw) {
76
+ continue;
77
+ }
78
+
79
+ let candidate = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `http://${raw}`;
80
+ let url;
81
+ try {
82
+ url = new URL(candidate);
83
+ } catch (err) {
84
+ url = null;
85
+ }
86
+
87
+ if (!url || url.protocol !== 'http:' || !url.hostname || url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
88
+ throw makeError(`${key} must be a host name or host:port of the metadata server, got ${JSON.stringify(raw)}`, 'EMetadataConfig');
89
+ }
90
+
91
+ return url.origin;
92
+ }
93
+
94
+ return `http://${DEFAULT_METADATA_HOST}`;
95
+ }
96
+
97
+ function describeNetworkError(err) {
98
+ let cause = (err && err.cause) || err;
99
+ if (cause && (cause.name === 'TimeoutError' || cause.name === 'AbortError')) {
100
+ return `no answer within ${Math.round(REQUEST_TIMEOUT / 1000)}s`;
101
+ }
102
+ return (cause && (cause.code || cause.message)) || 'connection failed';
103
+ }
104
+
105
+ /**
106
+ * GETs one metadata path and returns the response text.
107
+ *
108
+ * @param {string} path - one of the fixed metadata paths
109
+ * @param {Object} [opts]
110
+ * @param {Object} [opts.env] - environment to resolve the host from (tests)
111
+ * @param {Function} [opts.fetchImpl] - fetch implementation (tests)
112
+ * @returns {Promise<string>}
113
+ */
114
+ async function metadataRequest(path, opts) {
115
+ opts = opts || {};
116
+ const fetchImpl = opts.fetchImpl || undiciFetch;
117
+
118
+ let origin = resolveMetadataOrigin(opts.env);
119
+
120
+ for (let attempt = 0; ; attempt++) {
121
+ let res;
122
+ let body;
123
+ try {
124
+ res = await fetchImpl(origin + path, {
125
+ method: 'GET',
126
+ headers: { [FLAVOR_HEADER]: FLAVOR_VALUE, 'User-Agent': USER_AGENT },
127
+ redirect: 'error',
128
+ dispatcher: metadataAgent,
129
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT)
130
+ });
131
+ body = await res.text();
132
+ } catch (err) {
133
+ throw makeError(`The metadata server at ${origin} could not be reached (${describeNetworkError(err)})`, 'EMetadataUnreachable', null, {
134
+ cause: err
135
+ });
136
+ }
137
+
138
+ if (res.status === 503 && attempt === 0) {
139
+ await timers.setTimeout(MAINTENANCE_RETRY_DELAY);
140
+ continue;
141
+ }
142
+
143
+ if (!res.ok) {
144
+ throw makeError(`The metadata server at ${origin} returned HTTP ${res.status} for ${path}`, 'EMetadataServer', res.status, {
145
+ responseText: body.slice(0, MAX_RESPONSE_TEXT)
146
+ });
147
+ }
148
+
149
+ if (res.headers.get(FLAVOR_HEADER) !== FLAVOR_VALUE) {
150
+ throw makeError(
151
+ `The server at ${origin} is not a Google Cloud metadata server (no "${FLAVOR_HEADER}: ${FLAVOR_VALUE}" header)`,
152
+ 'EMetadataServer',
153
+ null,
154
+ {
155
+ wrongFlavor: true
156
+ }
157
+ );
158
+ }
159
+
160
+ return body;
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Fetches an access token for the attached service account.
166
+ *
167
+ * The metadata server caches the token itself and hands out the same one until five minutes before
168
+ * it expires, so asking again is cheap; the caller still caches it like any other service token.
169
+ *
170
+ * @param {Object} [opts] - see metadataRequest()
171
+ * @returns {Promise<{ access_token: string, expires_in: number, token_type: string }>}
172
+ */
173
+ async function fetchAccessToken(opts) {
174
+ let body = await metadataRequest(TOKEN_PATH, opts);
175
+
176
+ let data;
177
+ try {
178
+ data = JSON.parse(body);
179
+ } catch (err) {
180
+ data = null;
181
+ }
182
+
183
+ if (!data || typeof data.access_token !== 'string' || !data.access_token) {
184
+ throw makeError('The metadata server answered without an access token', 'EMetadataResponse');
185
+ }
186
+
187
+ let expiresIn = Number(data.expires_in);
188
+
189
+ return {
190
+ access_token: data.access_token,
191
+ expires_in: Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : undefined,
192
+ token_type: data.token_type || 'Bearer'
193
+ };
194
+ }
195
+
196
+ /**
197
+ * Reads the attached service account's email address.
198
+ *
199
+ * @param {Object} [opts] - see metadataRequest()
200
+ * @returns {Promise<string>}
201
+ */
202
+ async function fetchServiceAccountEmail(opts) {
203
+ return (await metadataRequest(EMAIL_PATH, opts)).trim();
204
+ }
205
+
206
+ /**
207
+ * Reads the attached service account's email address and the project id.
208
+ *
209
+ * @param {Object} [opts] - see metadataRequest()
210
+ * @returns {Promise<{ serviceAccountEmail: string, projectId: string }>}
211
+ */
212
+ async function describeAttachedIdentity(opts) {
213
+ let [serviceAccountEmail, projectId] = await Promise.all([fetchServiceAccountEmail(opts), metadataRequest(PROJECT_ID_PATH, opts)]);
214
+ return { serviceAccountEmail, projectId: projectId.trim() };
215
+ }
216
+
217
+ module.exports = {
218
+ resolveMetadataOrigin,
219
+ fetchAccessToken,
220
+ fetchServiceAccountEmail,
221
+ describeAttachedIdentity
222
+ };
@@ -8,8 +8,23 @@ const { fetch: fetchCmd } = require('undici');
8
8
 
9
9
  const { ExternalAccountSigner } = require('./external-account-signer');
10
10
  const { fetchTokenRequest } = require('./token-fetch');
11
+ const gcpMetadata = require('./gcp-metadata');
12
+
13
+ // The stored credential each service account authentication method presents. The attached service
14
+ // account (metadataServer) stores none: the metadata server holds it
15
+ const SERVICE_AUTH_CREDENTIALS = {
16
+ serviceKey: 'serviceKey',
17
+ externalAccount: 'externalAccount',
18
+ metadataServer: null
19
+ };
20
+
21
+ const SERVICE_AUTH_METHODS = new Set(Object.keys(SERVICE_AUTH_CREDENTIALS));
11
22
 
12
- const SERVICE_AUTH_METHODS = new Set(['serviceKey', 'externalAccount']);
23
+ // The stored authentication method of a gmailService app. Apps saved before the method was
24
+ // recorded carry none, and those were all key-signed
25
+ function normalizeAuthMethod(authMethod) {
26
+ return SERVICE_AUTH_METHODS.has(authMethod) ? authMethod : 'serviceKey';
27
+ }
13
28
 
14
29
  class LocalKeySigner {
15
30
  constructor(opts) {
@@ -234,14 +249,20 @@ function workspaceDomainOf(idTokenPayload) {
234
249
 
235
250
  class GmailOauth {
236
251
  constructor(opts) {
252
+ // The network route of the account this client acts for (see getAccountHttpRoute()). Every
253
+ // token and API request it makes takes that route; null for an app-level client.
254
+ this.route = opts.route || null;
255
+
237
256
  const defaultBaseScopes = (opts.baseScopes && GMAIL_SCOPES[opts.baseScopes]) || GMAIL_SCOPES.imap;
238
257
 
239
258
  let requestedScopes = [].concat(opts.scopes || defaultBaseScopes);
240
259
 
241
260
  // Only include OpenID Connect scopes for regular OAuth (not service accounts)
242
261
  // Service accounts use JWT-based authentication and don't need OpenID scopes
243
- // These are non-privileged scopes that provide email and profile info for 3-legged OAuth
244
- if (!opts.serviceClient) {
262
+ // These are non-privileged scopes that provide email and profile info for 3-legged OAuth.
263
+ // An app using the attached service account names no service client, the metadata server
264
+ // knows which account it is, but it is a service app all the same
265
+ if (!opts.serviceClient && opts.authMethod !== 'metadataServer') {
245
266
  const openidScopes = OPENID_SCOPES;
246
267
 
247
268
  // Add OpenID scopes if not already present
@@ -285,9 +306,12 @@ class GmailOauth {
285
306
  }
286
307
  this.authMethod = authMethod;
287
308
 
288
- // Only build a signer when this is a service-account-mode app.
289
- // 3-legged OAuth has no serviceClient and never reaches generateServiceRequest.
290
- if (this.serviceClient) {
309
+ // Only build a signer when this is a service-account-mode app that signs an assertion.
310
+ // 3-legged OAuth has no serviceClient and never reaches generateServiceRequest, and the
311
+ // metadata server hands out the access token itself, so there is nothing to sign
312
+ this.metadataClient = opts.metadataClient || gcpMetadata;
313
+
314
+ if (this.serviceClient && this.authMethod !== 'metadataServer') {
291
315
  if (this.authMethod === 'externalAccount') {
292
316
  // The signer caches the federated token and deduplicates concurrent refreshes, which
293
317
  // only pays off when it outlives this client: every token renewal builds a new
@@ -399,12 +423,17 @@ class GmailOauth {
399
423
  body: tokenRequest.body
400
424
  };
401
425
 
402
- let res = await fetchTokenRequest(requestUrl, fetchOpts, {
403
- grant: 'authorization_code',
404
- provider: this.provider,
405
- clientId: this.clientId,
406
- serviceClient: this.serviceClient
407
- });
426
+ let res = await fetchTokenRequest(
427
+ requestUrl,
428
+ fetchOpts,
429
+ {
430
+ grant: 'authorization_code',
431
+ provider: this.provider,
432
+ clientId: this.clientId,
433
+ serviceClient: this.serviceClient
434
+ },
435
+ this.route
436
+ );
408
437
 
409
438
  let responseJson;
410
439
  try {
@@ -477,6 +506,10 @@ class GmailOauth {
477
506
  async refreshToken(opts) {
478
507
  opts = opts || {};
479
508
 
509
+ if (this.authMethod === 'metadataServer') {
510
+ return await this.refreshFromMetadataServer(opts);
511
+ }
512
+
480
513
  const url = new URL(this.tokenUrl);
481
514
 
482
515
  if (this.serviceClient) {
@@ -514,12 +547,17 @@ class GmailOauth {
514
547
  body: bodyString
515
548
  };
516
549
 
517
- let res = await fetchTokenRequest(requestUrl, fetchOpts, {
518
- grant: 'refresh_token',
519
- provider: this.provider,
520
- clientId: this.clientId,
521
- serviceClient: this.serviceClient
522
- });
550
+ let res = await fetchTokenRequest(
551
+ requestUrl,
552
+ fetchOpts,
553
+ {
554
+ grant: 'refresh_token',
555
+ provider: this.provider,
556
+ clientId: this.clientId,
557
+ serviceClient: this.serviceClient
558
+ },
559
+ this.route
560
+ );
523
561
 
524
562
  let responseJson;
525
563
  try {
@@ -594,6 +632,61 @@ class GmailOauth {
594
632
  return responseJson;
595
633
  }
596
634
 
635
+ // The attached service account's token comes straight from the metadata server. That token is
636
+ // the service account's own, and nothing can turn it into a Workspace user's: domain-wide
637
+ // delegation needs an assertion signed as the service account, which this method has no way to
638
+ // produce. The schema keeps the method to Pub/Sub apps; this refuses a delegated request anyway
639
+ async refreshFromMetadataServer(opts) {
640
+ if (!opts.isPrincipal) {
641
+ let err = new Error('An app using the attached service account can only request a token for the service account itself');
642
+ err.code = 'EDelegationUnsupported';
643
+ throw err;
644
+ }
645
+
646
+ let response;
647
+ try {
648
+ response = await this.metadataClient.fetchAccessToken();
649
+ } catch (err) {
650
+ // Same level as the token endpoint requests; the caller logs the error itself
651
+ if (this.logger) {
652
+ this.logger.info({
653
+ msg: 'OAuth2 authentication request',
654
+ action: 'oauth2Fetch',
655
+ fn: 'refreshFromMetadataServer',
656
+ provider: this.provider,
657
+ success: false,
658
+ status: err.statusCode,
659
+ code: err.code,
660
+ error: err.message
661
+ });
662
+ }
663
+
664
+ let flag = {
665
+ message: `Failed to get an access token for the attached service account: ${err.message}`,
666
+ code: 'METADATA_SERVER'
667
+ };
668
+ await this.setFlag(flag);
669
+ err.tokenRequest = { provider: this.provider, signer: this.authMethod, status: err.statusCode, flag };
670
+ throw err;
671
+ }
672
+
673
+ if (this.logger) {
674
+ this.logger.info({
675
+ msg: 'OAuth2 authentication request',
676
+ action: 'oauth2Fetch',
677
+ fn: 'refreshFromMetadataServer',
678
+ provider: this.provider,
679
+ success: true,
680
+ response: formatFetchResponse(response, this.logRaw)
681
+ });
682
+ }
683
+
684
+ // clear potential auth flag
685
+ await this.setFlag();
686
+
687
+ return response;
688
+ }
689
+
597
690
  async request(accessToken, url, method, payload, options) {
598
691
  options = options || {};
599
692
 
@@ -608,7 +701,7 @@ class GmailOauth {
608
701
  // what Gmail answered, and that is decided by the request layer above this one
609
702
  // (lib/email-client/api-retry.js); a transport that retried on its own replayed sends
610
703
  // after a socket drop and multiplied throttled calls
611
- dispatcher: httpAgent.fetch,
704
+ dispatcher: httpAgent.forRoute(this.route).fetch,
612
705
  signal: options.signal || undefined
613
706
  };
614
707
 
@@ -812,7 +905,7 @@ class GmailOauth {
812
905
  };
813
906
 
814
907
  try {
815
- let res = await fetchCmd(this.revokeUrl, Object.assign(fetchOpts, { dispatcher: httpAgent.retry }));
908
+ let res = await fetchCmd(this.revokeUrl, Object.assign(fetchOpts, { dispatcher: httpAgent.forRoute(this.route).retry }));
816
909
 
817
910
  let responseText;
818
911
  try {
@@ -862,3 +955,5 @@ module.exports.OPENID_SCOPES = OPENID_SCOPES;
862
955
  module.exports.LocalKeySigner = LocalKeySigner;
863
956
  module.exports.parseExternalAccountConfig = parseExternalAccountConfig;
864
957
  module.exports.SERVICE_AUTH_METHODS = SERVICE_AUTH_METHODS;
958
+ module.exports.SERVICE_AUTH_CREDENTIALS = SERVICE_AUTH_CREDENTIALS;
959
+ module.exports.normalizeAuthMethod = normalizeAuthMethod;
@@ -52,6 +52,10 @@ const formatFetchResponse = (responseObj, logRaw) => {
52
52
 
53
53
  class MailRuOauth {
54
54
  constructor(opts) {
55
+ // The network route of the account this client acts for (see getAccountHttpRoute()). Every
56
+ // token and API request it makes takes that route; null for an app-level client.
57
+ this.route = opts.route || null;
58
+
55
59
  this.scopes = [].concat(opts.scopes || MAIL_RU_SCOPES);
56
60
  this.clientId = opts.clientId;
57
61
  this.clientSecret = opts.clientSecret;
@@ -121,7 +125,8 @@ class MailRuOauth {
121
125
  },
122
126
  body: tokenRequest.body
123
127
  },
124
- { grant: 'authorization_code', provider: this.provider, clientId: this.clientId }
128
+ { grant: 'authorization_code', provider: this.provider, clientId: this.clientId },
129
+ this.route
125
130
  );
126
131
 
127
132
  let responseJson;
@@ -208,7 +213,8 @@ class MailRuOauth {
208
213
  },
209
214
  body: bodyString
210
215
  },
211
- { grant: 'refresh_token', provider: this.provider, clientId: this.clientId }
216
+ { grant: 'refresh_token', provider: this.provider, clientId: this.clientId },
217
+ this.route
212
218
  );
213
219
 
214
220
  let responseJson;
@@ -276,7 +282,7 @@ class MailRuOauth {
276
282
  headers: {
277
283
  'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
278
284
  },
279
- dispatcher: httpAgent.retry
285
+ dispatcher: httpAgent.forRoute(this.route).retry
280
286
  };
281
287
 
282
288
  if (payload) {
@@ -290,7 +296,7 @@ class MailRuOauth {
290
296
  reqData.body = payload;
291
297
  if (payload.length > 0) {
292
298
  // Non-empty buffers use non-retry dispatcher to prevent ArrayBuffer detachment
293
- reqData.dispatcher = httpAgent.fetch;
299
+ reqData.dispatcher = httpAgent.forRoute(this.route).fetch;
294
300
  }
295
301
  }
296
302
  }
@@ -161,6 +161,10 @@ const formatFetchResponse = (responseObj, logRaw) => {
161
161
 
162
162
  class OutlookOauth {
163
163
  constructor(opts) {
164
+ // The network route of the account this client acts for (see getAccountHttpRoute()). Every
165
+ // token and API request it makes takes that route; null for an app-level client.
166
+ this.route = opts.route || null;
167
+
164
168
  this.cloud = opts.cloud || 'global';
165
169
 
166
170
  const defaultBaseScopes = (opts.baseScopes && outlookScopes(this.cloud)[opts.baseScopes]) || outlookScopes(this.cloud).imap;
@@ -280,7 +284,8 @@ class OutlookOauth {
280
284
  },
281
285
  body: tokenRequest.body
282
286
  },
283
- { grant: 'authorization_code', provider: this.provider, clientId: this.clientId, authority: this.authority }
287
+ { grant: 'authorization_code', provider: this.provider, clientId: this.clientId, authority: this.authority },
288
+ this.route
284
289
  );
285
290
 
286
291
  let responseJson;
@@ -384,7 +389,8 @@ class OutlookOauth {
384
389
  },
385
390
  body: bodyString
386
391
  },
387
- { grant: 'refresh_token', provider: this.provider, clientId: this.clientId, authority: this.authority }
392
+ { grant: 'refresh_token', provider: this.provider, clientId: this.clientId, authority: this.authority },
393
+ this.route
388
394
  );
389
395
 
390
396
  let responseJson;
@@ -478,7 +484,8 @@ class OutlookOauth {
478
484
  },
479
485
  body: bodyString
480
486
  },
481
- { grant: 'client_credentials', provider: this.provider, clientId: this.clientId, authority: this.authority }
487
+ { grant: 'client_credentials', provider: this.provider, clientId: this.clientId, authority: this.authority },
488
+ this.route
482
489
  );
483
490
 
484
491
  let responseJson;
@@ -559,7 +566,7 @@ class OutlookOauth {
559
566
  // (lib/email-client/api-retry.js); a transport that retried on its own replayed sends
560
567
  // after a socket drop (a repeated draft /send then failed with 404, reporting a sent
561
568
  // message as failed) and multiplied throttled calls
562
- dispatcher: httpAgent.fetch
569
+ dispatcher: httpAgent.forRoute(this.route).fetch
563
570
  };
564
571
 
565
572
  if (options.headers) {
@@ -23,13 +23,15 @@ const { httpAgent } = require('../tools');
23
23
  * @param {Object} options - fetch options; the retrying dispatcher is applied here and cannot be overridden
24
24
  * @param {Object} context - what to record about the attempt, as the rejected-response path records it.
25
25
  * The method is read from `options`, so the two cannot disagree
26
+ * @param {Object} [route] - the account's network route ({ proxy, localAddress }, see getAccountHttpRoute()),
27
+ * so a token request leaves the way the account's other traffic does
26
28
  * @returns {Promise<Response>} the response, whatever its status
27
29
  */
28
- async function fetchTokenRequest(url, options, context) {
30
+ async function fetchTokenRequest(url, options, context, route) {
29
31
  try {
30
32
  // The dispatcher is applied last, so this helper really is the one place that decides it -
31
33
  // with the default first, a caller that passed one would silently lose the retrying agent
32
- return await fetchCmd(url, Object.assign({}, options, { dispatcher: httpAgent.retry }));
34
+ return await fetchCmd(url, Object.assign({}, options, { dispatcher: httpAgent.forRoute(route).retry }));
33
35
  } catch (err) {
34
36
  // The cause carries the actionable code. Promoted onto the error itself so the connectError
35
37
  // webhook has something to report - the transient check consults both, so no verdict changes.