@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
@@ -3,6 +3,8 @@ import AmpState from 'ampersand-state';
3
3
  import {union} from 'lodash';
4
4
  import ServiceDetail from './service-detail';
5
5
  import {IServiceDetail, ServiceGroup} from './types';
6
+ import {matchAllowedDomain, normalizeAllowedDomains} from '../domains';
7
+ import {matchesParsedCatalogUrl, parseCatalogUrl} from '../services/service-catalog';
6
8
 
7
9
  /**
8
10
  * @class
@@ -198,9 +200,17 @@ const ServiceCatalog = AmpState.extend({
198
200
  findServiceDetailFromUrl(url: string): IServiceDetail | undefined {
199
201
  const serviceDetails = this._getAllServiceDetails();
200
202
 
203
+ let candidateUrl: URL;
204
+
205
+ try {
206
+ candidateUrl = new URL(url);
207
+ } catch {
208
+ return undefined;
209
+ }
210
+
201
211
  return serviceDetails.find(({serviceUrls}) => {
202
212
  for (const serviceUrl of serviceUrls) {
203
- if (url.startsWith(serviceUrl.baseUrl)) {
213
+ if (matchesParsedCatalogUrl(candidateUrl, parseCatalogUrl(serviceUrl.baseUrl))) {
204
214
  return true;
205
215
  }
206
216
  }
@@ -210,20 +220,14 @@ const ServiceCatalog = AmpState.extend({
210
220
  },
211
221
 
212
222
  /**
213
- * Finds an allowed domain that matches a specific url.
223
+ * Finds an allowed domain that matches a specific url. The url's hostname
224
+ * must be the allowed domain itself or a subdomain of it.
214
225
  *
215
226
  * @param {string} url - The url to match the allowed domains against.
216
227
  * @returns {string} - The matching allowed domain.
217
228
  */
218
229
  findAllowedDomain(url: string): string {
219
- try {
220
- const urlObj = new URL(url);
221
-
222
- return this.allowedDomains.find((allowedDomain) => urlObj.host.includes(allowedDomain));
223
- } catch {
224
- // If the URL is invalid or can't be found, return undefined
225
- return undefined;
226
- }
230
+ return matchAllowedDomain(url, this.allowedDomains);
227
231
  },
228
232
 
229
233
  /**
@@ -282,7 +286,7 @@ const ServiceCatalog = AmpState.extend({
282
286
  * @returns {void}
283
287
  */
284
288
  setAllowedDomains(allowedDomains: Array<string>): void {
285
- this.allowedDomains = [...allowedDomains];
289
+ this.allowedDomains = normalizeAllowedDomains(allowedDomains);
286
290
  },
287
291
 
288
292
  /**
@@ -291,7 +295,7 @@ const ServiceCatalog = AmpState.extend({
291
295
  * @returns {void}
292
296
  */
293
297
  addAllowedDomains(newAllowedDomains: Array<string>): void {
294
- this.allowedDomains = union(this.allowedDomains, newAllowedDomains);
298
+ this.allowedDomains = union(this.allowedDomains, normalizeAllowedDomains(newAllowedDomains));
295
299
  },
296
300
 
297
301
  /**
@@ -7,6 +7,13 @@ import METRICS from '../metrics';
7
7
  import ServiceCatalog from './service-catalog';
8
8
  import fedRampServices from './service-fed-ramp';
9
9
  import {COMMERCIAL_ALLOWED_DOMAINS} from '../constants';
10
+ import {
11
+ clearCatalogAuthFailure,
12
+ getCatalogAuthFailure,
13
+ recordCatalogAuthFailure,
14
+ serviceLookupError,
15
+ } from '../services/catalog-auth';
16
+ import {matchesCatalogUrl} from '../services/service-catalog';
10
17
  import {
11
18
  ActiveServices,
12
19
  IServiceCatalog,
@@ -15,6 +22,7 @@ import {
15
22
  ServiceHostmap,
16
23
  ServiceGroup,
17
24
  ServiceHost,
25
+ ServiceUrl,
18
26
  SelectionMeta,
19
27
  } from './types';
20
28
 
@@ -44,6 +52,22 @@ const Services = WebexPlugin.extend({
44
52
  initFailed: ['boolean', false, false],
45
53
  },
46
54
 
55
+ session: {
56
+ /**
57
+ * Becomes `true` once the initial catalog collection has completed
58
+ * (successfully or otherwise) and any in-flight credentials refresh has
59
+ * settled. Blocks `webex.ready` so consumers can rely on `webex.ready`
60
+ * implying "catalogs populated AND credential state stable".
61
+ * @instance
62
+ * @memberof Services
63
+ * @type {boolean}
64
+ */
65
+ ready: {
66
+ default: false,
67
+ type: 'boolean',
68
+ },
69
+ },
70
+
47
71
  _catalogs: new WeakMap(),
