@webex/webex-core 3.8.0-next.2 → 3.8.0-next.20

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 (48) hide show
  1. package/dist/index.js +43 -0
  2. package/dist/index.js.map +1 -1
  3. package/dist/lib/batcher.js +1 -1
  4. package/dist/lib/credentials/credentials.js +1 -1
  5. package/dist/lib/credentials/token.js +1 -1
  6. package/dist/lib/services/service-catalog.js +23 -68
  7. package/dist/lib/services/service-catalog.js.map +1 -1
  8. package/dist/lib/services/services.js +1 -1
  9. package/dist/lib/services-v2/constants.js +17 -0
  10. package/dist/lib/services-v2/constants.js.map +1 -0
  11. package/dist/lib/services-v2/index.js +58 -0
  12. package/dist/lib/services-v2/index.js.map +1 -0
  13. package/dist/lib/services-v2/interceptors/hostmap.js +64 -0
  14. package/dist/lib/services-v2/interceptors/hostmap.js.map +1 -0
  15. package/dist/lib/services-v2/interceptors/server-error.js +77 -0
  16. package/dist/lib/services-v2/interceptors/server-error.js.map +1 -0
  17. package/dist/lib/services-v2/interceptors/service.js +137 -0
  18. package/dist/lib/services-v2/interceptors/service.js.map +1 -0
  19. package/dist/lib/services-v2/metrics.js +12 -0
  20. package/dist/lib/services-v2/metrics.js.map +1 -0
  21. package/dist/lib/services-v2/service-catalog.js +433 -0
  22. package/dist/lib/services-v2/service-catalog.js.map +1 -0
  23. package/dist/lib/services-v2/service-fed-ramp.js +13 -0
  24. package/dist/lib/services-v2/service-fed-ramp.js.map +1 -0
  25. package/dist/lib/services-v2/service-url.js +119 -0
  26. package/dist/lib/services-v2/service-url.js.map +1 -0
  27. package/dist/lib/services-v2/services-v2.js +963 -0
  28. package/dist/lib/services-v2/services-v2.js.map +1 -0
  29. package/dist/plugins/logger.js +1 -1
  30. package/dist/webex-core.js +2 -2
  31. package/dist/webex-core.js.map +1 -1
  32. package/package.json +13 -13
  33. package/src/index.js +10 -0
  34. package/src/lib/services/service-catalog.js +14 -54
  35. package/src/lib/services-v2/README.md +3 -0
  36. package/src/lib/services-v2/constants.js +21 -0
  37. package/src/lib/services-v2/index.js +23 -0
  38. package/src/lib/services-v2/interceptors/hostmap.js +36 -0
  39. package/src/lib/services-v2/interceptors/server-error.js +48 -0
  40. package/src/lib/services-v2/interceptors/service.js +101 -0
  41. package/src/lib/services-v2/metrics.js +4 -0
  42. package/src/lib/services-v2/service-catalog.js +455 -0
  43. package/src/lib/services-v2/service-fed-ramp.js +5 -0
  44. package/src/lib/services-v2/service-url.js +124 -0
  45. package/src/lib/services-v2/services-v2.js +971 -0
  46. package/test/fixtures/host-catalog-v2.js +247 -0
  47. package/test/unit/spec/services/service-catalog.js +30 -90
  48. package/test/unit/spec/services-v2/services-v2.js +564 -0
