@webex/plugin-authorization-browser-first-party 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.
@@ -1,4 +1,4 @@
1
- // @ts-nocheck
1
+ // @ts-nocheck
2
2
  /* eslint-disable */
3
3
  /*!
4
4
  * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.
@@ -14,16 +14,13 @@ import querystring from 'querystring';
14
14
  import url from 'url';
15
15
  import {EventEmitter} from 'events';
16
16
 
17
- import {base64, oneFlight, whileInFlight} from '@webex/common';
17
+ import {decodeState, encodeState, oneFlight, whileInFlight} from '@webex/common';
18
18
  import {grantErrors, WebexPlugin} from '@webex/webex-core';
19
- import {cloneDeep, isEmpty, omit} from 'lodash';
19
+ import {cloneDeep, isEmpty, omit, isObject} from 'lodash';
20
20
  import uuid from 'uuid';
21
21
  import base64url from 'crypto-js/enc-base64url';
22
22
  import CryptoJS from 'crypto-js';
23
-
24
- // Necessary to require lodash this way in order to stub
25
- // methods in the unit test
26
- const lodash = require('lodash');
23
+ import {getClientAuthenticationOptions} from './config';
27
24
 
28
25
  const OAUTH2_CSRF_TOKEN = 'oauth2-csrf-token';
29
26
  const OAUTH2_CODE_VERIFIER = 'oauth2-code-verifier';
@@ -39,6 +36,18 @@ export const Events = {
39
36
  qRCodeLogin: 'qRCodeLogin',
40
37
  };
41
38
 
39
+ /**
40
+ * Terminal outcomes for the automatic authorization-code exchange performed
41
+ * during authorization plugin initialization.
42
+ *
43
+ * @enum {string}
44
+ */
45
+ export const InitialAuthorizationCodeGrantOutcomes = {
46
+ failure: 'failure',
47
+ notAttempted: 'not_attempted',
48
+ success: 'success',
49
+ };
50
+
42
51
  /**
43
52
  * Browser support for OAuth2 for first-party (Webex Web Client) usage.
44
53
  *
@@ -69,6 +78,37 @@ export const Events = {
69
78
  */
