@azure/msal-common 14.1.0 → 14.2.0-alpha.0

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 (230) hide show
  1. package/dist/account/AccountInfo.d.ts +31 -31
  2. package/dist/account/AuthToken.d.ts +17 -17
  3. package/dist/account/AuthToken.mjs +58 -58
  4. package/dist/account/CcsCredential.d.ts +9 -9
  5. package/dist/account/CcsCredential.mjs +8 -8
  6. package/dist/account/ClientCredentials.d.ts +14 -14
  7. package/dist/account/ClientInfo.d.ts +19 -19
  8. package/dist/account/ClientInfo.mjs +37 -37
  9. package/dist/account/TokenClaims.d.ts +65 -65
  10. package/dist/authority/Authority.d.ts +250 -235
  11. package/dist/authority/Authority.d.ts.map +1 -1
  12. package/dist/authority/Authority.mjs +795 -740
  13. package/dist/authority/Authority.mjs.map +1 -1
  14. package/dist/authority/AuthorityFactory.d.ts +31 -31
  15. package/dist/authority/AuthorityFactory.d.ts.map +1 -1
  16. package/dist/authority/AuthorityFactory.mjs +48 -48
  17. package/dist/authority/AuthorityMetadata.d.ts +646 -623
  18. package/dist/authority/AuthorityMetadata.d.ts.map +1 -1
  19. package/dist/authority/AuthorityMetadata.mjs +941 -885
  20. package/dist/authority/AuthorityMetadata.mjs.map +1 -1
  21. package/dist/authority/AuthorityOptions.d.ts +27 -21
  22. package/dist/authority/AuthorityOptions.d.ts.map +1 -1
  23. package/dist/authority/AuthorityOptions.mjs +18 -18
  24. package/dist/authority/AuthorityOptions.mjs.map +1 -1
  25. package/dist/authority/AuthorityType.d.ts +10 -10
  26. package/dist/authority/AuthorityType.mjs +13 -13
  27. package/dist/authority/AzureRegion.d.ts +1 -1
  28. package/dist/authority/AzureRegionConfiguration.d.ts +5 -5
  29. package/dist/authority/CloudDiscoveryMetadata.d.ts +5 -5
  30. package/dist/authority/CloudInstanceDiscoveryErrorResponse.d.ts +13 -13
  31. package/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs +8 -8
  32. package/dist/authority/CloudInstanceDiscoveryResponse.d.ts +9 -9
  33. package/dist/authority/CloudInstanceDiscoveryResponse.mjs +8 -8
  34. package/dist/authority/ImdsOptions.d.ts +5 -5
  35. package/dist/authority/OIDCOptions.d.ts +8 -8
  36. package/dist/authority/OpenIdConfigResponse.d.ts +11 -11
  37. package/dist/authority/OpenIdConfigResponse.mjs +10 -10
  38. package/dist/authority/ProtocolMode.d.ts +8 -8
  39. package/dist/authority/ProtocolMode.mjs +11 -11
  40. package/dist/authority/RegionDiscovery.d.ts +32 -32
  41. package/dist/authority/RegionDiscovery.mjs +106 -106
  42. package/dist/authority/RegionDiscoveryMetadata.d.ts +6 -6
  43. package/dist/broker/nativeBroker/INativeBrokerPlugin.d.ts +15 -15
  44. package/dist/cache/CacheManager.d.ts +480 -464
  45. package/dist/cache/CacheManager.d.ts.map +1 -1
  46. package/dist/cache/CacheManager.mjs +1089 -1049
  47. package/dist/cache/CacheManager.mjs.map +1 -1
  48. package/dist/cache/entities/AccessTokenEntity.d.ts +56 -56
  49. package/dist/cache/entities/AccessTokenEntity.mjs +109 -109
  50. package/dist/cache/entities/AccountEntity.d.ts +101 -101
  51. package/dist/cache/entities/AccountEntity.d.ts.map +1 -1
  52. package/dist/cache/entities/AccountEntity.mjs +218 -220
  53. package/dist/cache/entities/AccountEntity.mjs.map +1 -1
  54. package/dist/cache/entities/AppMetadataEntity.d.ts +39 -39
  55. package/dist/cache/entities/AppMetadataEntity.mjs +66 -66
  56. package/dist/cache/entities/AuthorityMetadataEntity.d.ts +48 -48
  57. package/dist/cache/entities/AuthorityMetadataEntity.mjs +78 -78
  58. package/dist/cache/entities/CacheRecord.d.ts +14 -14
  59. package/dist/cache/entities/CacheRecord.mjs +14 -14
  60. package/dist/cache/entities/CredentialEntity.d.ts +88 -88
  61. package/dist/cache/entities/CredentialEntity.mjs +136 -136
  62. package/dist/cache/entities/IdTokenEntity.d.ts +34 -34
  63. package/dist/cache/entities/IdTokenEntity.mjs +56 -56
  64. package/dist/cache/entities/RefreshTokenEntity.d.ts +36 -36
  65. package/dist/cache/entities/RefreshTokenEntity.mjs +59 -59
  66. package/dist/cache/entities/ServerTelemetryEntity.d.ts +12 -12
  67. package/dist/cache/entities/ServerTelemetryEntity.mjs +27 -27
  68. package/dist/cache/entities/ThrottlingEntity.d.ts +13 -13
  69. package/dist/cache/entities/ThrottlingEntity.mjs +23 -23
  70. package/dist/cache/interface/ICacheManager.d.ts +166 -166
  71. package/dist/cache/interface/ICachePlugin.d.ts +5 -5
  72. package/dist/cache/interface/ISerializableTokenCache.d.ts +4 -4
  73. package/dist/cache/persistence/TokenCacheContext.d.ts +23 -23
  74. package/dist/cache/persistence/TokenCacheContext.mjs +25 -25
  75. package/dist/cache/utils/CacheTypes.d.ts +67 -66
  76. package/dist/cache/utils/CacheTypes.d.ts.map +1 -1
  77. package/dist/client/AuthorizationCodeClient.d.ts +73 -73
  78. package/dist/client/AuthorizationCodeClient.d.ts.map +1 -1
  79. package/dist/client/AuthorizationCodeClient.mjs +408 -408
  80. package/dist/client/AuthorizationCodeClient.mjs.map +1 -1
  81. package/dist/client/BaseClient.d.ts +51 -51
  82. package/dist/client/BaseClient.d.ts.map +1 -1
  83. package/dist/client/BaseClient.mjs +100 -99
  84. package/dist/client/BaseClient.mjs.map +1 -1
  85. package/dist/client/RefreshTokenClient.d.ts +35 -35
  86. package/dist/client/RefreshTokenClient.d.ts.map +1 -1
  87. package/dist/client/RefreshTokenClient.mjs +187 -187
  88. package/dist/client/RefreshTokenClient.mjs.map +1 -1
  89. package/dist/client/SilentFlowClient.d.ts +27 -26
  90. package/dist/client/SilentFlowClient.d.ts.map +1 -1
  91. package/dist/client/SilentFlowClient.mjs +118 -125
  92. package/dist/client/SilentFlowClient.mjs.map +1 -1
  93. package/dist/config/AppTokenProvider.d.ts +38 -38
  94. package/dist/config/ClientConfiguration.d.ts +150 -150
  95. package/dist/config/ClientConfiguration.d.ts.map +1 -1
  96. package/dist/config/ClientConfiguration.mjs +96 -98
  97. package/dist/config/ClientConfiguration.mjs.map +1 -1
  98. package/dist/crypto/ICrypto.d.ts +58 -58
  99. package/dist/crypto/ICrypto.mjs +30 -30
  100. package/dist/crypto/IGuidGenerator.d.ts +4 -4
  101. package/dist/crypto/JoseHeader.d.ts +22 -22
  102. package/dist/crypto/JoseHeader.mjs +37 -37
  103. package/dist/crypto/PopTokenGenerator.d.ts +60 -60
  104. package/dist/crypto/PopTokenGenerator.mjs +82 -82
  105. package/dist/crypto/SignedHttpRequest.d.ts +11 -11
  106. package/dist/error/AuthError.d.ts +44 -44
  107. package/dist/error/AuthError.mjs +46 -46
  108. package/dist/error/AuthErrorCodes.d.ts +5 -5
  109. package/dist/error/AuthErrorCodes.mjs +9 -9
  110. package/dist/error/ClientAuthError.d.ts +237 -232
  111. package/dist/error/ClientAuthError.d.ts.map +1 -1
  112. package/dist/error/ClientAuthError.mjs +250 -245
  113. package/dist/error/ClientAuthError.mjs.map +1 -1
  114. package/dist/error/ClientAuthErrorCodes.d.ts +44 -43
  115. package/dist/error/ClientAuthErrorCodes.d.ts.map +1 -1
  116. package/dist/error/ClientAuthErrorCodes.mjs +50 -49
  117. package/dist/error/ClientAuthErrorCodes.mjs.map +1 -1
  118. package/dist/error/ClientConfigurationError.d.ts +128 -128
  119. package/dist/error/ClientConfigurationError.mjs +135 -135
  120. package/dist/error/ClientConfigurationErrorCodes.d.ts +22 -22
  121. package/dist/error/ClientConfigurationErrorCodes.mjs +26 -26
  122. package/dist/error/InteractionRequiredAuthError.d.ts +57 -57
  123. package/dist/error/InteractionRequiredAuthError.mjs +76 -76
  124. package/dist/error/InteractionRequiredAuthErrorCodes.d.ts +5 -5
  125. package/dist/error/InteractionRequiredAuthErrorCodes.mjs +11 -11
  126. package/dist/error/JoseHeaderError.d.ts +15 -15
  127. package/dist/error/JoseHeaderError.mjs +22 -22
  128. package/dist/error/JoseHeaderErrorCodes.d.ts +2 -2
  129. package/dist/error/JoseHeaderErrorCodes.mjs +6 -6
  130. package/dist/error/ServerError.d.ts +7 -7
  131. package/dist/error/ServerError.mjs +14 -14
  132. package/dist/index.cjs +8840 -8677
  133. package/dist/index.cjs.map +1 -1
  134. package/dist/index.d.ts +96 -96
  135. package/dist/index.d.ts.map +1 -1
  136. package/dist/index.mjs +3 -3
  137. package/dist/logger/Logger.d.ts +95 -95
  138. package/dist/logger/Logger.mjs +188 -188
  139. package/dist/network/INetworkModule.d.ts +29 -29
  140. package/dist/network/INetworkModule.mjs +12 -12
  141. package/dist/network/NetworkManager.d.ts +33 -33
  142. package/dist/network/NetworkManager.mjs +34 -34
  143. package/dist/network/RequestThumbprint.d.ts +16 -16
  144. package/dist/network/ThrottlingUtils.d.ts +42 -42
  145. package/dist/network/ThrottlingUtils.mjs +95 -95
  146. package/dist/packageMetadata.d.ts +2 -2
  147. package/dist/packageMetadata.d.ts.map +1 -1
  148. package/dist/packageMetadata.mjs +4 -4
  149. package/dist/packageMetadata.mjs.map +1 -1
  150. package/dist/request/AuthenticationHeaderParser.d.ts +19 -19
  151. package/dist/request/AuthenticationHeaderParser.mjs +55 -55
  152. package/dist/request/BaseAuthRequest.d.ts +40 -40
  153. package/dist/request/CommonAuthorizationCodeRequest.d.ts +27 -27
  154. package/dist/request/CommonAuthorizationUrlRequest.d.ts +50 -50
  155. package/dist/request/CommonClientCredentialRequest.d.ts +17 -17
  156. package/dist/request/CommonDeviceCodeRequest.d.ts +21 -21
  157. package/dist/request/CommonEndSessionRequest.d.ts +21 -21
  158. package/dist/request/CommonOnBehalfOfRequest.d.ts +13 -13
  159. package/dist/request/CommonRefreshTokenRequest.d.ts +22 -22
  160. package/dist/request/CommonSilentFlowRequest.d.ts +20 -20
  161. package/dist/request/CommonUsernamePasswordRequest.d.ts +17 -17
  162. package/dist/request/NativeRequest.d.ts +19 -19
  163. package/dist/request/NativeSignOutRequest.d.ts +5 -5
  164. package/dist/request/RequestParameterBuilder.d.ts +217 -217
  165. package/dist/request/RequestParameterBuilder.mjs +381 -381
  166. package/dist/request/RequestValidator.d.ts +33 -33
  167. package/dist/request/RequestValidator.mjs +81 -81
  168. package/dist/request/ScopeSet.d.ts +88 -88
  169. package/dist/request/ScopeSet.mjs +197 -197
  170. package/dist/request/StoreInCache.d.ts +8 -8
  171. package/dist/response/AuthenticationResult.d.ts +41 -41
  172. package/dist/response/AuthorizationCodePayload.d.ts +13 -13
  173. package/dist/response/DeviceCodeResponse.d.ts +25 -25
  174. package/dist/response/ExternalTokenResponse.d.ts +15 -15
  175. package/dist/response/IMDSBadResponse.d.ts +4 -4
  176. package/dist/response/ResponseHandler.d.ts +67 -67
  177. package/dist/response/ResponseHandler.d.ts.map +1 -1
  178. package/dist/response/ResponseHandler.mjs +315 -311
  179. package/dist/response/ResponseHandler.mjs.map +1 -1
  180. package/dist/response/ServerAuthorizationCodeResponse.d.ts +25 -25
  181. package/dist/response/ServerAuthorizationTokenResponse.d.ts +46 -46
  182. package/dist/telemetry/performance/IPerformanceClient.d.ts +51 -51
  183. package/dist/telemetry/performance/IPerformanceMeasurement.d.ts +5 -5
  184. package/dist/telemetry/performance/PerformanceClient.d.ts +191 -191
  185. package/dist/telemetry/performance/PerformanceClient.mjs +409 -409
  186. package/dist/telemetry/performance/PerformanceEvent.d.ts +457 -441
  187. package/dist/telemetry/performance/PerformanceEvent.d.ts.map +1 -1
  188. package/dist/telemetry/performance/PerformanceEvent.mjs +249 -242
  189. package/dist/telemetry/performance/PerformanceEvent.mjs.map +1 -1
  190. package/dist/telemetry/performance/StubPerformanceClient.d.ts +24 -24
  191. package/dist/telemetry/performance/StubPerformanceClient.mjs +76 -76
  192. package/dist/telemetry/server/ServerTelemetryManager.d.ts +66 -66
  193. package/dist/telemetry/server/ServerTelemetryManager.mjs +197 -197
  194. package/dist/telemetry/server/ServerTelemetryRequest.d.ts +8 -8
  195. package/dist/url/IUri.d.ts +12 -12
  196. package/dist/url/UrlString.d.ts +83 -83
  197. package/dist/url/UrlString.mjs +279 -279
  198. package/dist/utils/Constants.d.ts +368 -366
  199. package/dist/utils/Constants.d.ts.map +1 -1
  200. package/dist/utils/Constants.mjs +381 -378
  201. package/dist/utils/Constants.mjs.map +1 -1
  202. package/dist/utils/FunctionWrappers.d.ts +27 -27
  203. package/dist/utils/FunctionWrappers.mjs +84 -84
  204. package/dist/utils/MsalTypes.d.ts +6 -6
  205. package/dist/utils/ProtocolUtils.d.ts +42 -42
  206. package/dist/utils/ProtocolUtils.mjs +69 -69
  207. package/dist/utils/StringUtils.d.ts +40 -40
  208. package/dist/utils/StringUtils.mjs +95 -95
  209. package/dist/utils/TimeUtils.d.ts +27 -27
  210. package/dist/utils/TimeUtils.mjs +45 -45
  211. package/package.json +1 -1
  212. package/src/authority/Authority.ts +216 -130
  213. package/src/authority/AuthorityFactory.ts +4 -4
  214. package/src/authority/AuthorityMetadata.ts +87 -0
  215. package/src/authority/AuthorityOptions.ts +9 -0
  216. package/src/cache/CacheManager.ts +120 -52
  217. package/src/cache/entities/AccountEntity.ts +0 -3
  218. package/src/cache/utils/CacheTypes.ts +1 -0
  219. package/src/client/AuthorizationCodeClient.ts +9 -2
  220. package/src/client/BaseClient.ts +9 -6
  221. package/src/client/RefreshTokenClient.ts +17 -7
  222. package/src/client/SilentFlowClient.ts +49 -49
  223. package/src/config/ClientConfiguration.ts +4 -4
  224. package/src/error/ClientAuthError.ts +8 -0
  225. package/src/error/ClientAuthErrorCodes.ts +1 -0
  226. package/src/index.ts +7 -1
  227. package/src/packageMetadata.ts +1 -1
  228. package/src/response/ResponseHandler.ts +9 -3
  229. package/src/telemetry/performance/PerformanceEvent.ts +24 -2
  230. package/src/utils/Constants.ts +4 -0
