@okta/okta-auth-js 6.1.0 → 6.3.1

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 (170) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +53 -23
  3. package/cjs/AuthStateManager.js +14 -7
  4. package/cjs/AuthStateManager.js.map +1 -1
  5. package/cjs/OktaAuth.js +30 -14
  6. package/cjs/OktaAuth.js.map +1 -1
  7. package/cjs/OktaUserAgent.js +2 -2
  8. package/cjs/PromiseQueue.js +9 -2
  9. package/cjs/PromiseQueue.js.map +1 -1
  10. package/cjs/ServiceManager.js +195 -0
  11. package/cjs/ServiceManager.js.map +1 -0
  12. package/cjs/TokenManager.js +6 -14
  13. package/cjs/TokenManager.js.map +1 -1
  14. package/cjs/TransactionManager.js +11 -5
  15. package/cjs/TransactionManager.js.map +1 -1
  16. package/cjs/browser/browserStorage.js +31 -25
  17. package/cjs/browser/browserStorage.js.map +1 -1
  18. package/cjs/crypto/node.js +19 -13
  19. package/cjs/crypto/node.js.map +1 -1
  20. package/cjs/idx/authenticator/Authenticator.js.map +1 -1
  21. package/cjs/idx/authenticator/OktaPassword.js +12 -3
  22. package/cjs/idx/authenticator/OktaPassword.js.map +1 -1
  23. package/cjs/idx/authenticator/OktaVerifyTotp.js +9 -1
  24. package/cjs/idx/authenticator/OktaVerifyTotp.js.map +1 -1
  25. package/cjs/idx/authenticator/SecurityQuestionEnrollment.js +14 -1
  26. package/cjs/idx/authenticator/SecurityQuestionEnrollment.js.map +1 -1
  27. package/cjs/idx/authenticator/SecurityQuestionVerification.js +9 -1
  28. package/cjs/idx/authenticator/SecurityQuestionVerification.js.map +1 -1
  29. package/cjs/idx/authenticator/VerificationCodeAuthenticator.js +13 -3
  30. package/cjs/idx/authenticator/VerificationCodeAuthenticator.js.map +1 -1
  31. package/cjs/idx/authenticator/WebauthnEnrollment.js +5 -0
  32. package/cjs/idx/authenticator/WebauthnEnrollment.js.map +1 -1
  33. package/cjs/idx/authenticator/WebauthnVerification.js +5 -0
  34. package/cjs/idx/authenticator/WebauthnVerification.js.map +1 -1
  35. package/cjs/idx/authenticator/util.js +64 -0
  36. package/cjs/idx/authenticator/util.js.map +1 -0
  37. package/cjs/idx/idx-js/index.js +0 -122
  38. package/cjs/idx/idx-js/index.js.map +1 -1
  39. package/cjs/idx/idx-js/introspect.js +10 -6
  40. package/cjs/idx/idx-js/introspect.js.map +1 -1
  41. package/cjs/idx/idx-js/v1/generateIdxAction.js +17 -23
  42. package/cjs/idx/idx-js/v1/generateIdxAction.js.map +1 -1
  43. package/cjs/idx/idx-js/v1/makeIdxState.js +5 -4
  44. package/cjs/idx/idx-js/v1/makeIdxState.js.map +1 -1
  45. package/cjs/idx/introspect.js +13 -3
  46. package/cjs/idx/introspect.js.map +1 -1
  47. package/cjs/idx/proceed.js +14 -11
  48. package/cjs/idx/proceed.js.map +1 -1
  49. package/cjs/idx/remediate.js +68 -77
  50. package/cjs/idx/remediate.js.map +1 -1
  51. package/cjs/idx/remediators/AuthenticatorEnrollmentData.js +6 -2
  52. package/cjs/idx/remediators/AuthenticatorEnrollmentData.js.map +1 -1
  53. package/cjs/idx/remediators/AuthenticatorVerificationData.js +56 -15
  54. package/cjs/idx/remediators/AuthenticatorVerificationData.js.map +1 -1
  55. package/cjs/idx/remediators/Base/AuthenticatorData.js +22 -14
  56. package/cjs/idx/remediators/Base/AuthenticatorData.js.map +1 -1
  57. package/cjs/idx/remediators/Base/Remediator.js +85 -85
  58. package/cjs/idx/remediators/Base/Remediator.js.map +1 -1
  59. package/cjs/idx/remediators/Base/SelectAuthenticator.js +24 -15
  60. package/cjs/idx/remediators/Base/SelectAuthenticator.js.map +1 -1
  61. package/cjs/idx/remediators/Base/VerifyAuthenticator.js +15 -4
  62. package/cjs/idx/remediators/Base/VerifyAuthenticator.js.map +1 -1
  63. package/cjs/idx/remediators/ChallengePoll.js +8 -1
  64. package/cjs/idx/remediators/ChallengePoll.js.map +1 -1
  65. package/cjs/idx/remediators/EnrollPoll.js +1 -1
  66. package/cjs/idx/remediators/EnrollPoll.js.map +1 -1
  67. package/cjs/idx/remediators/EnrollProfile.js +15 -9
  68. package/cjs/idx/remediators/EnrollProfile.js.map +1 -1
  69. package/cjs/idx/remediators/EnrollmentChannelData.js +0 -8
  70. package/cjs/idx/remediators/EnrollmentChannelData.js.map +1 -1
  71. package/cjs/idx/remediators/Identify.js +12 -5
  72. package/cjs/idx/remediators/Identify.js.map +1 -1
  73. package/cjs/idx/remediators/ReEnrollAuthenticator.js +9 -8
  74. package/cjs/idx/remediators/ReEnrollAuthenticator.js.map +1 -1
  75. package/cjs/idx/remediators/SelectAuthenticatorAuthenticate.js +4 -3
  76. package/cjs/idx/remediators/SelectAuthenticatorAuthenticate.js.map +1 -1
  77. package/cjs/idx/remediators/SelectAuthenticatorUnlockAccount.js +0 -1
  78. package/cjs/idx/remediators/SelectAuthenticatorUnlockAccount.js.map +1 -1
  79. package/cjs/idx/remediators/Skip.js +1 -8
  80. package/cjs/idx/remediators/Skip.js.map +1 -1
  81. package/cjs/idx/remediators/util.js.map +1 -1
  82. package/cjs/idx/run.js +270 -195
  83. package/cjs/idx/run.js.map +1 -1
  84. package/cjs/idx/types/idx-js.js.map +1 -1
  85. package/cjs/idx/types/index.js +37 -0
  86. package/cjs/idx/types/index.js.map +1 -1
  87. package/cjs/idx/util.js +198 -0
  88. package/cjs/idx/util.js.map +1 -0
  89. package/cjs/options/browser.js +86 -0
  90. package/cjs/options/browser.js.map +1 -0
  91. package/cjs/options/index.js +94 -0
  92. package/cjs/options/index.js.map +1 -0
  93. package/cjs/options/node.js +45 -0
  94. package/cjs/options/node.js.map +1 -0
  95. package/cjs/options.js +11 -1
  96. package/cjs/options.js.map +1 -1
  97. package/cjs/server/serverStorage.js +7 -4
  98. package/cjs/server/serverStorage.js.map +1 -1
  99. package/cjs/services/AutoRenewService.js +94 -0
  100. package/cjs/services/AutoRenewService.js.map +1 -0
  101. package/cjs/services/SyncStorageService.js +93 -0
  102. package/cjs/services/SyncStorageService.js.map +1 -0
  103. package/cjs/services/index.js +30 -0
  104. package/cjs/services/index.js.map +1 -0
  105. package/cjs/types/Service.js +2 -0
  106. package/cjs/types/Service.js.map +1 -0
  107. package/cjs/types/index.js +13 -0
  108. package/cjs/types/index.js.map +1 -1
  109. package/dist/okta-auth-js.min.js +1 -1
  110. package/dist/okta-auth-js.min.js.LICENSE.txt +0 -8
  111. package/dist/okta-auth-js.min.js.map +1 -1
  112. package/dist/okta-auth-js.umd.js +1 -1
  113. package/dist/okta-auth-js.umd.js.LICENSE.txt +1 -7
  114. package/dist/okta-auth-js.umd.js.map +1 -1
  115. package/esm/{index.js → esm.browser.js} +2144 -2975
  116. package/esm/esm.browser.js.map +1 -0
  117. package/esm/esm.node.mjs +9595 -0
  118. package/esm/esm.node.mjs.map +1 -0
  119. package/lib/AuthStateManager.d.ts +3 -3
  120. package/lib/OktaAuth.d.ts +5 -4
  121. package/lib/PromiseQueue.d.ts +6 -2
  122. package/lib/ServiceManager.d.ts +38 -0
  123. package/lib/TokenManager.d.ts +0 -1
  124. package/lib/TransactionManager.d.ts +3 -4
  125. package/lib/idx/authenticator/Authenticator.d.ts +1 -1
  126. package/lib/idx/authenticator/OktaPassword.d.ts +2 -1
  127. package/lib/idx/authenticator/OktaVerifyTotp.d.ts +1 -1
  128. package/lib/idx/authenticator/SecurityQuestionEnrollment.d.ts +3 -5
  129. package/lib/idx/authenticator/SecurityQuestionVerification.d.ts +1 -1
  130. package/lib/idx/authenticator/VerificationCodeAuthenticator.d.ts +2 -1
  131. package/lib/idx/authenticator/WebauthnEnrollment.d.ts +1 -1
  132. package/lib/idx/authenticator/WebauthnVerification.d.ts +1 -1
  133. package/lib/idx/authenticator/util.d.ts +4 -0
  134. package/lib/idx/idx-js/index.d.ts +1 -17
  135. package/lib/idx/idx-js/introspect.d.ts +2 -1
  136. package/lib/idx/idx-js/v1/generateIdxAction.d.ts +1 -1
  137. package/lib/idx/idx-js/v1/makeIdxState.d.ts +2 -2
  138. package/lib/idx/proceed.d.ts +1 -3
  139. package/lib/idx/remediate.d.ts +2 -2
  140. package/lib/idx/remediators/AuthenticatorVerificationData.d.ts +6 -5
  141. package/lib/idx/remediators/Base/AuthenticatorData.d.ts +5 -9
  142. package/lib/idx/remediators/Base/Remediator.d.ts +5 -4
  143. package/lib/idx/remediators/Base/SelectAuthenticator.d.ts +7 -9
  144. package/lib/idx/remediators/Base/VerifyAuthenticator.d.ts +2 -4
  145. package/lib/idx/remediators/ChallengePoll.d.ts +1 -0
  146. package/lib/idx/remediators/EnrollProfile.d.ts +0 -3
  147. package/lib/idx/remediators/EnrollmentChannelData.d.ts +0 -4
  148. package/lib/idx/remediators/Identify.d.ts +3 -5
  149. package/lib/idx/remediators/ReEnrollAuthenticator.d.ts +2 -5
  150. package/lib/idx/remediators/SelectAuthenticatorAuthenticate.d.ts +2 -1
  151. package/lib/idx/remediators/SelectAuthenticatorUnlockAccount.d.ts +1 -2
  152. package/lib/idx/remediators/Skip.d.ts +0 -3
  153. package/lib/idx/types/idx-js.d.ts +5 -1
  154. package/lib/idx/types/index.d.ts +7 -3
  155. package/lib/idx/util.d.ts +11 -0
  156. package/lib/options/browser.d.ts +16 -0
  157. package/lib/options/index.d.ts +14 -0
  158. package/lib/options/node.d.ts +16 -0
  159. package/lib/services/AutoRenewService.d.ts +27 -0
  160. package/lib/services/{TokenService.d.ts → SyncStorageService.d.ts} +8 -5
  161. package/lib/services/index.d.ts +13 -0
  162. package/lib/types/OktaAuthOptions.d.ts +5 -0
  163. package/lib/types/Service.d.ts +23 -0
  164. package/lib/types/Storage.d.ts +7 -5
  165. package/lib/types/api.d.ts +6 -5
  166. package/lib/types/index.d.ts +1 -0
  167. package/package.json +26 -11
  168. package/cjs/services/TokenService.js +0 -111
  169. package/cjs/services/TokenService.js.map +0 -1
  170. package/esm/index.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,60 @@
