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