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