@webex/webex-core 3.12.0 → 3.13.0-next.10

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 (92) hide show
  1. package/.repo-context.json +653 -0
  2. package/.sdd/manifest.json +615 -0
  3. package/AGENTS.md +209 -0
  4. package/README.md +6 -3
  5. package/dist/config.js +46 -1
  6. package/dist/config.js.map +1 -1
  7. package/dist/credentials-config.js +21 -1
  8. package/dist/credentials-config.js.map +1 -1
  9. package/dist/index.js +14 -0
  10. package/dist/index.js.map +1 -1
  11. package/dist/interceptors/auth.js +10 -1
  12. package/dist/interceptors/auth.js.map +1 -1
  13. package/dist/interceptors/catalog-url.js +87 -0
  14. package/dist/interceptors/catalog-url.js.map +1 -0
  15. package/dist/interceptors/payload-transformer.js +25 -4
  16. package/dist/interceptors/payload-transformer.js.map +1 -1
  17. package/dist/lib/batcher.js +23 -7
  18. package/dist/lib/batcher.js.map +1 -1
  19. package/dist/lib/credentials/credentials.js +117 -5
  20. package/dist/lib/credentials/credentials.js.map +1 -1
  21. package/dist/lib/credentials/token.js +23 -9
  22. package/dist/lib/credentials/token.js.map +1 -1
  23. package/dist/lib/domains.js +90 -0
  24. package/dist/lib/domains.js.map +1 -0
  25. package/dist/lib/interceptors/service.js +5 -1
  26. package/dist/lib/interceptors/service.js.map +1 -1
  27. package/dist/lib/services/catalog-auth.js +114 -0
  28. package/dist/lib/services/catalog-auth.js.map +1 -0
  29. package/dist/lib/services/service-catalog.js +108 -18
  30. package/dist/lib/services/service-catalog.js.map +1 -1
  31. package/dist/lib/services/services.js +287 -40
  32. package/dist/lib/services/services.js.map +1 -1
  33. package/dist/lib/services-v2/service-catalog.js +14 -13
  34. package/dist/lib/services-v2/service-catalog.js.map +1 -1
  35. package/dist/lib/services-v2/services-v2.js +294 -44
  36. package/dist/lib/services-v2/services-v2.js.map +1 -1
  37. package/dist/lib/static-asset-loader.js +153 -0
  38. package/dist/lib/static-asset-loader.js.map +1 -0
  39. package/dist/plugins/logger.js +1 -1
  40. package/dist/webex-core.js +11 -3
  41. package/dist/webex-core.js.map +1 -1
  42. package/docs/adr/index.md +32 -0
  43. package/docs/architecture.md +298 -0
  44. package/docs/getting-started.md +96 -0
  45. package/docs/index.md +55 -0
  46. package/docs/specs/README.md +76 -0
  47. package/package.json +13 -13
  48. package/schemas/repo-context.schema.json +796 -0
  49. package/src/config.js +50 -1
  50. package/src/credentials-config.js +22 -0
  51. package/src/docs/README.md +732 -0
  52. package/src/index.js +2 -0
  53. package/src/interceptors/auth.js +14 -1
  54. package/src/interceptors/catalog-url.js +66 -0
  55. package/src/interceptors/docs/README.md +658 -0
  56. package/src/interceptors/payload-transformer.js +23 -1
  57. package/src/lib/batcher.js +25 -10
  58. package/src/lib/credentials/credentials.js +106 -4
  59. package/src/lib/credentials/docs/README.md +847 -0
  60. package/src/lib/credentials/token.js +15 -8
  61. package/src/lib/domains.ts +94 -0
  62. package/src/lib/interceptors/service.js +11 -3
  63. package/src/lib/services/catalog-auth.js +112 -0
  64. package/src/lib/services/docs/README.md +737 -0
  65. package/src/lib/services/service-catalog.js +112 -16
  66. package/src/lib/services/services.js +274 -24
  67. package/src/lib/services-v2/docs/README.md +751 -0
  68. package/src/lib/services-v2/service-catalog.ts +16 -12
  69. package/src/lib/services-v2/services-v2.ts +282 -26
  70. package/src/lib/static-asset-loader.ts +128 -0
  71. package/src/lib/storage/docs/README.md +646 -0
  72. package/src/webex-core.js +8 -0
  73. package/test/fixtures/activation-email.ts +22 -0
  74. package/test/integration/spec/credentials/credentials.js +3 -1
  75. package/test/integration/spec/credentials/token.js +8 -0
  76. package/test/integration/spec/services/service-catalog.js +5 -0
  77. package/test/integration/spec/services/services.js +183 -112
  78. package/test/integration/spec/services-v2/services-v2.js +169 -98
  79. package/test/integration/spec/unit-browser/token.js +7 -2
  80. package/test/unit/spec/credentials/credentials.js +326 -3
  81. package/test/unit/spec/credentials/token.js +259 -6
  82. package/test/unit/spec/interceptors/auth.js +92 -1
  83. package/test/unit/spec/interceptors/catalog-url.js +224 -0
  84. package/test/unit/spec/interceptors/payload-transformer.js +119 -1
  85. package/test/unit/spec/lib/batcher.js +56 -0
  86. package/test/unit/spec/services/interceptors/service.js +35 -1
  87. package/test/unit/spec/services/service-catalog.js +368 -11
  88. package/test/unit/spec/services/services.js +783 -10
  89. package/test/unit/spec/services-v2/service-catalog.ts +134 -11
  90. package/test/unit/spec/services-v2/services-v2.ts +825 -10
  91. package/test/unit/spec/static-asset-loader.ts +224 -0
  92. package/test/unit/spec/webex-core.js +77 -1