@@ -1,11 +1,11 @@
1
- /*! @azure/msal-common v14.1.0 2023-10-05 */
1
+ /*! @azure/msal-common v14.2.0-alpha.0 2023-12-07 */
2
2
  'use strict';
3
3
  import { AuthorityType } from './AuthorityType.mjs';
4
4
  import { isOpenIdConfigResponse } from './OpenIdConfigResponse.mjs';
5
5
  import { UrlString } from '../url/UrlString.mjs';
6
6
  import { createClientAuthError } from '../error/ClientAuthError.mjs';
7
7
  import { Constants, AuthorityMetadataSource, RegionDiscoveryOutcomes, AADAuthorityConstants } from '../utils/Constants.mjs';
8
- import { EndpointMetadata, InstanceDiscoveryMetadata, InstanceDiscoveryMetadataAliases } from './AuthorityMetadata.mjs';
8
+ import { EndpointMetadata, getCloudDiscoveryMetadataFromHardcodedValues, getCloudDiscoveryMetadataFromNetworkResponse, InstanceDiscoveryMetadataAliases } from './AuthorityMetadata.mjs';
9
9
  import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs';
10
10
  import { ProtocolMode } from './ProtocolMode.mjs';
11
11
  import { AuthorityMetadataEntity } from '../cache/entities/AuthorityMetadataEntity.mjs';
@@ -19,744 +19,799 @@ import { invokeAsync } from '../utils/FunctionWrappers.mjs';
19
19
  import { endpointResolutionError, endSessionEndpointNotSupported, openIdConfigError } from '../error/ClientAuthErrorCodes.mjs';
20
20
  import { invalidAuthorityMetadata, untrustedAuthority, invalidCloudDiscoveryMetadata } from '../error/ClientConfigurationErrorCodes.mjs';
21
21
 