@@ -0,0 +1,971 @@
1
+ import sha256 from 'crypto-js/sha256';
2
+
3
+ import {union, unionBy} from 'lodash';
4
+ import WebexPlugin from '../webex-plugin';
5
+
6
+ import METRICS from './metrics';
7
+ import ServiceCatalog from './service-catalog';
8
+ import fedRampServices from './service-fed-ramp';
9
+ import {COMMERCIAL_ALLOWED_DOMAINS} from './constants';
10
+
11
+ const trailingSlashes = /(?:^\/)|(?:\/$)/;
12
+
13
+ // The default cluster when one is not provided (usually as 'US' from hydra)
14
+ export const DEFAULT_CLUSTER = 'urn:TEAM:us-east-2_a';
15
+ // The default service name for convo (currently identityLookup due to some weird CSB issue)
16
+ export const DEFAULT_CLUSTER_SERVICE = 'identityLookup';
17
+
18
+ const CLUSTER_SERVICE = process.env.WEBEX_CONVERSATION_CLUSTER_SERVICE || DEFAULT_CLUSTER_SERVICE;
19
+ const DEFAULT_CLUSTER_IDENTIFIER =
20
+ process.env.WEBEX_CONVERSATION_DEFAULT_CLUSTER || `${DEFAULT_CLUSTER}:${CLUSTER_SERVICE}`;
21
+
22
+ /* eslint-disable no-underscore-dangle */
23
+ /**
24
+ * @class
25
+ */
26
+ const Services = WebexPlugin.extend({
27
+ namespace: 'Services',
28
+
29
+ props: {
30
+ validateDomains: ['boolean', false, true],
31
+ initFailed: ['boolean', false, false],
32
+ },
33
+
34
+ _catalogs: new WeakMap(),
35
+
36
+ _activeServices: {},
37
+
38
+ _services: [],
39
+
40
+ /**
41
+ * @private
42
+ * Get the current catalog based on the assocaited
43
+ * webex instance.
44
+ * @returns {ServiceCatalog}
45
+ */
46
+ _getCatalog() {
47
+ return this._catalogs.get(this.webex);
48
+ },
49
+
50
+ /**
51
+ * Get a service url from the current services list by name
52
+ * from the associated instance catalog.
53
+ * @param {string} name
54
+ * @param {boolean} [priorityHost]
55
+ * @param {string} [serviceGroup]
56
+ * @returns {string|undefined}
57
+ */
58
+ get(name, priorityHost, serviceGroup) {
59
+ const catalog = this._getCatalog();
60
+
61
+ return catalog.get(name, priorityHost, serviceGroup);
62
+ },
63
+
64
+ /**
65
+ * Determine if a whilelist exists in the service catalog.
66
+ *
67
+ * @returns {boolean} - True if a allowed domains list exists.
68
+ */
69
+ hasAllowedDomains() {
70
+ const catalog = this._getCatalog();
71
+
72
+ return catalog.getAllowedDomains().length > 0;
73
+ },
74
+
75
+ /**
76
+ * Generate a service catalog as an object from
77
+ * the associated instance catalog.
78
+ * @param {boolean} [priorityHost] - use highest priority host if set to `true`
79
+ * @param {string} [serviceGroup]
80
+ * @returns {Record<string, string>}
81
+ */
82
+ list(priorityHost, serviceGroup) {
83
+ const catalog = this._getCatalog();
84
+
85
+ return catalog.list(priorityHost, serviceGroup);
86
+ },
87
+
88
+ /**
89
+ * Mark a priority host service url as failed.
90
+ * This will mark the host associated with the
91
+ * `ServiceUrl` to be removed from the its
92
+ * respective host array, and then return the next
93
+ * viable host from the `ServiceUrls` host array,
94
+ * or the `ServiceUrls` default url if no other priority
95
+ * hosts are available, or if `noPriorityHosts` is set to
96
+ * `true`.
97
+ * @param {string} url
98
+ * @param {boolean} noPriorityHosts
99
+ * @returns {string}
100
+ */
101
+ markFailedUrl(url, noPriorityHosts) {
102
+ const catalog = this._getCatalog();
103
+
104
+ return catalog.markFailedUrl(url, noPriorityHosts);
105
+ },
106
+
107
+ /**
108
+ * saves all the services from the pre and post catalog service
109
+ * @param {Object} activeServices
110
+ * @returns {void}
111
+ */
112
+ _updateActiveServices(activeServices) {
113
+ this._activeServices = {...this._activeServices, ...activeServices};
114
+ },
115
+
116
+ /**
117
+ * saves the hostCatalog object
118
+ * @param {Object} services
119
+ * @returns {void}
120
+ */
121
+ _updateServices(services) {
122
+ this._services = unionBy(services, this._services, 'id');
123
+ },
124
+
125
+ /**
126
+ * Update a list of `serviceUrls` to the most current
127
+ * catalog via the defined `discoveryUrl` then returns the current
128
+ * list of services.
129
+ * @param {object} [param]
130
+ * @param {string} [param.from] - This accepts `limited` or `signin`
131
+ * @param {object} [param.query] - This accepts `email`, `orgId` or `userId` key values
132
+ * @param {string} [param.query.email] - must be a standard-format email
133
+ * @param {string} [param.query.orgId] - must be an organization id
134
+ * @param {string} [param.query.userId] - must be a user id
135
+ * @param {string} [param.token] - used for signin catalog
136
+ * @returns {Promise<object>}
137
+ */
138
+ updateServices({from, query, token, forceRefresh} = {}) {
139
+ const catalog = this._getCatalog();
140
+ let formattedQuery;
141
+ let serviceGroup;
142
+
143
+ // map catalog name to service group name.
144
+ switch (from) {
145
+ case 'limited':
146
+ serviceGroup = 'preauth';
147
+ break;
148
+ case 'signin':
149
+ serviceGroup = 'signin';
150
+ break;
151
+ default:
152
+ serviceGroup = 'postauth';
153
+ break;
154
+ }
155
+
156
+ // confirm catalog update for group is not in progress.
157
+ if (catalog.status[serviceGroup].collecting) {
158
+ return this.waitForCatalog(serviceGroup);
159
+ }
160
+
161
+ catalog.status[serviceGroup].collecting = true;
162
+
163
+ if (serviceGroup === 'preauth') {
164
+ const queryKey = query && Object.keys(query)[0];
165
+
166
+ if (!['email', 'emailhash', 'userId', 'orgId', 'mode'].includes(queryKey)) {
167
+ return Promise.reject(
168
+ new Error('a query param of email, emailhash, userId, orgId, or mode is required')
169
+ );
170
+ }
171
+ }
172
+ // encode email when query key is email
173
+ if (serviceGroup === 'preauth' || serviceGroup === 'signin') {
174
+ const queryKey = Object.keys(query)[0];
175
+
176
+ formattedQuery = {};
177
+
178
+ if (queryKey === 'email' && query.email) {
179
+ formattedQuery.emailhash = sha256(query.email.toLowerCase()).toString();
180
+ } else {
181
+ formattedQuery[queryKey] = query[queryKey];
182
+ }
183
+ }
184
+
185
+ return this._fetchNewServiceHostmap({
186
+ from,
187
+ token,
188
+ query: formattedQuery,
189
+ forceRefresh,
190
+ })
191
+ .then((serviceHostMap) => {
192
+ catalog.updateServiceUrls(serviceGroup, serviceHostMap);
193
+ this.updateCredentialsConfig();
194
+ catalog.status[serviceGroup].collecting = false;
195
+ })
196
+ .catch((error) => {
197
+ catalog.status[serviceGroup].collecting = false;
198
+
199
+ return Promise.reject(error);
200
+ });
201
+ },
202
+
203
+ /**
204
+ * User validation parameter transfer object for {@link validateUser}.
205
+ * @param {object} ValidateUserPTO
206
+ * @property {string} ValidateUserPTO.email - The email of the user.
207
+ * @property {string} [ValidateUserPTO.reqId] - The activation requester.
208
+ * @property {object} [ValidateUserPTO.activationOptions] - Extra options to pass when sending the activation
209
+ * @property {object} [ValidateUserPTO.preloginUserId] - The prelogin user id to set when sending the activation.
210
+ */
211
+
212
+ /**
213
+ * User validation return transfer object for {@link validateUser}.
214
+ * @param {object} ValidateUserRTO
215
+ * @property {boolean} ValidateUserRTO.activated - If the user is activated.
216
+ * @property {boolean} ValidateUserRTO.exists - If the user exists.
217
+ * @property {string} ValidateUserRTO.details - A descriptive status message.
218
+ * @property {object} ValidateUserRTO.user - **License** service user object.
219
+ */
220
+
221
+ /**
222
+ * Validate if a user is activated and update the service catalogs as needed
223
+ * based on the user's activation status.
224
+ *
225
+ * @param {ValidateUserPTO} - The parameter transfer object.
226
+ * @returns {ValidateUserRTO} - The return transfer object.
227
+ */
228
+ validateUser({
229
+ email,
230
+ reqId = 'WEBCLIENT',
231
+ forceRefresh = false,
232
+ activationOptions = {},
233
+ preloginUserId,
234
+ }) {
235
+ this.logger.info('services: validating a user');
236
+
237
+ // Validate that an email parameter key was provided.
238
+ if (!email) {
239
+ return Promise.reject(new Error('`email` is required'));
240
+ }
241
+
242
+ // Destructure the credentials object.
243
+ const {canAuthorize} = this.webex.credentials;
244
+
245
+ // Validate that the user is already authorized.
246
+ if (canAuthorize) {
247
+ return this.updateServices({forceRefresh})
248
+ .then(() => this.webex.credentials.getUserToken())
249
+ .then((token) =>
250
+ this.sendUserActivation({
251
+ email,
252
+ reqId,
253
+ token: token.toString(),
254
+ activationOptions,
255
+ preloginUserId,
256
+ })
257
+ )
258
+ .then((userObj) => ({
259
+ activated: true,
260
+ exists: true,
261
+ details: 'user is authorized via a user token',
262
+ user: userObj,
263
+ }));
264
+ }
265
+
266
+ // Destructure the client authorization details.
267
+ /* eslint-disable camelcase */
268
+ const {client_id, client_secret} = this.webex.credentials.config;
269
+
270
+ // Validate that client authentication details exist.
271
+ if (!client_id || !client_secret) {
272
+ return Promise.reject(new Error('client authentication details are not available'));
273
+ }
274
+ /* eslint-enable camelcase */
275
+
276
+ // Declare a class-memeber-scoped token for usage within the promise chain.
277
+ let token;
278
+
279
+ // Begin client authentication user validation.
280
+ return (
281
+ this.collectPreauthCatalog({email})
282
+ .then(() => {
283
+ // Retrieve the service url from the updated catalog. This is required
284
+ // since `WebexCore` is usually not fully initialized at the time this
285
+ // request completes.
286
+ const idbrokerService = this.get('idbroker', true);
287
+
288
+ // Collect the client auth token.
289
+ return this.webex.credentials.getClientToken({
290
+ uri: `${idbrokerService}idb/oauth2/v1/access_token`,
291
+ scope: 'webexsquare:admin webexsquare:get_conversation Identity:SCIM',
292
+ });
293
+ })
294
+ .then((tokenObj) => {
295
+ // Generate the token string.
296
+ token = tokenObj.toString();
297
+
298
+ // Collect the signin catalog using the client auth information.
299
+ return this.collectSigninCatalog({email, token, forceRefresh});
300
+ })
301
+ // Validate if collecting the signin catalog failed and populate the RTO
302
+ // with the appropriate content.
303
+ .catch((error) => ({
304
+ exists: error.name !== 'NotFound',
305
+ activated: false,
306
+ details:
307
+ error.name !== 'NotFound'
308
+ ? 'user exists but is not activated'
309
+ : 'user does not exist and is not activated',
310
+ }))
311
+ // Validate if the previous promise resolved with an RTO and populate the
312
+ // new RTO accordingly.
313
+ .then((rto) =>
314
+ Promise.all([
315
+ rto || {
316
+ activated: true,
317
+ exists: true,
318
+ details: 'user exists and is activated',
319
+ },
320
+ this.sendUserActivation({
321
+ email,
322
+ reqId,
323
+ token,
324
+ activationOptions,
325
+ preloginUserId,
326
+ }),
327
+ ])
328
+ )
329
+ .then(([rto, user]) => ({...rto, user}))
330
+ .catch((error) => {
331
+ const response = {
332
+ statusCode: error.statusCode,
333
+ responseText: error.body && error.body.message,
334
+ body: error.body,
335
+ };
336
+
337
+ return Promise.reject(response);
338
+ })
339
+ );
340
+ },
341
+
342
+ /**
343
+ * Get user meeting preferences (preferred webex site).
344
+ *
345
+ * @returns {object} - User Information including user preferrences .
346
+ */
347
+ getMeetingPreferences() {
348
+ return this.request({
349
+ method: 'GET',
350
+ service: 'hydra',
351
+ resource: 'meetingPreferences',
352
+ })
353
+ .then((res) => {
354
+ this.logger.info('services: received user region info');
355
+
356
+ return res.body;
357
+ })
358
+ .catch((err) => {
359
+ this.logger.info('services: was not able to fetch user login information', err);
360
+ // resolve successfully even if request failed
361
+ });
362
+ },
363
+
364
+ /**
365
+ * Fetches client region info such as countryCode and timezone.
366
+ *
367
+ * @returns {object} - The region info object.
368
+ */
369
+ fetchClientRegionInfo() {
370
+ const {services} = this.webex.config;
371
+
372
+ return this.request({
373
+ uri: services.discovery.sqdiscovery,
374
+ addAuthHeader: false,
375
+ headers: {
376
+ 'spark-user-agent': null,
377
+ },
378
+ timeout: 5000,
379
+ })
380
+ .then((res) => {
381
+ this.logger.info('services: received user region info');
382
+
383
+ return res.body;
384
+ })
385
+ .catch((err) => {
386
+ this.logger.info('services: was not able to get user region info', err);
387
+ // resolve successfully even if request failed
388
+ });
389
+ },
390
+
391
+ /**
392
+ * User activation parameter transfer object for {@link sendUserActivation}.
393
+ * @typedef {object} SendUserActivationPTO
394
+ * @property {string} SendUserActivationPTO.email - The email of the user.
395
+ * @property {string} SendUserActivationPTO.reqId - The activation requester.
396
+ * @property {string} SendUserActivationPTO.token - The client auth token.
397
+ * @property {object} SendUserActivationPTO.activationOptions - Extra options to pass when sending the activation.
398
+ * @property {object} SendUserActivationPTO.preloginUserId - The prelogin user id to set when sending the activation.
399
+ */
400
+
401
+ /**
402
+ * Send a request to activate a user using a client token.
403
+ *
404
+ * @param {SendUserActivationPTO} - The Parameter transfer object.
405
+ * @returns {LicenseDTO} - The DTO returned from the **License** service.
406
+ */
407
+ sendUserActivation({email, reqId, token, activationOptions, preloginUserId}) {
408
+ this.logger.info('services: sending user activation request');
409
+ let countryCode;
410
+ let timezone;
411
+
412
+ // try to fetch client region info first
413
+ return (
414
+ this.fetchClientRegionInfo()
415
+ .then((clientRegionInfo) => {
416
+ if (clientRegionInfo) {
417
+ ({countryCode, timezone} = clientRegionInfo);
418
+ }
419
+
420
+ // Send the user activation request to the **License** service.
421
+ return this.request({
422
+ service: 'license',
423
+ resource: 'users/activations',
424
+ method: 'POST',
425
+ headers: {
426
+ accept: 'application/json',
427
+ authorization: token,
428
+ 'x-prelogin-userid': preloginUserId,
429
+ },
430
+ body: {
431
+ email,
432
+ reqId,
433
+ countryCode,
434
+ timeZone: timezone,
435
+ ...activationOptions,
436
+ },
437
+ shouldRefreshAccessToken: false,
438
+ });
439
+ })
440
+ // On success, return the **License** user object.
441
+ .then(({body}) => body)
442
+ // On failure, reject with error from **License**.
443
+ .catch((error) => Promise.reject(error))
444
+ );
445
+ },
446
+
447
+ /**
448
+ * Updates a given service group i.e. preauth, signin, postauth with a new hostmap.
449
+ * @param {string} serviceGroup - preauth, signin, postauth
450
+ * @param {object} hostMap - The new hostmap to update the service group with.
451
+ * @returns {Promise<void>}
452
+ */
453
+ updateCatalog(serviceGroup, hostMap) {
454
+ const catalog = this._getCatalog();
455
+
456
+ const serviceHostMap = this._formatReceivedHostmap(hostMap);
457
+
458
+ return catalog.updateServiceUrls(serviceGroup, serviceHostMap);
459
+ },
460
+
461
+ /**
462
+ * simplified method to update the preauth catalog via email
463
+ *
464
+ * @param {object} query
465
+ * @param {string} query.email - A standard format email.
466
+ * @param {string} query.orgId - The user's OrgId.
467
+ * @param {boolean} forceRefresh - Boolean to bypass u2c cache control header
468
+ * @returns {Promise<void>}
469
+ */
470
+ collectPreauthCatalog(query, forceRefresh = false) {
471
+ if (!query) {
472
+ return this.updateServices({
473
+ from: 'limited',
474
+ query: {mode: 'DEFAULT_BY_PROXIMITY'},
475
+ forceRefresh,
476
+ });
477
+ }
478
+
479
+ return this.updateServices({from: 'limited', query, forceRefresh});
480
+ },
481
+
482
+ /**
483
+ * simplified method to update the signin catalog via email and token
484
+ * @param {object} param
485
+ * @param {string} param.email - must be a standard-format email
486
+ * @param {string} param.token - must be a client token
487
+ * @returns {Promise<void>}
488
+ */
489
+ collectSigninCatalog({email, token, forceRefresh} = {}) {
490
+ if (!email) {
491
+ return Promise.reject(new Error('`email` is required'));
492
+ }
493
+ if (!token) {
494
+ return Promise.reject(new Error('`token` is required'));
495
+ }
496
+
497
+ return this.updateServices({
498
+ from: 'signin',
499
+ query: {email},
500
+ token,
501
+ forceRefresh,
502
+ });
503
+ },
504
+
505
+ /**
506
+ * Updates credentials config to utilize u2c catalog
507
+ * urls.
508
+ * @returns {void}
509
+ */
510
+ updateCredentialsConfig() {
511
+ const {idbroker, identity} = this.list(true);
512
+
513
+ if (idbroker && identity) {
514
+ const {authorizationString, authorizeUrl} = this.webex.config.credentials;
515
+
516
+ // This must be set outside of the setConfig method used to assign the
517
+ // idbroker and identity url values.
518
+ this.webex.config.credentials.authorizeUrl = authorizationString
519
+ ? authorizeUrl
520
+ : `${idbroker.replace(trailingSlashes, '')}/idb/oauth2/v1/authorize`;
521
+
522
+ this.webex.setConfig({
523
+ credentials: {
524
+ idbroker: {
525
+ url: idbroker.replace(trailingSlashes, ''), // remove trailing slash
526
+ },
527
+ identity: {
528
+ url: identity.replace(trailingSlashes, ''), // remove trailing slash
529
+ },
530
+ },
531
+ });
532
+ }
533
+ },
534
+
535
+ /**
536
+ * Wait until the service catalog is available,
537
+ * or reject afte ra timeout of 60 seconds.
538
+ * @param {string} serviceGroup
539
+ * @param {number} [timeout] - in seconds
540
+ * @returns {Promise<void>}
541
+ */
542
+ waitForCatalog(serviceGroup, timeout) {
543
+ const catalog = this._getCatalog();
544
+ const {supertoken} = this.webex.credentials;
545
+
546
+ if (
547
+ serviceGroup === 'postauth' &&
548
+ supertoken &&
549
+ supertoken.access_token &&
550
+ !catalog.status.postauth.collecting &&
551
+ !catalog.status.postauth.ready
552
+ ) {
553
+ if (!catalog.status.preauth.ready) {
554
+ return this.initServiceCatalogs();
555
+ }
556
+
557
+ return this.updateServices();
558
+ }
559
+
560
+ return catalog.waitForCatalog(serviceGroup, timeout);
561
+ },
562
+
563
+ /**
564
+ * Service waiting parameter transfer object for {@link waitForService}.
565
+ *
566
+ * @typedef {object} WaitForServicePTO
567
+ * @property {string} [WaitForServicePTO.name] - The service name.
568
+ * @property {string} [WaitForServicePTO.url] - The service url.
569
+ * @property {string} [WaitForServicePTO.timeout] - wait duration in seconds.
570
+ */
571
+
572
+ /**
573
+ * Wait until the service has been ammended to any service catalog. This
574
+ * method prioritizes the service name over the service url when searching.
575
+ *
576
+ * @param {WaitForServicePTO} - The parameter transfer object.
577
+ * @returns {Promise<string>} - Resolves to the priority host of a service.
578
+ */
579
+ waitForService({name, timeout = 5, url}) {
580
+ const {services} = this.webex.config;
581
+
582
+ // Save memory by grabbing the catalog after there isn't a priortyURL
583
+ const catalog = this._getCatalog();
584
+
585
+ const fetchFromServiceUrl = services.servicesNotNeedValidation.find(
586
+ (service) => service === name
587
+ );
588
+
589
+ if (fetchFromServiceUrl) {
590
+ return Promise.resolve(this._activeServices[name]);
591
+ }
592
+
593
+ const priorityUrl = this.get(name, true);
594
+ const priorityUrlObj = this.getServiceFromUrl(url);
595
+
596
+ if (priorityUrl || priorityUrlObj) {
597
+ return Promise.resolve(priorityUrl || priorityUrlObj.priorityUrl);
598
+ }
599
+
600
+ if (catalog.isReady) {
601
+ if (url) {
602
+ return Promise.resolve(url);
603
+ }
604
+
605
+ this.webex.internal.metrics.submitClientMetrics(METRICS.JS_SDK_SERVICE_NOT_FOUND, {
606
+ fields: {service_name: name},
607
+ });
608
+
609
+ return Promise.reject(
610
+ new Error(`services: service '${name}' was not found in any of the catalogs`)
611
+ );
612
+ }
613
+
614
+ return new Promise((resolve, reject) => {
615
+ const groupsToCheck = ['preauth', 'signin', 'postauth'];
616
+ const checkCatalog = (catalogGroup) =>
617
+ catalog
618
+ .waitForCatalog(catalogGroup, timeout)
619
+ .then(() => {
620
+ const scopedPriorityUrl = this.get(name, true);
621
+ const scopedPrioriryUrlObj = this.getServiceFromUrl(url);
622
+
623
+ if (scopedPriorityUrl || scopedPrioriryUrlObj) {
624
+ resolve(scopedPriorityUrl || scopedPrioriryUrlObj.priorityUrl);
625
+ }
626
+ })
627
+ .catch(() => undefined);
628
+
629
+ Promise.all(groupsToCheck.map((group) => checkCatalog(group))).then(() => {
630
+ this.webex.internal.metrics.submitClientMetrics(METRICS.JS_SDK_SERVICE_NOT_FOUND, {
631
+ fields: {service_name: name},
632
+ });
633
+ reject(new Error(`services: service '${name}' was not found after waiting`));
634
+ });
635
+ });
636
+ },
637
+
638
+ /**
639
+ * Looks up the hostname in the host catalog
640
+ * and replaces it with the first host if it finds it
641
+ * @param {string} uri
642
+ * @returns {string} uri with the host replaced
643
+ */
644
+ replaceHostFromHostmap(uri) {
645
+ const url = new URL(uri);
646
+ const hostCatalog = this._services;
647
+
648
+ if (!hostCatalog) {
649
+ return uri;
650
+ }
651
+
652
+ const host = hostCatalog[url.host];
653
+
654
+ if (host && host[0]) {
655
+ const newHost = host[0].host;
656
+
657
+ url.host = newHost;
658
+
659
+ return url.toString();
660
+ }
661
+
662
+ return uri;
663
+ },
664
+
665
+ /**
666
+ * @private
667
+ * Organize a received hostmap from a service
668
+ * @param {object} serviceHostmap
669
+ * catalog endpoint.
670
+ * @returns {object}
671
+ */
672
+ _formatReceivedHostmap({services, activeServices}) {
673
+ const formattedHostmap = services.map(({id, serviceName, serviceUrls}) => {
674
+ const formattedServiceUrls = serviceUrls.map((serviceUrl) => ({
675
+ host: new URL(serviceUrl.baseUrl).host,
676
+ ...serviceUrl,
677
+ }));
678
+
679
+ return {
680
+ id,
681
+ serviceName,
682
+ serviceUrls: formattedServiceUrls,
683
+ };
684
+ });
685
+ this._updateActiveServices(activeServices);
686
+ this._updateServices(services);
687
+
688
+ return formattedHostmap;
689
+ },
690
+
691
+ /**
692
+ * Get the clusterId associated with a URL string.
693
+ * @param {string} url
694
+ * @returns {string} - Cluster ID of url provided
695
+ */
696
+ getClusterId(url) {
697
+ const catalog = this._getCatalog();
698
+
699
+ return catalog.findClusterId(url);
700
+ },
701
+
702
+ /**
703
+ * Get a service value from a provided clusterId. This method will
704
+ * return an object containing both the name and url of a found service.
705
+ * @param {object} params
706
+ * @param {string} params.clusterId - clusterId of found service
707
+ * @param {boolean} [params.priorityHost] - returns priority host url if true
708
+ * @param {string} [params.serviceGroup] - specify service group
709
+ * @returns {object} service
710
+ * @returns {string} service.name
711
+ * @returns {string} service.url
712
+ */
713
+ getServiceFromClusterId(params) {
714
+ const catalog = this._getCatalog();
715
+
716
+ return catalog.findServiceFromClusterId(params);
717
+ },
718
+
719
+ /**
720
+ * @param {String} cluster the cluster containing the id
721
+ * @param {UUID} [id] the id of the conversation.
722
+ * If empty, just return the base URL.
723
+ * @returns {String} url of the service
724
+ */
725
+ getServiceUrlFromClusterId({cluster = 'us'} = {}) {
726
+ let clusterId = cluster === 'us' ? DEFAULT_CLUSTER_IDENTIFIER : cluster;
727
+
728
+ // Determine if cluster has service name (non-US clusters from hydra do not)
729
+ if (clusterId.split(':').length < 4) {
730
+ // Add Service to cluster identifier
731
+ clusterId = `${cluster}:${CLUSTER_SERVICE}`;
732
+ }
733
+
734
+ const {url} = this.getServiceFromClusterId({clusterId}) || {};
735
+
736
+ if (!url) {
737
+ throw Error(`Could not find service for cluster [${cluster}]`);
738
+ }
739
+
740
+ return url;
741
+ },
742
+
743
+ /**
744
+ * Get a service object from a service url if the service url exists in the
745
+ * catalog.
746
+ *
747
+ * @param {string} url - The url to be validated.
748
+ * @returns {object} - Service object.
749
+ * @returns {object.name} - The name of the service found.
750
+ * @returns {object.priorityUrl} - The priority url of the found service.
751
+ * @returns {object.defaultUrl} - The default url of the found service.
752
+ */
753
+ getServiceFromUrl(url = '') {
754
+ const service = this._getCatalog().findServiceUrlFromUrl(url);
755
+
756
+ if (!service) {
757
+ return undefined;
758
+ }
759
+
760
+ return {
761
+ name: service.name,
762
+ priorityUrl: service.get(true),
763
+ defaultUrl: service.get(),
764
+ };
765
+ },
766
+
767
+ /**
768
+ * Determine if a provided url is in the catalog's allowed domains.
769
+ *
770
+ * @param {string} url - The url to match allowed domains against.
771
+ * @returns {boolean} - True if the url provided is allowed.
772
+ */
773
+ isAllowedDomainUrl(url) {
774
+ const catalog = this._getCatalog();
775
+
776
+ return !!catalog.findAllowedDomain(url);
777
+ },
778
+
779
+ /**
780
+ * Converts the host portion of the url from default host
781
+ * to a priority host
782
+ *
783
+ * @param {string} url a service url that contains a default host
784
+ * @returns {string} a service url that contains the top priority host.
785
+ * @throws if url isn't a service url
786
+ */
787
+ convertUrlToPriorityHostUrl(url = '') {
788
+ const data = this.getServiceFromUrl(url);
789
+
790
+ if (!data) {
791
+ throw Error(`No service associated with url: [${url}]`);
792
+ }
793
+
794
+ return url.replace(data.defaultUrl, data.priorityUrl);
795
+ },
796
+
797
+ /**
798
+ * @private
799
+ * Simplified method wrapper for sending a request to get
800
+ * an updated service hostmap.
801
+ * @param {object} [param]
802
+ * @param {string} [param.from] - This accepts `limited` or `signin`
803
+ * @param {object} [param.query] - This accepts `email`, `orgId` or `userId` key values
804
+ * @param {string} [param.query.email] - must be a standard-format email
805
+ * @param {string} [param.query.orgId] - must be an organization id
806
+ * @param {string} [param.query.userId] - must be a user id
807
+ * @param {string} [param.token] - used for signin catalog
808
+ * @returns {Promise<object>}
809
+ */
810
+ _fetchNewServiceHostmap({from, query, token, forceRefresh} = {}) {
811
+ const service = 'u2c';
812
+ const resource = from ? `/${from}/catalog` : '/catalog';
813
+ const qs = {...(query || {}), format: 'hostmap'};
814
+
815
+ if (forceRefresh) {
816
+ qs.timestamp = new Date().getTime();
817
+ }
818
+
819
+ const requestObject = {
820
+ method: 'GET',
821
+ service,
822
+ resource,
823
+ qs,
824
+ };
825
+
826
+ if (token) {
827
+ requestObject.headers = {authorization: token};
828
+ }
829
+
830
+ return this.webex.internal.newMetrics.callDiagnosticLatencies
831
+ .measureLatency(() => this.request(requestObject), 'internal.get.u2c.time')
832
+ .then(({body}) => this._formatReceivedHostmap(body));
833
+ },
834
+
835
+ /**
836
+ * Initialize the discovery services and the whitelisted services.
837
+ *
838
+ * @returns {void}
839
+ */
840
+ initConfig() {
841
+ // Get the catalog and destructure the services config.
842
+ const catalog = this._getCatalog();
843
+ const {services, fedramp} = this.webex.config;
844
+
845
+ // Validate that the services configuration exists.
846
+ if (services) {
847
+ if (fedramp) {
848
+ services.discovery = fedRampServices;
849
+ }
850
+ // Check for discovery services.
851
+ if (services.discovery) {
852
+ // Format the discovery configuration into an injectable array.
853
+ const formattedDiscoveryServices = Object.keys(services.discovery).map((key) => ({
854
+ name: key,
855
+ defaultUrl: services.discovery[key],
856
+ }));
857
+
858
+ // Inject formatted discovery services into services catalog.
859
+ catalog.updateServiceUrls('discovery', formattedDiscoveryServices);
860
+ }
861
+
862
+ if (services.override) {
863
+ // Format the override configuration into an injectable array.
864
+ const formattedOverrideServices = Object.keys(services.override).map((key) => ({
865
+ name: key,
866
+ defaultUrl: services.override[key],
867
+ }));
868
+
869
+ // Inject formatted override services into services catalog.
870
+ catalog.updateServiceUrls('override', formattedOverrideServices);
871
+ }
872
+
873
+ // if not fedramp, append on the commercialAllowedDomains
874
+ if (!fedramp) {
875
+ services.allowedDomains = union(services.allowedDomains, COMMERCIAL_ALLOWED_DOMAINS);
876
+ }
877
+
878
+ // Check for allowed host domains.
879
+ if (services.allowedDomains) {
880
+ // Store the allowed domains as a property of the catalog.
881
+ catalog.setAllowedDomains(services.allowedDomains);
882
+ }
883
+
884
+ // Set `validateDomains` property to match configuration
885
+ this.validateDomains = services.validateDomains;
886
+ }
887
+ },
888
+
889
+ /**
890
+ * Make the initial requests to collect the root catalogs.
891
+ *
892
+ * @returns {Promise<void, Error>} - Errors if the token is unavailable.
893
+ */
894
+ initServiceCatalogs() {
895
+ this.logger.info('services: initializing initial service catalogs');
896
+
897
+ // Destructure the credentials plugin.
898
+ const {credentials} = this.webex;
899
+
900
+ // Init a promise chain. Must be done as a Promise.resolve() to allow
901
+ // credentials#getOrgId() to properly throw.
902
+ return (
903
+ Promise.resolve()
904
+ // Get the user's OrgId.
905
+ .then(() => credentials.getOrgId())
906
+ // Begin collecting the preauth/limited catalog.
907
+ .then((orgId) => this.collectPreauthCatalog({orgId}))
908
+ .then(() => {
909
+ // Validate if the token is authorized.
910
+ if (credentials.canAuthorize) {
911
+ // Attempt to collect the postauth catalog.
912
+ return this.updateServices().catch(() => {
913
+ this.initFailed = true;
914
+ this.logger.warn('services: cannot retrieve postauth catalog');
915
+ });
916
+ }
917
+
918
+ // Return a resolved promise for consistent return value.
919
+ return Promise.resolve();
920
+ })
921
+ );
922
+ },
923
+
924
+ /**
925
+ * Initializer
926
+ *
927
+ * @instance
928
+ * @memberof Services
929
+ * @returns {Services}
930
+ */
931
+ initialize() {
932
+ const catalog = new ServiceCatalog();
933
+ this._catalogs.set(this.webex, catalog);
934
+
935
+ // Listen for configuration changes once.
936
+ this.listenToOnce(this.webex, 'change:config', () => {
937
+ this.initConfig();
938
+ });
939
+
940
+ // wait for webex instance to be ready before attempting
941
+ // to update the service catalogs
942
+ this.listenToOnce(this.webex, 'ready', () => {
943
+ const {supertoken} = this.webex.credentials;
944
+ // Validate if the supertoken exists.
945
+ if (supertoken && supertoken.access_token) {
946
+ this.initServiceCatalogs()
947
+ .then(() => {
948
+ catalog.isReady = true;
949
+ })
950
+ .catch((error) => {
951
+ this.initFailed = true;
952
+ this.logger.error(
953
+ `services: failed to init initial services when credentials available, ${error?.message}`
954
+ );
955
+ });
956
+ } else {
957
+ const {email} = this.webex.config;
958
+
959
+ this.collectPreauthCatalog(email ? {email} : undefined).catch((error) => {
960
+ this.initFailed = true;
961
+ this.logger.error(
962
+ `services: failed to init initial services when no credentials available, ${error?.message}`
963
+ );
964
+ });
965
+ }
966
+ });
967
+ },
968
+ });
969
+ /* eslint-enable no-underscore-dangle */
970
+
971
+ export default Services;