@@ -4,6 +4,100 @@ import AmpState from 'ampersand-state';
4
4
 
5
5
  import {union} from 'lodash';
6
6
  import ServiceUrl from './service-url';
7
+ import {matchAllowedDomain, normalizeAllowedDomains} from '../domains';
8
+
9
+ // Catalog base URLs are a small, stable set, so their parsed origin/path is
10
+ // memoized to avoid repeated `new URL()` work when scanning the catalog on the
11
+ // request hot path.
12
+ const catalogUrlCache = new Map();
13
+
14
+ /**
15
+ * Parse a catalog URL into the origin and normalized path used for matching,
16
+ * memoizing the result. Returns null when the URL is unparsable.
17
+ *
18
+ * @param {string} catalogUrlString - The catalog URL to parse
19
+ * @returns {{origin: string, path: string} | null} - Parsed catalog URL, or null
20
+ */
21
+ export function parseCatalogUrl(catalogUrlString) {
22
+ if (catalogUrlCache.has(catalogUrlString)) {
23
+ return catalogUrlCache.get(catalogUrlString);
24
+ }
25
+
26
+ let parsed = null;
27
+
28
+ try {
29
+ const catalogUrl = new URL(catalogUrlString);
30
+
31
+ // Normalize paths by removing trailing slashes (except root "/")
32
+ parsed = {origin: catalogUrl.origin, path: catalogUrl.pathname.replace(/\/$/, '') || '/'};
33
+ } catch {
34
+ parsed = null;
35
+ }
36
+
37
+ catalogUrlCache.set(catalogUrlString, parsed);
38
+
39
+ return parsed;
40
+ }
41
+
42
+ /**
43
+ * Check if an already-parsed candidate URL matches a parsed catalog URL with
44
+ * proper origin validation. Allocates nothing, so it is safe to call in a tight
45
+ * loop over the whole catalog.
46
+ *
47
+ * @param {URL} candidateUrl - The parsed candidate URL to validate
48
+ * @param {{origin: string, path: string} | null} parsedCatalogUrl - The parsed catalog URL
49
+ * @returns {boolean} - True if the candidate URL is under the catalog URL's origin and path
50
+ */
51
+ export function matchesParsedCatalogUrl(candidateUrl, parsedCatalogUrl) {
52
+ if (!candidateUrl || !parsedCatalogUrl) {
53
+ return false;
54
+ }
55
+
56
+ // Origins must match exactly (scheme + host + port)
57
+ if (candidateUrl.origin !== parsedCatalogUrl.origin) {
58
+ return false;
59
+ }
60
+
61
+ const catalogPath = parsedCatalogUrl.path;
62
+
63
+ if (catalogPath === '/') {
64
+ // Root path matches everything under this origin
65
+ return true;
66
+ }
67
+
68
+ const candidatePath = candidateUrl.pathname;
69
+
70
+ if (candidatePath.startsWith(catalogPath)) {
71
+ // Ensure we're at a path boundary, not mid-segment
72
+ // e.g., /api/v1 should match /api/v1/foo but not /api/v1extra
73
+ // nextChar is undefined for exact match, '/' for valid extension
74
+ const nextChar = candidatePath[catalogPath.length];
75
+
76
+ return nextChar === '/' || nextChar === undefined;
77
+ }
78
+
79
+ return false;
80
+ }
81
+
82
+ /**
83
+ * Check if a candidate URL matches a catalog URL with proper origin validation.
84
+ * This prevents bypasses like https://trusted.example.attacker.com matching https://trusted.example
85
+ *
86
+ * @param {string} candidateUrlString - The URL to validate
87
+ * @param {string} catalogUrlString - The catalog URL to compare against
88
+ * @returns {boolean} - True if the candidate URL is under the catalog URL's origin and path
89
+ */
90
+ export function matchesCatalogUrl(candidateUrlString, catalogUrlString) {
91
+ let candidateUrl;
92
+
93
+ try {
94
+ candidateUrl = new URL(candidateUrlString);
95
+ } catch {
96
+ return false;
97
+ }
98
+
99
+ return matchesParsedCatalogUrl(candidateUrl, parseCatalogUrl(catalogUrlString));
100
+ }
7
101
 
