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