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