8
102
  /* eslint-disable no-underscore-dangle */
9
103
  /**
@@ -245,20 +339,27 @@ const ServiceCatalog = AmpState.extend({
245
339
  ...this.serviceGroups.override,
246
340
  ];
247
341
 
342
+ // Invalid URLs cannot match any service
343
+ let candidateUrl;
344
+
345
+ try {
346
+ candidateUrl = new URL(url);
347
+ } catch {
348
+ return undefined;
349
+ }
350
+
248
351
  return serviceUrls.find((serviceUrl) => {
249
- // Check to see if the URL we are checking starts with the default URL
250
- if (url.startsWith(serviceUrl.defaultUrl)) {
352
+ // Check if the URL matches the default URL with proper origin validation
353
+ if (matchesParsedCatalogUrl(candidateUrl, parseCatalogUrl(serviceUrl.defaultUrl))) {
251
354
  return true;
252
355
  }
253
356
 
254
- // If not, we check to see if the alternate URLs match
255
- // These are made by swapping the host of the default URL
256
- // with that of an alternate host
357
+ // Check alternate URLs (built by swapping host with alternate hosts)
257
358
  for (const host of serviceUrl.hosts) {
258
359
  const alternateUrl = new URL(serviceUrl.defaultUrl);
259
360
  alternateUrl.host = host.host;
260
361
 
261
- if (url.startsWith(alternateUrl.toString())) {
362
+ if (matchesParsedCatalogUrl(candidateUrl, parseCatalogUrl(alternateUrl.toString()))) {
262
363
  return true;
263
364
  }
264
365
  }
@@ -268,19 +369,14 @@ const ServiceCatalog = AmpState.extend({
268
369
  },
269
370
 
270
371
  /**
271
- * Finds an allowed domain that matches a specific url.
372
+ * Finds an allowed domain that matches a specific url. The url's hostname
373
+ * must be the allowed domain itself or a subdomain of it.
272
374
  *
273
375
  * @param {string} url - The url to match the allowed domains against.
274
376
  * @returns {string} - The matching allowed domain.
275
377
  */
