@azure/msal-common 14.14.0 → 14.14.1

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