48
72
 
49
73
  _activeServices: {},
@@ -60,6 +84,36 @@ const Services = WebexPlugin.extend({
60
84
  return this._catalogs.get(this.webex);
61
85
  },
62
86
 
87
+ /**
88
+ * Remember a postauth catalog failure caused by HTTP 401 or 403.
89
+ * Other failures clear any previously stored auth failure.
90
+ * @private
91
+ * @param {Error} error
92
+ * @returns {void}
93
+ */
94
+ _recordCatalogAuthFailure(error) {
95
+ recordCatalogAuthFailure(this, error);
96
+ },
97
+
98
+ /**
99
+ * @private
100
+ * @returns {{status: number, reason: string}|null}
101
+ */
102
+ _getCatalogAuthFailure() {
103
+ return getCatalogAuthFailure(this);
104
+ },
105
+
106
+ /**
107
+ * Build the rejection for a service that could not be resolved.
108
+ * A stored catalog auth failure replaces the generic not-found text.
109
+ * @private
110
+ * @param {string} fallbackMessage
111
+ * @returns {Error}
112
+ */
113
+ _serviceLookupError(fallbackMessage: string) {
114
+ return serviceLookupError(this, fallbackMessage);
115
+ },
116
+
63
117
  /**
64
118
  * Safely access localStorage if available; returns the Storage or null.
65
119
  * @returns {Storage | null}
@@ -200,13 +254,23 @@ const Services = WebexPlugin.extend({
200
254
  },
201
255
 
202
256
  /**
203
- * Checks if the current environment is an integration (INT) environment
204
- * by examining the u2c discovery URL from webex config.
257
+ * Checks if the current environment is an integration (INT) environment.
258
+ * Uses the explicit environment config when set, otherwise examines the u2c discovery URL.
205
259
  * INT environments use discovery URLs containing 'intb' (e.g., u2c-intb.ciscospark.com).
206
260
  * @returns {boolean} True if INT environment, false otherwise
207
261
  */
208
262
  isIntegrationEnvironment(): boolean {
209
263
  try {
264
+ const configuredEnvironment = this.webex?.config?.environment;
265
+
266
+ if (configuredEnvironment !== undefined) {
267
+ const isIntFromConfig = configuredEnvironment === 'integration';
268
+
269
+ this.logger.info(`services: isIntegrationEnvironment: ${isIntFromConfig} (config)`);
270
+
271
+ return isIntFromConfig;
272
+ }
273
+
210
274
  const u2cUrl = this.webex?.config?.services?.discovery?.u2c || '';
211
275
  const isInt = u2cUrl.includes('intb');
212
276
 
@@ -329,10 +393,20 @@ const Services = WebexPlugin.extend({
329
393
  this._cacheCatalog(serviceGroup, serviceHostMap, selectionMeta);
330
394
  this.updateCredentialsConfig();
331
395
  catalog.status[serviceGroup].collecting = false;
396
+
397
+ // A successful postauth catalog replaces any remembered 401/403.
398
+ // Preauth and signin updates leave that marker alone.
399
+ if (serviceGroup === 'postauth') {
400
+ clearCatalogAuthFailure(this);
401
+ }
332
402
  })
333
403
  .catch((error) => {
334
404
  catalog.status[serviceGroup].collecting = false;
335
405
 
406
+ if (serviceGroup === 'postauth') {
407
+ this._recordCatalogAuthFailure(error);
408
+ }
409
+
336
410
  return Promise.reject(error);
337
411
  });
338
412
  },
@@ -814,7 +888,7 @@ const Services = WebexPlugin.extend({
814
888
  });
815
889
 
816
890
  return Promise.reject(
817
- new Error(`services: service '${name}' was not found in any of the catalogs`)
891
+ this._serviceLookupError(`services: service '${name}' was not found in any of the catalogs`)
818
892
  );
819
893
  }
820
894
 
@@ -837,7 +911,7 @@ const Services = WebexPlugin.extend({
837
911
  this.webex.internal.metrics.submitClientMetrics(METRICS.JS_SDK_SERVICE_NOT_FOUND, {
838
912
  fields: {service_name: name},
839
913
  });
840
- reject(new Error(`services: service '${name}' was not found after waiting`));
914
+ reject(this._serviceLookupError(`services: service '${name}' was not found after waiting`));
841
915
  });
842
916
  });