276
378
  findAllowedDomain(url) {
277
- const urlObj = Url.parse(url);
278
-
279
- if (!urlObj.host) {
280
- return undefined;
281
- }
282
-
283
- return this.allowedDomains.find((allowedDomain) => urlObj.host.includes(allowedDomain));
379
+ return matchAllowedDomain(url, this.allowedDomains);
284
380
  },
285
381
 
286
382
  /**
@@ -367,7 +463,7 @@ const ServiceCatalog = AmpState.extend({
367
463
  * @returns {void}
368
464
  */
369
465
  setAllowedDomains(allowedDomains) {
370
- this.allowedDomains = [...allowedDomains];
466
+ this.allowedDomains = normalizeAllowedDomains(allowedDomains);
371
467
  },
372
468
 
373
469
  /**
@@ -376,7 +472,7 @@ const ServiceCatalog = AmpState.extend({
376
472
  * @returns {void}
377
473
  */
378
474
  addAllowedDomains(newAllowedDomains) {
379
- this.allowedDomains = union(this.allowedDomains, newAllowedDomains);
475
+ this.allowedDomains = union(this.allowedDomains, normalizeAllowedDomains(newAllowedDomains));
380
476
  },
381
477
 
382
478
  /**
@@ -4,6 +4,12 @@ import {union, forEach} from 'lodash';
4
4
  import WebexPlugin from '../webex-plugin';
5
5
 
6
6
  import METRICS from '../metrics';
7
+ import {
8
+ clearCatalogAuthFailure,
9
+ getCatalogAuthFailure,
10
+ recordCatalogAuthFailure,
11
+ serviceLookupError,
12
+ } from './catalog-auth';
7
13
  import ServiceCatalog from './service-catalog';
8
14
  import ServiceRegistry from './service-registry';
9
15
  import ServiceState from './service-state';
@@ -57,6 +63,22 @@ const Services = WebexPlugin.extend({
57
63
  initFailed: ['boolean', false, false],
58
64
  },
59
65
 
66
+ session: {
67
+ /**
68
+ * Becomes `true` once the initial catalog collection has completed
69
+ * (successfully or otherwise) and any in-flight credentials refresh has
70
+ * settled. Blocks `webex.ready` so consumers can rely on `webex.ready`
71
+ * implying "catalogs populated AND credential state stable".
72
+ * @instance
73
+ * @memberof Services
74
+ * @type {boolean}
75
+ */
76
+ ready: {
77
+ default: false,
78
+ type: 'boolean',
79
+ },
80
+ },
81
+
60
82
  _catalogs: new WeakMap(),
61
83
 
62
84
  _serviceUrls: null,
