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