22
- /*
23
- * Copyright (c) Microsoft Corporation. All rights reserved.
24
- * Licensed under the MIT License.
25
- */
26
- /**
27
- * The authority class validates the authority URIs used by the user, and retrieves the OpenID Configuration Data from the
28
- * endpoint. It will store the pertinent config data in this object for use during token calls.
29
- * @internal
30
- */
31
- class Authority {
32
- constructor(authority, networkInterface, cacheManager, authorityOptions, logger, performanceClient, correlationId) {
33
- this.canonicalAuthority = authority;
34
- this._canonicalAuthority.validateAsUri();
35
- this.networkInterface = networkInterface;
36
- this.cacheManager = cacheManager;
37
- this.authorityOptions = authorityOptions;
38
- this.regionDiscoveryMetadata = {
39
- region_used: undefined,
40
- region_source: undefined,
41
- region_outcome: undefined,
42
- };
43
- this.logger = logger;
44
- this.performanceClient = performanceClient;
45
- this.correlationId = correlationId;
46
- this.regionDiscovery = new RegionDiscovery(networkInterface, this.logger, this.performanceClient, this.correlationId);
47
- }
48
- /**
49
- * Get {@link AuthorityType}
50
- * @param authorityUri {@link IUri}
51
- * @private
52
- */
53
- getAuthorityType(authorityUri) {
54
- // CIAM auth url pattern is being standardized as: <tenant>.ciamlogin.com
55
- if (authorityUri.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL)) {
56
- return AuthorityType.Ciam;
57
- }
58
- const pathSegments = authorityUri.PathSegments;
59
- if (pathSegments.length) {
60
- switch (pathSegments[0].toLowerCase()) {
61
- case Constants.ADFS:
62
- return AuthorityType.Adfs;
63
- case Constants.DSTS:
64
- return AuthorityType.Dsts;
65
- }
66
- }
67
- return AuthorityType.Default;
68
- }
69
- // See above for AuthorityType
70
- get authorityType() {
71
- return this.getAuthorityType(this.canonicalAuthorityUrlComponents);
72
- }
73
- /**
74
- * ProtocolMode enum representing the way endpoints are constructed.
75
- */
76
- get protocolMode() {
77
- return this.authorityOptions.protocolMode;
78
- }
79
- /**
80
- * Returns authorityOptions which can be used to reinstantiate a new authority instance
81
- */
82
- get options() {
83
- return this.authorityOptions;
84
- }
85
- /**
86
- * A URL that is the authority set by the developer
87
- */
88
- get canonicalAuthority() {
89
- return this._canonicalAuthority.urlString;
90
- }
91
- /**
92
- * Sets canonical authority.
93
- */
94
- set canonicalAuthority(url) {
95
- this._canonicalAuthority = new UrlString(url);
96
- this._canonicalAuthority.validateAsUri();
97
- this._canonicalAuthorityUrlComponents = null;
98
- }
99
- /**
100
- * Get authority components.
101
- */
102
- get canonicalAuthorityUrlComponents() {
103
- if (!this._canonicalAuthorityUrlComponents) {
104
- this._canonicalAuthorityUrlComponents =
105
- this._canonicalAuthority.getUrlComponents();
106
- }
107
- return this._canonicalAuthorityUrlComponents;
108
- }
109
- /**
110
- * Get hostname and port i.e. login.microsoftonline.com
111
- */
112
- get hostnameAndPort() {
113
- return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase();
114
- }
115
- /**
116
- * Get tenant for authority.
117
- */
118
- get tenant() {
119
- return this.canonicalAuthorityUrlComponents.PathSegments[0];
120
- }
121
- /**
122
- * OAuth /authorize endpoint for requests
123
- */
124
- get authorizationEndpoint() {
125
- if (this.discoveryComplete()) {
126
- return this.replacePath(this.metadata.authorization_endpoint);
127
- }
128
- else {
129
- throw createClientAuthError(endpointResolutionError);
130
- }
131
- }
132
- /**
133
- * OAuth /token endpoint for requests
134
- */
135
- get tokenEndpoint() {
136
- if (this.discoveryComplete()) {
137
- return this.replacePath(this.metadata.token_endpoint);
138
- }
139
- else {
140
- throw createClientAuthError(endpointResolutionError);
141
- }
142
- }
143
- get deviceCodeEndpoint() {
144
- if (this.discoveryComplete()) {
145
- return this.replacePath(this.metadata.token_endpoint.replace("/token", "/devicecode"));
146
- }
147
- else {
148
- throw createClientAuthError(endpointResolutionError);
149
- }
150
- }
151
- /**
152
- * OAuth logout endpoint for requests
153
- */
154
- get endSessionEndpoint() {
155
- if (this.discoveryComplete()) {
156
- // ROPC policies may not have end_session_endpoint set
157
- if (!this.metadata.end_session_endpoint) {
158
- throw createClientAuthError(endSessionEndpointNotSupported);
159
- }
160
- return this.replacePath(this.metadata.end_session_endpoint);
161
- }
162
- else {
163
- throw createClientAuthError(endpointResolutionError);
164
- }
165
- }
166
- /**
167
- * OAuth issuer for requests
168
- */
169
- get selfSignedJwtAudience() {
170
- if (this.discoveryComplete()) {
171
- return this.replacePath(this.metadata.issuer);
172
- }
173
- else {
174
- throw createClientAuthError(endpointResolutionError);
175
- }
176
- }
177
- /**
178
- * Jwks_uri for token signing keys
179
- */
180
- get jwksUri() {
181
- if (this.discoveryComplete()) {
182
- return this.replacePath(this.metadata.jwks_uri);
183
- }
184
- else {
185
- throw createClientAuthError(endpointResolutionError);
186
- }
187
- }
188
- /**
189
- * Returns a flag indicating that tenant name can be replaced in authority {@link IUri}
190
- * @param authorityUri {@link IUri}
191
- * @private
192
- */
193
- canReplaceTenant(authorityUri) {
194
- return (authorityUri.PathSegments.length === 1 &&
195
- !Authority.reservedTenantDomains.has(authorityUri.PathSegments[0]) &&
196
- this.getAuthorityType(authorityUri) === AuthorityType.Default &&
197
- this.protocolMode === ProtocolMode.AAD);
198
- }
199
- /**
200
- * Replaces tenant in url path with current tenant. Defaults to common.
201
- * @param urlString
202
- */
203
- replaceTenant(urlString) {
204
- return urlString.replace(/{tenant}|{tenantid}/g, this.tenant);
205
- }
206
- /**
207
- * Replaces path such as tenant or policy with the current tenant or policy.
208
- * @param urlString
209
- */
210
- replacePath(urlString) {
211
- let endpoint = urlString;
212
- const cachedAuthorityUrl = new UrlString(this.metadata.canonical_authority);
213
- const cachedAuthorityUrlComponents = cachedAuthorityUrl.getUrlComponents();
214
- const cachedAuthorityParts = cachedAuthorityUrlComponents.PathSegments;
215
- const currentAuthorityParts = this.canonicalAuthorityUrlComponents.PathSegments;
216
- currentAuthorityParts.forEach((currentPart, index) => {
217
- let cachedPart = cachedAuthorityParts[index];
218
- if (index === 0 &&
219
- this.canReplaceTenant(cachedAuthorityUrlComponents)) {
220
- const tenantId = new UrlString(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0];
221
- /**
222
- * Check if AAD canonical authority contains tenant domain name, for example "testdomain.onmicrosoft.com",
223
- * by comparing its first path segment to the corresponding authorization endpoint path segment, which is
224
- * always resolved with tenant id by OIDC.
225
- */
226
- if (cachedPart !== tenantId) {
227
- this.logger.verbose(`Replacing tenant domain name ${cachedPart} with id ${tenantId}`);
228
- cachedPart = tenantId;
229
- }
230
- }
231
- if (currentPart !== cachedPart) {
232
- endpoint = endpoint.replace(`/${cachedPart}/`, `/${currentPart}/`);
233
- }
234
- });
235
- return this.replaceTenant(endpoint);
236
- }
237
- /**
238
- * The default open id configuration endpoint for any canonical authority.
239
- */
240
- get defaultOpenIdConfigurationEndpoint() {
241
- const canonicalAuthorityHost = this.hostnameAndPort;
242
- if (this.canonicalAuthority.endsWith("v2.0/") ||
243
- this.authorityType === AuthorityType.Adfs ||
244
- (this.protocolMode !== ProtocolMode.AAD &&
245
- !this.isAliasOfKnownMicrosoftAuthority(canonicalAuthorityHost))) {
246
- return `${this.canonicalAuthority}.well-known/openid-configuration`;
247
- }
248
- return `${this.canonicalAuthority}v2.0/.well-known/openid-configuration`;
249
- }
250
- /**
251
- * Boolean that returns whethr or not tenant discovery has been completed.
252
- */
253
- discoveryComplete() {
254
- return !!this.metadata;
255
- }
256
- /**
257
- * Perform endpoint discovery to discover aliases, preferred_cache, preferred_network
258
- * and the /authorize, /token and logout endpoints.
259
- */
260
- async resolveEndpointsAsync() {
261
- this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityResolveEndpointsAsync, this.correlationId);
262
- let metadataEntity = this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort);
263
- if (!metadataEntity) {
264
- metadataEntity = new AuthorityMetadataEntity();
265
- metadataEntity.updateCanonicalAuthority(this.canonicalAuthority);
266
- }
267
- const cloudDiscoverySource = await invokeAsync(this.updateCloudDiscoveryMetadata.bind(this), PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
268
- this.canonicalAuthority = this.canonicalAuthority.replace(this.hostnameAndPort, metadataEntity.preferred_network);
269
- const endpointSource = await invokeAsync(this.updateEndpointMetadata.bind(this), PerformanceEvents.AuthorityUpdateEndpointMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
270
- if (cloudDiscoverySource !== AuthorityMetadataSource.CACHE &&
271
- endpointSource !== AuthorityMetadataSource.CACHE) {
272
- // Reset the expiration time unless both values came from a successful cache lookup
273
- metadataEntity.resetExpiresAt();
274
- metadataEntity.updateCanonicalAuthority(this.canonicalAuthority);
275
- }
276
- const cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(metadataEntity.preferred_cache);
277
- this.cacheManager.setAuthorityMetadata(cacheKey, metadataEntity);
278
- this.metadata = metadataEntity;
279
- }
280
- /**
281
- * Update AuthorityMetadataEntity with new endpoints and return where the information came from
282
- * @param metadataEntity
283
- */
284
- async updateEndpointMetadata(metadataEntity) {
285
- this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateEndpointMetadata, this.correlationId);
286
- this.logger.verbose("Attempting to get endpoint metadata from authority configuration");
287
- let metadata = this.getEndpointMetadataFromConfig();
288
- if (metadata) {
289
- this.logger.verbose("Found endpoint metadata in authority configuration");
290
- metadataEntity.updateEndpointMetadata(metadata, false);
291
- return AuthorityMetadataSource.CONFIG;
292
- }
293
- this.logger.verbose("Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values.");
294
- // skipAuthorityMetadataCache is used to bypass hardcoded authority metadata and force a network metadata cache lookup and network metadata request if no cached response is available.
295
- if (this.authorityOptions.skipAuthorityMetadataCache) {
296
- this.logger.verbose("Skipping hardcoded metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get endpoint metadata from the network metadata cache.");
297
- }
298
- else {
299
- let hardcodedMetadata = this.getEndpointMetadataFromHardcodedValues();
300
- if (hardcodedMetadata) {
301
- this.logger.verbose("Found endpoint metadata from hardcoded values.");
302
- // If the user prefers to use an azure region replace the global endpoints with regional information.
303
- if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
304
- hardcodedMetadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(hardcodedMetadata);
305
- }
306
- metadataEntity.updateEndpointMetadata(hardcodedMetadata, false);
307
- return AuthorityMetadataSource.HARDCODED_VALUES;
308
- }
309
- else {
310
- this.logger.verbose("Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache.");
311
- }
312
- }
313
- // Check cached metadata entity expiration status
314
- const metadataEntityExpired = metadataEntity.isExpired();
315
- if (this.isAuthoritySameType(metadataEntity) &&
316
- metadataEntity.endpointsFromNetwork &&
317
- !metadataEntityExpired) {
318
- // No need to update
319
- this.logger.verbose("Found endpoint metadata in the cache.");
320
- return AuthorityMetadataSource.CACHE;
321
- }
322
- else if (metadataEntityExpired) {
323
- this.logger.verbose("The metadata entity is expired.");
324
- }
325
- metadata = await invokeAsync(this.getEndpointMetadataFromNetwork.bind(this), PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
326
- if (metadata) {
327
- // If the user prefers to use an azure region replace the global endpoints with regional information.
328
- if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
329
- metadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(metadata);
330
- }
331
- metadataEntity.updateEndpointMetadata(metadata, true);
332
- return AuthorityMetadataSource.NETWORK;
333
- }
334
- else {
335
- // Metadata could not be obtained from the config, cache, network or hardcoded values
336
- throw createClientAuthError(openIdConfigError, this.defaultOpenIdConfigurationEndpoint);
337
- }
338
- }
339
- /**
340
- * Compares the number of url components after the domain to determine if the cached
341
- * authority metadata can be used for the requested authority. Protects against same domain different
342
- * authority such as login.microsoftonline.com/tenant and login.microsoftonline.com/tfp/tenant/policy
343
- * @param metadataEntity
344
- */
345
- isAuthoritySameType(metadataEntity) {
346
- const cachedAuthorityUrl = new UrlString(metadataEntity.canonical_authority);
347
- const cachedParts = cachedAuthorityUrl.getUrlComponents().PathSegments;
348
- return (cachedParts.length ===
349
- this.canonicalAuthorityUrlComponents.PathSegments.length);
350
- }
351
- /**
352
- * Parse authorityMetadata config option
353
- */
354
- getEndpointMetadataFromConfig() {
355
- if (this.authorityOptions.authorityMetadata) {
356
- try {
357
- return JSON.parse(this.authorityOptions.authorityMetadata);
358
- }
359
- catch (e) {
360
- throw createClientConfigurationError(invalidAuthorityMetadata);
361
- }
362
- }
363
- return null;
364
- }
365
- /**
366
- * Gets OAuth endpoints from the given OpenID configuration endpoint.
367
- *
368
- * @param hasHardcodedMetadata boolean
369
- */
370
- async getEndpointMetadataFromNetwork() {
371
- this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.correlationId);
372
- const options = {};
373
- /*
374
- * TODO: Add a timeout if the authority exists in our library's
375
- * hardcoded list of metadata
376
- */
377
- const openIdConfigurationEndpoint = this.defaultOpenIdConfigurationEndpoint;
378
- this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from ${openIdConfigurationEndpoint}`);
379
- try {
380
- const response = await this.networkInterface.sendGetRequestAsync(openIdConfigurationEndpoint, options);
381
- const isValidResponse = isOpenIdConfigResponse(response.body);
382
- if (isValidResponse) {
383
- return response.body;
384
- }
385
- else {
386
- this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration`);
387
- return null;
388
- }
389
- }
390
- catch (e) {
391
- this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: ${e}`);
392
- return null;
393
- }
394
- }
395
- /**
396
- * Get OAuth endpoints for common authorities.
397
- */
398
- getEndpointMetadataFromHardcodedValues() {
399
- if (this.canonicalAuthority in EndpointMetadata) {
400
- return EndpointMetadata[this.canonicalAuthority];
401
- }
402
- return null;
403
- }
404
- /**
405
- * Update the retrieved metadata with regional information.
406
- * User selected Azure region will be used if configured.
407
- */
408
- async updateMetadataWithRegionalInformation(metadata) {
409
- this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
410
- const userConfiguredAzureRegion = this.authorityOptions.azureRegionConfiguration?.azureRegion;
411
- if (userConfiguredAzureRegion) {
412
- if (userConfiguredAzureRegion !==
413
- Constants.AZURE_REGION_AUTO_DISCOVER_FLAG) {
414
- this.regionDiscoveryMetadata.region_outcome =
415
- RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION;
416
- this.regionDiscoveryMetadata.region_used =
417
- userConfiguredAzureRegion;
418
- return Authority.replaceWithRegionalInformation(metadata, userConfiguredAzureRegion);
419
- }
420
- const autodetectedRegionName = await invokeAsync(this.regionDiscovery.detectRegion.bind(this.regionDiscovery), PerformanceEvents.RegionDiscoveryDetectRegion, this.logger, this.performanceClient, this.correlationId)(this.authorityOptions.azureRegionConfiguration
421
- ?.environmentRegion, this.regionDiscoveryMetadata);
422
- if (autodetectedRegionName) {
423
- this.regionDiscoveryMetadata.region_outcome =
424
- RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL;
425
- this.regionDiscoveryMetadata.region_used =
426
- autodetectedRegionName;
427
- return Authority.replaceWithRegionalInformation(metadata, autodetectedRegionName);
428
- }
429
- this.regionDiscoveryMetadata.region_outcome =
430
- RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED;
431
- }
432
- return metadata;
433
- }
434
- /**
435
- * Updates the AuthorityMetadataEntity with new aliases, preferred_network and preferred_cache
436
- * and returns where the information was retrieved from
437
- * @param metadataEntity
438
- * @returns AuthorityMetadataSource
439
- */
440
- async updateCloudDiscoveryMetadata(metadataEntity) {
441
- this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.correlationId);
442
- this.logger.verbose("Attempting to get cloud discovery metadata from authority configuration");
443
- this.logger.verbosePii(`Known Authorities: ${this.authorityOptions.knownAuthorities ||
444
- Constants.NOT_APPLICABLE}`);
445
- this.logger.verbosePii(`Authority Metadata: ${this.authorityOptions.authorityMetadata ||
446
- Constants.NOT_APPLICABLE}`);
447
- this.logger.verbosePii(`Canonical Authority: ${metadataEntity.canonical_authority || Constants.NOT_APPLICABLE}`);
448
- let metadata = this.getCloudDiscoveryMetadataFromConfig();
449
- if (metadata) {
450
- this.logger.verbose("Found cloud discovery metadata in authority configuration");
451
- metadataEntity.updateCloudDiscoveryMetadata(metadata, false);
452
- return AuthorityMetadataSource.CONFIG;
453
- }
454
- // If the cached metadata came from config but that config was not passed to this instance, we must go to hardcoded values
455
- this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values.");
456
- if (this.options.skipAuthorityMetadataCache) {
457
- this.logger.verbose("Skipping hardcoded cloud discovery metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get cloud discovery metadata from the network metadata cache.");
458
- }
459
- else {
460
- const hardcodedMetadata = this.getCloudDiscoveryMetadataFromHardcodedValues();
461
- if (hardcodedMetadata) {
462
- this.logger.verbose("Found cloud discovery metadata from hardcoded values.");
463
- metadataEntity.updateCloudDiscoveryMetadata(hardcodedMetadata, false);
464
- return AuthorityMetadataSource.HARDCODED_VALUES;
465
- }
466
- this.logger.verbose("Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache.");
467
- }
468
- const metadataEntityExpired = metadataEntity.isExpired();
469
- if (this.isAuthoritySameType(metadataEntity) &&
470
- metadataEntity.aliasesFromNetwork &&
471
- !metadataEntityExpired) {
472
- this.logger.verbose("Found cloud discovery metadata in the cache.");
473
- // No need to update
474
- return AuthorityMetadataSource.CACHE;
475
- }
476
- else if (metadataEntityExpired) {
477
- this.logger.verbose("The metadata entity is expired.");
478
- }
479
- metadata = await invokeAsync(this.getCloudDiscoveryMetadataFromNetwork.bind(this), PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
480
- if (metadata) {
481
- metadataEntity.updateCloudDiscoveryMetadata(metadata, true);
482
- return AuthorityMetadataSource.NETWORK;
483
- }
484
- // Metadata could not be obtained from the config, cache, network or hardcoded values
485
- throw createClientConfigurationError(untrustedAuthority);
486
- }
487
- /**
488
- * Parse cloudDiscoveryMetadata config or check knownAuthorities
489
- */
490
- getCloudDiscoveryMetadataFromConfig() {
491
- // CIAM does not support cloud discovery metadata
492
- if (this.authorityType === AuthorityType.Ciam) {
493
- this.logger.verbose("CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host.");
494
- return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
495
- }
496
- // Check if network response was provided in config
497
- if (this.authorityOptions.cloudDiscoveryMetadata) {
498
- this.logger.verbose("The cloud discovery metadata has been provided as a network response, in the config.");
499
- try {
500
- this.logger.verbose("Attempting to parse the cloud discovery metadata.");
501
- const parsedResponse = JSON.parse(this.authorityOptions.cloudDiscoveryMetadata);
502
- const metadata = Authority.getCloudDiscoveryMetadataFromNetworkResponse(parsedResponse.metadata, this.hostnameAndPort);
503
- this.logger.verbose("Parsed the cloud discovery metadata.");
504
- if (metadata) {
505
- this.logger.verbose("There is returnable metadata attached to the parsed cloud discovery metadata.");
506
- return metadata;
507
- }
508
- else {
509
- this.logger.verbose("There is no metadata attached to the parsed cloud discovery metadata.");
510
- }
511
- }
512
- catch (e) {
513
- this.logger.verbose("Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error.");
514
- throw createClientConfigurationError(invalidCloudDiscoveryMetadata);
515
- }
516
- }
517
- // If cloudDiscoveryMetadata is empty or does not contain the host, check knownAuthorities
518
- if (this.isInKnownAuthorities()) {
519
- this.logger.verbose("The host is included in knownAuthorities. Creating new cloud discovery metadata from the host.");
520
- return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
521
- }
522
- return null;
523
- }
524
- /**
525
- * Called to get metadata from network if CloudDiscoveryMetadata was not populated by config
526
- *
527
- * @param hasHardcodedMetadata boolean
528
- */
529
- async getCloudDiscoveryMetadataFromNetwork() {
530
- this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.correlationId);
531
- const instanceDiscoveryEndpoint = `${Constants.AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`;
532
- const options = {};
533
- /*
534
- * TODO: Add a timeout if the authority exists in our library's
535
- * hardcoded list of metadata
536
- */
537
- let match = null;
538
- try {
539
- const response = await this.networkInterface.sendGetRequestAsync(instanceDiscoveryEndpoint, options);
540
- let typedResponseBody;
541
- let metadata;
542
- if (isCloudInstanceDiscoveryResponse(response.body)) {
543
- typedResponseBody =
544
- response.body;
545
- metadata = typedResponseBody.metadata;
546
- this.logger.verbosePii(`tenant_discovery_endpoint is: ${typedResponseBody.tenant_discovery_endpoint}`);
547
- }
548
- else if (isCloudInstanceDiscoveryErrorResponse(response.body)) {
549
- this.logger.warning(`A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: ${response.status}`);
550
- typedResponseBody =
551
- response.body;
552
- if (typedResponseBody.error === Constants.INVALID_INSTANCE) {
553
- this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invalid_instance.");
554
- return null;
555
- }
556
- this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error is ${typedResponseBody.error}`);
557
- this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error description is ${typedResponseBody.error_description}`);
558
- this.logger.warning("Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network) to []");
559
- metadata = [];
560
- }
561
- else {
562
- this.logger.error("AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse");
563
- return null;
564
- }
565
- this.logger.verbose("Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request.");
566
- match = Authority.getCloudDiscoveryMetadataFromNetworkResponse(metadata, this.hostnameAndPort);
567
- }
568
- catch (error) {
569
- if (error instanceof AuthError) {
570
- this.logger.error(`There was a network error while attempting to get the cloud discovery instance metadata.\nError: ${error.errorCode}\nError Description: ${error.errorMessage}`);
571
- }
572
- else {
573
- const typedError = error;
574
- this.logger.error(`A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.\nError: ${typedError.name}\nError Description: ${typedError.message}`);
575
- }
576
- return null;
577
- }
578
- // Custom Domain scenario, host is trusted because Instance Discovery call succeeded
579
- if (!match) {
580
- this.logger.warning("The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request.");
581
- this.logger.verbose("Creating custom Authority for custom domain scenario.");
582
- match = Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
583
- }
584
- return match;
585
- }
586
- /**
587
- * Get cloud discovery metadata for common authorities
588
- */
589
- getCloudDiscoveryMetadataFromHardcodedValues() {
590
- if (this.canonicalAuthority in InstanceDiscoveryMetadata) {
591
- const hardcodedMetadataResponse = InstanceDiscoveryMetadata[this.canonicalAuthority];
592
- const metadata = Authority.getCloudDiscoveryMetadataFromNetworkResponse(hardcodedMetadataResponse.metadata, this.hostnameAndPort);
593
- return metadata;
594
- }
595
- return null;
596
- }
597
- /**
598
- * Helper function to determine if this host is included in the knownAuthorities config option
599
- */
600
- isInKnownAuthorities() {
601
- const matches = this.authorityOptions.knownAuthorities.filter((authority) => {
602
- return (UrlString.getDomainFromUrl(authority).toLowerCase() ===
603
- this.hostnameAndPort);
604
- });
605
- return matches.length > 0;
606
- }
607
- /**
608
- * helper function to populate the authority based on azureCloudOptions
609
- * @param authorityString
610
- * @param azureCloudOptions
611
- */
612
- static generateAuthority(authorityString, azureCloudOptions) {
613
- let authorityAzureCloudInstance;
614
- if (azureCloudOptions &&
615
- azureCloudOptions.azureCloudInstance !== AzureCloudInstance.None) {
616
- const tenant = azureCloudOptions.tenant
617
- ? azureCloudOptions.tenant
618
- : Constants.DEFAULT_COMMON_TENANT;
619
- authorityAzureCloudInstance = `${azureCloudOptions.azureCloudInstance}/${tenant}/`;
620
- }
621
- return authorityAzureCloudInstance
622
- ? authorityAzureCloudInstance
623
- : authorityString;
624
- }
625
- /**
626
- * Creates cloud discovery metadata object from a given host
627
- * @param host
628
- */
629
- static createCloudDiscoveryMetadataFromHost(host) {
630
- return {
631
- preferred_network: host,
632
- preferred_cache: host,
633
- aliases: [host],
634
- };
635
- }
636
- /**
637
- * Searches instance discovery network response for the entry that contains the host in the aliases list
638
- * @param response
639
- * @param authority
640
- */
641
- static getCloudDiscoveryMetadataFromNetworkResponse(response, authority) {
642
- for (let i = 0; i < response.length; i++) {
643
- const metadata = response[i];
644
- if (metadata.aliases.indexOf(authority) > -1) {
645
- return metadata;
646
- }
647
- }
648
- return null;
649
- }
650
- /**
651
- * helper function to generate environment from authority object
652
- */
653
- getPreferredCache() {
654
- if (this.discoveryComplete()) {
655
- return this.metadata.preferred_cache;
656
- }
657
- else {
658
- throw createClientAuthError(endpointResolutionError);
659
- }
660
- }
661
- /**
662
- * Returns whether or not the provided host is an alias of this authority instance
663
- * @param host
664
- */
665
- isAlias(host) {
666
- return this.metadata.aliases.indexOf(host) > -1;
667
- }
668
- /**
669
- * Returns whether or not the provided host is an alias of a known Microsoft authority for purposes of endpoint discovery
670
- * @param host
671
- */
672
- isAliasOfKnownMicrosoftAuthority(host) {
673
- return InstanceDiscoveryMetadataAliases.has(host);
674
- }
675
- /**
676
- * Checks whether the provided host is that of a public cloud authority
677
- *
678
- * @param authority string
679
- * @returns bool
680
- */
681
- static isPublicCloudAuthority(host) {
682
- return Constants.KNOWN_PUBLIC_CLOUDS.indexOf(host) >= 0;
683
- }
684
- /**
685
- * Rebuild the authority string with the region
686
- *
687
- * @param host string
688
- * @param region string
689
- */
690
- static buildRegionalAuthorityString(host, region, queryString) {
691
- // Create and validate a Url string object with the initial authority string
692
- const authorityUrlInstance = new UrlString(host);
693
- authorityUrlInstance.validateAsUri();
694
- const authorityUrlParts = authorityUrlInstance.getUrlComponents();
695
- let hostNameAndPort = `${region}.${authorityUrlParts.HostNameAndPort}`;
696
- if (this.isPublicCloudAuthority(authorityUrlParts.HostNameAndPort)) {
697
- hostNameAndPort = `${region}.${Constants.REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`;
698
- }
699
- // Include the query string portion of the url
700
- const url = UrlString.constructAuthorityUriFromObject({
701
- ...authorityUrlInstance.getUrlComponents(),
702
- HostNameAndPort: hostNameAndPort,
703
- }).urlString;
704
- // Add the query string if a query string was provided
705
- if (queryString)
706
- return `${url}?${queryString}`;
707
- return url;
708
- }
709
- /**
710
- * Replace the endpoints in the metadata object with their regional equivalents.
711
- *
712
- * @param metadata OpenIdConfigResponse
713
- * @param azureRegion string
714
- */
715
- static replaceWithRegionalInformation(metadata, azureRegion) {
716
- const regionalMetadata = { ...metadata };
717
- regionalMetadata.authorization_endpoint =
718
- Authority.buildRegionalAuthorityString(regionalMetadata.authorization_endpoint, azureRegion);
719
- // TODO: Enquire on whether we should leave the query string or remove it before releasing the feature
720
- regionalMetadata.token_endpoint =
721
- Authority.buildRegionalAuthorityString(regionalMetadata.token_endpoint, azureRegion, Constants.REGIONAL_AUTH_NON_MSI_QUERY_STRING);
722
- if (regionalMetadata.end_session_endpoint) {
723
- regionalMetadata.end_session_endpoint =
724
- Authority.buildRegionalAuthorityString(regionalMetadata.end_session_endpoint, azureRegion);
725
- }
726
- return regionalMetadata;
727
- }
728
- /**
729
- * Transform CIAM_AUTHORIY as per the below rules:
730
- * If no path segments found and it is a CIAM authority (hostname ends with .ciamlogin.com), then transform it
731
- *
732
- * NOTE: The transformation path should go away once STS supports CIAM with the format: `tenantIdorDomain.ciamlogin.com`
733
- * `ciamlogin.com` can also change in the future and we should accommodate the same
734
- *
735
- * @param authority
736
- */
737
- static transformCIAMAuthority(authority) {
738
- let ciamAuthority = authority.endsWith(Constants.FORWARD_SLASH)
739
- ? authority
740
- : `${authority}${Constants.FORWARD_SLASH}`;
741
- const authorityUrl = new UrlString(authority);
742
- const authorityUrlComponents = authorityUrl.getUrlComponents();
743
- // check if transformation is needed
744
- if (authorityUrlComponents.PathSegments.length === 0 &&
745
- authorityUrlComponents.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL)) {
746
- const tenantIdOrDomain = authorityUrlComponents.HostNameAndPort.split(".")[0];
747
- ciamAuthority = `${ciamAuthority}${tenantIdOrDomain}${Constants.AAD_TENANT_DOMAIN_SUFFIX}`;
748
- }
749
- return ciamAuthority;
750
- }
22
+ /*
23
+ * Copyright (c) Microsoft Corporation. All rights reserved.
24
+ * Licensed under the MIT License.
25
+ */
26
+ /**
27
+ * The authority class validates the authority URIs used by the user, and retrieves the OpenID Configuration Data from the
28
+ * endpoint. It will store the pertinent config data in this object for use during token calls.
29
+ * @internal
30
+ */
31
+ class Authority {
32
+ constructor(authority, networkInterface, cacheManager, authorityOptions, logger, performanceClient, correlationId, managedIdentity) {
33
+ this.canonicalAuthority = authority;
34
+ this._canonicalAuthority.validateAsUri();
35
+ this.networkInterface = networkInterface;
36
+ this.cacheManager = cacheManager;
37
+ this.authorityOptions = authorityOptions;
38
+ this.regionDiscoveryMetadata = {
39
+ region_used: undefined,
40
+ region_source: undefined,
41
+ region_outcome: undefined,
42
+ };
43
+ this.logger = logger;
44
+ this.performanceClient = performanceClient;
45
+ this.correlationId = correlationId;
46
+ this.managedIdentity = managedIdentity || false;
47
+ this.regionDiscovery = new RegionDiscovery(networkInterface, this.logger, this.performanceClient, this.correlationId);
48
+ }
49
+ /**
50
+ * Get {@link AuthorityType}
51
+ * @param authorityUri {@link IUri}
52
+ * @private
53
+ */
54
+ getAuthorityType(authorityUri) {
55
+ // CIAM auth url pattern is being standardized as: <tenant>.ciamlogin.com
56
+ if (authorityUri.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL)) {
57
+ return AuthorityType.Ciam;
58
+ }
59
+ const pathSegments = authorityUri.PathSegments;
60
+ if (pathSegments.length) {
61
+ switch (pathSegments[0].toLowerCase()) {
62
+ case Constants.ADFS:
63
+ return AuthorityType.Adfs;
64
+ case Constants.DSTS:
65
+ return AuthorityType.Dsts;
66
+ }
67
+ }
68
+ return AuthorityType.Default;
69
+ }
70
+ // See above for AuthorityType
71
+ get authorityType() {
72
+ return this.getAuthorityType(this.canonicalAuthorityUrlComponents);
73
+ }
74
+ /**
75
+ * ProtocolMode enum representing the way endpoints are constructed.
76
+ */
77
+ get protocolMode() {
78
+ return this.authorityOptions.protocolMode;
79
+ }
80
+ /**
81
+ * Returns authorityOptions which can be used to reinstantiate a new authority instance
82
+ */
83
+ get options() {
84
+ return this.authorityOptions;
85
+ }
86
+ /**
87
+ * A URL that is the authority set by the developer
88
+ */
89
+ get canonicalAuthority() {
90
+ return this._canonicalAuthority.urlString;
91
+ }
92
+ /**
93
+ * Sets canonical authority.
94
+ */
95
+ set canonicalAuthority(url) {
96
+ this._canonicalAuthority = new UrlString(url);
97
+ this._canonicalAuthority.validateAsUri();
98
+ this._canonicalAuthorityUrlComponents = null;
99
+ }
100
+ /**
101
+ * Get authority components.
102
+ */
103
+ get canonicalAuthorityUrlComponents() {
104
+ if (!this._canonicalAuthorityUrlComponents) {
105
+ this._canonicalAuthorityUrlComponents =
106
+ this._canonicalAuthority.getUrlComponents();
107
+ }
108
+ return this._canonicalAuthorityUrlComponents;
109
+ }
110
+ /**
111
+ * Get hostname and port i.e. login.microsoftonline.com
112
+ */
113
+ get hostnameAndPort() {
114
+ return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase();
115
+ }
116
+ /**
117
+ * Get tenant for authority.
118
+ */
119
+ get tenant() {
120
+ return this.canonicalAuthorityUrlComponents.PathSegments[0];
121
+ }
122
+ /**
123
+ * OAuth /authorize endpoint for requests
124
+ */
125
+ get authorizationEndpoint() {
126
+ if (this.discoveryComplete()) {
127
+ return this.replacePath(this.metadata.authorization_endpoint);
128
+ }
129
+ else {
130
+ throw createClientAuthError(endpointResolutionError);
131
+ }
132
+ }
133
+ /**
134
+ * OAuth /token endpoint for requests
135
+ */
136
+ get tokenEndpoint() {
137
+ if (this.discoveryComplete()) {
138
+ return this.replacePath(this.metadata.token_endpoint);
139
+ }
140
+ else {
141
+ throw createClientAuthError(endpointResolutionError);
142
+ }
143
+ }
144
+ get deviceCodeEndpoint() {
145
+ if (this.discoveryComplete()) {
146
+ return this.replacePath(this.metadata.token_endpoint.replace("/token", "/devicecode"));
147
+ }
148
+ else {
149
+ throw createClientAuthError(endpointResolutionError);
150
+ }
151
+ }
152
+ /**
153
+ * OAuth logout endpoint for requests
154
+ */
155
+ get endSessionEndpoint() {
156
+ if (this.discoveryComplete()) {
157
+ // ROPC policies may not have end_session_endpoint set
158
+ if (!this.metadata.end_session_endpoint) {
159
+ throw createClientAuthError(endSessionEndpointNotSupported);
160
+ }
161
+ return this.replacePath(this.metadata.end_session_endpoint);
162
+ }
163
+ else {
164
+ throw createClientAuthError(endpointResolutionError);
165
+ }
166
+ }
167
+ /**
168
+ * OAuth issuer for requests
169
+ */
170
+ get selfSignedJwtAudience() {
171
+ if (this.discoveryComplete()) {
172
+ return this.replacePath(this.metadata.issuer);
173
+ }
174
+ else {
175
+ throw createClientAuthError(endpointResolutionError);
176
+ }
177
+ }
178
+ /**
179
+ * Jwks_uri for token signing keys
180
+ */
181
+ get jwksUri() {
182
+ if (this.discoveryComplete()) {
183
+ return this.replacePath(this.metadata.jwks_uri);
184
+ }
185
+ else {
186
+ throw createClientAuthError(endpointResolutionError);
187
+ }
188
+ }
189
+ /**
190
+ * Returns a flag indicating that tenant name can be replaced in authority {@link IUri}
191
+ * @param authorityUri {@link IUri}
192
+ * @private
193
+ */
194
+ canReplaceTenant(authorityUri) {
195
+ return (authorityUri.PathSegments.length === 1 &&
196
+ !Authority.reservedTenantDomains.has(authorityUri.PathSegments[0]) &&
197
+ this.getAuthorityType(authorityUri) === AuthorityType.Default &&
198
+ this.protocolMode === ProtocolMode.AAD);
199
+ }
200
+ /**
201
+ * Replaces tenant in url path with current tenant. Defaults to common.
202
+ * @param urlString
203
+ */
204
+ replaceTenant(urlString) {
205
+ return urlString.replace(/{tenant}|{tenantid}/g, this.tenant);
206
+ }
207
+ /**
208
+ * Replaces path such as tenant or policy with the current tenant or policy.
209
+ * @param urlString
210
+ */
211
+ replacePath(urlString) {
212
+ let endpoint = urlString;
213
+ const cachedAuthorityUrl = new UrlString(this.metadata.canonical_authority);
214
+ const cachedAuthorityUrlComponents = cachedAuthorityUrl.getUrlComponents();
215
+ const cachedAuthorityParts = cachedAuthorityUrlComponents.PathSegments;
216
+ const currentAuthorityParts = this.canonicalAuthorityUrlComponents.PathSegments;
217
+ currentAuthorityParts.forEach((currentPart, index) => {
218
+ let cachedPart = cachedAuthorityParts[index];
219
+ if (index === 0 &&
220
+ this.canReplaceTenant(cachedAuthorityUrlComponents)) {
221
+ const tenantId = new UrlString(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0];
222
+ /**
223
+ * Check if AAD canonical authority contains tenant domain name, for example "testdomain.onmicrosoft.com",
224
+ * by comparing its first path segment to the corresponding authorization endpoint path segment, which is
225
+ * always resolved with tenant id by OIDC.
226
+ */
227
+ if (cachedPart !== tenantId) {
228
+ this.logger.verbose(`Replacing tenant domain name ${cachedPart} with id ${tenantId}`);
229
+ cachedPart = tenantId;
230
+ }
231
+ }
232
+ if (currentPart !== cachedPart) {
233
+ endpoint = endpoint.replace(`/${cachedPart}/`, `/${currentPart}/`);
234
+ }
235
+ });
236
+ return this.replaceTenant(endpoint);
237
+ }
238
+ /**
239
+ * The default open id configuration endpoint for any canonical authority.
240
+ */
241
+ get defaultOpenIdConfigurationEndpoint() {
242
+ const canonicalAuthorityHost = this.hostnameAndPort;
243
+ if (this.canonicalAuthority.endsWith("v2.0/") ||
244
+ this.authorityType === AuthorityType.Adfs ||
245
+ (this.protocolMode !== ProtocolMode.AAD &&
246
+ !this.isAliasOfKnownMicrosoftAuthority(canonicalAuthorityHost))) {
247
+ return `${this.canonicalAuthority}.well-known/openid-configuration`;
248
+ }
249
+ return `${this.canonicalAuthority}v2.0/.well-known/openid-configuration`;
250
+ }
251
+ /**
252
+ * Boolean that returns whether or not tenant discovery has been completed.
253
+ */
254
+ discoveryComplete() {
255
+ return !!this.metadata;
256
+ }
257
+ /**
258
+ * Perform endpoint discovery to discover aliases, preferred_cache, preferred_network
259
+ * and the /authorize, /token and logout endpoints.
260
+ */
261
+ async resolveEndpointsAsync() {
262
+ this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityResolveEndpointsAsync, this.correlationId);
263
+ const metadataEntity = this.getCurrentMetadataEntity();
264
+ const cloudDiscoverySource = await invokeAsync(this.updateCloudDiscoveryMetadata.bind(this), PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
265
+ this.canonicalAuthority = this.canonicalAuthority.replace(this.hostnameAndPort, metadataEntity.preferred_network);
266
+ const endpointSource = await invokeAsync(this.updateEndpointMetadata.bind(this), PerformanceEvents.AuthorityUpdateEndpointMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
267
+ this.updateCachedMetadata(metadataEntity, cloudDiscoverySource, {
268
+ source: endpointSource,
269
+ });
270
+ }
271
+ /**
272
+ * Returns metadata entity from cache if it exists, otherwiser returns a new metadata entity built
273
+ * from the configured canonical authority
274
+ * @returns
275
+ */
276
+ getCurrentMetadataEntity() {
277
+ let metadataEntity = this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort);
278
+ if (!metadataEntity) {
279
+ metadataEntity = new AuthorityMetadataEntity();
280
+ metadataEntity.updateCanonicalAuthority(this.canonicalAuthority);
281
+ }
282
+ return metadataEntity;
283
+ }
284
+ /**
285
+ * Updates cached metadata based on metadata source and sets the instance's metadata
286
+ * property to the same value
287
+ * @param metadataEntity
288
+ * @param cloudDiscoverySource
289
+ * @param endpointMetadataResult
290
+ */
291
+ updateCachedMetadata(metadataEntity, cloudDiscoverySource, endpointMetadataResult) {
292
+ if (cloudDiscoverySource !== AuthorityMetadataSource.CACHE &&
293
+ endpointMetadataResult?.source !== AuthorityMetadataSource.CACHE) {
294
+ // Reset the expiration time unless both values came from a successful cache lookup
295
+ metadataEntity.resetExpiresAt();
296
+ metadataEntity.updateCanonicalAuthority(this.canonicalAuthority);
297
+ }
298
+ const cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(metadataEntity.preferred_cache);
299
+ this.cacheManager.setAuthorityMetadata(cacheKey, metadataEntity);
300
+ this.metadata = metadataEntity;
301
+ }
302
+ /**
303
+ * Update AuthorityMetadataEntity with new endpoints and return where the information came from
304
+ * @param metadataEntity
305
+ */
306
+ async updateEndpointMetadata(metadataEntity) {
307
+ this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateEndpointMetadata, this.correlationId);
308
+ const localMetadata = this.updateEndpointMetadataFromLocalSources(metadataEntity);
309
+ // Further update may be required for hardcoded metadata if regional metadata is preferred
310
+ if (localMetadata) {
311
+ if (localMetadata.source ===
312
+ AuthorityMetadataSource.HARDCODED_VALUES) {
313
+ // If the user prefers to use an azure region replace the global endpoints with regional information.
314
+ if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
315
+ if (localMetadata.metadata) {
316
+ const hardcodedMetadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(localMetadata.metadata);
317
+ metadataEntity.updateEndpointMetadata(hardcodedMetadata, false);
318
+ }
319
+ }
320
+ }
321
+ return localMetadata.source;
322
+ }
323
+ // Get metadata from network if local sources aren't available
324
+ let metadata = await invokeAsync(this.getEndpointMetadataFromNetwork.bind(this), PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
325
+ if (metadata) {
326
+ // If the user prefers to use an azure region replace the global endpoints with regional information.
327
+ if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
328
+ metadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(metadata);
329
+ }
330
+ metadataEntity.updateEndpointMetadata(metadata, true);
331
+ return AuthorityMetadataSource.NETWORK;
332
+ }
333
+ else {
334
+ // Metadata could not be obtained from the config, cache, network or hardcoded values
335
+ throw createClientAuthError(openIdConfigError, this.defaultOpenIdConfigurationEndpoint);
336
+ }
337
+ }
338
+ /**
339
+ * Updates endpoint metadata from local sources and returns where the information was retrieved from and the metadata config
340
+ * response if the source is hardcoded metadata
341
+ * @param metadataEntity
342
+ * @returns
343
+ */
344
+ updateEndpointMetadataFromLocalSources(metadataEntity) {
345
+ this.logger.verbose("Attempting to get endpoint metadata from authority configuration");
346
+ const configMetadata = this.getEndpointMetadataFromConfig();
347
+ if (configMetadata) {
348
+ this.logger.verbose("Found endpoint metadata in authority configuration");
349
+ metadataEntity.updateEndpointMetadata(configMetadata, false);
350
+ return {
351
+ source: AuthorityMetadataSource.CONFIG,
352
+ };
353
+ }
354
+ this.logger.verbose("Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values.");
355
+ // skipAuthorityMetadataCache is used to bypass hardcoded authority metadata and force a network metadata cache lookup and network metadata request if no cached response is available.
356
+ if (this.authorityOptions.skipAuthorityMetadataCache) {
357
+ this.logger.verbose("Skipping hardcoded metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get endpoint metadata from the network metadata cache.");
358
+ }
359
+ else {
360
+ const hardcodedMetadata = this.getEndpointMetadataFromHardcodedValues();
361
+ if (hardcodedMetadata) {
362
+ metadataEntity.updateEndpointMetadata(hardcodedMetadata, false);
363
+ return {
364
+ source: AuthorityMetadataSource.HARDCODED_VALUES,
365
+ metadata: hardcodedMetadata,
366
+ };
367
+ }
368
+ else {
369
+ this.logger.verbose("Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache.");
370
+ }
371
+ }
372
+ // Check cached metadata entity expiration status
373
+ const metadataEntityExpired = metadataEntity.isExpired();
374
+ if (this.isAuthoritySameType(metadataEntity) &&
375
+ metadataEntity.endpointsFromNetwork &&
376
+ !metadataEntityExpired) {
377
+ // No need to update
378
+ this.logger.verbose("Found endpoint metadata in the cache.");
379
+ return { source: AuthorityMetadataSource.CACHE };
380
+ }
381
+ else if (metadataEntityExpired) {
382
+ this.logger.verbose("The metadata entity is expired.");
383
+ }
384
+ return null;
385
+ }
386
+ /**
387
+ * Compares the number of url components after the domain to determine if the cached
388
+ * authority metadata can be used for the requested authority. Protects against same domain different
389
+ * authority such as login.microsoftonline.com/tenant and login.microsoftonline.com/tfp/tenant/policy
390
+ * @param metadataEntity
391
+ */
392
+ isAuthoritySameType(metadataEntity) {
393
+ const cachedAuthorityUrl = new UrlString(metadataEntity.canonical_authority);
394
+ const cachedParts = cachedAuthorityUrl.getUrlComponents().PathSegments;
395
+ return (cachedParts.length ===
396
+ this.canonicalAuthorityUrlComponents.PathSegments.length);
397
+ }
398
+ /**
399
+ * Parse authorityMetadata config option
400
+ */
401
+ getEndpointMetadataFromConfig() {
402
+ if (this.authorityOptions.authorityMetadata) {
403
+ try {
404
+ return JSON.parse(this.authorityOptions.authorityMetadata);
405
+ }
406
+ catch (e) {
407
+ throw createClientConfigurationError(invalidAuthorityMetadata);
408
+ }
409
+ }
410
+ return null;
411
+ }
412
+ /**
413
+ * Gets OAuth endpoints from the given OpenID configuration endpoint.
414
+ *
415
+ * @param hasHardcodedMetadata boolean
416
+ */
417
+ async getEndpointMetadataFromNetwork() {
418
+ this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.correlationId);
419
+ const options = {};
420
+ /*
421
+ * TODO: Add a timeout if the authority exists in our library's
422
+ * hardcoded list of metadata
423
+ */
424
+ const openIdConfigurationEndpoint = this.defaultOpenIdConfigurationEndpoint;
425
+ this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from ${openIdConfigurationEndpoint}`);
426
+ try {
427
+ const response = await this.networkInterface.sendGetRequestAsync(openIdConfigurationEndpoint, options);
428
+ const isValidResponse = isOpenIdConfigResponse(response.body);
429
+ if (isValidResponse) {
430
+ return response.body;
431
+ }
432
+ else {
433
+ this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration`);
434
+ return null;
435
+ }
436
+ }
437
+ catch (e) {
438
+ this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: ${e}`);
439
+ return null;
440
+ }
441
+ }
442
+ /**
443
+ * Get OAuth endpoints for common authorities.
444
+ */
445
+ getEndpointMetadataFromHardcodedValues() {
446
+ if (this.canonicalAuthority in EndpointMetadata) {
447
+ return EndpointMetadata[this.canonicalAuthority];
448
+ }
449
+ return null;
450
+ }
451
+ /**
452
+ * Update the retrieved metadata with regional information.
453
+ * User selected Azure region will be used if configured.
454
+ */
455
+ async updateMetadataWithRegionalInformation(metadata) {
456
+ this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
457
+ const userConfiguredAzureRegion = this.authorityOptions.azureRegionConfiguration?.azureRegion;
458
+ if (userConfiguredAzureRegion) {
459
+ if (userConfiguredAzureRegion !==
460
+ Constants.AZURE_REGION_AUTO_DISCOVER_FLAG) {
461
+ this.regionDiscoveryMetadata.region_outcome =
462
+ RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION;
463
+ this.regionDiscoveryMetadata.region_used =
464
+ userConfiguredAzureRegion;
465
+ return Authority.replaceWithRegionalInformation(metadata, userConfiguredAzureRegion);
466
+ }
467
+ const autodetectedRegionName = await invokeAsync(this.regionDiscovery.detectRegion.bind(this.regionDiscovery), PerformanceEvents.RegionDiscoveryDetectRegion, this.logger, this.performanceClient, this.correlationId)(this.authorityOptions.azureRegionConfiguration
468
+ ?.environmentRegion, this.regionDiscoveryMetadata);
469
+ if (autodetectedRegionName) {
470
+ this.regionDiscoveryMetadata.region_outcome =
471
+ RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL;
472
+ this.regionDiscoveryMetadata.region_used =
473
+ autodetectedRegionName;
474
+ return Authority.replaceWithRegionalInformation(metadata, autodetectedRegionName);
475
+ }
476
+ this.regionDiscoveryMetadata.region_outcome =
477
+ RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED;
478
+ }
479
+ return metadata;
480
+ }
481
+ /**
482
+ * Updates the AuthorityMetadataEntity with new aliases, preferred_network and preferred_cache
483
+ * and returns where the information was retrieved from
484
+ * @param metadataEntity
485
+ * @returns AuthorityMetadataSource
486
+ */
487
+ async updateCloudDiscoveryMetadata(metadataEntity) {
488
+ this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.correlationId);
489
+ const localMetadataSource = this.updateCloudDiscoveryMetadataFromLocalSources(metadataEntity);
490
+ if (localMetadataSource) {
491
+ return localMetadataSource;
492
+ }
493
+ // Fallback to network as metadata source
494
+ const metadata = await invokeAsync(this.getCloudDiscoveryMetadataFromNetwork.bind(this), PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
495
+ if (metadata) {
496
+ metadataEntity.updateCloudDiscoveryMetadata(metadata, true);
497
+ return AuthorityMetadataSource.NETWORK;
498
+ }
499
+ // Metadata could not be obtained from the config, cache, network or hardcoded values
500
+ throw createClientConfigurationError(untrustedAuthority);
501
+ }
502
+ updateCloudDiscoveryMetadataFromLocalSources(metadataEntity) {
503
+ this.logger.verbose("Attempting to get cloud discovery metadata from authority configuration");
504
+ this.logger.verbosePii(`Known Authorities: ${this.authorityOptions.knownAuthorities ||
505
+ Constants.NOT_APPLICABLE}`);
506
+ this.logger.verbosePii(`Authority Metadata: ${this.authorityOptions.authorityMetadata ||
507
+ Constants.NOT_APPLICABLE}`);
508
+ this.logger.verbosePii(`Canonical Authority: ${metadataEntity.canonical_authority || Constants.NOT_APPLICABLE}`);
509
+ const metadata = this.getCloudDiscoveryMetadataFromConfig();
510
+ if (metadata) {
511
+ this.logger.verbose("Found cloud discovery metadata in authority configuration");
512
+ metadataEntity.updateCloudDiscoveryMetadata(metadata, false);
513
+ return AuthorityMetadataSource.CONFIG;
514
+ }
515
+ // If the cached metadata came from config but that config was not passed to this instance, we must go to hardcoded values
516
+ this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values.");
517
+ if (this.options.skipAuthorityMetadataCache) {
518
+ this.logger.verbose("Skipping hardcoded cloud discovery metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get cloud discovery metadata from the network metadata cache.");
519
+ }
520
+ else {
521
+ const hardcodedMetadata = getCloudDiscoveryMetadataFromHardcodedValues(this.canonicalAuthority);
522
+ if (hardcodedMetadata) {
523
+ this.logger.verbose("Found cloud discovery metadata from hardcoded values.");
524
+ metadataEntity.updateCloudDiscoveryMetadata(hardcodedMetadata, false);
525
+ return AuthorityMetadataSource.HARDCODED_VALUES;
526
+ }
527
+ this.logger.verbose("Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache.");
528
+ }
529
+ const metadataEntityExpired = metadataEntity.isExpired();
530
+ if (this.isAuthoritySameType(metadataEntity) &&
531
+ metadataEntity.aliasesFromNetwork &&
532
+ !metadataEntityExpired) {
533
+ this.logger.verbose("Found cloud discovery metadata in the cache.");
534
+ // No need to update
535
+ return AuthorityMetadataSource.CACHE;
536
+ }
537
+ else if (metadataEntityExpired) {
538
+ this.logger.verbose("The metadata entity is expired.");
539
+ }
540
+ return null;
541
+ }
542
+ /**
543
+ * Parse cloudDiscoveryMetadata config or check knownAuthorities
544
+ */
545
+ getCloudDiscoveryMetadataFromConfig() {
546
+ // CIAM does not support cloud discovery metadata
547
+ if (this.authorityType === AuthorityType.Ciam) {
548
+ this.logger.verbose("CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host.");
549
+ return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
550
+ }
551
+ // Check if network response was provided in config
552
+ if (this.authorityOptions.cloudDiscoveryMetadata) {
553
+ this.logger.verbose("The cloud discovery metadata has been provided as a network response, in the config.");
554
+ try {
555
+ this.logger.verbose("Attempting to parse the cloud discovery metadata.");
556
+ const parsedResponse = JSON.parse(this.authorityOptions.cloudDiscoveryMetadata);
557
+ const metadata = getCloudDiscoveryMetadataFromNetworkResponse(parsedResponse.metadata, this.hostnameAndPort);
558
+ this.logger.verbose("Parsed the cloud discovery metadata.");
559
+ if (metadata) {
560
+ this.logger.verbose("There is returnable metadata attached to the parsed cloud discovery metadata.");
561
+ return metadata;
562
+ }
563
+ else {
564
+ this.logger.verbose("There is no metadata attached to the parsed cloud discovery metadata.");
565
+ }
566
+ }
567
+ catch (e) {
568
+ this.logger.verbose("Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error.");
569
+ throw createClientConfigurationError(invalidCloudDiscoveryMetadata);
570
+ }
571
+ }
572
+ // If cloudDiscoveryMetadata is empty or does not contain the host, check knownAuthorities
573
+ if (this.isInKnownAuthorities()) {
574
+ this.logger.verbose("The host is included in knownAuthorities. Creating new cloud discovery metadata from the host.");
575
+ return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
576
+ }
577
+ return null;
578
+ }
579
+ /**
580
+ * Called to get metadata from network if CloudDiscoveryMetadata was not populated by config
581
+ *
582
+ * @param hasHardcodedMetadata boolean
583
+ */
584
+ async getCloudDiscoveryMetadataFromNetwork() {
585
+ this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.correlationId);
586
+ const instanceDiscoveryEndpoint = `${Constants.AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`;
587
+ const options = {};
588
+ /*
589
+ * TODO: Add a timeout if the authority exists in our library's
590
+ * hardcoded list of metadata
591
+ */
592
+ let match = null;
593
+ try {
594
+ const response = await this.networkInterface.sendGetRequestAsync(instanceDiscoveryEndpoint, options);
595
+ let typedResponseBody;
596
+ let metadata;
597
+ if (isCloudInstanceDiscoveryResponse(response.body)) {
598
+ typedResponseBody =
599
+ response.body;
600
+ metadata = typedResponseBody.metadata;
601
+ this.logger.verbosePii(`tenant_discovery_endpoint is: ${typedResponseBody.tenant_discovery_endpoint}`);
602
+ }
603
+ else if (isCloudInstanceDiscoveryErrorResponse(response.body)) {
604
+ this.logger.warning(`A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: ${response.status}`);
605
+ typedResponseBody =
606
+ response.body;
607
+ if (typedResponseBody.error === Constants.INVALID_INSTANCE) {
608
+ this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invalid_instance.");
609
+ return null;
610
+ }
611
+ this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error is ${typedResponseBody.error}`);
612
+ this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error description is ${typedResponseBody.error_description}`);
613
+ this.logger.warning("Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network) to []");
614
+ metadata = [];
615
+ }
616
+ else {
617
+ this.logger.error("AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse");
618
+ return null;
619
+ }
620
+ this.logger.verbose("Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request.");
621
+ match = getCloudDiscoveryMetadataFromNetworkResponse(metadata, this.hostnameAndPort);
622
+ }
623
+ catch (error) {
624
+ if (error instanceof AuthError) {
625
+ this.logger.error(`There was a network error while attempting to get the cloud discovery instance metadata.\nError: ${error.errorCode}\nError Description: ${error.errorMessage}`);
626
+ }
627
+ else {
628
+ const typedError = error;
629
+ this.logger.error(`A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.\nError: ${typedError.name}\nError Description: ${typedError.message}`);
630
+ }
631
+ return null;
632
+ }
633
+ // Custom Domain scenario, host is trusted because Instance Discovery call succeeded
634
+ if (!match) {
635
+ this.logger.warning("The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request.");
636
+ this.logger.verbose("Creating custom Authority for custom domain scenario.");
637
+ match = Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
638
+ }
639
+ return match;
640
+ }
641
+ /**
642
+ * Helper function to determine if this host is included in the knownAuthorities config option
643
+ */
644
+ isInKnownAuthorities() {
645
+ const matches = this.authorityOptions.knownAuthorities.filter((authority) => {
646
+ return (UrlString.getDomainFromUrl(authority).toLowerCase() ===
647
+ this.hostnameAndPort);
648
+ });
649
+ return matches.length > 0;
650
+ }
651
+ /**
652
+ * helper function to populate the authority based on azureCloudOptions
653
+ * @param authorityString
654
+ * @param azureCloudOptions
655
+ */
656
+ static generateAuthority(authorityString, azureCloudOptions) {
657
+ let authorityAzureCloudInstance;
658
+ if (azureCloudOptions &&
659
+ azureCloudOptions.azureCloudInstance !== AzureCloudInstance.None) {
660
+ const tenant = azureCloudOptions.tenant
661
+ ? azureCloudOptions.tenant
662
+ : Constants.DEFAULT_COMMON_TENANT;
663
+ authorityAzureCloudInstance = `${azureCloudOptions.azureCloudInstance}/${tenant}/`;
664
+ }
665
+ return authorityAzureCloudInstance
666
+ ? authorityAzureCloudInstance
667
+ : authorityString;
668
+ }
669
+ /**
670
+ * Creates cloud discovery metadata object from a given host
671
+ * @param host
672
+ */
673
+ static createCloudDiscoveryMetadataFromHost(host) {
674
+ return {
675
+ preferred_network: host,
676
+ preferred_cache: host,
677
+ aliases: [host],
678
+ };
679
+ }
680
+ /**
681
+ * helper function to generate environment from authority object
682
+ */
683
+ getPreferredCache() {
684
+ if (this.managedIdentity) {
685
+ return Constants.DEFAULT_AUTHORITY_HOST;
686
+ }
687
+ else if (this.discoveryComplete()) {
688
+ return this.metadata.preferred_cache;
689
+ }
690
+ else {
691
+ throw createClientAuthError(endpointResolutionError);
692
+ }
693
+ }
694
+ /**
695
+ * Returns whether or not the provided host is an alias of this authority instance
696
+ * @param host
697
+ */
698
+ isAlias(host) {
699
+ return this.metadata.aliases.indexOf(host) > -1;
700
+ }
701
+ /**
702
+ * Returns whether or not the provided host is an alias of a known Microsoft authority for purposes of endpoint discovery
703
+ * @param host
704
+ */
705
+ isAliasOfKnownMicrosoftAuthority(host) {
706
+ return InstanceDiscoveryMetadataAliases.has(host);
707
+ }
708
+ /**
709
+ * Checks whether the provided host is that of a public cloud authority
710
+ *
711
+ * @param authority string
712
+ * @returns bool
713
+ */
714
+ static isPublicCloudAuthority(host) {
715
+ return Constants.KNOWN_PUBLIC_CLOUDS.indexOf(host) >= 0;
716
+ }
717
+ /**
718
+ * Rebuild the authority string with the region
719
+ *
720
+ * @param host string
721
+ * @param region string
722
+ */
723
+ static buildRegionalAuthorityString(host, region, queryString) {
724
+ // Create and validate a Url string object with the initial authority string
725
+ const authorityUrlInstance = new UrlString(host);
726
+ authorityUrlInstance.validateAsUri();
727
+ const authorityUrlParts = authorityUrlInstance.getUrlComponents();
728
+ let hostNameAndPort = `${region}.${authorityUrlParts.HostNameAndPort}`;
729
+ if (this.isPublicCloudAuthority(authorityUrlParts.HostNameAndPort)) {
730
+ hostNameAndPort = `${region}.${Constants.REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`;
731
+ }
732
+ // Include the query string portion of the url
733
+ const url = UrlString.constructAuthorityUriFromObject({
734
+ ...authorityUrlInstance.getUrlComponents(),
735
+ HostNameAndPort: hostNameAndPort,
736
+ }).urlString;
737
+ // Add the query string if a query string was provided
738
+ if (queryString)
739
+ return `${url}?${queryString}`;
740
+ return url;
741
+ }
742
+ /**
743
+ * Replace the endpoints in the metadata object with their regional equivalents.
744
+ *
745
+ * @param metadata OpenIdConfigResponse
746
+ * @param azureRegion string
747
+ */
748
+ static replaceWithRegionalInformation(metadata, azureRegion) {
749
+ const regionalMetadata = { ...metadata };
750
+ regionalMetadata.authorization_endpoint =
751
+ Authority.buildRegionalAuthorityString(regionalMetadata.authorization_endpoint, azureRegion);
752
+ // TODO: Enquire on whether we should leave the query string or remove it before releasing the feature
753
+ regionalMetadata.token_endpoint =
754
+ Authority.buildRegionalAuthorityString(regionalMetadata.token_endpoint, azureRegion, Constants.REGIONAL_AUTH_NON_MSI_QUERY_STRING);
755
+ if (regionalMetadata.end_session_endpoint) {
756
+ regionalMetadata.end_session_endpoint =
757
+ Authority.buildRegionalAuthorityString(regionalMetadata.end_session_endpoint, azureRegion);
758
+ }
759
+ return regionalMetadata;
760
+ }
761
+ /**
762
+ * Transform CIAM_AUTHORIY as per the below rules:
763
+ * If no path segments found and it is a CIAM authority (hostname ends with .ciamlogin.com), then transform it
764
+ *
765
+ * NOTE: The transformation path should go away once STS supports CIAM with the format: `tenantIdorDomain.ciamlogin.com`
766
+ * `ciamlogin.com` can also change in the future and we should accommodate the same
767
+ *
768
+ * @param authority
769
+ */
770
+ static transformCIAMAuthority(authority) {
771
+ let ciamAuthority = authority;
772
+ const authorityUrl = new UrlString(authority);
773
+ const authorityUrlComponents = authorityUrl.getUrlComponents();
774
+ // check if transformation is needed
775
+ if (authorityUrlComponents.PathSegments.length === 0 &&
776
+ authorityUrlComponents.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL)) {
777
+ const tenantIdOrDomain = authorityUrlComponents.HostNameAndPort.split(".")[0];
778
+ ciamAuthority = `${ciamAuthority}${tenantIdOrDomain}${Constants.AAD_TENANT_DOMAIN_SUFFIX}`;
779
+ }
780
+ return ciamAuthority;
781
+ }
782
+ }
783
+ // Reserved tenant domain names that will not be replaced with tenant id
784
+ Authority.reservedTenantDomains = new Set([
785
+ "{tenant}",
786
+ "{tenantid}",
787
+ AADAuthorityConstants.COMMON,
788
+ AADAuthorityConstants.CONSUMERS,
789
+ AADAuthorityConstants.ORGANIZATIONS,
790
+ ]);
791
+ function formatAuthorityUri(authorityUri) {
792
+ return authorityUri.endsWith(Constants.FORWARD_SLASH)
793
+ ? authorityUri
794
+ : `${authorityUri}${Constants.FORWARD_SLASH}`;
795
+ }
796
+ function buildStaticAuthorityOptions(authOptions) {
797
+ const rawCloudDiscoveryMetadata = authOptions.cloudDiscoveryMetadata;
798
+ let cloudDiscoveryMetadata = undefined;
799
+ if (rawCloudDiscoveryMetadata) {
800
+ try {
801
+ cloudDiscoveryMetadata = JSON.parse(rawCloudDiscoveryMetadata).metadata;
802
+ }
803
+ catch (e) {
804
+ throw createClientConfigurationError(invalidCloudDiscoveryMetadata);
805
+ }
806
+ }
807
+ return {
808
+ canonicalAuthority: authOptions.authority
809
+ ? formatAuthorityUri(authOptions.authority)
810
+ : undefined,
811
+ knownAuthorities: authOptions.knownAuthorities,
812
+ cloudDiscoveryMetadata: cloudDiscoveryMetadata,
813
+ };
751
814
  }
752
- // Reserved tenant domain names that will not be replaced with tenant id
753
- Authority.reservedTenantDomains = new Set([
754
- "{tenant}",
755
- "{tenantid}",
756
- AADAuthorityConstants.COMMON,
757
- AADAuthorityConstants.CONSUMERS,
758
- AADAuthorityConstants.ORGANIZATIONS,
759
- ]);
760
815
 
761
- export { Authority };
816
+ export { Authority, buildStaticAuthorityOptions, formatAuthorityUri };
762
817
  //# sourceMappingURL=Authority.mjs.map