@@ -98,6 +120,42 @@ const Services = WebexPlugin.extend({
98
120
  return this._catalogs.get(this.webex);
99
121
  },
100
122
 
123
+ /**
124
+ * Remember a postauth catalog failure caused by HTTP 401 or 403.
125
+ * 401 means the access token was rejected. 403 means the token can be
126
+ * valid and the caller still has no access. A refresh or replay failure
127
+ * that replaced a catalog 401 is recorded as invalid_access_token.
128
+ * A refresh 403 keeps that original 401 on error.catalogAuthStatus.
129
+ * Other failures clear any previously stored auth failure.
130
+ *
131
+ * @private
132
+ * @param {Error} error
133
+ * @returns {void}
134
+ */
135
+ _recordCatalogAuthFailure(error) {
136
+ recordCatalogAuthFailure(this, error);
137
+ },
138
+
139
+ /**
140
+ * @private
141
+ * @returns {{status: number, reason: string}|null}
142
+ */
143
+ _getCatalogAuthFailure() {
144
+ return getCatalogAuthFailure(this);
145
+ },
146
+
147
+ /**
148
+ * Build the rejection for a service that could not be resolved.
149
+ * A stored catalog auth failure replaces the generic not-found text.
150
+ *
151
+ * @private
152
+ * @param {string} fallbackMessage
153
+ * @returns {Error}
154
+ */
155
+ _serviceLookupError(fallbackMessage) {
156
+ return serviceLookupError(this, fallbackMessage);
157
+ },
158
+
101
159
  /**
102
160
  * Safely access localStorage if available; returns the Storage or null.
103
161
  * @returns {Storage|null}
@@ -245,13 +303,23 @@ const Services = WebexPlugin.extend({
245
303
  },
246
304
 
247
305
  /**
248
- * Checks if the current environment is an integration (INT) environment
249
- * by examining the u2c discovery URL from webex config.
306
+ * Checks if the current environment is an integration (INT) environment.
307
+ * Uses the explicit environment config when set, otherwise examines the u2c discovery URL.
250
308
  * INT environments use discovery URLs containing 'intb' (e.g., u2c-intb.ciscospark.com).
251
309
  * @returns {boolean} True if INT environment, false otherwise
252
310
  */
253
311
  isIntegrationEnvironment() {
254
312
  try {
313
+ const configuredEnvironment = this.webex?.config?.environment;
314
+
315
+ if (configuredEnvironment !== undefined) {
316
+ const isIntFromConfig = configuredEnvironment === 'integration';
317
+
318
+ this.logger.info(`services: isIntegrationEnvironment: ${isIntFromConfig} (config)`);
319
+
320
+ return isIntFromConfig;
321
+ }
322
+
255
323
  const u2cUrl = this.webex?.config?.services?.discovery?.u2c || '';
256
324
  const isInt = u2cUrl.includes('intb');
257
325
 
@@ -375,10 +443,20 @@ const Services = WebexPlugin.extend({
375
443
  catalog.updateServiceUrls(serviceGroup, formattedServiceHostMap);
376
444
  this.updateCredentialsConfig();
377
445
  catalog.status[serviceGroup].collecting = false;
446
+
447
+ // A successful postauth catalog replaces any remembered 401/403.
448
+ // Preauth and signin updates leave that marker alone.
449
+ if (serviceGroup === 'postauth') {
450
+ clearCatalogAuthFailure(this);
451
+ }
378
452
  })
379
453
  .catch((error) => {
380
454
  catalog.status[serviceGroup].collecting = false;
381
455
 
456
+ if (serviceGroup === 'postauth') {
457
+ this._recordCatalogAuthFailure(error);
458
+ }
459
+
382
460
  return Promise.reject(error);
383
461
  });
384
462
  },
@@ -794,7 +872,7 @@ const Services = WebexPlugin.extend({
794
872
  });
795
873
 
796
874
  return Promise.reject(
797
- new Error(`services: service '${name}' was not found in any of the catalogs`)
875
+ this._serviceLookupError(`services: service '${name}' was not found in any of the catalogs`)
798
876
  );
799
877
  }
800
878
 
@@ -817,7 +895,7 @@ const Services = WebexPlugin.extend({
817
895
  this.webex.internal.metrics.submitClientMetrics(METRICS.JS_SDK_SERVICE_NOT_FOUND, {
818
896
  fields: {service_name: name},
819
897
  });
820
- reject(new Error(`services: service '${name}' was not found after waiting`));
898
+ reject(this._serviceLookupError(`services: service '${name}' was not found after waiting`));
821
899
  });
822
900
  });
823
901
  },
