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