843
917
  },
@@ -972,7 +1046,9 @@ const Services = WebexPlugin.extend({
972
1046
 
973
1047
  const priorityUrl = service.get();
974
1048
  const defaultUrl = new URL(
975
- service.serviceUrls.find((serviceUrl) => url.startsWith(serviceUrl.baseUrl)).baseUrl
1049
+ service.serviceUrls.find((serviceUrl: ServiceUrl) =>
1050
+ matchesCatalogUrl(url, serviceUrl.baseUrl)
1051
+ ).baseUrl
976
1052
  ).href;
977
1053
 
978
1054
  return {
@@ -1219,7 +1295,11 @@ const Services = WebexPlugin.extend({
1219
1295
  ): Promise<object> {
1220
1296
  const service = 'u2c';
1221
1297
  const resource = from ? `/${from}/catalog` : '/catalog';
1222
- const qs = {...(query || {}), format: 'U2CV2'};
1298
+ const qs = {
1299
+ ...(query || {}),
1300
+ format: 'U2CV2',
1301
+ ...(this.webex.config?.services?.useCatalogOverride && {useCatalogOverride: true}),
1302
+ };
1223
1303
 
1224
1304
  if (forceRefresh) {
1225
1305
  qs.timestamp = new Date().getTime();
@@ -1237,9 +1317,16 @@ const Services = WebexPlugin.extend({
1237
1317
  requestObject.headers = {authorization: token};
1238
1318
  }
1239
1319
 
1240
- return this.webex.internal.newMetrics.callDiagnosticLatencies
1241
- .measureLatency(() => this.request(requestObject), 'internal.get.u2c.time')
1242
- .then(({body}) => this._formatReceivedHostmap(body || {}));
1320
+ const sendRequest = () => this.request(requestObject);
1321
+
1322
+ const responsePromise = this.webex.internal.newMetrics
1323
+ ? this.webex.internal.newMetrics.callDiagnosticLatencies.measureLatency(
1324
+ sendRequest,
1325
+ 'internal.get.u2c.time'
1326
+ )
1327
+ : sendRequest();
1328
+
1329
+ return responsePromise.then(({body}) => this._formatReceivedHostmap(body || {}));
1243
1330
  },
1244
1331
 
1245
1332
  /**
@@ -1255,7 +1342,10 @@ const Services = WebexPlugin.extend({
1255
1342
  // Validate that the services configuration exists.
1256
1343
  if (services) {
1257
1344
  if (fedramp) {
1258
- services.discovery = fedRampServices;
1345
+ services.discovery = {
1346
+ ...fedRampServices,
1347
+ u2c: services.discovery?.u2c || fedRampServices.u2c,
1348
+ };
1259
1349
  }
1260
1350
  // Check for discovery services.
1261
1351
  if (services.discovery) {
@@ -1312,6 +1402,7 @@ const Services = WebexPlugin.extend({
1312
1402
 
1313
1403
  // Destructure the credentials plugin.
1314
1404
  const {credentials} = this.webex;
1405
+ const catalog = this._getCatalog();
1315
1406
 
1316
1407
  // Init a promise chain. Must be done as a Promise.resolve() to allow
1317
1408
  // credentials#getOrgId() to properly throw.
@@ -1324,11 +1415,18 @@ const Services = WebexPlugin.extend({
1324
1415
  .then(() => {
1325
1416
  // Validate if the token is authorized.
1326
1417
  if (credentials.canAuthorize) {
1327
- // Attempt to collect the postauth catalog.
1328
- return this.updateServices({forceRefresh: refresh}).catch(() => {
1329
- this.initFailed = true;
1330
- this.logger.warn('services: cannot retrieve postauth catalog');
1331
- });
1418
+ // Attempt to collect the postauth catalog, then mark the catalog
1419
+ // ready. Setting `isReady` here - rather than only in the init
1420
+ // callers - means a slow postauth fetch that loses the gated-init
1421
+ // timeout race still marks the catalog ready once it completes.
1422
+ return this.updateServices({forceRefresh: refresh})
1423
+ .then(() => {
1424
+ catalog.isReady = true;
1425
+ })
1426
+ .catch(() => {
1427
+ this.initFailed = true;
1428
+ this.logger.warn('services: cannot retrieve postauth catalog');
1429
+ });
1332
1430
  }
1333
1431
 
1334
1432
  // Return a resolved promise for consistent return value.
@@ -1337,6 +1435,51 @@ const Services = WebexPlugin.extend({
1337
1435
  );
1338
1436
  },
1339
1437
 
1438
+ /**
1439
+ * Await any in-flight credentials refresh, then flip `services.ready` so
1440
+ * `webex.ready` can fire. Closes the parallel-refresh window: if a credential
1441
+ * refresh is in flight when initial catalog collection settles, we must not
1442
+ * signal ready until the refresh has resolved - otherwise downstream
1443
+ * consumers may observe `canAuthorize`/token state that is about to change
1444
+ * under them.
1445
+ *
1446
+ * @private
1447
+ * @returns {Promise<void>}
1448
+ */
1449
+ async _finalizeReady(): Promise<void> {
1450
+ const {credentials} = this.webex;
1451
+
1452
+ if (credentials && credentials.isRefreshing) {
1453
+ await new Promise<void>((resolve) => {
1454
+ credentials.once('change:isRefreshing', resolve);
1455
+ });
1456
+ }
1457
+
1458
+ this.ready = true;
1459
+ },
1460
+
1461
+ /**
1462
+ * Build a promise that rejects once the catalog init timeout elapses. Race
1463
+ * this against catalog collection so a hung request never leaves
1464
+ * `services.ready` false forever - that would stall `webex.ready` and leave
1465
+ * consumers waiting on it indefinitely. Timeout is configurable via
1466
+ * `config.services.catalogInitTimeout` (defaults to 15s in config). Created
1467
+ * lazily so paths that skip catalog collection never schedule a stray timer.
1468
+ *
1469
+ * @private
1470
+ * @returns {Promise<never>}
1471
+ */
1472
+ _makeInitTimeout(): Promise<never> {
1473
+ const initTimeoutMs = this.webex.config?.services?.catalogInitTimeout;
1474
+
1475
+ return new Promise<never>((_, reject) => {
1476
+ setTimeout(
1477
+ () => reject(new Error(`services: init timed out after ${initTimeoutMs}ms`)),
1478
+ initTimeoutMs
1479
+ );
1480
+ });
1481
+ },
1482
+
1340
1483
  /**
1341
1484
  * Initializer
1342
1485
  *
@@ -1348,11 +1491,39 @@ const Services = WebexPlugin.extend({
1348
1491
  const catalog = new ServiceCatalog();
1349
1492
  this._catalogs.set(this.webex, catalog);
1350
1493
 
1351
- // Listen for configuration changes once.
1494
+ // Listen for configuration changes once. The config is not populated on the
1495
+ // webex instance until the `change:config` event fires, so any decision that
1496
+ // depends on config values (such as the gated-vs-ungated init below) must be
1497
+ // made from within this handler rather than synchronously in `initialize()`.
1352
1498
  this.listenToOnce(this.webex, 'change:config', () => {
1353
1499
  this.initConfig();
1500
+
1501
+ // Feature flag: when enabled, `webex.ready` is blocked until the initial
1502
+ // catalog collection has settled AND any in-flight credentials refresh has
1503
+ // completed. When disabled (the default), preserves the pre-existing
1504
+ // behavior where `webex.ready` fires as soon as `webex.loaded` does and
1505
+ // the catalog is collected out-of-band.
1506
+ const waitForCatalogInit = this.webex.config?.services?.waitForCatalogInit === true;
1507
+
1508
+ if (waitForCatalogInit) {
1509
+ this._initializeCatalogsGated(catalog);
1510
+ } else {
1511
+ // Not gating - immediately mark ready so we do not block webex.ready.
1512
+ this.ready = true;
1513
+ this._initializeCatalogsUngated(catalog);
1514
+ }
1354
1515
  });
1516
+ },
1355
1517
 
1518
+ /**
1519
+ * Original (pre-verified-ready) initialization path. Runs on `webex.ready`
1520
+ * and collects catalogs opportunistically without blocking anything.
1521
+ *
1522
+ * @private
1523
+ * @param {ServiceCatalog} catalog
1524
+ * @returns {void}
1525
+ */
1526
+ _initializeCatalogsUngated(catalog: ServiceCatalog): void {
1356
1527
  // wait for webex instance to be ready before attempting
1357
1528
  // to update the service catalogs
1358
1529
  this.listenToOnce(this.webex, 'ready', async () => {
@@ -1365,19 +1536,25 @@ const Services = WebexPlugin.extend({
1365
1536
  const {supertoken} = this.webex.credentials;
1366
1537
  // Validate if the supertoken exists.
1367
1538
  if (supertoken && supertoken.access_token) {
1368
- this.initServiceCatalogs()
1369
- .then(() => {
1370
- catalog.isReady = true;
1371
- })
1372
- .catch((error) => {
1373
- this.initFailed = true;
1374
- this.logger.error(
1375
- `services: failed to init initial services when credentials available, ${error?.message}`
1376
- );
1377
- });
1539
+ // `initServiceCatalogs` marks the catalog ready internally once the
1540
+ // postauth catalog is collected.
1541
+ this.initServiceCatalogs().catch((error) => {
1542
+ this.initFailed = true;
1543
+ this.logger.error(
1544
+ `services: failed to init initial services when credentials available, ${error?.message}`
1545
+ );
1546
+ });
1378
1547
  } else {
1379
1548
  const {email} = this.webex.config;
1380
1549
 
1550
+ if (this.webex.config?.services?.skipPreauthCatalogOnUnauthenticated === true) {
1551
+ this.logger.info(
1552
+ 'services: skipping preauth catalog collection while unauthenticated as per the config'
1553
+ );
1554
+
1555
+ return;
1556
+ }
1557
+
1381
1558
  this.collectPreauthCatalog(email ? {email} : undefined).catch((error) => {
1382
1559
  this.initFailed = true;
1383
1560
  this.logger.error(
@@ -1387,6 +1564,85 @@ const Services = WebexPlugin.extend({
1387
1564
  }
1388
1565
  });
1389
1566
  },
1567
+
1568
+ /**
1569
+ * Verified-ready initialization path. Blocks `webex.ready` until the initial
1570
+ * catalog fetch has settled (or timed out) AND any in-flight credentials
1571
+ * refresh has completed. Also handles the fresh-login case where OAuth
1572
+ * completes after `loaded` fires.
1573
+ *
1574
+ * @private
1575
+ * @param {ServiceCatalog} catalog
1576
+ * @returns {void}
1577
+ */
1578
+ _initializeCatalogsGated(catalog: ServiceCatalog): void {
1579
+ // Wait for storage to be loaded before attempting to update the service
1580
+ // catalogs. We listen for 'loaded' instead of 'ready' because `services.ready`
1581
+ // now blocks `webex.ready` - listening to 'ready' would deadlock.
1582
+ this.listenToOnce(this.webex, 'loaded', async () => {
1583
+ const warmed = await this._loadCatalogFromCache();
1584
+ if (warmed) {
1585
+ catalog.isReady = true;
1586
+ await this._finalizeReady();
1587
+
1588
+ return;
1589
+ }
1590
+ const {supertoken} = this.webex.credentials;
1591
+
1592
+ // Validate if the supertoken exists.
1593
+ if (supertoken && supertoken.access_token) {
1594
+ // `initServiceCatalogs` marks the catalog ready internally once the
1595
+ // postauth catalog is collected - even if it loses the timeout race
1596
+ // below, so a slow fetch still eventually flips `catalog.isReady`.
1597
+ Promise.race([this.initServiceCatalogs(), this._makeInitTimeout()])
1598
+ .catch((error) => {
1599
+ this.initFailed = true;
1600
+ this.logger.error(
1601
+ `services: failed to init initial services when credentials available, ${error?.message}`
1602
+ );
1603
+ })
1604
+ .finally(() => this._finalizeReady());
1605
+ } else {
1606
+ const {email} = this.webex.config;
1607
+
1608
+ // Handle fresh login: 'loaded' fires before OAuth completes, so listen
1609
+ // for `canAuthorize` flipping true and then collect the postauth catalog.
1610
+ this.listenToOnce(this.webex, 'change:canAuthorize', () => {
1611
+ if (this.webex.canAuthorize && !catalog.status.postauth.ready) {
1612
+ // `initServiceCatalogs` marks the catalog ready internally.
1613
+ this.initServiceCatalogs().catch((error) => {
1614
+ this.logger.error(
1615
+ `services: failed to init service catalogs after auth, ${error?.message}`
1616
+ );
1617
+ });
1618
+ }
1619
+ });
1620
+
1621
+ if (this.webex.config?.services?.skipPreauthCatalogOnUnauthenticated === true) {
1622
+ // Skip the preauth catalog fetch (it will be collected manually
1623
+ // later), but still finalize `services.ready` so `webex.ready` is not
1624
+ // stalled while unauthenticated. No timeout is created here so there
1625
+ // is no stray timer or unhandled rejection.
1626
+ this.logger.info(
1627
+ 'services: skipping preauth catalog collection while unauthenticated as per the config'
1628
+ );
1629
+ this._finalizeReady();
1630
+ } else {
1631
+ Promise.race([
1632
+ this.collectPreauthCatalog(email ? {email} : undefined),
1633
+ this._makeInitTimeout(),
1634
+ ])
1635
+ .catch((error) => {
1636
+ this.initFailed = true;
1637
+ this.logger.error(
1638
+ `services: failed to init initial services when no credentials available, ${error?.message}`
1639
+ );
1640
+ })
1641
+ .finally(() => this._finalizeReady());
1642
+ }
1643
+ }
1644
+ });
1645
+ },
1390
1646
  });
1391
1647
  /* eslint-enable no-underscore-dangle */
1392
1648
 
@@ -0,0 +1,128 @@
1
+ /*!
2
+ * Copyright (c) 2015-2026 Cisco Systems, Inc. See LICENSE file.
3
+ */
4
+
5
+ // @ts-ignore
6
+ import StatelessWebexPlugin from './stateless-webex-plugin';
7
+
8
+ /**
9
+ * Detects an HTML document prefix in an otherwise successful binary asset response.
10
+ * @param {ArrayBuffer} buffer
11
+ * @returns {boolean}
12
+ */
13
+ function looksLikeHtmlDocument(buffer: ArrayBuffer): boolean {
14
+ const prefix = new TextDecoder().decode(buffer.slice(0, 256)).trimStart();
15
+
16
+ return prefix.startsWith('<');
17
+ }
18
+
19
+ /**
20
+ * Resolves and downloads static assets for SDK plugins. Requests are shared between callers and
21
+ * cached after a successful response.
22
+ *
23
+ * IMPORTANT: When adding assets, ensure that their names are unique and versioned to avoid caching issues.
24
+ * Example: 'e2ee-0.0.1.wasm' instead of 'e2ee.wasm'
25
+ * or use content-based hashing in the filename to ensure uniqueness.
26
+ */
27
+ export default class StaticAssetLoader extends StatelessWebexPlugin {
28
+ private readonly baseUrl: string;
29
+
30
+ private readonly assets = new Map<string, Promise<ArrayBuffer>>();
31
+
32
+ /**
33
+ * @param {Object} attrs
34
+ * @param {string} attrs.baseUrl - Base URL for the plugin's static assets.
35
+ * @param {Object} options
36
+ * @param {Object} [options.parent] - The parent Webex SDK instance.
37
+ */
38
+ constructor(attrs: {baseUrl: string}, options: {parent?: any} = {}) {
39
+ super(attrs, options);
40
+ this.baseUrl = attrs.baseUrl.replace(/\/+$/, ''); // remove trailing slashes
41
+ }
42
+
43
+ /**
44
+ * Returns the URL for an asset in the configured asset directory.
45
+ * @param {string} assetName
46
+ * @returns {string}
47
+ */
48
+ getUrl(assetName: string): string {
49
+ return `${this.baseUrl}/${assetName.replace(/^\/+/, '')}`; // regex removes leading slashes from the asset name
50
+ }
51
+
52
+ /**
53
+ * Downloads an asset as bytes. Failed requests are evicted so a later call can retry.
54
+ * @param {string} assetName
55
+ * @returns {Promise<Uint8Array>}
56
+ */
57
+ async getBytes(assetName: string): Promise<Uint8Array> {
58
+ const url = this.getUrl(assetName);
59
+ let asset = this.assets.get(url);
60
+
61
+ if (!asset) {
62
+ // @ts-ignore - StatelessWebexPlugin exposes request from the parent Webex instance.
63
+ asset = this.request({
64
+ method: 'GET',
65
+ uri: url,
66
+ responseType: 'buffer',
67
+ // Assets may be hosted on a third-party CDN: never send the user's token, and suppress
68
+ // the SDK's custom headers so the request doesn't trigger a CORS preflight.
69
+ addAuthHeader: false,
70
+ headers: {
71
+ trackingid: null,
72
+ 'spark-user-agent': null,
73
+ 'cisco-no-http-redirect': null,
74
+ },
75
+ })
76
+ .then((response: any) => {
77
+ if (response.statusCode < 200 || response.statusCode >= 300) {
78
+ throw new Error(`Failed to fetch static asset ${url}: HTTP ${response.statusCode}`);
79
+ }
80
+
81
+ const contentType = response.headers?.['content-type']
82
+ ?.split(';')[0]
83
+ .trim()
84
+ .toLowerCase();
85
+
86
+ if (contentType === 'text/html' || contentType === 'application/xhtml+xml') {
87
+ throw new Error(
88
+ `Failed to fetch static asset ${url}: unexpected HTML content type "${contentType}"`
89
+ );
90
+ }
91
+
92
+ const responseBody = response.body;
93
+ let buffer: ArrayBuffer;
94
+
95
+ if (responseBody instanceof ArrayBuffer) {
96
+ buffer = responseBody;
97
+ } else if (ArrayBuffer.isView(responseBody)) {
98
+ buffer = responseBody.buffer.slice(
99
+ responseBody.byteOffset,
100
+ responseBody.byteOffset + responseBody.byteLength
101
+ ) as ArrayBuffer;
102
+ } else {
103
+ throw new Error(
104
+ `Failed to fetch static asset ${url}: response body is not binary data`
105
+ );
106
+ }
107
+
108
+ // Some static servers return an HTML fallback page with a successful status and a
109
+ // generic binary content type. Reject it before callers pass those bytes to modules
110
+ // that expect binary data, such as WASM.
111
+ if (looksLikeHtmlDocument(buffer)) {
112
+ throw new Error(
113
+ `Failed to fetch static asset ${url}: response body looks like an HTML document`
114
+ );
115
+ }
116
+
117
+ return buffer;
118
+ })
119
+ .catch((error: Error) => {
120
+ this.assets.delete(url);
121
+ throw error;
122
+ });
123
+ this.assets.set(url, asset);
124
+ }
125
+
126
+ return new Uint8Array((await asset).slice(0));
127
+ }
128
+ }