@@ -1087,9 +1165,16 @@ const Services = WebexPlugin.extend({
1087
1165
  requestObject.headers = {authorization: token};
1088
1166
  }
1089
1167
 
1090
- return this.webex.internal.newMetrics.callDiagnosticLatencies
1091
- .measureLatency(() => this.request(requestObject), 'internal.get.u2c.time')
1092
- .then(({body}) => body);
1168
+ const sendRequest = () => this.request(requestObject);
1169
+
1170
+ const responsePromise = this.webex.internal.newMetrics
1171
+ ? this.webex.internal.newMetrics.callDiagnosticLatencies.measureLatency(
1172
+ sendRequest,
1173
+ 'internal.get.u2c.time'
1174
+ )
1175
+ : sendRequest();
1176
+
1177
+ return responsePromise.then(({body}) => body);
1093
1178
  },
1094
1179
 
1095
1180
  /**
@@ -1346,6 +1431,7 @@ const Services = WebexPlugin.extend({
1346
1431
 
1347
1432
  // Destructure the credentials plugin.
1348
1433
  const {credentials} = this.webex;
1434
+ const catalog = this._getCatalog();
1349
1435
 
1350
1436
  // Init a promise chain. Must be done as a Promise.resolve() to allow
1351
1437
  // credentials#getOrgId() to properly throw.
@@ -1358,12 +1444,18 @@ const Services = WebexPlugin.extend({
1358
1444
  .then(() => {
1359
1445
  // Validate if the token is authorized.
1360
1446
  if (credentials.canAuthorize) {
1361
- // Attempt to collect the postauth catalog.
1362
-
1363
- return this.updateServices().catch(() => {
1364
- this.initFailed = true;
1365
- this.logger.warn('services: cannot retrieve postauth catalog');
1366
- });
1447
+ // Attempt to collect the postauth catalog, then mark the catalog
1448
+ // ready. Setting `isReady` here - rather than only in the init
1449
+ // callers - means a slow postauth fetch that loses the gated-init
1450
+ // timeout race still marks the catalog ready once it completes.
1451
+ return this.updateServices()
1452
+ .then(() => {
1453
+ catalog.isReady = true;
1454
+ })
1455
+ .catch(() => {
1456
+ this.initFailed = true;
1457
+ this.logger.warn('services: cannot retrieve postauth catalog');
1458
+ });
1367
1459
  }
1368
1460
 
1369
1461
  // Return a resolved promise for consistent return value.
@@ -1372,6 +1464,51 @@ const Services = WebexPlugin.extend({
1372
1464
  );
1373
1465
  },
1374
1466
 
1467
+ /**
1468
+ * Await any in-flight credentials refresh, then flip `services.ready` so
1469
+ * `webex.ready` can fire. Closes the parallel-refresh window: if a credential
1470
+ * refresh is in flight when initial catalog collection settles, we must not
1471
+ * signal ready until the refresh has resolved - otherwise downstream
1472
+ * consumers may observe `canAuthorize`/token state that is about to change
1473
+ * under them.
1474
+ *
1475
+ * @private
1476
+ * @returns {Promise<void>}
1477
+ */
1478
+ async _finalizeReady() {
1479
+ const {credentials} = this.webex;
1480
+
1481
+ if (credentials && credentials.isRefreshing) {
1482
+ await new Promise((resolve) => {
1483
+ credentials.once('change:isRefreshing', resolve);
1484
+ });
1485
+ }
1486
+
1487
+ this.ready = true;
1488
+ },
1489
+
1490
+ /**
1491
+ * Build a promise that rejects once the catalog init timeout elapses. Race
1492
+ * this against catalog collection so a hung request never leaves
1493
+ * `services.ready` false forever - that would stall `webex.ready` and leave
1494
+ * consumers waiting on it indefinitely. Timeout is configurable via
1495
+ * `config.services.catalogInitTimeout` (defaults to 15s in config). Created
1496
+ * lazily so paths that skip catalog collection never schedule a stray timer.
1497
+ *
1498
+ * @private
1499
+ * @returns {Promise<never>}
1500
+ */
1501
+ _makeInitTimeout() {
1502
+ const initTimeoutMs = this.webex.config?.services?.catalogInitTimeout;
1503
+
1504
+ return new Promise((_, reject) => {
1505
+ setTimeout(
1506
+ () => reject(new Error(`services: init timed out after ${initTimeoutMs}ms`)),
1507
+ initTimeoutMs
1508
+ );
1509
+ });
1510
+ },
1511
+
1375
1512
  /**
1376
1513
  * Initializer
1377
1514
  *
@@ -1388,11 +1525,39 @@ const Services = WebexPlugin.extend({
1388
1525
  this.registries.set(this.webex, registry);
1389
1526
  this.states.set(this.webex, state);
1390
1527
 
1391
- // Listen for configuration changes once.
1528
+ // Listen for configuration changes once. The config is not populated on the
1529
+ // webex instance until the `change:config` event fires, so any decision that
1530
+ // depends on config values (such as the gated-vs-ungated init below) must be
1531
+ // made from within this handler rather than synchronously in `initialize()`.
1392
1532
  this.listenToOnce(this.webex, 'change:config', () => {
1393
1533
  this.initConfig();
1534
+
1535
+ // Feature flag: when enabled, `webex.ready` is blocked until the initial
1536
+ // catalog collection has settled AND any in-flight credentials refresh has
1537
+ // completed. When disabled (the default), preserves the pre-existing
1538
+ // behavior where `webex.ready` fires as soon as `webex.loaded` does and
1539
+ // the catalog is collected out-of-band.
1540
+ const waitForCatalogInit = this.webex.config?.services?.waitForCatalogInit === true;
1541
+
1542
+ if (waitForCatalogInit) {
1543
+ this._initializeCatalogsGated(catalog);
1544
+ } else {
1545
+ // Not gating - immediately mark ready so we do not block webex.ready.
1546
+ this.ready = true;
1547
+ this._initializeCatalogsUngated(catalog);
1548
+ }
1394
1549
  });
1550
+ },
1395
1551
 
1552
+ /**
1553
+ * Original (pre-verified-ready) initialization path. Runs on `webex.ready`
1554
+ * and collects catalogs opportunistically without blocking anything.
1555
+ *
1556
+ * @private
1557
+ * @param {ServiceCatalog} catalog
1558
+ * @returns {void}
1559
+ */
1560
+ _initializeCatalogsUngated(catalog) {
1396
1561
  // wait for webex instance to be ready before attempting
1397
1562
  // to update the service catalogs
1398
1563
  // this can cause a race condition because credentials may
@@ -1407,19 +1572,25 @@ const Services = WebexPlugin.extend({
1407
1572
  const {supertoken} = this.webex.credentials;
1408
1573
  // Validate if the supertoken exists.
1409
1574
  if (supertoken && supertoken.access_token) {
1410
- this.initServiceCatalogs()
1411
- .then(() => {
1412
- catalog.isReady = true;
1413
- })
1414
- .catch((error) => {
1415
- this.initFailed = true;
1416
- this.logger.error(
1417
- `services: failed to init initial services when credentials available, ${error?.message}`
1418
- );
1419
- });
1575
+ // `initServiceCatalogs` marks the catalog ready internally once the
1576
+ // postauth catalog is collected.
1577
+ this.initServiceCatalogs().catch((error) => {
1578
+ this.initFailed = true;
1579
+ this.logger.error(
1580
+ `services: failed to init initial services when credentials available, ${error?.message}`
1581
+ );
1582
+ });
1420
1583
  } else {
1421
1584
  const {email} = this.webex.config;
1422
1585
 
1586
+ if (this.webex.config?.services?.skipPreauthCatalogOnUnauthenticated === true) {
1587
+ this.logger.info(
1588
+ 'services: skipping preauth catalog collection while unauthenticated as per the config'
1589
+ );
1590
+
1591
+ return;
1592
+ }
1593
+
1423
1594
  this.collectPreauthCatalog(email ? {email} : undefined).catch((error) => {
1424
1595
  this.initFailed = true;
1425
1596
  this.logger.error(
@@ -1429,6 +1600,85 @@ const Services = WebexPlugin.extend({
1429
1600
  }
1430
1601
  });
1431
1602
  },
1603
+
1604
+ /**
1605
+ * Verified-ready initialization path. Blocks `webex.ready` until the initial
1606
+ * catalog fetch has settled (or timed out) AND any in-flight credentials
1607
+ * refresh has completed. Also handles the fresh-login case where OAuth
1608
+ * completes after `loaded` fires.
1609
+ *
1610
+ * @private
1611
+ * @param {ServiceCatalog} catalog
1612
+ * @returns {void}
1613
+ */
1614
+ _initializeCatalogsGated(catalog) {
1615
+ // Wait for storage to be loaded before attempting to update the service
1616
+ // catalogs. We listen for 'loaded' instead of 'ready' because `services.ready`
1617
+ // now blocks `webex.ready` - listening to 'ready' would deadlock.
1618
+ this.listenToOnce(this.webex, 'loaded', async () => {
1619
+ const cachedCatalog = await this._loadCatalogFromCache();
1620
+ if (cachedCatalog) {
1621
+ catalog.isReady = true;
1622
+ await this._finalizeReady();
1623
+
1624
+ return; // skip initServiceCatalogs() on reload when cache exists
1625
+ }
1626
+ const {supertoken} = this.webex.credentials;
1627
+
1628
+ // Validate if the supertoken exists.
1629
+ if (supertoken && supertoken.access_token) {
1630
+ // `initServiceCatalogs` marks the catalog ready internally once the
1631
+ // postauth catalog is collected - even if it loses the timeout race
1632
+ // below, so a slow fetch still eventually flips `catalog.isReady`.
1633
+ Promise.race([this.initServiceCatalogs(), this._makeInitTimeout()])
1634
+ .catch((error) => {
1635
+ this.initFailed = true;
1636
+ this.logger.error(
1637
+ `services: failed to init initial services when credentials available, ${error?.message}`
1638
+ );
1639
+ })
1640
+ .finally(() => this._finalizeReady());
1641
+ } else {
1642
+ const {email} = this.webex.config;
1643
+
1644
+ // Handle fresh login: 'loaded' fires before OAuth completes, so listen
1645
+ // for `canAuthorize` flipping true and then collect the postauth catalog.
1646
+ this.listenToOnce(this.webex, 'change:canAuthorize', () => {
1647
+ if (this.webex.canAuthorize && !catalog.status.postauth.ready) {
1648
+ // `initServiceCatalogs` marks the catalog ready internally.
1649
+ this.initServiceCatalogs().catch((error) => {
1650
+ this.logger.error(
1651
+ `services: failed to init service catalogs after auth, ${error?.message}`
1652
+ );
1653
+ });
1654
+ }
1655
+ });
1656
+
1657
+ if (this.webex.config?.services?.skipPreauthCatalogOnUnauthenticated === true) {
1658
+ // Skip the preauth catalog fetch (it will be collected manually
1659
+ // later), but still finalize `services.ready` so `webex.ready` is not
1660
+ // stalled while unauthenticated. No timeout is created here so there
1661
+ // is no stray timer or unhandled rejection.
1662
+ this.logger.info(
1663
+ 'services: skipping preauth catalog collection while unauthenticated as per the config'
1664
+ );
1665
+ this._finalizeReady();
1666
+ } else {
1667
+ Promise.race([
1668
+ this.collectPreauthCatalog(email ? {email} : undefined),
1669
+ this._makeInitTimeout(),
1670
+ ])
1671
+ .catch((error) => {
1672
+ this.initFailed = true;
1673
+ this.logger.error(
1674
+ `services: failed to init initial services when no credentials available, ${error?.message}`
1675
+ );
1676
+ })
1677
+ .finally(() => this._finalizeReady());
1678
+ }
1679
+ }
1680
+ });
1681
+ },
1432
1682
  });
1433
1683
  /* eslint-enable no-underscore-dangle */
1434
1684