1
1
  # Changelog
2
2
 
3
+ ## 6.3.1
4
+
5
+ ### Fixes
6
+
7
+ - [#1160](https://github.com/okta/okta-auth-js/pull/1160)
8
+ - Fixes error handling for IDX actions
9
+ - Fixes saved IDX transaction
10
+
11
+ ## 6.3.0
12
+
13
+ ### Features
14
+
15
+ - [#1090](https://github.com/okta/okta-auth-js/pull/1090)
16
+ - An `authenticator` can be provided to IDX methods as either a string (representing the authenticator key) or an authenticator object
17
+ - IDX functions will accept the "canonical" name for inputs (as defined by server response). For example a `credentials` object can be passed to satisfy an "identify" remediation instead of `username` and `password`
18
+ - `idx.proceed` will continue without saved transaction meta if a `stateHandle` is available
19
+ - Unknown remediations/values will proceed if the proper data is supplied by the caller
20
+ - IDX response object has a new field `requestDidSucceed` which will be false if the XHR was returned with a non-2xx HTTP status
21
+
22
+ ### Fixes
23
+
24
+ - [#1090](https://github.com/okta/okta-auth-js/pull/1090)
25
+ - Fixes concurrency issue with `transformAuthState`. Concurrent auth state updates will now enqueue calls to `transformAuthState` so that they execute sequentially
26
+ - Fixes issue with in-memory storage provider, where storage was shared between AuthJS instances in the same page/process. In-memory storage will now be unique per AuthJS instance.
27
+ - Fixes issue with the `step` option in IDX flows: it will only be used for a single remediation cycle
28
+ - [#1136](https://github.com/okta/okta-auth-js/pull/1136) Fixes typo in security question enrollment
29
+
30
+ ### Other
31
+
32
+ - [#1090](https://github.com/okta/okta-auth-js/pull/1090) Removes runtime regenerator for development builds
33
+
34
+ ## 6.2.0
35
+
36
+ ### Features
37
+
38
+ - [#1113](https://github.com/okta/okta-auth-js/pull/1113) Updates types for `SigninWithCredentialsOptions` and `SignInOptions` to support `SP Initiated Auth`
39
+ - [#1125](https://github.com/okta/okta-auth-js/pull/1125) IDX - Supports auto select methodType (when only one selection is available) for `authenticator-verification-data` remediation
40
+ - [#1114](https://github.com/okta/okta-auth-js/pull/1114) Exposes ESM node bundle
41
+
42
+ ### Fixes
43
+
44
+ - [#1114](https://github.com/okta/okta-auth-js/pull/1114) Fixes ESM browser bundle issue by only using ESM `import` syntax
45
+
46
+ ### Fixes
47
+
48
+ - [#1130](https://github.com/okta/okta-auth-js/pull/1130) `state` now stored in session during verifyEmail flow
49
+
50
+ ### Other
51
+
52
+ - [#1124](https://github.com/okta/okta-auth-js/pull/1124)
53
+ - Adds multi-tab "leadership" election to prevent all tabs from renewing tokens at the same time
54
+ - Adds granular configurations for `autoRenew` (active vs passive)
55
+ - Adds options to `isAuthenticated` to override client configuration
56
+ - Fixes issue in token renew logic within `isAuthenticated`, tokens are now read from `tokenManager` (not memory) before expiration is checked
57
+
3
58
  ## 6.1.0
4
59
 
5
60
  ### Features
package/README.md CHANGED
@@ -234,7 +234,7 @@ var authClient = new OktaAuth(config);
234
234
 
235
235
  ### Running as a service
236
236
 
237
- By default, creating a new instance of `OktaAuth` will not create any asynchronous side-effects. However, certain features such as [token auto renew](#autorenew), [token auto remove](#autoremove) and [cross-tab synchronization](#syncstorage) require `OktaAuth` to be running as a service. This means timeouts are set in the background which will continue working until the service is stopped. To start the `OktaAuth` service, simply call the `start` method. To terminate all background processes, call `stop`.
237
+ By default, creating a new instance of `OktaAuth` will not create any asynchronous side-effects. However, certain features such as [token auto renew](#autorenew), [token auto remove](#autoremove) and [cross-tab synchronization](#syncstorage) require `OktaAuth` to be running as a service. This means timeouts are set in the background which will continue working until the service is stopped. To start the `OktaAuth` service, simply call the `start` method. To terminate all background processes, call `stop`. See [Service Configuration](#services) for more info.
238
238
 
239
239
  ```javascript
240
240
  var authClient = new OktaAuth(config);
@@ -697,18 +697,13 @@ var config = {
697
697
  ```
698
698
 
699
699
  ##### `autoRenew`
700
+ > :warning: Moved to [TokenService](#tokenservice). For backwards compatibility will set `services.tokenService.autoRenew`
700
701
 
701
- > :gear: Requires a [running service](#running-as-a-service)
702
-
703
- By default, the `tokenManager` will attempt to renew tokens before they expire. If you wish to manually control token renewal, set `autoRenew` to false to disable this feature. You can listen to [`expired`](#tokenmanageronevent-callback-context) events to know when the token has expired.
702
+ ##### `expireEarlySeconds`
704
703
 
705
- ```javascript
706
- tokenManager: {
707
- autoRenew: false
708
- }
709
- ```
704
+ > :warning: DEV ONLY
710
705
 
711
- Renewing tokens slightly early helps ensure a stable user experience. By default, the `expired` event will fire 30 seconds before actual expiration time. If `autoRenew` is set to true, tokens will be renewed within 30 seconds of expiration. You can customize this value by setting the `expireEarlySeconds` option. The value should be large enough to account for network latency and clock drift between the client and Okta's servers.
706
+ To facilitate a more stable user experience, tokens are considered expired 30 seconds before actual expiration time. You can customize this value by setting the `expireEarlySeconds` option. The value should be large enough to account for network latency and clock drift between the client and Okta's servers.
712
707
 
713
708
  **NOTE** `expireEarlySeconds` option is only allowed in the **DEV** environment (localhost). It will be reset to 30 seconds when running in environments other than **DEV**.
714
709
 
@@ -720,23 +715,17 @@ tokenManager: {
720
715
  }
721
716
  ```
722
717
 
723
- ###### `autoRemove`
724
-
725
- > :gear: Requires a [running service](#running-as-a-service)
726
-
727
- By default, the library will attempt to remove expired tokens during initialization when `autoRenew` is off. If you wish to to disable auto removal of tokens, set autoRemove to false.
718
+ ##### `autoRemove`
719
+ > :warning: Moved to [TokenService](#tokenservice). For backwards compatibility will set `services.tokenService.autoRenew`
728
720
 
729
721
  ##### `syncStorage`
722
+ > :warning: Moved to [SyncStorageService](#syncstorageservice). For backwards compatibility will set `services.syncStorageService.enable`
730
723
 
731
- > :gear: Requires a [running service](#running-as-a-service)
732
-
733
- Automatically syncs tokens across browser tabs when token storage is `localStorage`. To disable this behavior, set `syncStorage` to false.
734
-
735
- ###### `storageKey`
724
+ ##### `storageKey`
736
725
 
737
726
  By default all tokens will be stored under the key `okta-token-storage`. You may want to change this if you have multiple apps running on a single domain which share the same storage type. Giving each app a unique storage key will prevent them from reading or writing each other's token values.
738
727
 
739
- ###### `storage`
728
+ ##### `storage`
740
729
 
741
730
  Specify the [storage type](#storagetype) for tokens. This will override any value set for the `token` section in the [storageManager](#storagemanager) configuration. By default, [localStorage][] will be used. This will fall back to [sessionStorage][] or [cookie][] if the previous type is not available. You may pass an object or a string. If passing an object, it should meet the requirements of a [custom storage provider](#storage). Pass a string to specify one of the built-in storage types:
742
731
 
@@ -805,6 +794,39 @@ Defaults to `none` if the `secure` option is `true`, or `lax` if the `secure` op
805
794
 
806
795
  Defaults to `true`, set this option to false if you want to opt-out of the default clearing pendingRemove tokens behaviour when `tokenManager.start()` is called.
807
796
 
797
+ ### `services`
798
+ > :gear: Requires a [running service](#running-as-a-service)
799
+ The following configurations require `OktaAuth` to be running as a service. See [running service](#running-as-a-service) for more info.
800
+
801
+ Default configuration:
802
+ ```javascript
803
+ services: {
804
+ autoRenew: true,
805
+ autoRemove: true,
806
+ syncStorage: true,
807
+ }
808
+ ```
809
+
810
+ #### `autoRenew`
811
+ When `true`, the library will attempt to renew tokens before they expire. If you wish to manually control token renewal, set `autoRenew` to `false` to disable this feature. You can listen to [`expired`](#tokenmanageronevent-callback-context) events to know when the token has expired.
812
+
813
+ > **NOTE** tokens are considered `expired` slightly before their actual expiration time. For more info, see [expireEarlySeconds](#expireearlyseconds).
814
+
815
+ In version `6.X`, the `autoRenew` configuration was set in `config.tokenManager`. To maintain backwards compatibility, this configuration is still respected but with a slight caveat. `tokenManager.autoRenew` configures 2 token auto renew strategies, `active` and `passive`.
816
+ * `active` - Network requests are made in the background in an attempt to refresh tokens before they are truly expired to maintain a seamless UX.
817
+ > :warning: this can cause an unintended side effect where the session never expires because it is constantly being refreshed (extended) before the actual expiration time
818
+ * `passive` - Token refresh attempts are only made when `oktaAuth.isAuthenticated` is called and the current tokens are determined to be expired.
819
+
820
+ When `tokenManager.autoRenew` is `true` both renew strategies are enabled. To disable the `active` strategy, set `tokenManager.autoRenew` to `true` and `services.autoRenew` to `false`. To disable both renew strategies set either `tokenManager.autoRenew` or `services.autoRenew` to `false`
821
+
822
+ #### `autoRemove`
823
+ By default, the library will attempt to remove expired tokens when `autoRenew` is `false`. If you wish to disable auto removal of tokens, set `autoRemove` to `false`.
824
+
825
+ #### `syncStorage`
826
+ Automatically syncs tokens across browser tabs when token storage is `localStorage`. To disable this behavior, set `syncStorage` to false.
827
+
828
+ This is accomplished by selecting a single tab to handle the network requests to refresh the tokens and broadcasting to the other tabs. This is done to avoid all tabs sending refresh requests simultaneously, which can cause rate limiting/throttling issues.
829
+
808
830
  ## API Reference
809
831
  <!-- no toc -->
810
832
  * [start](#start)
@@ -821,7 +843,7 @@ Defaults to `true`, set this option to false if you want to opt-out of the defau
821
843
  * [verifyRecoveryToken](#verifyrecoverytokenoptions)
822
844
  * [webfinger](#webfingeroptions)
823
845
  * [fingerprint](#fingerprintoptions)
824
- * [isAuthenticated](#isauthenticatedtimeout)
846
+ * [isAuthenticated](#isauthenticatedoptions)
825
847
  * [getUser](#getuser)
826
848
  * [getIdToken](#getidtoken)
827
849
  * [getAccessToken](#getaccesstoken)
@@ -1052,12 +1074,20 @@ authClient.fingerprint()
1052
1074
  })
1053
1075
  ```
1054
1076
 
1055
- ### `isAuthenticated(timeout?)`
1077
+ ### `isAuthenticated(options?)`
1056
1078
 
1057
1079
  > :hourglass: async
1058
1080
 
1059
1081
  Resolves with `authState.isAuthenticated` from non-pending [authState](#authstatemanager).
1060
1082
 
1083
+ `options`
1084
+ * `expiredTokenBehavior`: `'renew'` (default) | `'remove'` | `'none'`
1085
+ * `'renew'` - attempt to renew token before `Promise` resolves
1086
+ * `'remove'` - removes token
1087
+ * `'none'` - neither renews or removes expired token
1088
+
1089
+ > NOTE: `tokenManager.autoRenew` and `tokenManager.autoRemove` determine the default value for `expiredTokenBehavior`
1090
+
1061
1091
  ### `getUser()`
1062
1092
 
1063
1093
  > :hourglass: async
@@ -8,12 +8,16 @@ var _stringify = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-
8
8
 
9
9
  var _promise = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/promise"));
10
10
 
11
+ var _pCancelable = _interopRequireDefault(require("p-cancelable"));
12
+
11
13
  var _errors = require("./errors");
12
14
 
13
15
  var _util = require("./util");
14
16
 
15
17
  var _TokenManager = require("./TokenManager");
16
18
 
19
+ var _PromiseQueue = _interopRequireDefault(require("./PromiseQueue"));
20
+
17
21
  /*!
18
22
  * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.
19
23
  * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
@@ -25,9 +29,8 @@ var _TokenManager = require("./TokenManager");
25
29
  *
26
30
  * See the License for the specific language governing permissions and limitations under the License.
27
31
  */
28
- // eslint-disable-next-line import/no-commonjs
29
- const PCancelable = require('p-cancelable');
30
-
32
+ // @ts-ignore
33
+ // Do not use this type in code, so it won't be emitted in the declaration output
31
34
  const INITIAL_AUTH_STATE = null;
32
35
  exports.INITIAL_AUTH_STATE = INITIAL_AUTH_STATE;
33
36
  const DEFAULT_PENDING = {
@@ -57,7 +60,10 @@ class AuthStateManager {
57
60
  };
58
61
  this._authState = INITIAL_AUTH_STATE;
59
62
  this._logOptions = {};
60
- this._prevAuthState = null; // Listen on tokenManager events to start updateState process
63
+ this._prevAuthState = null;
64
+ this._transformQueue = new _PromiseQueue.default({
65
+ quiet: true
66
+ }); // Listen on tokenManager events to start updateState process
61
67
  // "added" event is emitted in both add and renew process
62
68
  // Only listen on "added" event to update auth state
63
69
 
@@ -153,7 +159,7 @@ class AuthStateManager {
153
159
  /* eslint-disable complexity */
154
160
 
155
161
 
156
- const cancelablePromise = new PCancelable((resolve, _, onCancel) => {
162
+ const cancelablePromise = new _pCancelable.default((resolve, _, onCancel) => {
157
163
  onCancel.shouldReject = false;
158
164
  onCancel(() => {
159
165
  this._pending.updateAuthStatePromise = null;
@@ -192,8 +198,9 @@ class AuthStateManager {
192
198
  idToken,
193
199
  refreshToken,
194
200
  isAuthenticated: !!(accessToken && idToken)
195
- };
196
- const promise = transformAuthState ? transformAuthState(this._sdk, authState) : _promise.default.resolve(authState);
201
+ }; // Enqueue transformAuthState so that it does not run concurrently
202
+
203
+ const promise = transformAuthState ? this._transformQueue.push(transformAuthState, null, this._sdk, authState) : _promise.default.resolve(authState);
197
204
  promise.then(authState => emitAndResolve(authState)).catch(error => emitAndResolve({
198
205
  accessToken,
199
206
  idToken,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../lib/AuthStateManager.ts"],"names":["PCancelable","require","INITIAL_AUTH_STATE","DEFAULT_PENDING","updateAuthStatePromise","canceledTimes","EVENT_AUTH_STATE_CHANGE","MAX_PROMISE_CANCEL_TIMES","isSameAuthState","prevState","state","isAuthenticated","idToken","accessToken","error","AuthStateManager","constructor","sdk","emitter","AuthSdkError","_sdk","_pending","_authState","_logOptions","_prevAuthState","tokenManager","on","EVENT_ADDED","key","token","_setLogOptions","event","updateAuthState","EVENT_REMOVED","options","getAuthState","getPreviousAuthState","transformAuthState","devMode","log","status","group","groupEnd","emitAuthStateChange","authState","emit","finalPromise","origPromise","then","curPromise","cancel","cancelablePromise","resolve","_","onCancel","shouldReject","emitAndResolve","isCanceled","refreshToken","getTokensSync","promise","catch","subscribe","handler","unsubscribe","off"],"mappings":";;;;;;;;;;AAaA;;AAGA;;AACA;;AAjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAQA;AACA,MAAMA,WAAW,GAAGC,OAAO,CAAC,cAAD,CAA3B;;AAEO,MAAMC,kBAAkB,GAAG,IAA3B;;AACP,MAAMC,eAAe,GAAG;AACtBC,EAAAA,sBAAsB,EAAE,IADF;AAEtBC,EAAAA,aAAa,EAAE;AAFO,CAAxB;AAIA,MAAMC,uBAAuB,GAAG,iBAAhC;AACA,MAAMC,wBAAwB,GAAG,EAAjC,C,CAEA;;AACA,MAAMC,eAAe,GAAG,CAACC,SAAD,EAA8BC,KAA9B,KAAmD;AACzE;AACA,MAAI,CAACD,SAAL,EAAgB;AACd,WAAO,KAAP;AACD;;AAED,SAAOA,SAAS,CAACE,eAAV,KAA8BD,KAAK,CAACC,eAApC,IACF,wBAAeF,SAAS,CAACG,OAAzB,MAAsC,wBAAeF,KAAK,CAACE,OAArB,CADpC,IAEF,wBAAeH,SA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BkC,aAAvB,EAA/C;;AACA,cAAMf,SAAS,GAAG;AAChB/B,UAAAA,WADgB;AAEhBD,UAAAA,OAFgB;AAGhB8C,UAAAA,YAHgB;AAIhB/C,UAAAA,eAAe,EAAE,CAAC,EAAEE,WAAW,IAAID,OAAjB;AAJF,SAAlB;AAMA,cAAMgD,OAA2B,GAAGvB,kBAAkB,GAClDA,kBAAkB,CAAC,KAAKjB,IAAN,EAAYwB,SAAZ,CADgC,GAElD,iBAAQQ,OAAR,CAAgBR,SAAhB,CAFJ;AAIAgB,QAAAA,OAAO,CACJZ,IADH,CACQJ,SAAS,IAAIY,cAAc,CAACZ,SAAD,CADnC,EAEGiB,KAFH,CAES/C,KAAK,IAAI0C,cAAc,CAAC;AAC7B3C,UAAAA,WAD6B;AAE7BD,UAAAA,OAF6B;AAG7B8C,UAAAA,YAH6B;AAI7B/C,UAAAA,eAAe,EAAE,KAJY;AAK7BG,UAAAA;AAL6B,SAAD,CAFhC;AASD,OA3BH;AA4BD,KAjDyB,CAA1B;AAkDA;;AACA,SAAKO,QAAL,CAAcjB,sBAAd,GAAuC+C,iBAAvC;AAEA,WAAOL,YAAY,CAACK,iBAAD,CAAnB;AACD;;AAEDW,EAAAA,SAAS,CAACC,OAAD,EAAgB;AACvB,SAAK3C,IAAL,CAAUF,OAAV,CAAkBQ,EAAlB,CAAqBpB,uBAArB,EAA8CyD,OAA9C;AACD;;AAEDC,EAAAA,WAAW,CAACD,OAAD,EAAiB;AAC1B,SAAK3C,IAAL,CAAUF,OAAV,CAAkB+C,GAAlB,CAAsB3D,uBAAtB,EAA+CyD,OAA/C;AACD;;AA5J2B","sourcesContent":["/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { AuthSdkError } from './errors';\nimport { AuthState, AuthStateLogOptions } from './types';\nimport { OktaAuth } from '.';\nimport { getConsole } from './util';\nimport { EVENT_ADDED, EVENT_REMOVED } from './TokenManager';\n// eslint-disable-next-line import/no-commonjs\nconst PCancelable = require('p-cancelable');\n\nexport const INITIAL_AUTH_STATE = null;\nconst DEFAULT_PENDING = {\n updateAuthStatePromise: null,\n canceledTimes: 0\n};\nconst EVENT_AUTH_STATE_CHANGE = 'authStateChange';\nconst MAX_PROMISE_CANCEL_TIMES = 10;\n\n// only compare first level of authState\nconst isSameAuthState = (prevState: AuthState | null, state: AuthState) => {\n // initial state is null\n if (!prevState) {\n return false;\n }\n\n return prevState.isAuthenticated === state.isAuthenticated \n && JSON.stringify(prevState.idToken) === JSON.stringify(state.idToken)\n && JSON.stringify(prevState.accessToken) === JSON.stringify(state.accessToken)\n && prevState.error === state.error;\n};\n\nexport class AuthStateManager {\n _sdk: OktaAuth;\n _pending: { \n updateAuthStatePromise: typeof PCancelable;\n canceledTimes: number; \n };\n _authState: AuthState | null;\n _prevAuthState: AuthState | null;\n _logOptions: AuthStateLogOptions;\n\n constructor(sdk: OktaAuth) {\n if (!sdk.emitter) {\n throw new AuthSdkError('Emitter should be initialized before AuthStateManager');\n }\n\n this._sdk = sdk;\n this._pending = { ...DEFAULT_PENDING };\n this._authState = INITIAL_AUTH_STATE;\n this._logOptions = {};\n this._prevAuthState = null;\n \n // Listen on tokenManager events to start updateState process\n // \"added\" event is emitted in both add and renew process\n // Only listen on \"added\" event to update auth state\n sdk.tokenManager.on(EVENT_ADDED, (key, token) => {\n this._setLogOptions({ event: EVENT_ADDED, key, token });\n this.updateAuthState();\n });\n sdk.tokenManager.on(EVENT_REMOVED, (key, token) => {\n this._setLogOptions({ event: EVENT_REMOVED, key, token });\n this.updateAuthState();\n });\n }\n\n _setLogOptions(options) {\n this._logOptions = options;\n }\n\n getAuthState(): AuthState | null {\n return this._authState;\n }\n\n getPreviousAuthState(): AuthState | null {\n return this._prevAuthState;\n }\n\n async updateAuthState(): Promise<AuthState> {\n const { transformAuthState, devMode } = this._sdk.options;\n\n const log = (status) => {\n const { event, key, token } = this._logOptions;\n getConsole().group(`OKTA-AUTH-JS:updateAuthState: Event:${event} Status:${status}`);\n getConsole().log(key, token);\n getConsole().log('Current authState', this._authState);\n getConsole().groupEnd();\n \n // clear log options after logging\n this._logOptions = {};\n };\n\n const emitAuthStateChange = (authState) => {\n if (isSameAuthState(this._authState, authState)) {\n devMode && log('unchanged'); \n return;\n }\n this._prevAuthState = this._authState;\n this._authState = authState;\n // emit new authState object\n this._sdk.emitter.emit(EVENT_AUTH_STATE_CHANGE, { ...authState });\n devMode && log('emitted');\n };\n\n const finalPromise = (origPromise) => { \n return this._pending.updateAuthStatePromise.then(() => {\n const curPromise = this._pending.updateAuthStatePromise;\n if (curPromise && curPromise !== origPromise) {\n return finalPromise(curPromise);\n }\n return this.getAuthState();\n });\n };\n\n if (this._pending.updateAuthStatePromise) {\n if (this._pending.canceledTimes >= MAX_PROMISE_CANCEL_TIMES) {\n // stop canceling then starting a new promise\n // let existing promise finish to prevent running into loops\n devMode && log('terminated');\n return finalPromise(this._pending.updateAuthStatePromise);\n } else {\n this._pending.updateAuthStatePromise.cancel();\n }\n }\n\n /* eslint-disable complexity */\n const cancelablePromise = new PCancelable((resolve, _, onCancel) => {\n onCancel.shouldReject = false;\n onCancel(() => {\n this._pending.updateAuthStatePromise = null;\n this._pending.canceledTimes = this._pending.canceledTimes + 1;\n devMode && log('canceled');\n });\n\n const emitAndResolve = (authState) => {\n if (cancelablePromise.isCanceled) {\n resolve();\n return;\n }\n // emit event and resolve promise \n emitAuthStateChange(authState);\n resolve();\n\n // clear pending states after resolve\n this._pending = { ...DEFAULT_PENDING };\n };\n\n this._sdk.isAuthenticated()\n .then(() => {\n if (cancelablePromise.isCanceled) {\n resolve();\n return;\n }\n\n const { accessToken, idToken, refreshToken } = this._sdk.tokenManager.getTokensSync();\n const authState = {\n accessToken,\n idToken,\n refreshToken,\n isAuthenticated: !!(accessToken && idToken)\n };\n const promise: Promise<AuthState> = transformAuthState\n ? transformAuthState(this._sdk, authState)\n : Promise.resolve(authState);\n\n promise\n .then(authState => emitAndResolve(authState))\n .catch(error => emitAndResolve({\n accessToken, \n idToken, \n refreshToken,\n isAuthenticated: false, \n error\n }));\n });\n });\n /* eslint-enable complexity */\n this._pending.updateAuthStatePromise = cancelablePromise;\n\n return finalPromise(cancelablePromise);\n }\n\n subscribe(handler): void {\n this._sdk.emitter.on(EVENT_AUTH_STATE_CHANGE, handler);\n }\n\n unsubscribe(handler?): void {\n this._sdk.emitter.off(EVENT_AUTH_STATE_CHANGE, handler);\n }\n}\n"],"file":"AuthStateManager.js"}
1
+ {"version":3,"sources":["../../lib/AuthStateManager.ts"],"names":["INITIAL_AUTH_STATE","DEFAULT_PENDING","updateAuthStatePromise","canceledTimes","EVENT_AUTH_STATE_CHANGE","MAX_PROMISE_CANCEL_TIMES","isSameAuthState","prevState","state","isAuthenticated","idToken","accessToken","error","AuthStateManager","constructor","sdk","emitter","AuthSdkError","_sdk","_pending","_authState","_logOptions","_prevAuthState","_transformQueue","PromiseQueue","quiet","tokenManager","on","EVENT_ADDED","key","token","_setLogOptions","event","updateAuthState","EVENT_REMOVED","options","getAuthState","getPreviousAuthState","transformAuthState","devMode","log","status","group","groupEnd","emitAuthStateChange","authState","emit","finalPromise","origPromise","then","curPromise","cancel","cancelablePromise","PCancelable","resolve","_","onCancel","shouldReject","emitAndResolve","isCanceled","refreshToken","getTokensSync","promise","push","catch","subscribe","handler","unsubscribe","off"],"mappings":";;;;;;;;;;AAcA;;AACA;;AAGA;;AACA;;AACA;;AApBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AASO,MAAMA,kBAAkB,GAAG,IAA3B;;AACP,MAA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;;AACA,SAAKO,QAAL,CAAcjB,sBAAd,GAAuCkD,iBAAvC;AAEA,WAAOL,YAAY,CAACK,iBAAD,CAAnB;AACD;;AAEDa,EAAAA,SAAS,CAACC,OAAD,EAAgB;AACvB,SAAKhD,IAAL,CAAUF,OAAV,CAAkBW,EAAlB,CAAqBvB,uBAArB,EAA8C8D,OAA9C;AACD;;AAEDC,EAAAA,WAAW,CAACD,OAAD,EAAiB;AAC1B,SAAKhD,IAAL,CAAUF,OAAV,CAAkBoD,GAAlB,CAAsBhE,uBAAtB,EAA+C8D,OAA/C;AACD;;AAlK2B","sourcesContent":["/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n \n// @ts-ignore \n// Do not use this type in code, so it won't be emitted in the declaration output\nimport PCancelable from 'p-cancelable';\nimport { AuthSdkError } from './errors';\nimport { AuthState, AuthStateLogOptions } from './types';\nimport { OktaAuth } from '.';\nimport { getConsole } from './util';\nimport { EVENT_ADDED, EVENT_REMOVED } from './TokenManager';\nimport PromiseQueue from './PromiseQueue';\n\nexport const INITIAL_AUTH_STATE = null;\nconst DEFAULT_PENDING = {\n updateAuthStatePromise: null,\n canceledTimes: 0\n};\nconst EVENT_AUTH_STATE_CHANGE = 'authStateChange';\nconst MAX_PROMISE_CANCEL_TIMES = 10;\n\n// only compare first level of authState\nconst isSameAuthState = (prevState: AuthState | null, state: AuthState) => {\n // initial state is null\n if (!prevState) {\n return false;\n }\n\n return prevState.isAuthenticated === state.isAuthenticated \n && JSON.stringify(prevState.idToken) === JSON.stringify(state.idToken)\n && JSON.stringify(prevState.accessToken) === JSON.stringify(state.accessToken)\n && prevState.error === state.error;\n};\n\n\nexport class AuthStateManager {\n _sdk: OktaAuth;\n _pending: { \n updateAuthStatePromise: any;\n canceledTimes: number; \n };\n _authState: AuthState | null;\n _prevAuthState: AuthState | null;\n _logOptions: AuthStateLogOptions;\n _transformQueue: PromiseQueue;\n\n constructor(sdk: OktaAuth) {\n if (!sdk.emitter) {\n throw new AuthSdkError('Emitter should be initialized before AuthStateManager');\n }\n\n this._sdk = sdk;\n this._pending = { ...DEFAULT_PENDING };\n this._authState = INITIAL_AUTH_STATE;\n this._logOptions = {};\n this._prevAuthState = null;\n this._transformQueue = new PromiseQueue({\n quiet: true\n });\n\n // Listen on tokenManager events to start updateState process\n // \"added\" event is emitted in both add and renew process\n // Only listen on \"added\" event to update auth state\n sdk.tokenManager.on(EVENT_ADDED, (key, token) => {\n this._setLogOptions({ event: EVENT_ADDED, key, token });\n this.updateAuthState();\n });\n sdk.tokenManager.on(EVENT_REMOVED, (key, token) => {\n this._setLogOptions({ event: EVENT_REMOVED, key, token });\n this.updateAuthState();\n });\n }\n\n _setLogOptions(options) {\n this._logOptions = options;\n }\n\n getAuthState(): AuthState | null {\n return this._authState;\n }\n\n getPreviousAuthState(): AuthState | null {\n return this._prevAuthState;\n }\n\n async updateAuthState(): Promise<AuthState> {\n const { transformAuthState, devMode } = this._sdk.options;\n\n const log = (status) => {\n const { event, key, token } = this._logOptions;\n getConsole().group(`OKTA-AUTH-JS:updateAuthState: Event:${event} Status:${status}`);\n getConsole().log(key, token);\n getConsole().log('Current authState', this._authState);\n getConsole().groupEnd();\n \n // clear log options after logging\n this._logOptions = {};\n };\n\n const emitAuthStateChange = (authState) => {\n if (isSameAuthState(this._authState, authState)) {\n devMode && log('unchanged'); \n return;\n }\n this._prevAuthState = this._authState;\n this._authState = authState;\n // emit new authState object\n this._sdk.emitter.emit(EVENT_AUTH_STATE_CHANGE, { ...authState });\n devMode && log('emitted');\n };\n\n const finalPromise = (origPromise) => { \n return this._pending.updateAuthStatePromise.then(() => {\n const curPromise = this._pending.updateAuthStatePromise;\n if (curPromise && curPromise !== origPromise) {\n return finalPromise(curPromise);\n }\n return this.getAuthState();\n });\n };\n\n if (this._pending.updateAuthStatePromise) {\n if (this._pending.canceledTimes >= MAX_PROMISE_CANCEL_TIMES) {\n // stop canceling then starting a new promise\n // let existing promise finish to prevent running into loops\n devMode && log('terminated');\n return finalPromise(this._pending.updateAuthStatePromise);\n } else {\n this._pending.updateAuthStatePromise.cancel();\n }\n }\n\n /* eslint-disable complexity */\n const cancelablePromise = new PCancelable((resolve, _, onCancel) => {\n onCancel.shouldReject = false;\n onCancel(() => {\n this._pending.updateAuthStatePromise = null;\n this._pending.canceledTimes = this._pending.canceledTimes + 1;\n devMode && log('canceled');\n });\n\n const emitAndResolve = (authState) => {\n if (cancelablePromise.isCanceled) {\n resolve();\n return;\n }\n // emit event and resolve promise \n emitAuthStateChange(authState);\n resolve();\n\n // clear pending states after resolve\n this._pending = { ...DEFAULT_PENDING };\n };\n\n this._sdk.isAuthenticated()\n .then(() => {\n if (cancelablePromise.isCanceled) {\n resolve();\n return;\n }\n\n const { accessToken, idToken, refreshToken } = this._sdk.tokenManager.getTokensSync();\n const authState = {\n accessToken,\n idToken,\n refreshToken,\n isAuthenticated: !!(accessToken && idToken)\n };\n\n // Enqueue transformAuthState so that it does not run concurrently\n const promise: Promise<AuthState> = transformAuthState\n ? this._transformQueue.push(transformAuthState, null, this._sdk, authState) as Promise<AuthState>\n : Promise.resolve(authState);\n\n promise\n .then(authState => emitAndResolve(authState))\n .catch(error => emitAndResolve({\n accessToken, \n idToken, \n refreshToken,\n isAuthenticated: false, \n error\n }));\n });\n });\n /* eslint-enable complexity */\n this._pending.updateAuthStatePromise = cancelablePromise;\n\n return finalPromise(cancelablePromise);\n }\n\n subscribe(handler): void {\n this._sdk.emitter.on(EVENT_AUTH_STATE_CHANGE, handler);\n }\n\n unsubscribe(handler?): void {\n this._sdk.emitter.off(EVENT_AUTH_STATE_CHANGE, handler);\n }\n}\n"],"file":"AuthStateManager.js"}
package/cjs/OktaAuth.js CHANGED
@@ -38,6 +38,8 @@ var _util = require("./util");
38
38
 
39
39
  var _TokenManager = require("./TokenManager");
40
40
 
41
+ var _ServiceManager = require("./ServiceManager");
42
+
41
43
  var _http = require("./http");
42
44
 
43
45
  var _PromiseQueue = _interopRequireDefault(require("./PromiseQueue"));
@@ -62,6 +64,8 @@ var _parseFromUrl = require("./oidc/parseFromUrl");
62
64
 
63
65
  var _transactionMeta = require("./idx/transactionMeta");
64
66
 
67
+ var _tinyEmitter = _interopRequireDefault(require("tiny-emitter"));
68
+
65
69
  function _getRequireWildcardCache(nodeInterop) { if (typeof _WeakMap !== "function") return null; var cacheBabelInterop = new _WeakMap(); var cacheNodeInterop = new _WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
66
70
 
67
71
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && _Object$getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? _Object$getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
@@ -83,9 +87,8 @@ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj &&
83
87
  */
84
88
 
85
89
  /* global window */
86
- // eslint-disable-next-line import/no-commonjs
87
- const Emitter = require('tiny-emitter');
88
-
90
+ // @ts-ignore
91
+ // Do not use this type in code, so it won't be emitted in the declaration output
89
92
  class OktaAuth {
90
93
  constructor(args) {
91
94
  const options = this.options = (0, _options.buildOptions)(args); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
@@ -259,23 +262,30 @@ class OktaAuth {
259
262
  }; // Fingerprint API
260
263
 
261
264
  this.fingerprint = _fingerprint.default.bind(null, this);
262
- this.emitter = new Emitter(); // TokenManager
265
+ this.emitter = new _tinyEmitter.default(); // TokenManager
263
266
 
264
267
  this.tokenManager = new _TokenManager.TokenManager(this, args.tokenManager); // AuthStateManager
265
268
 
266
- this.authStateManager = new _AuthStateManager.AuthStateManager(this);
269
+ this.authStateManager = new _AuthStateManager.AuthStateManager(this); // ServiceManager
270
+
271
+ this.serviceManager = new _ServiceManager.ServiceManager(this, args.services);
267
272
  }
268
273
 
269
274
  start() {
275
+ // TODO: review tokenManager.start
270
276
  this.tokenManager.start();
271
277
 
272
278
  if (!this.token.isLoginRedirect()) {
273
279
  this.authStateManager.updateAuthState();
274
280
  }
281
+
282
+ this.serviceManager.start();
275
283
  }
276
284
 
277
285
  stop() {
286
+ // TODO: review tokenManager.stop
278
287
  this.tokenManager.stop();
288
+ this.serviceManager.stop();
279
289
  }
280
290
 
281
291
  setHeaders(headers) {
@@ -497,38 +507,44 @@ class OktaAuth {
497
507
  // If `autoRenew` option is set, will attempt to renew expired tokens before returning.
498
508
 
499
509
 
500
- async isAuthenticated() {
501
- let {
502
- accessToken,
503
- idToken
504
- } = this.tokenManager.getTokensSync();
510
+ async isAuthenticated(options = {}) {
511
+ // TODO: remove dependency on tokenManager options in next major version - OKTA-473815
505
512
  const {
506
513
  autoRenew,
507
514
  autoRemove
508
515
  } = this.tokenManager.getOptions();
516
+ const shouldRenew = options.onExpiredToken ? options.onExpiredToken === 'renew' : autoRenew;
517
+ const shouldRemove = options.onExpiredToken ? options.onExpiredToken === 'remove' : autoRemove;
518
+ let {
519
+ accessToken
520
+ } = this.tokenManager.getTokensSync();
509
521
 
510
522
  if (accessToken && this.tokenManager.hasExpired(accessToken)) {
511
523
  accessToken = undefined;
512
524
 
513
- if (autoRenew) {
525
+ if (shouldRenew) {
514
526
  try {
515
527
  accessToken = await this.tokenManager.renew('accessToken');
516
528
  } catch {// Renew errors will emit an "error" event
517
529
  }
518
- } else if (autoRemove) {
530
+ } else if (shouldRemove) {
519
531
  this.tokenManager.remove('accessToken');
520
532
  }
521
533
  }
522
534
 
535
+ let {
536
+ idToken
537
+ } = this.tokenManager.getTokensSync();
538
+
523
539
  if (idToken && this.tokenManager.hasExpired(idToken)) {
524
540
  idToken = undefined;
525
541
 
526
- if (autoRenew) {
542
+ if (shouldRenew) {
527
543
  try {
528
544
  idToken = await this.tokenManager.renew('idToken');
529
545
  } catch {// Renew errors will emit an "error" event
530
546
  }
531
- } else if (autoRemove) {
547
+ } else if (shouldRemove) {
532
548
  this.tokenManager.remove('idToken');
533
549
  }
534
550
  }