70
79
  const Authorization = WebexPlugin.extend({
71
80
  derived: {
81
+ /**
82
+ * Retains the terminal outcome of the automatic authorization-code exchange
83
+ * performed during this authorization plugin instance's initialization.
84
+ *
85
+ * This historical value does not represent current authorization state,
86
+ * credentials hydrated from storage, guest authentication, or
87
+ * authorization-code exchanges requested later on the same SDK instance. It
88
+ * is not reset by logout. OAuth redirect errors and CSRF validation failures
89
+ * occur before the exchange, so the value remains not_attempted; these errors
90
+ * can throw before ready becomes true.
91
+ *
92
+ * Calling logout({noRedirect: true}) does not cancel an initialization
93
+ * exchange already in flight. If that exchange later settles, it can still
94
+ * update credentials and this retained outcome.
95
+ *
96
+ * Interpret only after authorization readiness:
97
+ * - not_attempted: initialization did not invoke requestAuthorizationCodeGrant()
98
+ * - success: the initialization exchange fulfilled
99
+ * - failure: the initialization exchange threw or rejected
100
+ *
101
+ * @instance
102
+ * @memberof AuthorizationBrowserFirstParty
103
+ * @readonly
104
+ * @type {string}
105
+ */
106
+ initialAuthorizationCodeGrantOutcome: {
107
+ deps: ['_initialAuthorizationCodeGrantOutcome'],
108
+ fn() {
109
+ return this._initialAuthorizationCodeGrantOutcome;
110
+ },
111
+ },
72
112
  /**
73
113
  * Alias of {@link AuthorizationBrowserFirstParty#isAuthorizing}
74
114
  * @instance
@@ -94,6 +134,14 @@ const Authorization = WebexPlugin.extend({
94
134
  default: false,
95
135
  type: 'boolean',
96
136
  },
137
+ /**
138
+ * Internal backing state for the initial authorization-code grant outcome.
139
+ * @private
140
+ */
141
+ _initialAuthorizationCodeGrantOutcome: {
142
+ default: InitialAuthorizationCodeGrantOutcomes.notAttempted,
143
+ type: 'string',
144
+ },
97
145
  /**
98
146
  * Indicates that the plugin has finished any automatic startup
99
147
  * processing (e.g., exchanging a returned authorization code)
@@ -199,7 +247,7 @@ const Authorization = WebexPlugin.extend({
199
247
 
200
248
  // Decode and parse state object (if present)
201
249
  if (location.query.state) {
202
- location.query.state = JSON.parse(base64.decode(location.query.state));
250
+ location.query.state = decodeState(location.query.state);
203
251
  } else {
204
252
  location.query.state = {};
205
253
  }
@@ -233,7 +281,13 @@ const Authorization = WebexPlugin.extend({
233
281
  .collectPreauthCatalog(preauthCatalogParams)
234
282
  .catch(() => Promise.resolve()) // Non-fatal if catalog collection fails
235
283
  .then(() => this.requestAuthorizationCodeGrant({code, codeVerifier}))
284
+ .then(() => {
285
+ this._initialAuthorizationCodeGrantOutcome =
286
+ InitialAuthorizationCodeGrantOutcomes.success;
287
+ })
236
288
  .catch((error) => {
289
+ this._initialAuthorizationCodeGrantOutcome =
290
+ InitialAuthorizationCodeGrantOutcomes.failure;
237
291
  this.logger.warn('authorization: failed initial authorization code grant request', error);
238
292
  })
239
293
  .then(() => {
@@ -267,7 +321,7 @@ const Authorization = WebexPlugin.extend({
267
321
  eventType: 'initiateLogin',
268
322
  data: {
269
323
  hasEmail: !!options.email,
270
- hasState: !!options.state
324
+ hasState: !!options.state,
271
325
  },
272
326
  });
273
327
 
@@ -316,7 +370,7 @@ const Authorization = WebexPlugin.extend({
316
370
 
317
371
  this.eventEmitter.emit(Events.login, {
318
372
  eventType: 'redirectToLoginUrl',
319
- data: { loginUrl },
373
+ data: {loginUrl},
320
374
  });
321
375
 
322
376
  if (options?.separateWindow) {
@@ -343,6 +397,97 @@ const Authorization = WebexPlugin.extend({
343
397
  return Promise.resolve();
344
398
  },
345
399
 
400
+ /**
401
+ * Initiates third-party (social provider) login. Generates a CSRF token,
402
+ * embeds it in `options.state.csrf_token`, and delegates to
403
+ * `initiateThirdPartyLoginRedirect` for navigation.
404
+ *
405
+ * @instance
406
+ * @memberof AuthorizationBrowserFirstParty
407
+ * @param {Object} options
408
+ * @param {string} options.oauth2provider
409
+ * @param {string} options.returnURL
410
+ * @param {Object} [options.state] - Caller-supplied state object. Merged
411
+ * with the generated `csrf_token`.
412
+ * @returns {Promise<void>}
413
+ */
414
+ initiateThirdPartyLogin(options = {}) {
415
+ options = cloneDeep(options);
416
+ if (options.state !== undefined && !isObject(options.state)) {
417
+ throw new Error('if specified, `options.state` must be an object');
418
+ }
419
+ options.state = options.state || {};
420
+ options.state.csrf_token = this._generateSecurityToken();
421
+
422
+ return this.initiateThirdPartyLoginRedirect(options);
423
+ },
424
+
425
+ /**
426
+ * Performs the navigation step of the third-party login flow. Builds the
427
+ * IdBroker URL via `Credentials#buildThirdPartyLoginUrl` and assigns it
428
+ * to `getWindow().location`.
429
+ *
430
+ * Mirrors `initiateAuthorizationCodeGrant` for the `/authorize` flow.
431
+ * Consumers may override this method for custom navigation handling
432
+ * (e.g. postMessage in iframed contexts).
433
+ *
434
+ * @instance
435
+ * @memberof AuthorizationBrowserFirstParty
436
+ * @param {Object} options
437
+ * @param {string} options.oauth2provider
438
+ * @param {string} options.returnURL
439
+ * @returns {Promise<void>}
440
+ */
441
+ initiateThirdPartyLoginRedirect(options = {}) {
442
+ this.logger.info('authorization: initiating third-party login redirect');
443
+
444
+ try {
445
+ const url = this.webex.credentials.buildThirdPartyLoginUrl(options);
446
+
447
+ this.webex.getWindow().location = url;
448
+ } catch (err) {
449
+ return Promise.reject(err);
450
+ }
451
+
452
+ return Promise.resolve();
453
+ },
454
+
455
+ /**
456
+ * Handles the third-party (social provider) login callback. Reads the
457
+ * current `window.location`, decodes `state`, validates the CSRF token
458
+ * (`state.csrf_token`), scrubs sensitive parameters from the URL via
459
+ * `_cleanUrl`, and returns the parsed payload.
460
+ *
461
+ * Mirrors `initialize()` in always operating on the live
462
+ * `window.location`
463
+ *
464
+ * `idToken` is single-use: it is parsed out of the URL exactly once and
465
+ * the calling client is expected to exchange it (or discard it)
466
+ * immediately. The returned `state` has `csrf_token` removed.
467
+ *
468
+ * @instance
469
+ * @memberof AuthorizationBrowserFirstParty
470
+ * @returns {{idToken: string|undefined, email: string|undefined,
471
+ * error: string|undefined, state: Object}}
472
+ */
473
+ handleThirdPartyCallback() {
474
+ const location = url.parse(this.webex.getWindow().location.href, true);
475
+
476
+ location.query.state = decodeState(location.query.state || 'e30');
477
+
478
+ this._verifySecurityToken(location.query);
479
+ this._cleanUrl(location);
480
+
481
+ const {
482
+ id_token: idToken,
483
+ email,
484
+ error,
485
+ state: {csrf_token, ...state},
486
+ } = location.query;
487
+
488
+ return {idToken, email, error, state};
489
+ },
490
+
346
491
  /**
347
492
  * Called by {@link WebexCore#logout()}.
348
493
  * Constructs logout URL and (unless suppressed) navigates away to ensure
@@ -400,16 +545,16 @@ const Authorization = WebexPlugin.extend({
400
545
  form.code_verifier = options.codeVerifier;
401
546
  }
402
547
 
548
+ const {form: clientForm = {}, ...clientAuthentication} = getClientAuthenticationOptions(
549
+ this.config
550
+ );
551
+
403
552
  return this.webex
404
553
  .request({
405
554
  method: 'POST',
406
555
  uri: this.config.tokenUrl,
407
- form,
408
- auth: {
409
- user: this.config.client_id,
410
- pass: this.config.client_secret,
411
- sendImmediately: true,
412
- },
556
+ form: {...form, ...clientForm},
557
+ ...clientAuthentication,
413
558
  shouldRefreshAccessToken: false, // This is the token acquisition call itself
414
559
  })
415
560
  .then((res) => {
@@ -497,10 +642,11 @@ const Authorization = WebexPlugin.extend({
497
642
  })
498
643
  .then((res) => {
499
644
  const {user_code, verification_uri, verification_uri_complete} = res.body;
500
- const verificationUriComplete = this._generateQRCodeVerificationUrl(verification_uri_complete);
645
+ const verificationUriComplete =
646
+ this._generateQRCodeVerificationUrl(verification_uri_complete);
501
647
  this.eventEmitter.emit(Events.qRCodeLogin, {
502
648
  eventType: 'getUserCodeSuccess',
503
- userData: {
649
+ userData: {
504
650
  userCode: user_code,
505
651
  verificationUri: verification_uri,
506
652
  verificationUriComplete,
@@ -591,7 +737,7 @@ const Authorization = WebexPlugin.extend({
591
737
  // If polling canceled (id changed), ignore this response
592
738
  if (this.currentPollingId !== this.pollingId) return;
593
739
 
594
- this.eventEmitter.emit(Events.qRCodeLogin, {
740
+ this.eventEmitter.emit(Events.qRCodeLogin, {
595
741
  eventType: 'authorizationSuccess',
596
742
  data: res.body,
597
743
  });
@@ -703,8 +849,9 @@ const Authorization = WebexPlugin.extend({
703
849
  * - HTTP referrer headers to third-party content
704
850
  *
705
851
  * Approach:
706
- * - Remove 'code'.
707
- * - Remove 'state' entirely if only contained csrf_token.
852
+ * - Remove 'code' (OAuth code-grant), 'id_token', and 'email'
853
+ * (third-party callback).
854
+ * - Remove 'state' entirely if it only contained csrf_token.
708
855
  * - Else, re-encode remaining state fields (minus csrf_token).
709
856
  * - Replace current history entry (no page reload).
710
857
  *
@@ -718,12 +865,12 @@ const Authorization = WebexPlugin.extend({
718
865
  location = cloneDeep(location);
719
866
  if (this.webex.getWindow().history && this.webex.getWindow().history.replaceState) {
720
867
  Reflect.deleteProperty(location.query, 'code');
868
+ Reflect.deleteProperty(location.query, 'id_token');
869
+ Reflect.deleteProperty(location.query, 'email');
721
870
  if (isEmpty(omit(location.query.state, 'csrf_token'))) {
722
871
  Reflect.deleteProperty(location.query, 'state');
723
872
  } else {
724
- location.query.state = base64.encode(
725
- JSON.stringify(omit(location.query.state, 'csrf_token'))
726
- );
873
+ location.query.state = encodeState(omit(location.query.state, 'csrf_token'));
727
874
  }
728
875
  location.search = querystring.stringify(location.query);
729
876
  Reflect.deleteProperty(location, 'query');
@@ -737,7 +884,8 @@ const Authorization = WebexPlugin.extend({
737
884
  * during authorization code exchange; removes it once consumed.
738
885
  *
739
886
  * Implementation details:
740
- * - Creates a 128 character string using base64url safe alphabet.
887
+ * - Creates a 128 character string using a cryptographically secure random
888
+ * source and the base64url safe alphabet.
741
889
  * - Computes SHA256 hash, encodes to base64url (no padding).
742
890
  *
743
891
  * @instance
@@ -750,10 +898,14 @@ const Authorization = WebexPlugin.extend({
750
898
 
751
899
  // eslint-disable-next-line no-underscore-dangle
752
900
  const safeCharacterMap = base64url._safe_map;
901
+ const randomValues = new Uint8Array(128);
902
+
903
+ this.webex.getWindow().crypto.getRandomValues(randomValues);
753
904
 
754
- const codeVerifier = lodash
755
- .times(128, () => safeCharacterMap[lodash.random(0, safeCharacterMap.length - 1)])
756
- .join('');
905
+ const codeVerifier = Array.from(
906
+ randomValues,
907
+ (randomValue) => safeCharacterMap[randomValue & (safeCharacterMap.length - 1)]
908
+ ).join('');
757
909
 
758
910
  const codeChallenge = CryptoJS.SHA256(codeVerifier).toString(base64url);
759
911
 
@@ -792,7 +944,7 @@ const Authorization = WebexPlugin.extend({
792
944
  * - Ensure state + state.csrf_token exist.
793
945
  * - Compare values; throw descriptive errors on mismatch / absence.
794
946
  *
795
- * If no stored token (e.g., user navigated directly), silently returns.
947
+ * If no stored token exists, treats the callback as a CSRF failure.
796
948
  *
797
949
  * @instance
798
950
  * @memberof AuthorizationBrowserFirstParty
@@ -805,14 +957,10 @@ const Authorization = WebexPlugin.extend({
805
957
 
806
958
  this.webex.getWindow().sessionStorage.removeItem(OAUTH2_CSRF_TOKEN);
807
959
  if (!sessionToken) {
808
- return;
809
- }
810
-
811
- if (!query.state) {
812
- throw new Error(`Expected CSRF token ${sessionToken}, but not found in redirect query`);
960
+ throw new Error('CSRF token missing from session storage');
813
961
  }
814
962
 
815
- if (!query.state.csrf_token) {
963
+ if (!query.state?.csrf_token) {
816
964
  throw new Error(`Expected CSRF token ${sessionToken}, but not found in redirect query`);
817
965
  }
818
966
 
package/src/config.js CHANGED
@@ -2,12 +2,31 @@
2
2
  * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.
3
3
  */
4
4
 
5
+ export const getClientAuthenticationOptions = (config) => {
6
+ if (config.clientType === 'public') {
7
+ return {
8
+ addAuthHeader: false,
9
+ form: {
10
+ client_id: config.client_id,
11
+ },
12
+ };
13
+ }
14
+
15
+ return {
16
+ auth: {
17
+ user: config.client_id,
18
+ pass: config.client_secret,
19
+ sendImmediately: true,
20
+ },
21
+ };
22
+ };
23
+
5
24
  export default {
6
25
  credentials: {
7
26
  /**
8
- * Controls whether {@link Authorization#initiateLogin()} requests a token
9
- * or an auth code. Anything other than 'confidential' will be treated as
10
- * 'public'
27
+ * Controls how the OAuth client authenticates with the token endpoint.
28
+ * Public clients send their client ID in the request form. Confidential
29
+ * clients use HTTP Basic authentication with their client secret.
11
30
  * @private
12
31
  * @type {string}
13
32
  */
@@ -15,6 +34,10 @@ export default {
15
34
 
16
35
  refreshCallback(webex, token) {
17
36
  /* eslint-disable camelcase */
37
+ const {form: clientForm = {}, ...clientAuthentication} = getClientAuthenticationOptions(
38
+ token.config
39
+ );
40
+
18
41
  return webex
19
42
  .request({
20
43
  method: 'POST',
@@ -23,12 +46,9 @@ export default {
23
46
  grant_type: 'refresh_token',
24
47
  redirect_uri: token.config.redirect_uri,
25
48
  refresh_token: token.refresh_token,
49
+ ...clientForm,
26
50
  },
27
- auth: {
28
- user: token.config.client_id,
29
- pass: token.config.client_secret,
30
- sendImmediately: true,
31
- },
51
+ ...clientAuthentication,
32
52
  shouldRefreshAccessToken: false,
33
53
  })
34
54
  .then((res) => res.body);