@azure/msal-node 2.0.0-alpha.0 → 2.0.0-alpha.2

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 (432) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +182 -182
  3. package/dist/cache/ITokenCache.d.ts +15 -15
  4. package/dist/cache/NodeStorage.d.ts +182 -182
  5. package/dist/cache/NodeStorage.esm.js +401 -401
  6. package/dist/cache/NodeStorage.js +401 -401
  7. package/dist/cache/TokenCache.d.ts +90 -90
  8. package/dist/cache/TokenCache.esm.js +269 -269
  9. package/dist/cache/TokenCache.js +269 -269
  10. package/dist/cache/distributed/DistributedCachePlugin.d.ts +10 -10
  11. package/dist/cache/distributed/DistributedCachePlugin.esm.js +26 -26
  12. package/dist/cache/distributed/DistributedCachePlugin.js +26 -26
  13. package/dist/cache/distributed/ICacheClient.d.ts +17 -17
  14. package/dist/cache/distributed/IPartitionManager.d.ts +28 -28
  15. package/dist/cache/serializer/Deserializer.d.ts +42 -42
  16. package/dist/cache/serializer/Deserializer.esm.js +175 -175
  17. package/dist/cache/serializer/Deserializer.js +175 -175
  18. package/dist/cache/serializer/Serializer.d.ts +39 -39
  19. package/dist/cache/serializer/Serializer.esm.js +134 -134
  20. package/dist/cache/serializer/Serializer.js +134 -134
  21. package/dist/cache/serializer/SerializerTypes.d.ts +101 -101
  22. package/dist/client/ClientApplication.d.ts +142 -142
  23. package/dist/client/ClientApplication.esm.js +327 -327
  24. package/dist/client/ClientApplication.js +327 -327
  25. package/dist/client/ClientAssertion.d.ts +46 -46
  26. package/dist/client/ClientAssertion.esm.js +116 -116
  27. package/dist/client/ClientAssertion.js +116 -116
  28. package/dist/client/ClientCredentialClient.d.ts +33 -33
  29. package/dist/client/ClientCredentialClient.esm.js +157 -157
  30. package/dist/client/ClientCredentialClient.js +157 -157
  31. package/dist/client/ConfidentialClientApplication.d.ts +58 -58
  32. package/dist/client/ConfidentialClientApplication.esm.js +163 -163
  33. package/dist/client/ConfidentialClientApplication.js +163 -163
  34. package/dist/client/DeviceCodeClient.d.ts +53 -53
  35. package/dist/client/DeviceCodeClient.esm.js +207 -207
  36. package/dist/client/DeviceCodeClient.js +207 -207
  37. package/dist/client/IConfidentialClientApplication.d.ts +39 -39
  38. package/dist/client/IPublicClientApplication.d.ts +42 -42
  39. package/dist/client/OnBehalfOfClient.d.ts +47 -47
  40. package/dist/client/OnBehalfOfClient.esm.js +204 -204
  41. package/dist/client/OnBehalfOfClient.js +204 -204
  42. package/dist/client/PublicClientApplication.d.ts +65 -65
  43. package/dist/client/PublicClientApplication.esm.js +175 -175
  44. package/dist/client/PublicClientApplication.js +175 -175
  45. package/dist/client/UsernamePasswordClient.d.ts +25 -25
  46. package/dist/client/UsernamePasswordClient.esm.js +102 -102
  47. package/dist/client/UsernamePasswordClient.js +102 -102
  48. package/dist/config/Configuration.d.ts +105 -105
  49. package/dist/config/Configuration.esm.js +70 -70
  50. package/dist/config/Configuration.js +70 -70
  51. package/dist/crypto/CryptoProvider.d.ts +52 -52
  52. package/dist/crypto/CryptoProvider.esm.js +75 -75
  53. package/dist/crypto/CryptoProvider.js +75 -75
  54. package/dist/crypto/GuidGenerator.d.ts +14 -14
  55. package/dist/crypto/GuidGenerator.esm.js +22 -22
  56. package/dist/crypto/GuidGenerator.js +22 -22
  57. package/dist/crypto/HashUtils.d.ts +8 -8
  58. package/dist/crypto/HashUtils.esm.js +13 -13
  59. package/dist/crypto/HashUtils.js +13 -13
  60. package/dist/crypto/PkceGenerator.d.ts +22 -22
  61. package/dist/crypto/PkceGenerator.esm.js +49 -49
  62. package/dist/crypto/PkceGenerator.js +49 -49
  63. package/dist/error/NodeAuthError.d.ts +65 -65
  64. package/dist/error/NodeAuthError.esm.js +85 -85
  65. package/dist/error/NodeAuthError.js +85 -85
  66. package/dist/index.d.ts +41 -41
  67. package/dist/index.esm.js +1 -1
  68. package/dist/index.js +1 -1
  69. package/dist/internals.d.ts +6 -6
  70. package/dist/internals.esm.js +4 -4
  71. package/dist/internals.js +4 -4
  72. package/dist/network/HttpClient.d.ts +25 -25
  73. package/dist/network/HttpClient.esm.js +276 -276
  74. package/dist/network/HttpClient.js +276 -276
  75. package/dist/network/ILoopbackClient.d.ts +10 -10
  76. package/dist/network/LoopbackClient.d.ts +21 -21
  77. package/dist/network/LoopbackClient.esm.js +84 -84
  78. package/dist/network/LoopbackClient.js +84 -84
  79. package/dist/packageMetadata.d.ts +2 -2
  80. package/dist/packageMetadata.esm.js +4 -4
  81. package/dist/packageMetadata.js +4 -4
  82. package/dist/request/AuthorizationCodeRequest.d.ts +21 -21
  83. package/dist/request/AuthorizationUrlRequest.d.ts +33 -33
  84. package/dist/request/ClientCredentialRequest.d.ts +15 -15
  85. package/dist/request/DeviceCodeRequest.d.ts +15 -15
  86. package/dist/request/InteractiveRequest.d.ts +22 -22
  87. package/dist/request/OnBehalfOfRequest.d.ts +14 -14
  88. package/dist/request/RefreshTokenRequest.d.ts +17 -17
  89. package/dist/request/SignOutRequest.d.ts +5 -5
  90. package/dist/request/SilentFlowRequest.d.ts +16 -16
  91. package/dist/request/UsernamePasswordRequest.d.ts +19 -19
  92. package/dist/utils/Constants.d.ts +92 -92
  93. package/dist/utils/Constants.esm.js +93 -93
  94. package/dist/utils/Constants.js +93 -93
  95. package/dist/utils/EncodingUtils.d.ts +26 -26
  96. package/dist/utils/EncodingUtils.esm.js +44 -44
  97. package/dist/utils/EncodingUtils.js +44 -44
  98. package/dist/utils/NetworkUtils.d.ts +5 -5
  99. package/dist/utils/NetworkUtils.esm.js +38 -38
  100. package/dist/utils/NetworkUtils.js +38 -38
  101. package/package.json +73 -76
  102. package/dist/msal-node.cjs.development.js +0 -2705
  103. package/dist/msal-node.cjs.development.js.map +0 -1
  104. package/dist/msal-node.cjs.production.min.js +0 -2
  105. package/dist/msal-node.cjs.production.min.js.map +0 -1
  106. package/dist/msal-node.esm.js +0 -2594
  107. package/dist/msal-node.esm.js.map +0 -1
  108. package/node_modules/@azure/msal-common/LICENSE +0 -21
  109. package/node_modules/@azure/msal-common/README.md +0 -62
  110. package/node_modules/@azure/msal-common/dist/account/AccountInfo.d.ts +0 -32
  111. package/node_modules/@azure/msal-common/dist/account/AccountInfo.d.ts.map +0 -1
  112. package/node_modules/@azure/msal-common/dist/account/AuthToken.d.ts +0 -21
  113. package/node_modules/@azure/msal-common/dist/account/AuthToken.d.ts.map +0 -1
  114. package/node_modules/@azure/msal-common/dist/account/AuthToken.js +0 -56
  115. package/node_modules/@azure/msal-common/dist/account/AuthToken.js.map +0 -1
  116. package/node_modules/@azure/msal-common/dist/account/CcsCredential.d.ts +0 -9
  117. package/node_modules/@azure/msal-common/dist/account/CcsCredential.d.ts.map +0 -1
  118. package/node_modules/@azure/msal-common/dist/account/CcsCredential.js +0 -14
  119. package/node_modules/@azure/msal-common/dist/account/CcsCredential.js.map +0 -1
  120. package/node_modules/@azure/msal-common/dist/account/ClientCredentials.d.ts +0 -15
  121. package/node_modules/@azure/msal-common/dist/account/ClientCredentials.d.ts.map +0 -1
  122. package/node_modules/@azure/msal-common/dist/account/ClientInfo.d.ts +0 -20
  123. package/node_modules/@azure/msal-common/dist/account/ClientInfo.d.ts.map +0 -1
  124. package/node_modules/@azure/msal-common/dist/account/ClientInfo.js +0 -46
  125. package/node_modules/@azure/msal-common/dist/account/ClientInfo.js.map +0 -1
  126. package/node_modules/@azure/msal-common/dist/account/DecodedAuthToken.d.ts +0 -9
  127. package/node_modules/@azure/msal-common/dist/account/DecodedAuthToken.d.ts.map +0 -1
  128. package/node_modules/@azure/msal-common/dist/account/TokenClaims.d.ts +0 -66
  129. package/node_modules/@azure/msal-common/dist/account/TokenClaims.d.ts.map +0 -1
  130. package/node_modules/@azure/msal-common/dist/authority/Authority.d.ts +0 -216
  131. package/node_modules/@azure/msal-common/dist/authority/Authority.d.ts.map +0 -1
  132. package/node_modules/@azure/msal-common/dist/authority/Authority.js +0 -688
  133. package/node_modules/@azure/msal-common/dist/authority/Authority.js.map +0 -1
  134. package/node_modules/@azure/msal-common/dist/authority/AuthorityFactory.d.ts +0 -31
  135. package/node_modules/@azure/msal-common/dist/authority/AuthorityFactory.d.ts.map +0 -1
  136. package/node_modules/@azure/msal-common/dist/authority/AuthorityFactory.js +0 -58
  137. package/node_modules/@azure/msal-common/dist/authority/AuthorityFactory.js.map +0 -1
  138. package/node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.d.ts +0 -623
  139. package/node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.d.ts.map +0 -1
  140. package/node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.js +0 -881
  141. package/node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.js.map +0 -1
  142. package/node_modules/@azure/msal-common/dist/authority/AuthorityOptions.d.ts +0 -19
  143. package/node_modules/@azure/msal-common/dist/authority/AuthorityOptions.d.ts.map +0 -1
  144. package/node_modules/@azure/msal-common/dist/authority/AuthorityOptions.js +0 -24
  145. package/node_modules/@azure/msal-common/dist/authority/AuthorityOptions.js.map +0 -1
  146. package/node_modules/@azure/msal-common/dist/authority/AuthorityType.d.ts +0 -10
  147. package/node_modules/@azure/msal-common/dist/authority/AuthorityType.d.ts.map +0 -1
  148. package/node_modules/@azure/msal-common/dist/authority/AuthorityType.js +0 -19
  149. package/node_modules/@azure/msal-common/dist/authority/AuthorityType.js.map +0 -1
  150. package/node_modules/@azure/msal-common/dist/authority/AzureRegion.d.ts +0 -2
  151. package/node_modules/@azure/msal-common/dist/authority/AzureRegion.d.ts.map +0 -1
  152. package/node_modules/@azure/msal-common/dist/authority/AzureRegionConfiguration.d.ts +0 -6
  153. package/node_modules/@azure/msal-common/dist/authority/AzureRegionConfiguration.d.ts.map +0 -1
  154. package/node_modules/@azure/msal-common/dist/authority/CloudDiscoveryMetadata.d.ts +0 -6
  155. package/node_modules/@azure/msal-common/dist/authority/CloudDiscoveryMetadata.d.ts.map +0 -1
  156. package/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.d.ts +0 -14
  157. package/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.d.ts.map +0 -1
  158. package/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.js +0 -13
  159. package/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.js.map +0 -1
  160. package/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.d.ts +0 -10
  161. package/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.d.ts.map +0 -1
  162. package/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.js +0 -13
  163. package/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.js.map +0 -1
  164. package/node_modules/@azure/msal-common/dist/authority/ImdsOptions.d.ts +0 -6
  165. package/node_modules/@azure/msal-common/dist/authority/ImdsOptions.d.ts.map +0 -1
  166. package/node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.d.ts +0 -12
  167. package/node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.d.ts.map +0 -1
  168. package/node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.js +0 -15
  169. package/node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.js.map +0 -1
  170. package/node_modules/@azure/msal-common/dist/authority/ProtocolMode.d.ts +0 -8
  171. package/node_modules/@azure/msal-common/dist/authority/ProtocolMode.d.ts.map +0 -1
  172. package/node_modules/@azure/msal-common/dist/authority/ProtocolMode.js +0 -17
  173. package/node_modules/@azure/msal-common/dist/authority/ProtocolMode.js.map +0 -1
  174. package/node_modules/@azure/msal-common/dist/authority/RegionDiscovery.d.ts +0 -31
  175. package/node_modules/@azure/msal-common/dist/authority/RegionDiscovery.d.ts.map +0 -1
  176. package/node_modules/@azure/msal-common/dist/authority/RegionDiscovery.js +0 -116
  177. package/node_modules/@azure/msal-common/dist/authority/RegionDiscovery.js.map +0 -1
  178. package/node_modules/@azure/msal-common/dist/authority/RegionDiscoveryMetadata.d.ts +0 -7
  179. package/node_modules/@azure/msal-common/dist/authority/RegionDiscoveryMetadata.d.ts.map +0 -1
  180. package/node_modules/@azure/msal-common/dist/broker/nativeBroker/INativeBrokerPlugin.d.ts +0 -16
  181. package/node_modules/@azure/msal-common/dist/broker/nativeBroker/INativeBrokerPlugin.d.ts.map +0 -1
  182. package/node_modules/@azure/msal-common/dist/cache/CacheManager.d.ts +0 -444
  183. package/node_modules/@azure/msal-common/dist/cache/CacheManager.d.ts.map +0 -1
  184. package/node_modules/@azure/msal-common/dist/cache/CacheManager.js +0 -1024
  185. package/node_modules/@azure/msal-common/dist/cache/CacheManager.js.map +0 -1
  186. package/node_modules/@azure/msal-common/dist/cache/entities/AccessTokenEntity.d.ts +0 -57
  187. package/node_modules/@azure/msal-common/dist/cache/entities/AccessTokenEntity.d.ts.map +0 -1
  188. package/node_modules/@azure/msal-common/dist/cache/entities/AccessTokenEntity.js +0 -123
  189. package/node_modules/@azure/msal-common/dist/cache/entities/AccessTokenEntity.js.map +0 -1
  190. package/node_modules/@azure/msal-common/dist/cache/entities/AccountEntity.d.ts +0 -100
  191. package/node_modules/@azure/msal-common/dist/cache/entities/AccountEntity.d.ts.map +0 -1
  192. package/node_modules/@azure/msal-common/dist/cache/entities/AccountEntity.js +0 -259
  193. package/node_modules/@azure/msal-common/dist/cache/entities/AccountEntity.js.map +0 -1
  194. package/node_modules/@azure/msal-common/dist/cache/entities/AppMetadataEntity.d.ts +0 -40
  195. package/node_modules/@azure/msal-common/dist/cache/entities/AppMetadataEntity.d.ts.map +0 -1
  196. package/node_modules/@azure/msal-common/dist/cache/entities/AppMetadataEntity.js +0 -73
  197. package/node_modules/@azure/msal-common/dist/cache/entities/AppMetadataEntity.js.map +0 -1
  198. package/node_modules/@azure/msal-common/dist/cache/entities/AuthorityMetadataEntity.d.ts +0 -48
  199. package/node_modules/@azure/msal-common/dist/cache/entities/AuthorityMetadataEntity.d.ts.map +0 -1
  200. package/node_modules/@azure/msal-common/dist/cache/entities/AuthorityMetadataEntity.js +0 -85
  201. package/node_modules/@azure/msal-common/dist/cache/entities/AuthorityMetadataEntity.js.map +0 -1
  202. package/node_modules/@azure/msal-common/dist/cache/entities/CacheRecord.d.ts +0 -14
  203. package/node_modules/@azure/msal-common/dist/cache/entities/CacheRecord.d.ts.map +0 -1
  204. package/node_modules/@azure/msal-common/dist/cache/entities/CacheRecord.js +0 -18
  205. package/node_modules/@azure/msal-common/dist/cache/entities/CacheRecord.js.map +0 -1
  206. package/node_modules/@azure/msal-common/dist/cache/entities/CredentialEntity.d.ts +0 -89
  207. package/node_modules/@azure/msal-common/dist/cache/entities/CredentialEntity.d.ts.map +0 -1
  208. package/node_modules/@azure/msal-common/dist/cache/entities/CredentialEntity.js +0 -144
  209. package/node_modules/@azure/msal-common/dist/cache/entities/CredentialEntity.js.map +0 -1
  210. package/node_modules/@azure/msal-common/dist/cache/entities/IdTokenEntity.d.ts +0 -35
  211. package/node_modules/@azure/msal-common/dist/cache/entities/IdTokenEntity.d.ts.map +0 -1
  212. package/node_modules/@azure/msal-common/dist/cache/entities/IdTokenEntity.js +0 -64
  213. package/node_modules/@azure/msal-common/dist/cache/entities/IdTokenEntity.js.map +0 -1
  214. package/node_modules/@azure/msal-common/dist/cache/entities/RefreshTokenEntity.d.ts +0 -37
  215. package/node_modules/@azure/msal-common/dist/cache/entities/RefreshTokenEntity.d.ts.map +0 -1
  216. package/node_modules/@azure/msal-common/dist/cache/entities/RefreshTokenEntity.js +0 -67
  217. package/node_modules/@azure/msal-common/dist/cache/entities/RefreshTokenEntity.js.map +0 -1
  218. package/node_modules/@azure/msal-common/dist/cache/entities/ServerTelemetryEntity.d.ts +0 -13
  219. package/node_modules/@azure/msal-common/dist/cache/entities/ServerTelemetryEntity.d.ts.map +0 -1
  220. package/node_modules/@azure/msal-common/dist/cache/entities/ServerTelemetryEntity.js +0 -34
  221. package/node_modules/@azure/msal-common/dist/cache/entities/ServerTelemetryEntity.js.map +0 -1
  222. package/node_modules/@azure/msal-common/dist/cache/entities/ThrottlingEntity.d.ts +0 -14
  223. package/node_modules/@azure/msal-common/dist/cache/entities/ThrottlingEntity.d.ts.map +0 -1
  224. package/node_modules/@azure/msal-common/dist/cache/entities/ThrottlingEntity.js +0 -30
  225. package/node_modules/@azure/msal-common/dist/cache/entities/ThrottlingEntity.js.map +0 -1
  226. package/node_modules/@azure/msal-common/dist/cache/interface/ICacheManager.d.ts +0 -166
  227. package/node_modules/@azure/msal-common/dist/cache/interface/ICacheManager.d.ts.map +0 -1
  228. package/node_modules/@azure/msal-common/dist/cache/interface/ICachePlugin.d.ts +0 -6
  229. package/node_modules/@azure/msal-common/dist/cache/interface/ICachePlugin.d.ts.map +0 -1
  230. package/node_modules/@azure/msal-common/dist/cache/interface/ISerializableTokenCache.d.ts +0 -5
  231. package/node_modules/@azure/msal-common/dist/cache/interface/ISerializableTokenCache.d.ts.map +0 -1
  232. package/node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.d.ts +0 -24
  233. package/node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.d.ts.map +0 -1
  234. package/node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.js +0 -30
  235. package/node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.js.map +0 -1
  236. package/node_modules/@azure/msal-common/dist/cache/utils/CacheTypes.d.ts +0 -63
  237. package/node_modules/@azure/msal-common/dist/cache/utils/CacheTypes.d.ts.map +0 -1
  238. package/node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.d.ts +0 -72
  239. package/node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.d.ts.map +0 -1
  240. package/node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.js +0 -453
  241. package/node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.js.map +0 -1
  242. package/node_modules/@azure/msal-common/dist/client/BaseClient.d.ts +0 -51
  243. package/node_modules/@azure/msal-common/dist/client/BaseClient.d.ts.map +0 -1
  244. package/node_modules/@azure/msal-common/dist/client/BaseClient.js +0 -107
  245. package/node_modules/@azure/msal-common/dist/client/BaseClient.js.map +0 -1
  246. package/node_modules/@azure/msal-common/dist/client/RefreshTokenClient.d.ts +0 -35
  247. package/node_modules/@azure/msal-common/dist/client/RefreshTokenClient.d.ts.map +0 -1
  248. package/node_modules/@azure/msal-common/dist/client/RefreshTokenClient.js +0 -260
  249. package/node_modules/@azure/msal-common/dist/client/RefreshTokenClient.js.map +0 -1
  250. package/node_modules/@azure/msal-common/dist/client/SilentFlowClient.d.ts +0 -25
  251. package/node_modules/@azure/msal-common/dist/client/SilentFlowClient.d.ts.map +0 -1
  252. package/node_modules/@azure/msal-common/dist/client/SilentFlowClient.js +0 -108
  253. package/node_modules/@azure/msal-common/dist/client/SilentFlowClient.js.map +0 -1
  254. package/node_modules/@azure/msal-common/dist/config/AppTokenProvider.d.ts +0 -39
  255. package/node_modules/@azure/msal-common/dist/config/AppTokenProvider.d.ts.map +0 -1
  256. package/node_modules/@azure/msal-common/dist/config/ClientConfiguration.d.ts +0 -134
  257. package/node_modules/@azure/msal-common/dist/config/ClientConfiguration.d.ts.map +0 -1
  258. package/node_modules/@azure/msal-common/dist/config/ClientConfiguration.js +0 -101
  259. package/node_modules/@azure/msal-common/dist/config/ClientConfiguration.js.map +0 -1
  260. package/node_modules/@azure/msal-common/dist/crypto/ICrypto.d.ts +0 -63
  261. package/node_modules/@azure/msal-common/dist/crypto/ICrypto.d.ts.map +0 -1
  262. package/node_modules/@azure/msal-common/dist/crypto/ICrypto.js +0 -49
  263. package/node_modules/@azure/msal-common/dist/crypto/ICrypto.js.map +0 -1
  264. package/node_modules/@azure/msal-common/dist/crypto/IGuidGenerator.d.ts +0 -5
  265. package/node_modules/@azure/msal-common/dist/crypto/IGuidGenerator.d.ts.map +0 -1
  266. package/node_modules/@azure/msal-common/dist/crypto/JoseHeader.d.ts +0 -22
  267. package/node_modules/@azure/msal-common/dist/crypto/JoseHeader.d.ts.map +0 -1
  268. package/node_modules/@azure/msal-common/dist/crypto/JoseHeader.js +0 -44
  269. package/node_modules/@azure/msal-common/dist/crypto/JoseHeader.js.map +0 -1
  270. package/node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.d.ts +0 -58
  271. package/node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.d.ts.map +0 -1
  272. package/node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.js +0 -92
  273. package/node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.js.map +0 -1
  274. package/node_modules/@azure/msal-common/dist/crypto/SignedHttpRequest.d.ts +0 -12
  275. package/node_modules/@azure/msal-common/dist/crypto/SignedHttpRequest.d.ts.map +0 -1
  276. package/node_modules/@azure/msal-common/dist/error/AuthError.d.ts +0 -48
  277. package/node_modules/@azure/msal-common/dist/error/AuthError.d.ts.map +0 -1
  278. package/node_modules/@azure/msal-common/dist/error/AuthError.js +0 -58
  279. package/node_modules/@azure/msal-common/dist/error/AuthError.js.map +0 -1
  280. package/node_modules/@azure/msal-common/dist/error/ClientAuthError.d.ts +0 -413
  281. package/node_modules/@azure/msal-common/dist/error/ClientAuthError.d.ts.map +0 -1
  282. package/node_modules/@azure/msal-common/dist/error/ClientAuthError.js +0 -526
  283. package/node_modules/@azure/msal-common/dist/error/ClientAuthError.js.map +0 -1
  284. package/node_modules/@azure/msal-common/dist/error/ClientConfigurationError.d.ts +0 -199
  285. package/node_modules/@azure/msal-common/dist/error/ClientConfigurationError.d.ts.map +0 -1
  286. package/node_modules/@azure/msal-common/dist/error/ClientConfigurationError.js +0 -256
  287. package/node_modules/@azure/msal-common/dist/error/ClientConfigurationError.js.map +0 -1
  288. package/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.d.ts +0 -60
  289. package/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.d.ts.map +0 -1
  290. package/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.js +0 -86
  291. package/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.js.map +0 -1
  292. package/node_modules/@azure/msal-common/dist/error/JoseHeaderError.d.ts +0 -29
  293. package/node_modules/@azure/msal-common/dist/error/JoseHeaderError.d.ts.map +0 -1
  294. package/node_modules/@azure/msal-common/dist/error/JoseHeaderError.js +0 -46
  295. package/node_modules/@azure/msal-common/dist/error/JoseHeaderError.js.map +0 -1
  296. package/node_modules/@azure/msal-common/dist/error/ServerError.d.ts +0 -8
  297. package/node_modules/@azure/msal-common/dist/error/ServerError.d.ts.map +0 -1
  298. package/node_modules/@azure/msal-common/dist/error/ServerError.js +0 -21
  299. package/node_modules/@azure/msal-common/dist/error/ServerError.js.map +0 -1
  300. package/node_modules/@azure/msal-common/dist/index.cjs.js +0 -8975
  301. package/node_modules/@azure/msal-common/dist/index.cjs.js.map +0 -1
  302. package/node_modules/@azure/msal-common/dist/index.d.ts +0 -94
  303. package/node_modules/@azure/msal-common/dist/index.d.ts.map +0 -1
  304. package/node_modules/@azure/msal-common/dist/index.js +0 -54
  305. package/node_modules/@azure/msal-common/dist/index.js.map +0 -1
  306. package/node_modules/@azure/msal-common/dist/logger/Logger.d.ts +0 -96
  307. package/node_modules/@azure/msal-common/dist/logger/Logger.d.ts.map +0 -1
  308. package/node_modules/@azure/msal-common/dist/logger/Logger.js +0 -205
  309. package/node_modules/@azure/msal-common/dist/logger/Logger.js.map +0 -1
  310. package/node_modules/@azure/msal-common/dist/network/INetworkModule.d.ts +0 -30
  311. package/node_modules/@azure/msal-common/dist/network/INetworkModule.d.ts.map +0 -1
  312. package/node_modules/@azure/msal-common/dist/network/INetworkModule.js +0 -21
  313. package/node_modules/@azure/msal-common/dist/network/INetworkModule.js.map +0 -1
  314. package/node_modules/@azure/msal-common/dist/network/NetworkManager.d.ts +0 -33
  315. package/node_modules/@azure/msal-common/dist/network/NetworkManager.d.ts.map +0 -1
  316. package/node_modules/@azure/msal-common/dist/network/NetworkManager.js +0 -42
  317. package/node_modules/@azure/msal-common/dist/network/NetworkManager.js.map +0 -1
  318. package/node_modules/@azure/msal-common/dist/network/RequestThumbprint.d.ts +0 -17
  319. package/node_modules/@azure/msal-common/dist/network/RequestThumbprint.d.ts.map +0 -1
  320. package/node_modules/@azure/msal-common/dist/network/ThrottlingUtils.d.ts +0 -42
  321. package/node_modules/@azure/msal-common/dist/network/ThrottlingUtils.d.ts.map +0 -1
  322. package/node_modules/@azure/msal-common/dist/network/ThrottlingUtils.js +0 -102
  323. package/node_modules/@azure/msal-common/dist/network/ThrottlingUtils.js.map +0 -1
  324. package/node_modules/@azure/msal-common/dist/packageMetadata.d.ts +0 -3
  325. package/node_modules/@azure/msal-common/dist/packageMetadata.d.ts.map +0 -1
  326. package/node_modules/@azure/msal-common/dist/packageMetadata.js +0 -8
  327. package/node_modules/@azure/msal-common/dist/packageMetadata.js.map +0 -1
  328. package/node_modules/@azure/msal-common/dist/request/AuthenticationHeaderParser.d.ts +0 -20
  329. package/node_modules/@azure/msal-common/dist/request/AuthenticationHeaderParser.d.ts.map +0 -1
  330. package/node_modules/@azure/msal-common/dist/request/AuthenticationHeaderParser.js +0 -63
  331. package/node_modules/@azure/msal-common/dist/request/AuthenticationHeaderParser.js.map +0 -1
  332. package/node_modules/@azure/msal-common/dist/request/BaseAuthRequest.d.ts +0 -38
  333. package/node_modules/@azure/msal-common/dist/request/BaseAuthRequest.d.ts.map +0 -1
  334. package/node_modules/@azure/msal-common/dist/request/CommonAuthorizationCodeRequest.d.ts +0 -28
  335. package/node_modules/@azure/msal-common/dist/request/CommonAuthorizationCodeRequest.d.ts.map +0 -1
  336. package/node_modules/@azure/msal-common/dist/request/CommonAuthorizationUrlRequest.d.ts +0 -51
  337. package/node_modules/@azure/msal-common/dist/request/CommonAuthorizationUrlRequest.d.ts.map +0 -1
  338. package/node_modules/@azure/msal-common/dist/request/CommonClientCredentialRequest.d.ts +0 -18
  339. package/node_modules/@azure/msal-common/dist/request/CommonClientCredentialRequest.d.ts.map +0 -1
  340. package/node_modules/@azure/msal-common/dist/request/CommonDeviceCodeRequest.d.ts +0 -22
  341. package/node_modules/@azure/msal-common/dist/request/CommonDeviceCodeRequest.d.ts.map +0 -1
  342. package/node_modules/@azure/msal-common/dist/request/CommonEndSessionRequest.d.ts +0 -22
  343. package/node_modules/@azure/msal-common/dist/request/CommonEndSessionRequest.d.ts.map +0 -1
  344. package/node_modules/@azure/msal-common/dist/request/CommonOnBehalfOfRequest.d.ts +0 -14
  345. package/node_modules/@azure/msal-common/dist/request/CommonOnBehalfOfRequest.d.ts.map +0 -1
  346. package/node_modules/@azure/msal-common/dist/request/CommonRefreshTokenRequest.d.ts +0 -20
  347. package/node_modules/@azure/msal-common/dist/request/CommonRefreshTokenRequest.d.ts.map +0 -1
  348. package/node_modules/@azure/msal-common/dist/request/CommonSilentFlowRequest.d.ts +0 -19
  349. package/node_modules/@azure/msal-common/dist/request/CommonSilentFlowRequest.d.ts.map +0 -1
  350. package/node_modules/@azure/msal-common/dist/request/CommonUsernamePasswordRequest.d.ts +0 -18
  351. package/node_modules/@azure/msal-common/dist/request/CommonUsernamePasswordRequest.d.ts.map +0 -1
  352. package/node_modules/@azure/msal-common/dist/request/NativeRequest.d.ts +0 -20
  353. package/node_modules/@azure/msal-common/dist/request/NativeRequest.d.ts.map +0 -1
  354. package/node_modules/@azure/msal-common/dist/request/NativeSignOutRequest.d.ts +0 -6
  355. package/node_modules/@azure/msal-common/dist/request/NativeSignOutRequest.d.ts.map +0 -1
  356. package/node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.d.ts +0 -217
  357. package/node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.d.ts.map +0 -1
  358. package/node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.js +0 -385
  359. package/node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.js.map +0 -1
  360. package/node_modules/@azure/msal-common/dist/request/RequestValidator.d.ts +0 -34
  361. package/node_modules/@azure/msal-common/dist/request/RequestValidator.d.ts.map +0 -1
  362. package/node_modules/@azure/msal-common/dist/request/RequestValidator.js +0 -92
  363. package/node_modules/@azure/msal-common/dist/request/RequestValidator.js.map +0 -1
  364. package/node_modules/@azure/msal-common/dist/request/ScopeSet.d.ts +0 -89
  365. package/node_modules/@azure/msal-common/dist/request/ScopeSet.d.ts.map +0 -1
  366. package/node_modules/@azure/msal-common/dist/request/ScopeSet.js +0 -207
  367. package/node_modules/@azure/msal-common/dist/request/ScopeSet.js.map +0 -1
  368. package/node_modules/@azure/msal-common/dist/response/AuthenticationResult.d.ts +0 -40
  369. package/node_modules/@azure/msal-common/dist/response/AuthenticationResult.d.ts.map +0 -1
  370. package/node_modules/@azure/msal-common/dist/response/AuthorizationCodePayload.d.ts +0 -14
  371. package/node_modules/@azure/msal-common/dist/response/AuthorizationCodePayload.d.ts.map +0 -1
  372. package/node_modules/@azure/msal-common/dist/response/DeviceCodeResponse.d.ts +0 -26
  373. package/node_modules/@azure/msal-common/dist/response/DeviceCodeResponse.d.ts.map +0 -1
  374. package/node_modules/@azure/msal-common/dist/response/ExternalTokenResponse.d.ts +0 -16
  375. package/node_modules/@azure/msal-common/dist/response/ExternalTokenResponse.d.ts.map +0 -1
  376. package/node_modules/@azure/msal-common/dist/response/IMDSBadResponse.d.ts +0 -5
  377. package/node_modules/@azure/msal-common/dist/response/IMDSBadResponse.d.ts.map +0 -1
  378. package/node_modules/@azure/msal-common/dist/response/ResponseHandler.d.ts +0 -73
  379. package/node_modules/@azure/msal-common/dist/response/ResponseHandler.d.ts.map +0 -1
  380. package/node_modules/@azure/msal-common/dist/response/ResponseHandler.js +0 -325
  381. package/node_modules/@azure/msal-common/dist/response/ResponseHandler.js.map +0 -1
  382. package/node_modules/@azure/msal-common/dist/response/ServerAuthorizationCodeResponse.d.ts +0 -26
  383. package/node_modules/@azure/msal-common/dist/response/ServerAuthorizationCodeResponse.d.ts.map +0 -1
  384. package/node_modules/@azure/msal-common/dist/response/ServerAuthorizationTokenResponse.d.ts +0 -45
  385. package/node_modules/@azure/msal-common/dist/response/ServerAuthorizationTokenResponse.d.ts.map +0 -1
  386. package/node_modules/@azure/msal-common/dist/telemetry/performance/IPerformanceClient.d.ts +0 -43
  387. package/node_modules/@azure/msal-common/dist/telemetry/performance/IPerformanceClient.d.ts.map +0 -1
  388. package/node_modules/@azure/msal-common/dist/telemetry/performance/IPerformanceMeasurement.d.ts +0 -6
  389. package/node_modules/@azure/msal-common/dist/telemetry/performance/IPerformanceMeasurement.d.ts.map +0 -1
  390. package/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceClient.d.ts +0 -190
  391. package/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceClient.d.ts.map +0 -1
  392. package/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceClient.js +0 -413
  393. package/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceClient.js.map +0 -1
  394. package/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.d.ts +0 -440
  395. package/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.d.ts.map +0 -1
  396. package/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.js +0 -232
  397. package/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.js.map +0 -1
  398. package/node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.d.ts +0 -20
  399. package/node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.d.ts.map +0 -1
  400. package/node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.js +0 -43
  401. package/node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.js.map +0 -1
  402. package/node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.d.ts +0 -66
  403. package/node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.d.ts.map +0 -1
  404. package/node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.js +0 -206
  405. package/node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.js.map +0 -1
  406. package/node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryRequest.d.ts +0 -9
  407. package/node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryRequest.d.ts.map +0 -1
  408. package/node_modules/@azure/msal-common/dist/url/IUri.d.ts +0 -13
  409. package/node_modules/@azure/msal-common/dist/url/IUri.d.ts.map +0 -1
  410. package/node_modules/@azure/msal-common/dist/url/UrlString.d.ts +0 -71
  411. package/node_modules/@azure/msal-common/dist/url/UrlString.d.ts.map +0 -1
  412. package/node_modules/@azure/msal-common/dist/url/UrlString.js +0 -252
  413. package/node_modules/@azure/msal-common/dist/url/UrlString.js.map +0 -1
  414. package/node_modules/@azure/msal-common/dist/utils/Constants.d.ts +0 -332
  415. package/node_modules/@azure/msal-common/dist/utils/Constants.d.ts.map +0 -1
  416. package/node_modules/@azure/msal-common/dist/utils/Constants.js +0 -378
  417. package/node_modules/@azure/msal-common/dist/utils/Constants.js.map +0 -1
  418. package/node_modules/@azure/msal-common/dist/utils/MsalTypes.d.ts +0 -7
  419. package/node_modules/@azure/msal-common/dist/utils/MsalTypes.d.ts.map +0 -1
  420. package/node_modules/@azure/msal-common/dist/utils/ProtocolUtils.d.ts +0 -43
  421. package/node_modules/@azure/msal-common/dist/utils/ProtocolUtils.d.ts.map +0 -1
  422. package/node_modules/@azure/msal-common/dist/utils/ProtocolUtils.js +0 -80
  423. package/node_modules/@azure/msal-common/dist/utils/ProtocolUtils.js.map +0 -1
  424. package/node_modules/@azure/msal-common/dist/utils/StringUtils.d.ts +0 -54
  425. package/node_modules/@azure/msal-common/dist/utils/StringUtils.d.ts.map +0 -1
  426. package/node_modules/@azure/msal-common/dist/utils/StringUtils.js +0 -131
  427. package/node_modules/@azure/msal-common/dist/utils/StringUtils.js.map +0 -1
  428. package/node_modules/@azure/msal-common/dist/utils/TimeUtils.d.ts +0 -28
  429. package/node_modules/@azure/msal-common/dist/utils/TimeUtils.d.ts.map +0 -1
  430. package/node_modules/@azure/msal-common/dist/utils/TimeUtils.js +0 -50
  431. package/node_modules/@azure/msal-common/dist/utils/TimeUtils.js.map +0 -1
  432. package/node_modules/@azure/msal-common/package.json +0 -79
@@ -1,2594 +0,0 @@
1
- import { Constants as Constants$1, ProtocolMode, AzureCloudInstance, LogLevel, StringUtils, AccountEntity, CacheManager, IdTokenEntity, AccessTokenEntity, RefreshTokenEntity, AppMetadataEntity, ServerTelemetryEntity, AuthorityMetadataEntity, ThrottlingEntity, TokenCacheContext, AuthError, Logger, ResponseMode, AuthenticationScheme, AuthorizationCodeClient, RefreshTokenClient, SilentFlowClient, UsernamePasswordClient, ClientAuthError, OIDC_DEFAULT_SCOPES, ServerTelemetryManager, Authority, AuthorityFactory, UrlString, DeviceCodeClient, ServerError, CodeChallengeMethodValues, TimeUtils, ClientCredentialClient, OnBehalfOfClient } from '@azure/msal-common';
2
- export { AuthError, AuthErrorMessage, AzureCloudInstance, ClientAuthError, ClientAuthErrorMessage, ClientConfigurationError, ClientConfigurationErrorMessage, InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage, LogLevel, Logger, PromptValue, ProtocolMode, ResponseMode, ServerError, TokenCacheContext } from '@azure/msal-common';
3
- import http, { createServer } from 'http';
4
- import https from 'https';
5
- import { v4 } from 'uuid';
6
- import crypto from 'crypto';
7
- import { sign } from 'jsonwebtoken';
8
-
9
- /*
10
- * Copyright (c) Microsoft Corporation. All rights reserved.
11
- * Licensed under the MIT License.
12
- */
13
- /**
14
- * http methods
15
- */
16
- var HttpMethod;
17
- (function (HttpMethod) {
18
- HttpMethod["GET"] = "get";
19
- HttpMethod["POST"] = "post";
20
- })(HttpMethod || (HttpMethod = {}));
21
- var HttpStatus;
22
- (function (HttpStatus) {
23
- HttpStatus[HttpStatus["SUCCESS_RANGE_START"] = 200] = "SUCCESS_RANGE_START";
24
- HttpStatus[HttpStatus["SUCCESS_RANGE_END"] = 299] = "SUCCESS_RANGE_END";
25
- HttpStatus[HttpStatus["REDIRECT"] = 302] = "REDIRECT";
26
- HttpStatus[HttpStatus["CLIENT_ERROR_RANGE_START"] = 400] = "CLIENT_ERROR_RANGE_START";
27
- HttpStatus[HttpStatus["CLIENT_ERROR_RANGE_END"] = 499] = "CLIENT_ERROR_RANGE_END";
28
- HttpStatus[HttpStatus["SERVER_ERROR_RANGE_START"] = 500] = "SERVER_ERROR_RANGE_START";
29
- HttpStatus[HttpStatus["SERVER_ERROR_RANGE_END"] = 599] = "SERVER_ERROR_RANGE_END";
30
- })(HttpStatus || (HttpStatus = {}));
31
- var ProxyStatus;
32
- (function (ProxyStatus) {
33
- ProxyStatus[ProxyStatus["SUCCESS_RANGE_START"] = 200] = "SUCCESS_RANGE_START";
34
- ProxyStatus[ProxyStatus["SUCCESS_RANGE_END"] = 299] = "SUCCESS_RANGE_END";
35
- ProxyStatus[ProxyStatus["SERVER_ERROR"] = 500] = "SERVER_ERROR";
36
- })(ProxyStatus || (ProxyStatus = {}));
37
- /**
38
- * Constants used for region discovery
39
- */
40
- const REGION_ENVIRONMENT_VARIABLE = "REGION_NAME";
41
- /**
42
- * Constant used for PKCE
43
- */
44
- const RANDOM_OCTET_SIZE = 32;
45
- /**
46
- * Constants used in PKCE
47
- */
48
- const Hash = {
49
- SHA256: "sha256"
50
- };
51
- /**
52
- * Constants for encoding schemes
53
- */
54
- const CharSet = {
55
- CV_CHARSET: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
56
- };
57
- /**
58
- * Constants
59
- */
60
- const Constants = {
61
- MSAL_SKU: "msal.js.node",
62
- JWT_BEARER_ASSERTION_TYPE: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
63
- AUTHORIZATION_PENDING: "authorization_pending",
64
- HTTP_PROTOCOL: "http://",
65
- LOCALHOST: "localhost"
66
- };
67
- /**
68
- * API Codes for Telemetry purposes.
69
- * Before adding a new code you must claim it in the MSAL Telemetry tracker as these number spaces are shared across all MSALs
70
- * 0-99 Silent Flow
71
- * 600-699 Device Code Flow
72
- * 800-899 Auth Code Flow
73
- */
74
- var ApiId;
75
- (function (ApiId) {
76
- ApiId[ApiId["acquireTokenSilent"] = 62] = "acquireTokenSilent";
77
- ApiId[ApiId["acquireTokenByUsernamePassword"] = 371] = "acquireTokenByUsernamePassword";
78
- ApiId[ApiId["acquireTokenByDeviceCode"] = 671] = "acquireTokenByDeviceCode";
79
- ApiId[ApiId["acquireTokenByClientCredential"] = 771] = "acquireTokenByClientCredential";
80
- ApiId[ApiId["acquireTokenByCode"] = 871] = "acquireTokenByCode";
81
- ApiId[ApiId["acquireTokenByRefreshToken"] = 872] = "acquireTokenByRefreshToken";
82
- })(ApiId || (ApiId = {}));
83
- /**
84
- * JWT constants
85
- */
86
- const JwtConstants = {
87
- ALGORITHM: "alg",
88
- RSA_256: "RS256",
89
- X5T: "x5t",
90
- X5C: "x5c",
91
- AUDIENCE: "aud",
92
- EXPIRATION_TIME: "exp",
93
- ISSUER: "iss",
94
- SUBJECT: "sub",
95
- NOT_BEFORE: "nbf",
96
- JWT_ID: "jti"
97
- };
98
- const LOOPBACK_SERVER_CONSTANTS = {
99
- INTERVAL_MS: 100,
100
- TIMEOUT_MS: 5000
101
- };
102
-
103
- /*
104
- * Copyright (c) Microsoft Corporation. All rights reserved.
105
- * Licensed under the MIT License.
106
- */
107
- class NetworkUtils {
108
- static getNetworkResponse(headers, body, statusCode) {
109
- return {
110
- headers: headers,
111
- body: body,
112
- status: statusCode
113
- };
114
- }
115
- /*
116
- * Utility function that converts a URL object into an ordinary options object as expected by the
117
- * http.request and https.request APIs.
118
- * https://github.com/nodejs/node/blob/main/lib/internal/url.js#L1090
119
- */
120
- static urlToHttpOptions(url) {
121
- const options = {
122
- protocol: url.protocol,
123
- hostname: url.hostname && url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname,
124
- hash: url.hash,
125
- search: url.search,
126
- pathname: url.pathname,
127
- path: `${url.pathname || ""}${url.search || ""}`,
128
- href: url.href
129
- };
130
- if (url.port !== "") {
131
- options.port = Number(url.port);
132
- }
133
- if (url.username || url.password) {
134
- options.auth = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;
135
- }
136
- return options;
137
- }
138
- }
139
-
140
- /*
141
- * Copyright (c) Microsoft Corporation. All rights reserved.
142
- * Licensed under the MIT License.
143
- */
144
- /**
145
- * This class implements the API for network requests.
146
- */
147
- class HttpClient {
148
- constructor(proxyUrl, customAgentOptions) {
149
- this.proxyUrl = proxyUrl || "";
150
- this.customAgentOptions = customAgentOptions || {};
151
- }
152
- /**
153
- * Http Get request
154
- * @param url
155
- * @param options
156
- */
157
- async sendGetRequestAsync(url, options) {
158
- if (this.proxyUrl) {
159
- return networkRequestViaProxy(url, this.proxyUrl, HttpMethod.GET, options, this.customAgentOptions);
160
- } else {
161
- return networkRequestViaHttps(url, HttpMethod.GET, options, this.customAgentOptions);
162
- }
163
- }
164
- /**
165
- * Http Post request
166
- * @param url
167
- * @param options
168
- */
169
- async sendPostRequestAsync(url, options, cancellationToken) {
170
- if (this.proxyUrl) {
171
- return networkRequestViaProxy(url, this.proxyUrl, HttpMethod.POST, options, this.customAgentOptions, cancellationToken);
172
- } else {
173
- return networkRequestViaHttps(url, HttpMethod.POST, options, this.customAgentOptions, cancellationToken);
174
- }
175
- }
176
- }
177
- const networkRequestViaProxy = (destinationUrlString, proxyUrlString, httpMethod, options, agentOptions, timeout) => {
178
- const destinationUrl = new URL(destinationUrlString);
179
- const proxyUrl = new URL(proxyUrlString);
180
- // "method: connect" must be used to establish a connection to the proxy
181
- const headers = (options == null ? void 0 : options.headers) || {};
182
- const tunnelRequestOptions = {
183
- host: proxyUrl.hostname,
184
- port: proxyUrl.port,
185
- method: "CONNECT",
186
- path: destinationUrl.hostname,
187
- headers: headers
188
- };
189
- if (timeout) {
190
- tunnelRequestOptions.timeout = timeout;
191
- }
192
- if (agentOptions && Object.keys(agentOptions).length) {
193
- tunnelRequestOptions.agent = new http.Agent(agentOptions);
194
- }
195
- // compose a request string for the socket
196
- let postRequestStringContent = "";
197
- if (httpMethod === HttpMethod.POST) {
198
- const body = (options == null ? void 0 : options.body) || "";
199
- postRequestStringContent = "Content-Type: application/x-www-form-urlencoded\r\n" + `Content-Length: ${body.length}\r\n` + `\r\n${body}`;
200
- }
201
- const outgoingRequestString = `${httpMethod.toUpperCase()} ${destinationUrl.href} HTTP/1.1\r\n` + `Host: ${destinationUrl.host}\r\n` + "Connection: close\r\n" + postRequestStringContent + "\r\n";
202
- return new Promise((resolve, reject) => {
203
- const request = http.request(tunnelRequestOptions);
204
- if (tunnelRequestOptions.timeout) {
205
- request.on("timeout", () => {
206
- request.destroy();
207
- reject(new Error("Request time out"));
208
- });
209
- }
210
- request.end();
211
- // establish connection to the proxy
212
- request.on("connect", (response, socket) => {
213
- const proxyStatusCode = (response == null ? void 0 : response.statusCode) || ProxyStatus.SERVER_ERROR;
214
- if (proxyStatusCode < ProxyStatus.SUCCESS_RANGE_START || proxyStatusCode > ProxyStatus.SUCCESS_RANGE_END) {
215
- request.destroy();
216
- socket.destroy();
217
- reject(new Error(`Error connecting to proxy. Http status code: ${response.statusCode}. Http status message: ${(response == null ? void 0 : response.statusMessage) || "Unknown"}`));
218
- }
219
- if (tunnelRequestOptions.timeout) {
220
- socket.setTimeout(tunnelRequestOptions.timeout);
221
- socket.on("timeout", () => {
222
- request.destroy();
223
- socket.destroy();
224
- reject(new Error("Request time out"));
225
- });
226
- }
227
- // make a request over an HTTP tunnel
228
- socket.write(outgoingRequestString);
229
- const data = [];
230
- socket.on("data", chunk => {
231
- data.push(chunk);
232
- });
233
- socket.on("end", () => {
234
- // combine all received buffer streams into one buffer, and then into a string
235
- const dataString = Buffer.concat([...data]).toString();
236
- // separate each line into it's own entry in an arry
237
- const dataStringArray = dataString.split("\r\n");
238
- // the first entry will contain the statusCode and statusMessage
239
- const httpStatusCode = parseInt(dataStringArray[0].split(" ")[1]);
240
- // remove "HTTP/1.1" and the status code to get the status message
241
- const statusMessage = dataStringArray[0].split(" ").slice(2).join(" ");
242
- // the last entry will contain the body
243
- const body = dataStringArray[dataStringArray.length - 1];
244
- // everything in between the first and last entries are the headers
245
- const headersArray = dataStringArray.slice(1, dataStringArray.length - 2);
246
- // build an object out of all the headers
247
- const entries = new Map();
248
- headersArray.forEach(header => {
249
- /**
250
- * the header might look like "Content-Length: 1531", but that is just a string
251
- * it needs to be converted to a key/value pair
252
- * split the string at the first instance of ":"
253
- * there may be more than one ":" if the value of the header is supposed to be a JSON object
254
- */
255
- const headerKeyValue = header.split(new RegExp(/:\s(.*)/s));
256
- const headerKey = headerKeyValue[0];
257
- let headerValue = headerKeyValue[1];
258
- // check if the value of the header is supposed to be a JSON object
259
- try {
260
- const object = JSON.parse(headerValue);
261
- // if it is, then convert it from a string to a JSON object
262
- if (object && typeof object === "object") {
263
- headerValue = object;
264
- }
265
- } catch (e) {
266
- // otherwise, leave it as a string
267
- }
268
- entries.set(headerKey, headerValue);
269
- });
270
- const headers = Object.fromEntries(entries);
271
- const parsedHeaders = headers;
272
- const networkResponse = NetworkUtils.getNetworkResponse(parsedHeaders, parseBody(httpStatusCode, statusMessage, parsedHeaders, body), httpStatusCode);
273
- if ((httpStatusCode < HttpStatus.SUCCESS_RANGE_START || httpStatusCode > HttpStatus.SUCCESS_RANGE_END) &&
274
- // do not destroy the request for the device code flow
275
- networkResponse.body["error"] !== Constants.AUTHORIZATION_PENDING) {
276
- request.destroy();
277
- }
278
- resolve(networkResponse);
279
- });
280
- socket.on("error", chunk => {
281
- request.destroy();
282
- socket.destroy();
283
- reject(new Error(chunk.toString()));
284
- });
285
- });
286
- request.on("error", chunk => {
287
- request.destroy();
288
- reject(new Error(chunk.toString()));
289
- });
290
- });
291
- };
292
- const networkRequestViaHttps = (urlString, httpMethod, options, agentOptions, timeout) => {
293
- const isPostRequest = httpMethod === HttpMethod.POST;
294
- const body = (options == null ? void 0 : options.body) || "";
295
- const url = new URL(urlString);
296
- const headers = (options == null ? void 0 : options.headers) || {};
297
- const customOptions = {
298
- method: httpMethod,
299
- headers: headers,
300
- ...NetworkUtils.urlToHttpOptions(url)
301
- };
302
- if (timeout) {
303
- customOptions.timeout = timeout;
304
- }
305
- if (agentOptions && Object.keys(agentOptions).length) {
306
- customOptions.agent = new https.Agent(agentOptions);
307
- }
308
- if (isPostRequest) {
309
- // needed for post request to work
310
- customOptions.headers = {
311
- ...customOptions.headers,
312
- "Content-Length": body.length
313
- };
314
- }
315
- return new Promise((resolve, reject) => {
316
- const request = https.request(customOptions);
317
- if (timeout) {
318
- request.on("timeout", () => {
319
- request.destroy();
320
- reject(new Error("Request time out"));
321
- });
322
- }
323
- if (isPostRequest) {
324
- request.write(body);
325
- }
326
- request.end();
327
- request.on("response", response => {
328
- const headers = response.headers;
329
- const statusCode = response.statusCode;
330
- const statusMessage = response.statusMessage;
331
- const data = [];
332
- response.on("data", chunk => {
333
- data.push(chunk);
334
- });
335
- response.on("end", () => {
336
- // combine all received buffer streams into one buffer, and then into a string
337
- const body = Buffer.concat([...data]).toString();
338
- const parsedHeaders = headers;
339
- const networkResponse = NetworkUtils.getNetworkResponse(parsedHeaders, parseBody(statusCode, statusMessage, parsedHeaders, body), statusCode);
340
- if ((statusCode < HttpStatus.SUCCESS_RANGE_START || statusCode > HttpStatus.SUCCESS_RANGE_END) &&
341
- // do not destroy the request for the device code flow
342
- networkResponse.body["error"] !== Constants.AUTHORIZATION_PENDING) {
343
- request.destroy();
344
- }
345
- resolve(networkResponse);
346
- });
347
- });
348
- request.on("error", chunk => {
349
- request.destroy();
350
- reject(new Error(chunk.toString()));
351
- });
352
- });
353
- };
354
- /**
355
- * Check if extra parsing is needed on the repsonse from the server
356
- * @param statusCode {number} the status code of the response from the server
357
- * @param statusMessage {string | undefined} the status message of the response from the server
358
- * @param headers {Record<string, string>} the headers of the response from the server
359
- * @param body {string} the body from the response of the server
360
- * @returns {Object} JSON parsed body or error object
361
- */
362
- const parseBody = (statusCode, statusMessage, headers, body) => {
363
- /*
364
- * Informational responses (100 – 199)
365
- * Successful responses (200 – 299)
366
- * Redirection messages (300 – 399)
367
- * Client error responses (400 – 499)
368
- * Server error responses (500 – 599)
369
- */
370
- let parsedBody;
371
- try {
372
- parsedBody = JSON.parse(body);
373
- } catch (error) {
374
- let errorType;
375
- let errorDescriptionHelper;
376
- if (statusCode >= HttpStatus.CLIENT_ERROR_RANGE_START && statusCode <= HttpStatus.CLIENT_ERROR_RANGE_END) {
377
- errorType = "client_error";
378
- errorDescriptionHelper = "A client";
379
- } else if (statusCode >= HttpStatus.SERVER_ERROR_RANGE_START && statusCode <= HttpStatus.SERVER_ERROR_RANGE_END) {
380
- errorType = "server_error";
381
- errorDescriptionHelper = "A server";
382
- } else {
383
- errorType = "unknown_error";
384
- errorDescriptionHelper = "An unknown";
385
- }
386
- parsedBody = {
387
- error: errorType,
388
- error_description: `${errorDescriptionHelper} error occured.\nHttp status code: ${statusCode}\nHttp status message: ${statusMessage || "Unknown"}\nHeaders: ${JSON.stringify(headers)}`
389
- };
390
- }
391
- return parsedBody;
392
- };
393
-
394
- /*
395
- * Copyright (c) Microsoft Corporation. All rights reserved.
396
- * Licensed under the MIT License.
397
- */
398
- const DEFAULT_AUTH_OPTIONS = {
399
- clientId: Constants$1.EMPTY_STRING,
400
- authority: Constants$1.DEFAULT_AUTHORITY,
401
- clientSecret: Constants$1.EMPTY_STRING,
402
- clientAssertion: Constants$1.EMPTY_STRING,
403
- clientCertificate: {
404
- thumbprint: Constants$1.EMPTY_STRING,
405
- privateKey: Constants$1.EMPTY_STRING,
406
- x5c: Constants$1.EMPTY_STRING
407
- },
408
- knownAuthorities: [],
409
- cloudDiscoveryMetadata: Constants$1.EMPTY_STRING,
410
- authorityMetadata: Constants$1.EMPTY_STRING,
411
- clientCapabilities: [],
412
- protocolMode: ProtocolMode.AAD,
413
- azureCloudOptions: {
414
- azureCloudInstance: AzureCloudInstance.None,
415
- tenant: Constants$1.EMPTY_STRING
416
- },
417
- skipAuthorityMetadataCache: false
418
- };
419
- const DEFAULT_CACHE_OPTIONS = {};
420
- const DEFAULT_LOGGER_OPTIONS = {
421
- loggerCallback: () => {
422
- // allow users to not set logger call back
423
- },
424
- piiLoggingEnabled: false,
425
- logLevel: LogLevel.Info
426
- };
427
- const DEFAULT_SYSTEM_OPTIONS = {
428
- loggerOptions: DEFAULT_LOGGER_OPTIONS,
429
- networkClient: /*#__PURE__*/new HttpClient(),
430
- proxyUrl: Constants$1.EMPTY_STRING,
431
- customAgentOptions: {}
432
- };
433
- const DEFAULT_TELEMETRY_OPTIONS = {
434
- application: {
435
- appName: Constants$1.EMPTY_STRING,
436
- appVersion: Constants$1.EMPTY_STRING
437
- }
438
- };
439
- /**
440
- * Sets the default options when not explicitly configured from app developer
441
- *
442
- * @param auth - Authentication options
443
- * @param cache - Cache options
444
- * @param system - System options
445
- * @param telemetry - Telemetry options
446
- *
447
- * @returns Configuration
448
- * @public
449
- */
450
- function buildAppConfiguration({
451
- auth,
452
- broker,
453
- cache,
454
- system,
455
- telemetry
456
- }) {
457
- const systemOptions = {
458
- ...DEFAULT_SYSTEM_OPTIONS,
459
- networkClient: new HttpClient(system == null ? void 0 : system.proxyUrl, system == null ? void 0 : system.customAgentOptions),
460
- loggerOptions: (system == null ? void 0 : system.loggerOptions) || DEFAULT_LOGGER_OPTIONS
461
- };
462
- return {
463
- auth: {
464
- ...DEFAULT_AUTH_OPTIONS,
465
- ...auth
466
- },
467
- broker: {
468
- ...broker
469
- },
470
- cache: {
471
- ...DEFAULT_CACHE_OPTIONS,
472
- ...cache
473
- },
474
- system: {
475
- ...systemOptions,
476
- ...system
477
- },
478
- telemetry: {
479
- ...DEFAULT_TELEMETRY_OPTIONS,
480
- ...telemetry
481
- }
482
- };
483
- }
484
-
485
- /*
486
- * Copyright (c) Microsoft Corporation. All rights reserved.
487
- * Licensed under the MIT License.
488
- */
489
- class GuidGenerator {
490
- /**
491
- *
492
- * RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or pseudo-random numbers.
493
- * uuidv4 generates guids from cryprtographically-string random
494
- */
495
- generateGuid() {
496
- return v4();
497
- }
498
- /**
499
- * verifies if a string is GUID
500
- * @param guid
501
- */
502
- isGuid(guid) {
503
- const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
504
- return regexGuid.test(guid);
505
- }
506
- }
507
-
508
- /*
509
- * Copyright (c) Microsoft Corporation. All rights reserved.
510
- * Licensed under the MIT License.
511
- */
512
- class EncodingUtils {
513
- /**
514
- * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.
515
- * 'base64': Base64 encoding.
516
- *
517
- * @param str text
518
- */
519
- static base64Encode(str, encoding) {
520
- return Buffer.from(str, encoding).toString("base64");
521
- }
522
- /**
523
- * encode a URL
524
- * @param str
525
- */
526
- static base64EncodeUrl(str, encoding) {
527
- return EncodingUtils.base64Encode(str, encoding).replace(/=/g, Constants$1.EMPTY_STRING).replace(/\+/g, "-").replace(/\//g, "_");
528
- }
529
- /**
530
- * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.
531
- * 'base64': Base64 encoding.
532
- *
533
- * @param base64Str Base64 encoded text
534
- */
535
- static base64Decode(base64Str) {
536
- return Buffer.from(base64Str, "base64").toString("utf8");
537
- }
538
- /**
539
- * @param base64Str Base64 encoded Url
540
- */
541
- static base64DecodeUrl(base64Str) {
542
- let str = base64Str.replace(/-/g, "+").replace(/_/g, "/");
543
- while (str.length % 4) {
544
- str += "=";
545
- }
546
- return EncodingUtils.base64Decode(str);
547
- }
548
- }
549
-
550
- /*
551
- * Copyright (c) Microsoft Corporation. All rights reserved.
552
- * Licensed under the MIT License.
553
- */
554
- class HashUtils {
555
- /**
556
- * generate 'SHA256' hash
557
- * @param buffer
558
- */
559
- sha256(buffer) {
560
- return crypto.createHash(Hash.SHA256).update(buffer).digest();
561
- }
562
- }
563
-
564
- /*
565
- * Copyright (c) Microsoft Corporation. All rights reserved.
566
- * Licensed under the MIT License.
567
- */
568
- /**
569
- * https://tools.ietf.org/html/rfc7636#page-8
570
- */
571
- class PkceGenerator {
572
- constructor() {
573
- this.hashUtils = new HashUtils();
574
- }
575
- /**
576
- * generates the codeVerfier and the challenge from the codeVerfier
577
- * reference: https://tools.ietf.org/html/rfc7636#section-4.1 and https://tools.ietf.org/html/rfc7636#section-4.2
578
- */
579
- async generatePkceCodes() {
580
- const verifier = this.generateCodeVerifier();
581
- const challenge = this.generateCodeChallengeFromVerifier(verifier);
582
- return {
583
- verifier,
584
- challenge
585
- };
586
- }
587
- /**
588
- * generates the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.1
589
- */
590
- generateCodeVerifier() {
591
- const charArr = [];
592
- const maxNumber = 256 - 256 % CharSet.CV_CHARSET.length;
593
- while (charArr.length <= RANDOM_OCTET_SIZE) {
594
- const byte = crypto.randomBytes(1)[0];
595
- if (byte >= maxNumber) {
596
- /*
597
- * Ignore this number to maintain randomness.
598
- * Including it would result in an unequal distribution of characters after doing the modulo
599
- */
600
- continue;
601
- }
602
- const index = byte % CharSet.CV_CHARSET.length;
603
- charArr.push(CharSet.CV_CHARSET[index]);
604
- }
605
- const verifier = charArr.join(Constants$1.EMPTY_STRING);
606
- return EncodingUtils.base64EncodeUrl(verifier);
607
- }
608
- /**
609
- * generate the challenge from the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.2
610
- * @param codeVerifier
611
- */
612
- generateCodeChallengeFromVerifier(codeVerifier) {
613
- return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(codeVerifier).toString("base64"), "base64");
614
- }
615
- }
616
-
617
- /*
618
- * Copyright (c) Microsoft Corporation. All rights reserved.
619
- * Licensed under the MIT License.
620
- */
621
- /**
622
- * This class implements MSAL node's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and
623
- * implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636).
624
- * @public
625
- */
626
- class CryptoProvider {
627
- constructor() {
628
- // Browser crypto needs to be validated first before any other classes can be set.
629
- this.pkceGenerator = new PkceGenerator();
630
- this.guidGenerator = new GuidGenerator();
631
- this.hashUtils = new HashUtils();
632
- }
633
- /**
634
- * Creates a new random GUID - used to populate state and nonce.
635
- * @returns string (GUID)
636
- */
637
- createNewGuid() {
638
- return this.guidGenerator.generateGuid();
639
- }
640
- /**
641
- * Encodes input string to base64.
642
- * @param input - string to be encoded
643
- */
644
- base64Encode(input) {
645
- return EncodingUtils.base64Encode(input);
646
- }
647
- /**
648
- * Decodes input string from base64.
649
- * @param input - string to be decoded
650
- */
651
- base64Decode(input) {
652
- return EncodingUtils.base64Decode(input);
653
- }
654
- /**
655
- * Generates PKCE codes used in Authorization Code Flow.
656
- */
657
- generatePkceCodes() {
658
- return this.pkceGenerator.generatePkceCodes();
659
- }
660
- /**
661
- * Generates a keypair, stores it and returns a thumbprint - not yet implemented for node
662
- */
663
- getPublicKeyThumbprint() {
664
- throw new Error("Method not implemented.");
665
- }
666
- /**
667
- * Removes cryptographic keypair from key store matching the keyId passed in
668
- * @param kid
669
- */
670
- removeTokenBindingKey() {
671
- throw new Error("Method not implemented.");
672
- }
673
- /**
674
- * Removes all cryptographic keys from Keystore
675
- */
676
- clearKeystore() {
677
- throw new Error("Method not implemented.");
678
- }
679
- /**
680
- * Signs the given object as a jwt payload with private key retrieved by given kid - currently not implemented for node
681
- */
682
- signJwt() {
683
- throw new Error("Method not implemented.");
684
- }
685
- /**
686
- * Returns the SHA-256 hash of an input string
687
- */
688
- async hashString(plainText) {
689
- return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(plainText).toString("base64"), "base64");
690
- }
691
- }
692
-
693
- /*
694
- * Copyright (c) Microsoft Corporation. All rights reserved.
695
- * Licensed under the MIT License.
696
- */
697
- /**
698
- * This class deserializes cache entities read from the file into in memory object types defined internally
699
- */
700
- class Deserializer {
701
- /**
702
- * Parse the JSON blob in memory and deserialize the content
703
- * @param cachedJson
704
- */
705
- static deserializeJSONBlob(jsonFile) {
706
- const deserializedCache = StringUtils.isEmpty(jsonFile) ? {} : JSON.parse(jsonFile);
707
- return deserializedCache;
708
- }
709
- /**
710
- * Deserializes accounts to AccountEntity objects
711
- * @param accounts
712
- */
713
- static deserializeAccounts(accounts) {
714
- const accountObjects = {};
715
- if (accounts) {
716
- Object.keys(accounts).map(function (key) {
717
- const serializedAcc = accounts[key];
718
- const mappedAcc = {
719
- homeAccountId: serializedAcc.home_account_id,
720
- environment: serializedAcc.environment,
721
- realm: serializedAcc.realm,
722
- localAccountId: serializedAcc.local_account_id,
723
- username: serializedAcc.username,
724
- authorityType: serializedAcc.authority_type,
725
- name: serializedAcc.name,
726
- clientInfo: serializedAcc.client_info,
727
- lastModificationTime: serializedAcc.last_modification_time,
728
- lastModificationApp: serializedAcc.last_modification_app
729
- };
730
- const account = new AccountEntity();
731
- CacheManager.toObject(account, mappedAcc);
732
- accountObjects[key] = account;
733
- });
734
- }
735
- return accountObjects;
736
- }
737
- /**
738
- * Deserializes id tokens to IdTokenEntity objects
739
- * @param idTokens
740
- */
741
- static deserializeIdTokens(idTokens) {
742
- const idObjects = {};
743
- if (idTokens) {
744
- Object.keys(idTokens).map(function (key) {
745
- const serializedIdT = idTokens[key];
746
- const mappedIdT = {
747
- homeAccountId: serializedIdT.home_account_id,
748
- environment: serializedIdT.environment,
749
- credentialType: serializedIdT.credential_type,
750
- clientId: serializedIdT.client_id,
751
- secret: serializedIdT.secret,
752
- realm: serializedIdT.realm
753
- };
754
- const idToken = new IdTokenEntity();
755
- CacheManager.toObject(idToken, mappedIdT);
756
- idObjects[key] = idToken;
757
- });
758
- }
759
- return idObjects;
760
- }
761
- /**
762
- * Deserializes access tokens to AccessTokenEntity objects
763
- * @param accessTokens
764
- */
765
- static deserializeAccessTokens(accessTokens) {
766
- const atObjects = {};
767
- if (accessTokens) {
768
- Object.keys(accessTokens).map(function (key) {
769
- const serializedAT = accessTokens[key];
770
- const mappedAT = {
771
- homeAccountId: serializedAT.home_account_id,
772
- environment: serializedAT.environment,
773
- credentialType: serializedAT.credential_type,
774
- clientId: serializedAT.client_id,
775
- secret: serializedAT.secret,
776
- realm: serializedAT.realm,
777
- target: serializedAT.target,
778
- cachedAt: serializedAT.cached_at,
779
- expiresOn: serializedAT.expires_on,
780
- extendedExpiresOn: serializedAT.extended_expires_on,
781
- refreshOn: serializedAT.refresh_on,
782
- keyId: serializedAT.key_id,
783
- tokenType: serializedAT.token_type,
784
- requestedClaims: serializedAT.requestedClaims,
785
- requestedClaimsHash: serializedAT.requestedClaimsHash,
786
- userAssertionHash: serializedAT.userAssertionHash
787
- };
788
- const accessToken = new AccessTokenEntity();
789
- CacheManager.toObject(accessToken, mappedAT);
790
- atObjects[key] = accessToken;
791
- });
792
- }
793
- return atObjects;
794
- }
795
- /**
796
- * Deserializes refresh tokens to RefreshTokenEntity objects
797
- * @param refreshTokens
798
- */
799
- static deserializeRefreshTokens(refreshTokens) {
800
- const rtObjects = {};
801
- if (refreshTokens) {
802
- Object.keys(refreshTokens).map(function (key) {
803
- const serializedRT = refreshTokens[key];
804
- const mappedRT = {
805
- homeAccountId: serializedRT.home_account_id,
806
- environment: serializedRT.environment,
807
- credentialType: serializedRT.credential_type,
808
- clientId: serializedRT.client_id,
809
- secret: serializedRT.secret,
810
- familyId: serializedRT.family_id,
811
- target: serializedRT.target,
812
- realm: serializedRT.realm
813
- };
814
- const refreshToken = new RefreshTokenEntity();
815
- CacheManager.toObject(refreshToken, mappedRT);
816
- rtObjects[key] = refreshToken;
817
- });
818
- }
819
- return rtObjects;
820
- }
821
- /**
822
- * Deserializes appMetadata to AppMetaData objects
823
- * @param appMetadata
824
- */
825
- static deserializeAppMetadata(appMetadata) {
826
- const appMetadataObjects = {};
827
- if (appMetadata) {
828
- Object.keys(appMetadata).map(function (key) {
829
- const serializedAmdt = appMetadata[key];
830
- const mappedAmd = {
831
- clientId: serializedAmdt.client_id,
832
- environment: serializedAmdt.environment,
833
- familyId: serializedAmdt.family_id
834
- };
835
- const amd = new AppMetadataEntity();
836
- CacheManager.toObject(amd, mappedAmd);
837
- appMetadataObjects[key] = amd;
838
- });
839
- }
840
- return appMetadataObjects;
841
- }
842
- /**
843
- * Deserialize an inMemory Cache
844
- * @param jsonCache
845
- */
846
- static deserializeAllCache(jsonCache) {
847
- return {
848
- accounts: jsonCache.Account ? this.deserializeAccounts(jsonCache.Account) : {},
849
- idTokens: jsonCache.IdToken ? this.deserializeIdTokens(jsonCache.IdToken) : {},
850
- accessTokens: jsonCache.AccessToken ? this.deserializeAccessTokens(jsonCache.AccessToken) : {},
851
- refreshTokens: jsonCache.RefreshToken ? this.deserializeRefreshTokens(jsonCache.RefreshToken) : {},
852
- appMetadata: jsonCache.AppMetadata ? this.deserializeAppMetadata(jsonCache.AppMetadata) : {}
853
- };
854
- }
855
- }
856
-
857
- /*
858
- * Copyright (c) Microsoft Corporation. All rights reserved.
859
- * Licensed under the MIT License.
860
- */
861
- class Serializer {
862
- /**
863
- * serialize the JSON blob
864
- * @param data
865
- */
866
- static serializeJSONBlob(data) {
867
- return JSON.stringify(data);
868
- }
869
- /**
870
- * Serialize Accounts
871
- * @param accCache
872
- */
873
- static serializeAccounts(accCache) {
874
- const accounts = {};
875
- Object.keys(accCache).map(function (key) {
876
- const accountEntity = accCache[key];
877
- accounts[key] = {
878
- home_account_id: accountEntity.homeAccountId,
879
- environment: accountEntity.environment,
880
- realm: accountEntity.realm,
881
- local_account_id: accountEntity.localAccountId,
882
- username: accountEntity.username,
883
- authority_type: accountEntity.authorityType,
884
- name: accountEntity.name,
885
- client_info: accountEntity.clientInfo,
886
- last_modification_time: accountEntity.lastModificationTime,
887
- last_modification_app: accountEntity.lastModificationApp
888
- };
889
- });
890
- return accounts;
891
- }
892
- /**
893
- * Serialize IdTokens
894
- * @param idTCache
895
- */
896
- static serializeIdTokens(idTCache) {
897
- const idTokens = {};
898
- Object.keys(idTCache).map(function (key) {
899
- const idTEntity = idTCache[key];
900
- idTokens[key] = {
901
- home_account_id: idTEntity.homeAccountId,
902
- environment: idTEntity.environment,
903
- credential_type: idTEntity.credentialType,
904
- client_id: idTEntity.clientId,
905
- secret: idTEntity.secret,
906
- realm: idTEntity.realm
907
- };
908
- });
909
- return idTokens;
910
- }
911
- /**
912
- * Serializes AccessTokens
913
- * @param atCache
914
- */
915
- static serializeAccessTokens(atCache) {
916
- const accessTokens = {};
917
- Object.keys(atCache).map(function (key) {
918
- const atEntity = atCache[key];
919
- accessTokens[key] = {
920
- home_account_id: atEntity.homeAccountId,
921
- environment: atEntity.environment,
922
- credential_type: atEntity.credentialType,
923
- client_id: atEntity.clientId,
924
- secret: atEntity.secret,
925
- realm: atEntity.realm,
926
- target: atEntity.target,
927
- cached_at: atEntity.cachedAt,
928
- expires_on: atEntity.expiresOn,
929
- extended_expires_on: atEntity.extendedExpiresOn,
930
- refresh_on: atEntity.refreshOn,
931
- key_id: atEntity.keyId,
932
- token_type: atEntity.tokenType,
933
- requestedClaims: atEntity.requestedClaims,
934
- requestedClaimsHash: atEntity.requestedClaimsHash,
935
- userAssertionHash: atEntity.userAssertionHash
936
- };
937
- });
938
- return accessTokens;
939
- }
940
- /**
941
- * Serialize refreshTokens
942
- * @param rtCache
943
- */
944
- static serializeRefreshTokens(rtCache) {
945
- const refreshTokens = {};
946
- Object.keys(rtCache).map(function (key) {
947
- const rtEntity = rtCache[key];
948
- refreshTokens[key] = {
949
- home_account_id: rtEntity.homeAccountId,
950
- environment: rtEntity.environment,
951
- credential_type: rtEntity.credentialType,
952
- client_id: rtEntity.clientId,
953
- secret: rtEntity.secret,
954
- family_id: rtEntity.familyId,
955
- target: rtEntity.target,
956
- realm: rtEntity.realm
957
- };
958
- });
959
- return refreshTokens;
960
- }
961
- /**
962
- * Serialize amdtCache
963
- * @param amdtCache
964
- */
965
- static serializeAppMetadata(amdtCache) {
966
- const appMetadata = {};
967
- Object.keys(amdtCache).map(function (key) {
968
- const amdtEntity = amdtCache[key];
969
- appMetadata[key] = {
970
- client_id: amdtEntity.clientId,
971
- environment: amdtEntity.environment,
972
- family_id: amdtEntity.familyId
973
- };
974
- });
975
- return appMetadata;
976
- }
977
- /**
978
- * Serialize the cache
979
- * @param jsonContent
980
- */
981
- static serializeAllCache(inMemCache) {
982
- return {
983
- Account: this.serializeAccounts(inMemCache.accounts),
984
- IdToken: this.serializeIdTokens(inMemCache.idTokens),
985
- AccessToken: this.serializeAccessTokens(inMemCache.accessTokens),
986
- RefreshToken: this.serializeRefreshTokens(inMemCache.refreshTokens),
987
- AppMetadata: this.serializeAppMetadata(inMemCache.appMetadata)
988
- };
989
- }
990
- }
991
-
992
- /*
993
- * Copyright (c) Microsoft Corporation. All rights reserved.
994
- * Licensed under the MIT License.
995
- */
996
- /**
997
- * This class implements Storage for node, reading cache from user specified storage location or an extension library
998
- * @public
999
- */
1000
- class NodeStorage extends CacheManager {
1001
- constructor(logger, clientId, cryptoImpl) {
1002
- super(clientId, cryptoImpl, logger);
1003
- this.cache = {};
1004
- this.changeEmitters = [];
1005
- this.logger = logger;
1006
- }
1007
- /**
1008
- * Queue up callbacks
1009
- * @param func - a callback function for cache change indication
1010
- */
1011
- registerChangeEmitter(func) {
1012
- this.changeEmitters.push(func);
1013
- }
1014
- /**
1015
- * Invoke the callback when cache changes
1016
- */
1017
- emitChange() {
1018
- this.changeEmitters.forEach(func => func.call(null));
1019
- }
1020
- /**
1021
- * Converts cacheKVStore to InMemoryCache
1022
- * @param cache - key value store
1023
- */
1024
- cacheToInMemoryCache(cache) {
1025
- const inMemoryCache = {
1026
- accounts: {},
1027
- idTokens: {},
1028
- accessTokens: {},
1029
- refreshTokens: {},
1030
- appMetadata: {}
1031
- };
1032
- for (const key in cache) {
1033
- if (cache[key] instanceof AccountEntity) {
1034
- inMemoryCache.accounts[key] = cache[key];
1035
- } else if (cache[key] instanceof IdTokenEntity) {
1036
- inMemoryCache.idTokens[key] = cache[key];
1037
- } else if (cache[key] instanceof AccessTokenEntity) {
1038
- inMemoryCache.accessTokens[key] = cache[key];
1039
- } else if (cache[key] instanceof RefreshTokenEntity) {
1040
- inMemoryCache.refreshTokens[key] = cache[key];
1041
- } else if (cache[key] instanceof AppMetadataEntity) {
1042
- inMemoryCache.appMetadata[key] = cache[key];
1043
- } else {
1044
- continue;
1045
- }
1046
- }
1047
- return inMemoryCache;
1048
- }
1049
- /**
1050
- * converts inMemoryCache to CacheKVStore
1051
- * @param inMemoryCache - kvstore map for inmemory
1052
- */
1053
- inMemoryCacheToCache(inMemoryCache) {
1054
- // convert in memory cache to a flat Key-Value map
1055
- let cache = this.getCache();
1056
- cache = {
1057
- ...cache,
1058
- ...inMemoryCache.accounts,
1059
- ...inMemoryCache.idTokens,
1060
- ...inMemoryCache.accessTokens,
1061
- ...inMemoryCache.refreshTokens,
1062
- ...inMemoryCache.appMetadata
1063
- };
1064
- // convert in memory cache to a flat Key-Value map
1065
- return cache;
1066
- }
1067
- /**
1068
- * gets the current in memory cache for the client
1069
- */
1070
- getInMemoryCache() {
1071
- this.logger.trace("Getting in-memory cache");
1072
- // convert the cache key value store to inMemoryCache
1073
- const inMemoryCache = this.cacheToInMemoryCache(this.getCache());
1074
- return inMemoryCache;
1075
- }
1076
- /**
1077
- * sets the current in memory cache for the client
1078
- * @param inMemoryCache - key value map in memory
1079
- */
1080
- setInMemoryCache(inMemoryCache) {
1081
- this.logger.trace("Setting in-memory cache");
1082
- // convert and append the inMemoryCache to cacheKVStore
1083
- const cache = this.inMemoryCacheToCache(inMemoryCache);
1084
- this.setCache(cache);
1085
- this.emitChange();
1086
- }
1087
- /**
1088
- * get the current cache key-value store
1089
- */
1090
- getCache() {
1091
- this.logger.trace("Getting cache key-value store");
1092
- return this.cache;
1093
- }
1094
- /**
1095
- * sets the current cache (key value store)
1096
- * @param cacheMap - key value map
1097
- */
1098
- setCache(cache) {
1099
- this.logger.trace("Setting cache key value store");
1100
- this.cache = cache;
1101
- // mark change in cache
1102
- this.emitChange();
1103
- }
1104
- /**
1105
- * Gets cache item with given key.
1106
- * @param key - lookup key for the cache entry
1107
- */
1108
- getItem(key) {
1109
- this.logger.tracePii(`Item key: ${key}`);
1110
- // read cache
1111
- const cache = this.getCache();
1112
- return cache[key];
1113
- }
1114
- /**
1115
- * Gets cache item with given key-value
1116
- * @param key - lookup key for the cache entry
1117
- * @param value - value of the cache entry
1118
- */
1119
- setItem(key, value) {
1120
- this.logger.tracePii(`Item key: ${key}`);
1121
- // read cache
1122
- const cache = this.getCache();
1123
- cache[key] = value;
1124
- // write to cache
1125
- this.setCache(cache);
1126
- }
1127
- getAccountKeys() {
1128
- const inMemoryCache = this.getInMemoryCache();
1129
- const accountKeys = Object.keys(inMemoryCache.accounts);
1130
- return accountKeys;
1131
- }
1132
- getTokenKeys() {
1133
- const inMemoryCache = this.getInMemoryCache();
1134
- const tokenKeys = {
1135
- idToken: Object.keys(inMemoryCache.idTokens),
1136
- accessToken: Object.keys(inMemoryCache.accessTokens),
1137
- refreshToken: Object.keys(inMemoryCache.refreshTokens)
1138
- };
1139
- return tokenKeys;
1140
- }
1141
- /**
1142
- * fetch the account entity
1143
- * @param accountKey - lookup key to fetch cache type AccountEntity
1144
- */
1145
- getAccount(accountKey) {
1146
- const account = this.getItem(accountKey);
1147
- if (AccountEntity.isAccountEntity(account)) {
1148
- return account;
1149
- }
1150
- return null;
1151
- }
1152
- /**
1153
- * set account entity
1154
- * @param account - cache value to be set of type AccountEntity
1155
- */
1156
- setAccount(account) {
1157
- const accountKey = account.generateAccountKey();
1158
- this.setItem(accountKey, account);
1159
- }
1160
- /**
1161
- * fetch the idToken credential
1162
- * @param idTokenKey - lookup key to fetch cache type IdTokenEntity
1163
- */
1164
- getIdTokenCredential(idTokenKey) {
1165
- const idToken = this.getItem(idTokenKey);
1166
- if (IdTokenEntity.isIdTokenEntity(idToken)) {
1167
- return idToken;
1168
- }
1169
- return null;
1170
- }
1171
- /**
1172
- * set idToken credential
1173
- * @param idToken - cache value to be set of type IdTokenEntity
1174
- */
1175
- setIdTokenCredential(idToken) {
1176
- const idTokenKey = idToken.generateCredentialKey();
1177
- this.setItem(idTokenKey, idToken);
1178
- }
1179
- /**
1180
- * fetch the accessToken credential
1181
- * @param accessTokenKey - lookup key to fetch cache type AccessTokenEntity
1182
- */
1183
- getAccessTokenCredential(accessTokenKey) {
1184
- const accessToken = this.getItem(accessTokenKey);
1185
- if (AccessTokenEntity.isAccessTokenEntity(accessToken)) {
1186
- return accessToken;
1187
- }
1188
- return null;
1189
- }
1190
- /**
1191
- * set accessToken credential
1192
- * @param accessToken - cache value to be set of type AccessTokenEntity
1193
- */
1194
- setAccessTokenCredential(accessToken) {
1195
- const accessTokenKey = accessToken.generateCredentialKey();
1196
- this.setItem(accessTokenKey, accessToken);
1197
- }
1198
- /**
1199
- * fetch the refreshToken credential
1200
- * @param refreshTokenKey - lookup key to fetch cache type RefreshTokenEntity
1201
- */
1202
- getRefreshTokenCredential(refreshTokenKey) {
1203
- const refreshToken = this.getItem(refreshTokenKey);
1204
- if (RefreshTokenEntity.isRefreshTokenEntity(refreshToken)) {
1205
- return refreshToken;
1206
- }
1207
- return null;
1208
- }
1209
- /**
1210
- * set refreshToken credential
1211
- * @param refreshToken - cache value to be set of type RefreshTokenEntity
1212
- */
1213
- setRefreshTokenCredential(refreshToken) {
1214
- const refreshTokenKey = refreshToken.generateCredentialKey();
1215
- this.setItem(refreshTokenKey, refreshToken);
1216
- }
1217
- /**
1218
- * fetch appMetadata entity from the platform cache
1219
- * @param appMetadataKey - lookup key to fetch cache type AppMetadataEntity
1220
- */
1221
- getAppMetadata(appMetadataKey) {
1222
- const appMetadata = this.getItem(appMetadataKey);
1223
- if (AppMetadataEntity.isAppMetadataEntity(appMetadataKey, appMetadata)) {
1224
- return appMetadata;
1225
- }
1226
- return null;
1227
- }
1228
- /**
1229
- * set appMetadata entity to the platform cache
1230
- * @param appMetadata - cache value to be set of type AppMetadataEntity
1231
- */
1232
- setAppMetadata(appMetadata) {
1233
- const appMetadataKey = appMetadata.generateAppMetadataKey();
1234
- this.setItem(appMetadataKey, appMetadata);
1235
- }
1236
- /**
1237
- * fetch server telemetry entity from the platform cache
1238
- * @param serverTelemetrykey - lookup key to fetch cache type ServerTelemetryEntity
1239
- */
1240
- getServerTelemetry(serverTelemetrykey) {
1241
- const serverTelemetryEntity = this.getItem(serverTelemetrykey);
1242
- if (serverTelemetryEntity && ServerTelemetryEntity.isServerTelemetryEntity(serverTelemetrykey, serverTelemetryEntity)) {
1243
- return serverTelemetryEntity;
1244
- }
1245
- return null;
1246
- }
1247
- /**
1248
- * set server telemetry entity to the platform cache
1249
- * @param serverTelemetryKey - lookup key to fetch cache type ServerTelemetryEntity
1250
- * @param serverTelemetry - cache value to be set of type ServerTelemetryEntity
1251
- */
1252
- setServerTelemetry(serverTelemetryKey, serverTelemetry) {
1253
- this.setItem(serverTelemetryKey, serverTelemetry);
1254
- }
1255
- /**
1256
- * fetch authority metadata entity from the platform cache
1257
- * @param key - lookup key to fetch cache type AuthorityMetadataEntity
1258
- */
1259
- getAuthorityMetadata(key) {
1260
- const authorityMetadataEntity = this.getItem(key);
1261
- if (authorityMetadataEntity && AuthorityMetadataEntity.isAuthorityMetadataEntity(key, authorityMetadataEntity)) {
1262
- return authorityMetadataEntity;
1263
- }
1264
- return null;
1265
- }
1266
- /**
1267
- * Get all authority metadata keys
1268
- */
1269
- getAuthorityMetadataKeys() {
1270
- return this.getKeys().filter(key => {
1271
- return this.isAuthorityMetadata(key);
1272
- });
1273
- }
1274
- /**
1275
- * set authority metadata entity to the platform cache
1276
- * @param key - lookup key to fetch cache type AuthorityMetadataEntity
1277
- * @param metadata - cache value to be set of type AuthorityMetadataEntity
1278
- */
1279
- setAuthorityMetadata(key, metadata) {
1280
- this.setItem(key, metadata);
1281
- }
1282
- /**
1283
- * fetch throttling entity from the platform cache
1284
- * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity
1285
- */
1286
- getThrottlingCache(throttlingCacheKey) {
1287
- const throttlingCache = this.getItem(throttlingCacheKey);
1288
- if (throttlingCache && ThrottlingEntity.isThrottlingEntity(throttlingCacheKey, throttlingCache)) {
1289
- return throttlingCache;
1290
- }
1291
- return null;
1292
- }
1293
- /**
1294
- * set throttling entity to the platform cache
1295
- * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity
1296
- * @param throttlingCache - cache value to be set of type ThrottlingEntity
1297
- */
1298
- setThrottlingCache(throttlingCacheKey, throttlingCache) {
1299
- this.setItem(throttlingCacheKey, throttlingCache);
1300
- }
1301
- /**
1302
- * Removes the cache item from memory with the given key.
1303
- * @param key - lookup key to remove a cache entity
1304
- * @param inMemory - key value map of the cache
1305
- */
1306
- removeItem(key) {
1307
- this.logger.tracePii(`Item key: ${key}`);
1308
- // read inMemoryCache
1309
- let result = false;
1310
- const cache = this.getCache();
1311
- if (!!cache[key]) {
1312
- delete cache[key];
1313
- result = true;
1314
- }
1315
- // write to the cache after removal
1316
- if (result) {
1317
- this.setCache(cache);
1318
- this.emitChange();
1319
- }
1320
- return result;
1321
- }
1322
- /**
1323
- * Checks whether key is in cache.
1324
- * @param key - look up key for a cache entity
1325
- */
1326
- containsKey(key) {
1327
- return this.getKeys().includes(key);
1328
- }
1329
- /**
1330
- * Gets all keys in window.
1331
- */
1332
- getKeys() {
1333
- this.logger.trace("Retrieving all cache keys");
1334
- // read cache
1335
- const cache = this.getCache();
1336
- return [...Object.keys(cache)];
1337
- }
1338
- /**
1339
- * Clears all cache entries created by MSAL (except tokens).
1340
- */
1341
- async clear() {
1342
- this.logger.trace("Clearing cache entries created by MSAL");
1343
- // read inMemoryCache
1344
- const cacheKeys = this.getKeys();
1345
- // delete each element
1346
- cacheKeys.forEach(key => {
1347
- this.removeItem(key);
1348
- });
1349
- this.emitChange();
1350
- }
1351
- /**
1352
- * Initialize in memory cache from an exisiting cache vault
1353
- * @param cache - blob formatted cache (JSON)
1354
- */
1355
- static generateInMemoryCache(cache) {
1356
- return Deserializer.deserializeAllCache(Deserializer.deserializeJSONBlob(cache));
1357
- }
1358
- /**
1359
- * retrieves the final JSON
1360
- * @param inMemoryCache - itemised cache read from the JSON
1361
- */
1362
- static generateJsonCache(inMemoryCache) {
1363
- return Serializer.serializeAllCache(inMemoryCache);
1364
- }
1365
- /**
1366
- * Updates a credential's cache key if the current cache key is outdated
1367
- */
1368
- updateCredentialCacheKey(currentCacheKey, credential) {
1369
- const updatedCacheKey = credential.generateCredentialKey();
1370
- if (currentCacheKey !== updatedCacheKey) {
1371
- const cacheItem = this.getItem(currentCacheKey);
1372
- if (cacheItem) {
1373
- this.removeItem(currentCacheKey);
1374
- this.setItem(updatedCacheKey, cacheItem);
1375
- this.logger.verbose(`Updated an outdated ${credential.credentialType} cache key`);
1376
- return updatedCacheKey;
1377
- } else {
1378
- this.logger.error(`Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`);
1379
- }
1380
- }
1381
- return currentCacheKey;
1382
- }
1383
- }
1384
-
1385
- /*
1386
- * Copyright (c) Microsoft Corporation. All rights reserved.
1387
- * Licensed under the MIT License.
1388
- */
1389
- const defaultSerializedCache = {
1390
- Account: {},
1391
- IdToken: {},
1392
- AccessToken: {},
1393
- RefreshToken: {},
1394
- AppMetadata: {}
1395
- };
1396
- /**
1397
- * In-memory token cache manager
1398
- * @public
1399
- */
1400
- class TokenCache {
1401
- constructor(storage, logger, cachePlugin) {
1402
- this.cacheHasChanged = false;
1403
- this.storage = storage;
1404
- this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this));
1405
- if (cachePlugin) {
1406
- this.persistence = cachePlugin;
1407
- }
1408
- this.logger = logger;
1409
- }
1410
- /**
1411
- * Set to true if cache state has changed since last time serialize or writeToPersistence was called
1412
- */
1413
- hasChanged() {
1414
- return this.cacheHasChanged;
1415
- }
1416
- /**
1417
- * Serializes in memory cache to JSON
1418
- */
1419
- serialize() {
1420
- this.logger.trace("Serializing in-memory cache");
1421
- let finalState = Serializer.serializeAllCache(this.storage.getInMemoryCache());
1422
- // if cacheSnapshot not null or empty, merge
1423
- if (!StringUtils.isEmpty(this.cacheSnapshot)) {
1424
- this.logger.trace("Reading cache snapshot from disk");
1425
- finalState = this.mergeState(JSON.parse(this.cacheSnapshot), finalState);
1426
- } else {
1427
- this.logger.trace("No cache snapshot to merge");
1428
- }
1429
- this.cacheHasChanged = false;
1430
- return JSON.stringify(finalState);
1431
- }
1432
- /**
1433
- * Deserializes JSON to in-memory cache. JSON should be in MSAL cache schema format
1434
- * @param cache - blob formatted cache
1435
- */
1436
- deserialize(cache) {
1437
- this.logger.trace("Deserializing JSON to in-memory cache");
1438
- this.cacheSnapshot = cache;
1439
- if (!StringUtils.isEmpty(this.cacheSnapshot)) {
1440
- this.logger.trace("Reading cache snapshot from disk");
1441
- const deserializedCache = Deserializer.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot)));
1442
- this.storage.setInMemoryCache(deserializedCache);
1443
- } else {
1444
- this.logger.trace("No cache snapshot to deserialize");
1445
- }
1446
- }
1447
- /**
1448
- * Fetches the cache key-value map
1449
- */
1450
- getKVStore() {
1451
- return this.storage.getCache();
1452
- }
1453
- /**
1454
- * API that retrieves all accounts currently in cache to the user
1455
- */
1456
- async getAllAccounts() {
1457
- this.logger.trace("getAllAccounts called");
1458
- let cacheContext;
1459
- try {
1460
- if (this.persistence) {
1461
- cacheContext = new TokenCacheContext(this, false);
1462
- await this.persistence.beforeCacheAccess(cacheContext);
1463
- }
1464
- return this.storage.getAllAccounts();
1465
- } finally {
1466
- if (this.persistence && cacheContext) {
1467
- await this.persistence.afterCacheAccess(cacheContext);
1468
- }
1469
- }
1470
- }
1471
- /**
1472
- * Returns the signed in account matching homeAccountId.
1473
- * (the account object is created at the time of successful login)
1474
- * or null when no matching account is found
1475
- * @param homeAccountId - unique identifier for an account (uid.utid)
1476
- */
1477
- async getAccountByHomeId(homeAccountId) {
1478
- const allAccounts = await this.getAllAccounts();
1479
- if (!StringUtils.isEmpty(homeAccountId) && allAccounts && allAccounts.length) {
1480
- return allAccounts.filter(accountObj => accountObj.homeAccountId === homeAccountId)[0] || null;
1481
- } else {
1482
- return null;
1483
- }
1484
- }
1485
- /**
1486
- * Returns the signed in account matching localAccountId.
1487
- * (the account object is created at the time of successful login)
1488
- * or null when no matching account is found
1489
- * @param localAccountId - unique identifier of an account (sub/obj when homeAccountId cannot be populated)
1490
- */
1491
- async getAccountByLocalId(localAccountId) {
1492
- const allAccounts = await this.getAllAccounts();
1493
- if (!StringUtils.isEmpty(localAccountId) && allAccounts && allAccounts.length) {
1494
- return allAccounts.filter(accountObj => accountObj.localAccountId === localAccountId)[0] || null;
1495
- } else {
1496
- return null;
1497
- }
1498
- }
1499
- /**
1500
- * API to remove a specific account and the relevant data from cache
1501
- * @param account - AccountInfo passed by the user
1502
- */
1503
- async removeAccount(account) {
1504
- this.logger.trace("removeAccount called");
1505
- let cacheContext;
1506
- try {
1507
- if (this.persistence) {
1508
- cacheContext = new TokenCacheContext(this, true);
1509
- await this.persistence.beforeCacheAccess(cacheContext);
1510
- }
1511
- await this.storage.removeAccount(AccountEntity.generateAccountCacheKey(account));
1512
- } finally {
1513
- if (this.persistence && cacheContext) {
1514
- await this.persistence.afterCacheAccess(cacheContext);
1515
- }
1516
- }
1517
- }
1518
- /**
1519
- * Called when the cache has changed state.
1520
- */
1521
- handleChangeEvent() {
1522
- this.cacheHasChanged = true;
1523
- }
1524
- /**
1525
- * Merge in memory cache with the cache snapshot.
1526
- * @param oldState - cache before changes
1527
- * @param currentState - current cache state in the library
1528
- */
1529
- mergeState(oldState, currentState) {
1530
- this.logger.trace("Merging in-memory cache with cache snapshot");
1531
- const stateAfterRemoval = this.mergeRemovals(oldState, currentState);
1532
- return this.mergeUpdates(stateAfterRemoval, currentState);
1533
- }
1534
- /**
1535
- * Deep update of oldState based on newState values
1536
- * @param oldState - cache before changes
1537
- * @param newState - updated cache
1538
- */
1539
- mergeUpdates(oldState, newState) {
1540
- Object.keys(newState).forEach(newKey => {
1541
- const newValue = newState[newKey];
1542
- // if oldState does not contain value but newValue does, add it
1543
- if (!oldState.hasOwnProperty(newKey)) {
1544
- if (newValue !== null) {
1545
- oldState[newKey] = newValue;
1546
- }
1547
- } else {
1548
- // both oldState and newState contain the key, do deep update
1549
- const newValueNotNull = newValue !== null;
1550
- const newValueIsObject = typeof newValue === "object";
1551
- const newValueIsNotArray = !Array.isArray(newValue);
1552
- const oldStateNotUndefinedOrNull = typeof oldState[newKey] !== "undefined" && oldState[newKey] !== null;
1553
- if (newValueNotNull && newValueIsObject && newValueIsNotArray && oldStateNotUndefinedOrNull) {
1554
- this.mergeUpdates(oldState[newKey], newValue);
1555
- } else {
1556
- oldState[newKey] = newValue;
1557
- }
1558
- }
1559
- });
1560
- return oldState;
1561
- }
1562
- /**
1563
- * Removes entities in oldState that the were removed from newState. If there are any unknown values in root of
1564
- * oldState that are not recognized, they are left untouched.
1565
- * @param oldState - cache before changes
1566
- * @param newState - updated cache
1567
- */
1568
- mergeRemovals(oldState, newState) {
1569
- this.logger.trace("Remove updated entries in cache");
1570
- const accounts = oldState.Account ? this.mergeRemovalsDict(oldState.Account, newState.Account) : oldState.Account;
1571
- const accessTokens = oldState.AccessToken ? this.mergeRemovalsDict(oldState.AccessToken, newState.AccessToken) : oldState.AccessToken;
1572
- const refreshTokens = oldState.RefreshToken ? this.mergeRemovalsDict(oldState.RefreshToken, newState.RefreshToken) : oldState.RefreshToken;
1573
- const idTokens = oldState.IdToken ? this.mergeRemovalsDict(oldState.IdToken, newState.IdToken) : oldState.IdToken;
1574
- const appMetadata = oldState.AppMetadata ? this.mergeRemovalsDict(oldState.AppMetadata, newState.AppMetadata) : oldState.AppMetadata;
1575
- return {
1576
- ...oldState,
1577
- Account: accounts,
1578
- AccessToken: accessTokens,
1579
- RefreshToken: refreshTokens,
1580
- IdToken: idTokens,
1581
- AppMetadata: appMetadata
1582
- };
1583
- }
1584
- /**
1585
- * Helper to merge new cache with the old one
1586
- * @param oldState - cache before changes
1587
- * @param newState - updated cache
1588
- */
1589
- mergeRemovalsDict(oldState, newState) {
1590
- const finalState = {
1591
- ...oldState
1592
- };
1593
- Object.keys(oldState).forEach(oldKey => {
1594
- if (!newState || !newState.hasOwnProperty(oldKey)) {
1595
- delete finalState[oldKey];
1596
- }
1597
- });
1598
- return finalState;
1599
- }
1600
- /**
1601
- * Helper to overlay as a part of cache merge
1602
- * @param passedInCache - cache read from the blob
1603
- */
1604
- overlayDefaults(passedInCache) {
1605
- this.logger.trace("Overlaying input cache with the default cache");
1606
- return {
1607
- Account: {
1608
- ...defaultSerializedCache.Account,
1609
- ...passedInCache.Account
1610
- },
1611
- IdToken: {
1612
- ...defaultSerializedCache.IdToken,
1613
- ...passedInCache.IdToken
1614
- },
1615
- AccessToken: {
1616
- ...defaultSerializedCache.AccessToken,
1617
- ...passedInCache.AccessToken
1618
- },
1619
- RefreshToken: {
1620
- ...defaultSerializedCache.RefreshToken,
1621
- ...passedInCache.RefreshToken
1622
- },
1623
- AppMetadata: {
1624
- ...defaultSerializedCache.AppMetadata,
1625
- ...passedInCache.AppMetadata
1626
- }
1627
- };
1628
- }
1629
- }
1630
-
1631
- /* eslint-disable header/header */
1632
- const name = "@azure/msal-node";
1633
- const version = "1.17.2";
1634
-
1635
- /*
1636
- * Copyright (c) Microsoft Corporation. All rights reserved.
1637
- * Licensed under the MIT License.
1638
- */
1639
- /**
1640
- * NodeAuthErrorMessage class containing string constants used by error codes and messages.
1641
- */
1642
- const NodeAuthErrorMessage = {
1643
- invalidLoopbackAddressType: {
1644
- code: "invalid_loopback_server_address_type",
1645
- desc: "Loopback server address is not type string. This is unexpected."
1646
- },
1647
- unableToLoadRedirectUri: {
1648
- code: "unable_to_load_redirectUrl",
1649
- desc: "Loopback server callback was invoked without a url. This is unexpected."
1650
- },
1651
- noAuthCodeInResponse: {
1652
- code: "no_auth_code_in_response",
1653
- desc: "No auth code found in the server response. Please check your network trace to determine what happened."
1654
- },
1655
- noLoopbackServerExists: {
1656
- code: "no_loopback_server_exists",
1657
- desc: "No loopback server exists yet."
1658
- },
1659
- loopbackServerAlreadyExists: {
1660
- code: "loopback_server_already_exists",
1661
- desc: "Loopback server already exists. Cannot create another."
1662
- },
1663
- loopbackServerTimeout: {
1664
- code: "loopback_server_timeout",
1665
- desc: "Timed out waiting for auth code listener to be registered."
1666
- },
1667
- stateNotFoundError: {
1668
- code: "state_not_found",
1669
- desc: "State not found. Please verify that the request originated from msal."
1670
- }
1671
- };
1672
- class NodeAuthError extends AuthError {
1673
- constructor(errorCode, errorMessage) {
1674
- super(errorCode, errorMessage);
1675
- this.name = "NodeAuthError";
1676
- }
1677
- /**
1678
- * Creates an error thrown if loopback server address is of type string.
1679
- */
1680
- static createInvalidLoopbackAddressTypeError() {
1681
- return new NodeAuthError(NodeAuthErrorMessage.invalidLoopbackAddressType.code, `${NodeAuthErrorMessage.invalidLoopbackAddressType.desc}`);
1682
- }
1683
- /**
1684
- * Creates an error thrown if the loopback server is unable to get a url.
1685
- */
1686
- static createUnableToLoadRedirectUrlError() {
1687
- return new NodeAuthError(NodeAuthErrorMessage.unableToLoadRedirectUri.code, `${NodeAuthErrorMessage.unableToLoadRedirectUri.desc}`);
1688
- }
1689
- /**
1690
- * Creates an error thrown if the server response does not contain an auth code.
1691
- */
1692
- static createNoAuthCodeInResponseError() {
1693
- return new NodeAuthError(NodeAuthErrorMessage.noAuthCodeInResponse.code, `${NodeAuthErrorMessage.noAuthCodeInResponse.desc}`);
1694
- }
1695
- /**
1696
- * Creates an error thrown if the loopback server has not been spun up yet.
1697
- */
1698
- static createNoLoopbackServerExistsError() {
1699
- return new NodeAuthError(NodeAuthErrorMessage.noLoopbackServerExists.code, `${NodeAuthErrorMessage.noLoopbackServerExists.desc}`);
1700
- }
1701
- /**
1702
- * Creates an error thrown if a loopback server already exists when attempting to create another one.
1703
- */
1704
- static createLoopbackServerAlreadyExistsError() {
1705
- return new NodeAuthError(NodeAuthErrorMessage.loopbackServerAlreadyExists.code, `${NodeAuthErrorMessage.loopbackServerAlreadyExists.desc}`);
1706
- }
1707
- /**
1708
- * Creates an error thrown if the loopback server times out registering the auth code listener.
1709
- */
1710
- static createLoopbackServerTimeoutError() {
1711
- return new NodeAuthError(NodeAuthErrorMessage.loopbackServerTimeout.code, `${NodeAuthErrorMessage.loopbackServerTimeout.desc}`);
1712
- }
1713
- /**
1714
- * Creates an error thrown when the state is not present.
1715
- */
1716
- static createStateNotFoundError() {
1717
- return new NodeAuthError(NodeAuthErrorMessage.stateNotFoundError.code, NodeAuthErrorMessage.stateNotFoundError.desc);
1718
- }
1719
- }
1720
-
1721
- /*
1722
- * Copyright (c) Microsoft Corporation. All rights reserved.
1723
- * Licensed under the MIT License.
1724
- */
1725
- /**
1726
- * Base abstract class for all ClientApplications - public and confidential
1727
- * @public
1728
- */
1729
- class ClientApplication {
1730
- /**
1731
- * Constructor for the ClientApplication
1732
- */
1733
- constructor(configuration) {
1734
- this.config = buildAppConfiguration(configuration);
1735
- this.cryptoProvider = new CryptoProvider();
1736
- this.logger = new Logger(this.config.system.loggerOptions, name, version);
1737
- this.storage = new NodeStorage(this.logger, this.config.auth.clientId, this.cryptoProvider);
1738
- this.tokenCache = new TokenCache(this.storage, this.logger, this.config.cache.cachePlugin);
1739
- }
1740
- /**
1741
- * Creates the URL of the authorization request, letting the user input credentials and consent to the
1742
- * application. The URL targets the /authorize endpoint of the authority configured in the
1743
- * application object.
1744
- *
1745
- * Once the user inputs their credentials and consents, the authority will send a response to the redirect URI
1746
- * sent in the request and should contain an authorization code, which can then be used to acquire tokens via
1747
- * `acquireTokenByCode(AuthorizationCodeRequest)`.
1748
- */
1749
- async getAuthCodeUrl(request) {
1750
- this.logger.info("getAuthCodeUrl called", request.correlationId);
1751
- const validRequest = {
1752
- ...request,
1753
- ...(await this.initializeBaseRequest(request)),
1754
- responseMode: request.responseMode || ResponseMode.QUERY,
1755
- authenticationScheme: AuthenticationScheme.BEARER
1756
- };
1757
- const authClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, undefined, undefined, request.azureCloudOptions);
1758
- const authorizationCodeClient = new AuthorizationCodeClient(authClientConfig);
1759
- this.logger.verbose("Auth code client created", validRequest.correlationId);
1760
- return authorizationCodeClient.getAuthCodeUrl(validRequest);
1761
- }
1762
- /**
1763
- * Acquires a token by exchanging the Authorization Code received from the first step of OAuth2.0
1764
- * Authorization Code flow.
1765
- *
1766
- * `getAuthCodeUrl(AuthorizationCodeUrlRequest)` can be used to create the URL for the first step of OAuth2.0
1767
- * Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and
1768
- * AuthorizationCodeRequest are the same.
1769
- */
1770
- async acquireTokenByCode(request, authCodePayLoad) {
1771
- this.logger.info("acquireTokenByCode called");
1772
- if (request.state && authCodePayLoad) {
1773
- this.logger.info("acquireTokenByCode - validating state");
1774
- this.validateState(request.state, authCodePayLoad.state || "");
1775
- // eslint-disable-next-line no-param-reassign
1776
- authCodePayLoad = {
1777
- ...authCodePayLoad,
1778
- state: ""
1779
- };
1780
- }
1781
- const validRequest = {
1782
- ...request,
1783
- ...(await this.initializeBaseRequest(request)),
1784
- authenticationScheme: AuthenticationScheme.BEARER
1785
- };
1786
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByCode, validRequest.correlationId);
1787
- try {
1788
- const authClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
1789
- const authorizationCodeClient = new AuthorizationCodeClient(authClientConfig);
1790
- this.logger.verbose("Auth code client created", validRequest.correlationId);
1791
- return authorizationCodeClient.acquireToken(validRequest, authCodePayLoad);
1792
- } catch (e) {
1793
- if (e instanceof AuthError) {
1794
- e.setCorrelationId(validRequest.correlationId);
1795
- }
1796
- serverTelemetryManager.cacheFailedRequest(e);
1797
- throw e;
1798
- }
1799
- }
1800
- /**
1801
- * Acquires a token by exchanging the refresh token provided for a new set of tokens.
1802
- *
1803
- * This API is provided only for scenarios where you would like to migrate from ADAL to MSAL. Otherwise, it is
1804
- * recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will
1805
- * handle the caching and refreshing of tokens automatically.
1806
- */
1807
- async acquireTokenByRefreshToken(request) {
1808
- this.logger.info("acquireTokenByRefreshToken called", request.correlationId);
1809
- const validRequest = {
1810
- ...request,
1811
- ...(await this.initializeBaseRequest(request)),
1812
- authenticationScheme: AuthenticationScheme.BEARER
1813
- };
1814
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByRefreshToken, validRequest.correlationId);
1815
- try {
1816
- const refreshTokenClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
1817
- const refreshTokenClient = new RefreshTokenClient(refreshTokenClientConfig);
1818
- this.logger.verbose("Refresh token client created", validRequest.correlationId);
1819
- return refreshTokenClient.acquireToken(validRequest);
1820
- } catch (e) {
1821
- if (e instanceof AuthError) {
1822
- e.setCorrelationId(validRequest.correlationId);
1823
- }
1824
- serverTelemetryManager.cacheFailedRequest(e);
1825
- throw e;
1826
- }
1827
- }
1828
- /**
1829
- * Acquires a token silently when a user specifies the account the token is requested for.
1830
- *
1831
- * This API expects the user to provide an account object and looks into the cache to retrieve the token if present.
1832
- * There is also an optional "forceRefresh" boolean the user can send to bypass the cache for access_token and id_token.
1833
- * In case the refresh_token is expired or not found, an error is thrown
1834
- * and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`).
1835
- */
1836
- async acquireTokenSilent(request) {
1837
- const validRequest = {
1838
- ...request,
1839
- ...(await this.initializeBaseRequest(request)),
1840
- forceRefresh: request.forceRefresh || false
1841
- };
1842
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenSilent, validRequest.correlationId, validRequest.forceRefresh);
1843
- try {
1844
- const silentFlowClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
1845
- const silentFlowClient = new SilentFlowClient(silentFlowClientConfig);
1846
- this.logger.verbose("Silent flow client created", validRequest.correlationId);
1847
- return silentFlowClient.acquireToken(validRequest);
1848
- } catch (e) {
1849
- if (e instanceof AuthError) {
1850
- e.setCorrelationId(validRequest.correlationId);
1851
- }
1852
- serverTelemetryManager.cacheFailedRequest(e);
1853
- throw e;
1854
- }
1855
- }
1856
- /**
1857
- * Acquires tokens with password grant by exchanging client applications username and password for credentials
1858
- *
1859
- * The latest OAuth 2.0 Security Best Current Practice disallows the password grant entirely.
1860
- * More details on this recommendation at https://tools.ietf.org/html/draft-ietf-oauth-security-topics-13#section-3.4
1861
- * Microsoft's documentation and recommendations are at:
1862
- * https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#usernamepassword
1863
- *
1864
- * @param request - UsenamePasswordRequest
1865
- */
1866
- async acquireTokenByUsernamePassword(request) {
1867
- this.logger.info("acquireTokenByUsernamePassword called", request.correlationId);
1868
- const validRequest = {
1869
- ...request,
1870
- ...(await this.initializeBaseRequest(request))
1871
- };
1872
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByUsernamePassword, validRequest.correlationId);
1873
- try {
1874
- const usernamePasswordClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
1875
- const usernamePasswordClient = new UsernamePasswordClient(usernamePasswordClientConfig);
1876
- this.logger.verbose("Username password client created", validRequest.correlationId);
1877
- return usernamePasswordClient.acquireToken(validRequest);
1878
- } catch (e) {
1879
- if (e instanceof AuthError) {
1880
- e.setCorrelationId(validRequest.correlationId);
1881
- }
1882
- serverTelemetryManager.cacheFailedRequest(e);
1883
- throw e;
1884
- }
1885
- }
1886
- /**
1887
- * Gets the token cache for the application.
1888
- */
1889
- getTokenCache() {
1890
- this.logger.info("getTokenCache called");
1891
- return this.tokenCache;
1892
- }
1893
- /**
1894
- * Validates OIDC state by comparing the user cached state with the state received from the server.
1895
- *
1896
- * This API is provided for scenarios where you would use OAuth2.0 state parameter to mitigate against
1897
- * CSRF attacks.
1898
- * For more information about state, visit https://datatracker.ietf.org/doc/html/rfc6819#section-3.6.
1899
- * @param state
1900
- * @param cachedState
1901
- */
1902
- validateState(state, cachedState) {
1903
- if (!state) {
1904
- throw NodeAuthError.createStateNotFoundError();
1905
- }
1906
- if (state !== cachedState) {
1907
- throw ClientAuthError.createStateMismatchError();
1908
- }
1909
- }
1910
- /**
1911
- * Returns the logger instance
1912
- */
1913
- getLogger() {
1914
- return this.logger;
1915
- }
1916
- /**
1917
- * Replaces the default logger set in configurations with new Logger with new configurations
1918
- * @param logger - Logger instance
1919
- */
1920
- setLogger(logger) {
1921
- this.logger = logger;
1922
- }
1923
- /**
1924
- * Builds the common configuration to be passed to the common component based on the platform configurarion
1925
- * @param authority - user passed authority in configuration
1926
- * @param serverTelemetryManager - initializes servertelemetry if passed
1927
- */
1928
- async buildOauthClientConfiguration(authority, requestCorrelationId, serverTelemetryManager, azureRegionConfiguration, azureCloudOptions) {
1929
- this.logger.verbose("buildOauthClientConfiguration called", requestCorrelationId);
1930
- // precedence - azureCloudInstance + tenant >> authority and request >> config
1931
- const userAzureCloudOptions = azureCloudOptions ? azureCloudOptions : this.config.auth.azureCloudOptions;
1932
- // using null assertion operator as we ensure that all config values have default values in buildConfiguration()
1933
- this.logger.verbose(`building oauth client configuration with the authority: ${authority}`, requestCorrelationId);
1934
- const discoveredAuthority = await this.createAuthority(authority, azureRegionConfiguration, requestCorrelationId, userAzureCloudOptions);
1935
- serverTelemetryManager == null ? void 0 : serverTelemetryManager.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata);
1936
- const clientConfiguration = {
1937
- authOptions: {
1938
- clientId: this.config.auth.clientId,
1939
- authority: discoveredAuthority,
1940
- clientCapabilities: this.config.auth.clientCapabilities
1941
- },
1942
- loggerOptions: {
1943
- logLevel: this.config.system.loggerOptions.logLevel,
1944
- loggerCallback: this.config.system.loggerOptions.loggerCallback,
1945
- piiLoggingEnabled: this.config.system.loggerOptions.piiLoggingEnabled,
1946
- correlationId: requestCorrelationId
1947
- },
1948
- cryptoInterface: this.cryptoProvider,
1949
- networkInterface: this.config.system.networkClient,
1950
- storageInterface: this.storage,
1951
- serverTelemetryManager: serverTelemetryManager,
1952
- clientCredentials: {
1953
- clientSecret: this.clientSecret,
1954
- clientAssertion: this.clientAssertion ? this.getClientAssertion(discoveredAuthority) : undefined
1955
- },
1956
- libraryInfo: {
1957
- sku: Constants.MSAL_SKU,
1958
- version: version,
1959
- cpu: process.arch || Constants$1.EMPTY_STRING,
1960
- os: process.platform || Constants$1.EMPTY_STRING
1961
- },
1962
- telemetry: this.config.telemetry,
1963
- persistencePlugin: this.config.cache.cachePlugin,
1964
- serializableCache: this.tokenCache
1965
- };
1966
- return clientConfiguration;
1967
- }
1968
- getClientAssertion(authority) {
1969
- return {
1970
- assertion: this.clientAssertion.getJwt(this.cryptoProvider, this.config.auth.clientId, authority.tokenEndpoint),
1971
- assertionType: Constants.JWT_BEARER_ASSERTION_TYPE
1972
- };
1973
- }
1974
- /**
1975
- * Generates a request with the default scopes & generates a correlationId.
1976
- * @param authRequest - BaseAuthRequest for initialization
1977
- */
1978
- async initializeBaseRequest(authRequest) {
1979
- this.logger.verbose("initializeRequestScopes called", authRequest.correlationId);
1980
- // Default authenticationScheme to Bearer, log that POP isn't supported yet
1981
- if (authRequest.authenticationScheme && authRequest.authenticationScheme === AuthenticationScheme.POP) {
1982
- this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request", authRequest.correlationId);
1983
- }
1984
- authRequest.authenticationScheme = AuthenticationScheme.BEARER;
1985
- // Set requested claims hash if claims were requested
1986
- if (authRequest.claims && !StringUtils.isEmpty(authRequest.claims)) {
1987
- authRequest.requestedClaimsHash = await this.cryptoProvider.hashString(authRequest.claims);
1988
- }
1989
- return {
1990
- ...authRequest,
1991
- scopes: [...(authRequest && authRequest.scopes || []), ...OIDC_DEFAULT_SCOPES],
1992
- correlationId: authRequest && authRequest.correlationId || this.cryptoProvider.createNewGuid(),
1993
- authority: authRequest.authority || this.config.auth.authority
1994
- };
1995
- }
1996
- /**
1997
- * Initializes the server telemetry payload
1998
- * @param apiId - Id for a specific request
1999
- * @param correlationId - GUID
2000
- * @param forceRefresh - boolean to indicate network call
2001
- */
2002
- initializeServerTelemetryManager(apiId, correlationId, forceRefresh) {
2003
- const telemetryPayload = {
2004
- clientId: this.config.auth.clientId,
2005
- correlationId: correlationId,
2006
- apiId: apiId,
2007
- forceRefresh: forceRefresh || false
2008
- };
2009
- return new ServerTelemetryManager(telemetryPayload, this.storage);
2010
- }
2011
- /**
2012
- * Create authority instance. If authority not passed in request, default to authority set on the application
2013
- * object. If no authority set in application object, then default to common authority.
2014
- * @param authorityString - authority from user configuration
2015
- */
2016
- async createAuthority(authorityString, azureRegionConfiguration, requestCorrelationId, azureCloudOptions) {
2017
- this.logger.verbose("createAuthority called", requestCorrelationId);
2018
- // build authority string based on auth params - azureCloudInstance is prioritized if provided
2019
- const authorityUrl = Authority.generateAuthority(authorityString, azureCloudOptions);
2020
- const authorityOptions = {
2021
- protocolMode: this.config.auth.protocolMode,
2022
- knownAuthorities: this.config.auth.knownAuthorities,
2023
- cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,
2024
- authorityMetadata: this.config.auth.authorityMetadata,
2025
- azureRegionConfiguration,
2026
- skipAuthorityMetadataCache: this.config.auth.skipAuthorityMetadataCache
2027
- };
2028
- return await AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger);
2029
- }
2030
- /**
2031
- * Clear the cache
2032
- */
2033
- clearCache() {
2034
- this.storage.clear();
2035
- }
2036
- }
2037
-
2038
- /*
2039
- * Copyright (c) Microsoft Corporation. All rights reserved.
2040
- * Licensed under the MIT License.
2041
- */
2042
- class LoopbackClient {
2043
- /**
2044
- * Spins up a loopback server which returns the server response when the localhost redirectUri is hit
2045
- * @param successTemplate
2046
- * @param errorTemplate
2047
- * @returns
2048
- */
2049
- async listenForAuthCode(successTemplate, errorTemplate) {
2050
- if (!!this.server) {
2051
- throw NodeAuthError.createLoopbackServerAlreadyExistsError();
2052
- }
2053
- const authCodeListener = new Promise((resolve, reject) => {
2054
- this.server = createServer(async (req, res) => {
2055
- const url = req.url;
2056
- if (!url) {
2057
- res.end(errorTemplate || "Error occurred loading redirectUrl");
2058
- reject(NodeAuthError.createUnableToLoadRedirectUrlError());
2059
- return;
2060
- } else if (url === Constants$1.FORWARD_SLASH) {
2061
- res.end(successTemplate || "Auth code was successfully acquired. You can close this window now.");
2062
- return;
2063
- }
2064
- const authCodeResponse = UrlString.getDeserializedQueryString(url);
2065
- if (authCodeResponse.code) {
2066
- const redirectUri = await this.getRedirectUri();
2067
- res.writeHead(HttpStatus.REDIRECT, {
2068
- location: redirectUri
2069
- }); // Prevent auth code from being saved in the browser history
2070
- res.end();
2071
- }
2072
- resolve(authCodeResponse);
2073
- });
2074
- this.server.listen(0); // Listen on any available port
2075
- });
2076
- // Wait for server to be listening
2077
- await new Promise(resolve => {
2078
- let ticks = 0;
2079
- const id = setInterval(() => {
2080
- if (LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS / LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS < ticks) {
2081
- throw NodeAuthError.createLoopbackServerTimeoutError();
2082
- }
2083
- if (this.server.listening) {
2084
- clearInterval(id);
2085
- resolve();
2086
- }
2087
- ticks++;
2088
- }, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS);
2089
- });
2090
- return authCodeListener;
2091
- }
2092
- /**
2093
- * Get the port that the loopback server is running on
2094
- * @returns
2095
- */
2096
- getRedirectUri() {
2097
- if (!this.server) {
2098
- throw NodeAuthError.createNoLoopbackServerExistsError();
2099
- }
2100
- const address = this.server.address();
2101
- if (!address || typeof address === "string" || !address.port) {
2102
- this.closeServer();
2103
- throw NodeAuthError.createInvalidLoopbackAddressTypeError();
2104
- }
2105
- const port = address && address.port;
2106
- return `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}:${port}`;
2107
- }
2108
- /**
2109
- * Close the loopback server
2110
- */
2111
- closeServer() {
2112
- if (!!this.server) {
2113
- this.server.close();
2114
- }
2115
- }
2116
- }
2117
-
2118
- /*
2119
- * Copyright (c) Microsoft Corporation. All rights reserved.
2120
- * Licensed under the MIT License.
2121
- */
2122
- /**
2123
- * This class is to be used to acquire tokens for public client applications (desktop, mobile). Public client applications
2124
- * are not trusted to safely store application secrets, and therefore can only request tokens in the name of an user.
2125
- * @public
2126
- */
2127
- class PublicClientApplication extends ClientApplication {
2128
- /**
2129
- * Important attributes in the Configuration object for auth are:
2130
- * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal.
2131
- * - authority: the authority URL for your application.
2132
- *
2133
- * AAD authorities are of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
2134
- * - If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
2135
- * - If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
2136
- * - If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
2137
- * - To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
2138
- *
2139
- * Azure B2C authorities are of the form https://\{instance\}/\{tenant\}/\{policy\}. Each policy is considered
2140
- * its own authority. You will have to set the all of the knownAuthorities at the time of the client application
2141
- * construction.
2142
- *
2143
- * ADFS authorities are of the form https://\{instance\}/adfs.
2144
- */
2145
- constructor(configuration) {
2146
- super(configuration);
2147
- if (this.config.broker.nativeBrokerPlugin) {
2148
- if (this.config.broker.nativeBrokerPlugin.isBrokerAvailable) {
2149
- this.nativeBrokerPlugin = this.config.broker.nativeBrokerPlugin;
2150
- this.nativeBrokerPlugin.setLogger(this.config.system.loggerOptions);
2151
- } else {
2152
- this.logger.warning("NativeBroker implementation was provided but the broker is unavailable.");
2153
- }
2154
- }
2155
- }
2156
- /**
2157
- * Acquires a token from the authority using OAuth2.0 device code flow.
2158
- * This flow is designed for devices that do not have access to a browser or have input constraints.
2159
- * The authorization server issues a DeviceCode object with a verification code, an end-user code,
2160
- * and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be
2161
- * instructed to use another device to navigate to the verification URI to input credentials.
2162
- * Since the client cannot receive incoming requests, it polls the authorization server repeatedly
2163
- * until the end-user completes input of credentials.
2164
- */
2165
- async acquireTokenByDeviceCode(request) {
2166
- this.logger.info("acquireTokenByDeviceCode called", request.correlationId);
2167
- const validRequest = Object.assign(request, await this.initializeBaseRequest(request));
2168
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByDeviceCode, validRequest.correlationId);
2169
- try {
2170
- const deviceCodeConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
2171
- const deviceCodeClient = new DeviceCodeClient(deviceCodeConfig);
2172
- this.logger.verbose("Device code client created", validRequest.correlationId);
2173
- return deviceCodeClient.acquireToken(validRequest);
2174
- } catch (e) {
2175
- if (e instanceof AuthError) {
2176
- e.setCorrelationId(validRequest.correlationId);
2177
- }
2178
- serverTelemetryManager.cacheFailedRequest(e);
2179
- throw e;
2180
- }
2181
- }
2182
- /**
2183
- * Acquires a token interactively via the browser by requesting an authorization code then exchanging it for a token.
2184
- */
2185
- async acquireTokenInteractive(request) {
2186
- const correlationId = request.correlationId || this.cryptoProvider.createNewGuid();
2187
- this.logger.trace("acquireTokenInteractive called", correlationId);
2188
- const {
2189
- openBrowser,
2190
- successTemplate,
2191
- errorTemplate,
2192
- windowHandle,
2193
- loopbackClient: customLoopbackClient,
2194
- ...remainingProperties
2195
- } = request;
2196
- if (this.nativeBrokerPlugin) {
2197
- var _remainingProperties$;
2198
- const brokerRequest = {
2199
- ...remainingProperties,
2200
- clientId: this.config.auth.clientId,
2201
- scopes: request.scopes || OIDC_DEFAULT_SCOPES,
2202
- redirectUri: `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}`,
2203
- authority: request.authority || this.config.auth.authority,
2204
- correlationId: correlationId,
2205
- extraParameters: {
2206
- ...remainingProperties.extraQueryParameters,
2207
- ...remainingProperties.tokenQueryParameters
2208
- },
2209
- accountId: (_remainingProperties$ = remainingProperties.account) == null ? void 0 : _remainingProperties$.nativeAccountId
2210
- };
2211
- return this.nativeBrokerPlugin.acquireTokenInteractive(brokerRequest, windowHandle);
2212
- }
2213
- const {
2214
- verifier,
2215
- challenge
2216
- } = await this.cryptoProvider.generatePkceCodes();
2217
- const loopbackClient = customLoopbackClient || new LoopbackClient();
2218
- const authCodeListener = loopbackClient.listenForAuthCode(successTemplate, errorTemplate);
2219
- const redirectUri = loopbackClient.getRedirectUri();
2220
- const validRequest = {
2221
- ...remainingProperties,
2222
- correlationId: correlationId,
2223
- scopes: request.scopes || OIDC_DEFAULT_SCOPES,
2224
- redirectUri: redirectUri,
2225
- responseMode: ResponseMode.QUERY,
2226
- codeChallenge: challenge,
2227
- codeChallengeMethod: CodeChallengeMethodValues.S256
2228
- };
2229
- const authCodeUrl = await this.getAuthCodeUrl(validRequest);
2230
- await openBrowser(authCodeUrl);
2231
- const authCodeResponse = await authCodeListener.finally(() => {
2232
- loopbackClient.closeServer();
2233
- });
2234
- if (authCodeResponse.error) {
2235
- throw new ServerError(authCodeResponse.error, authCodeResponse.error_description, authCodeResponse.suberror);
2236
- } else if (!authCodeResponse.code) {
2237
- throw NodeAuthError.createNoAuthCodeInResponseError();
2238
- }
2239
- const clientInfo = authCodeResponse.client_info;
2240
- const tokenRequest = {
2241
- code: authCodeResponse.code,
2242
- codeVerifier: verifier,
2243
- clientInfo: clientInfo || Constants$1.EMPTY_STRING,
2244
- ...validRequest
2245
- };
2246
- return this.acquireTokenByCode(tokenRequest);
2247
- }
2248
- /**
2249
- * Returns a token retrieved either from the cache or by exchanging the refresh token for a fresh access token. If brokering is enabled the token request will be serviced by the broker.
2250
- * @param request
2251
- * @returns
2252
- */
2253
- async acquireTokenSilent(request) {
2254
- const correlationId = request.correlationId || this.cryptoProvider.createNewGuid();
2255
- this.logger.trace("acquireTokenSilent called", correlationId);
2256
- if (this.nativeBrokerPlugin) {
2257
- const brokerRequest = {
2258
- ...request,
2259
- clientId: this.config.auth.clientId,
2260
- scopes: request.scopes || OIDC_DEFAULT_SCOPES,
2261
- redirectUri: `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}`,
2262
- authority: request.authority || this.config.auth.authority,
2263
- correlationId: correlationId,
2264
- extraParameters: request.tokenQueryParameters,
2265
- accountId: request.account.nativeAccountId,
2266
- forceRefresh: request.forceRefresh || false
2267
- };
2268
- return this.nativeBrokerPlugin.acquireTokenSilent(brokerRequest);
2269
- }
2270
- return super.acquireTokenSilent(request);
2271
- }
2272
- /**
2273
- * Removes cache artifacts associated with the given account
2274
- * @param request
2275
- * @returns
2276
- */
2277
- async signOut(request) {
2278
- if (this.nativeBrokerPlugin && request.account.nativeAccountId) {
2279
- const signoutRequest = {
2280
- clientId: this.config.auth.clientId,
2281
- accountId: request.account.nativeAccountId,
2282
- correlationId: request.correlationId || this.cryptoProvider.createNewGuid()
2283
- };
2284
- await this.nativeBrokerPlugin.signOut(signoutRequest);
2285
- }
2286
- await this.getTokenCache().removeAccount(request.account);
2287
- }
2288
- /**
2289
- * Returns all cached accounts for this application. If brokering is enabled this request will be serviced by the broker.
2290
- * @returns
2291
- */
2292
- async getAllAccounts() {
2293
- if (this.nativeBrokerPlugin) {
2294
- const correlationId = this.cryptoProvider.createNewGuid();
2295
- return this.nativeBrokerPlugin.getAllAccounts(this.config.auth.clientId, correlationId);
2296
- }
2297
- return this.getTokenCache().getAllAccounts();
2298
- }
2299
- }
2300
-
2301
- /*
2302
- * Copyright (c) Microsoft Corporation. All rights reserved.
2303
- * Licensed under the MIT License.
2304
- */
2305
- /**
2306
- * Client assertion of type jwt-bearer used in confidential client flows
2307
- * @public
2308
- */
2309
- class ClientAssertion {
2310
- /**
2311
- * Initialize the ClientAssertion class from the clientAssertion passed by the user
2312
- * @param assertion - refer https://tools.ietf.org/html/rfc7521
2313
- */
2314
- static fromAssertion(assertion) {
2315
- const clientAssertion = new ClientAssertion();
2316
- clientAssertion.jwt = assertion;
2317
- return clientAssertion;
2318
- }
2319
- /**
2320
- * Initialize the ClientAssertion class from the certificate passed by the user
2321
- * @param thumbprint - identifier of a certificate
2322
- * @param privateKey - secret key
2323
- * @param publicCertificate - electronic document provided to prove the ownership of the public key
2324
- */
2325
- static fromCertificate(thumbprint, privateKey, publicCertificate) {
2326
- const clientAssertion = new ClientAssertion();
2327
- clientAssertion.privateKey = privateKey;
2328
- clientAssertion.thumbprint = thumbprint;
2329
- if (publicCertificate) {
2330
- clientAssertion.publicCertificate = this.parseCertificate(publicCertificate);
2331
- }
2332
- return clientAssertion;
2333
- }
2334
- /**
2335
- * Update JWT for certificate based clientAssertion, if passed by the user, uses it as is
2336
- * @param cryptoProvider - library's crypto helper
2337
- * @param issuer - iss claim
2338
- * @param jwtAudience - aud claim
2339
- */
2340
- getJwt(cryptoProvider, issuer, jwtAudience) {
2341
- // if assertion was created from certificate, check if jwt is expired and create new one.
2342
- if (this.privateKey && this.thumbprint) {
2343
- if (this.jwt && !this.isExpired() && issuer === this.issuer && jwtAudience === this.jwtAudience) {
2344
- return this.jwt;
2345
- }
2346
- return this.createJwt(cryptoProvider, issuer, jwtAudience);
2347
- }
2348
- /*
2349
- * if assertion was created by caller, then we just append it. It is up to the caller to
2350
- * ensure that it contains necessary claims and that it is not expired.
2351
- */
2352
- if (this.jwt) {
2353
- return this.jwt;
2354
- }
2355
- throw ClientAuthError.createInvalidAssertionError();
2356
- }
2357
- /**
2358
- * JWT format and required claims specified: https://tools.ietf.org/html/rfc7523#section-3
2359
- */
2360
- createJwt(cryptoProvider, issuer, jwtAudience) {
2361
- this.issuer = issuer;
2362
- this.jwtAudience = jwtAudience;
2363
- const issuedAt = TimeUtils.nowSeconds();
2364
- this.expirationTime = issuedAt + 600;
2365
- const header = {
2366
- alg: JwtConstants.RSA_256,
2367
- x5t: EncodingUtils.base64EncodeUrl(this.thumbprint, "hex")
2368
- };
2369
- if (this.publicCertificate) {
2370
- Object.assign(header, {
2371
- x5c: this.publicCertificate
2372
- });
2373
- }
2374
- const payload = {
2375
- [JwtConstants.AUDIENCE]: this.jwtAudience,
2376
- [JwtConstants.EXPIRATION_TIME]: this.expirationTime,
2377
- [JwtConstants.ISSUER]: this.issuer,
2378
- [JwtConstants.SUBJECT]: this.issuer,
2379
- [JwtConstants.NOT_BEFORE]: issuedAt,
2380
- [JwtConstants.JWT_ID]: cryptoProvider.createNewGuid()
2381
- };
2382
- this.jwt = sign(payload, this.privateKey, {
2383
- header
2384
- });
2385
- return this.jwt;
2386
- }
2387
- /**
2388
- * Utility API to check expiration
2389
- */
2390
- isExpired() {
2391
- return this.expirationTime < TimeUtils.nowSeconds();
2392
- }
2393
- /**
2394
- * Extracts the raw certs from a given certificate string and returns them in an array.
2395
- * @param publicCertificate - electronic document provided to prove the ownership of the public key
2396
- */
2397
- static parseCertificate(publicCertificate) {
2398
- /**
2399
- * This is regex to identify the certs in a given certificate string.
2400
- * We want to look for the contents between the BEGIN and END certificate strings, without the associated newlines.
2401
- * The information in parens "(.+?)" is the capture group to represent the cert we want isolated.
2402
- * "." means any string character, "+" means match 1 or more times, and "?" means the shortest match.
2403
- * The "g" at the end of the regex means search the string globally, and the "s" enables the "." to match newlines.
2404
- */
2405
- const regexToFindCerts = /-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs;
2406
- const certs = [];
2407
- let matches;
2408
- while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) {
2409
- // matches[1] represents the first parens capture group in the regex.
2410
- certs.push(matches[1].replace(/\r*\n/g, Constants$1.EMPTY_STRING));
2411
- }
2412
- return certs;
2413
- }
2414
- }
2415
-
2416
- /*
2417
- * Copyright (c) Microsoft Corporation. All rights reserved.
2418
- * Licensed under the MIT License.
2419
- */
2420
- /**
2421
- * This class is to be used to acquire tokens for confidential client applications (webApp, webAPI). Confidential client applications
2422
- * will configure application secrets, client certificates/assertions as applicable
2423
- * @public
2424
- */
2425
- class ConfidentialClientApplication extends ClientApplication {
2426
- /**
2427
- * Constructor for the ConfidentialClientApplication
2428
- *
2429
- * Required attributes in the Configuration object are:
2430
- * - clientID: the application ID of your application. You can obtain one by registering your application with our application registration portal
2431
- * - authority: the authority URL for your application.
2432
- * - client credential: Must set either client secret, certificate, or assertion for confidential clients. You can obtain a client secret from the application registration portal.
2433
- *
2434
- * In Azure AD, authority is a URL indicating of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
2435
- * If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
2436
- * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
2437
- * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
2438
- * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
2439
- *
2440
- * In Azure B2C, authority is of the form https://\{instance\}/tfp/\{tenant\}/\{policyName\}/
2441
- * Full B2C functionality will be available in this library in future versions.
2442
- *
2443
- * @param Configuration - configuration object for the MSAL ConfidentialClientApplication instance
2444
- */
2445
- constructor(configuration) {
2446
- super(configuration);
2447
- this.setClientCredential(this.config);
2448
- this.appTokenProvider = undefined;
2449
- }
2450
- /**
2451
- * This extensibility point only works for the client_credential flow, i.e. acquireTokenByClientCredential and
2452
- * is meant for Azure SDK to enhance Managed Identity support.
2453
- *
2454
- * @param IAppTokenProvider - Extensibility interface, which allows the app developer to return a token from a custom source.
2455
- */
2456
- SetAppTokenProvider(provider) {
2457
- this.appTokenProvider = provider;
2458
- }
2459
- /**
2460
- * Acquires tokens from the authority for the application (not for an end user).
2461
- */
2462
- async acquireTokenByClientCredential(request) {
2463
- this.logger.info("acquireTokenByClientCredential called", request.correlationId);
2464
- // If there is a client assertion present in the request, it overrides the one present in the client configuration
2465
- let clientAssertion;
2466
- if (request.clientAssertion) {
2467
- clientAssertion = {
2468
- assertion: request.clientAssertion,
2469
- assertionType: Constants.JWT_BEARER_ASSERTION_TYPE
2470
- };
2471
- }
2472
- const baseRequest = await this.initializeBaseRequest(request);
2473
- // valid base request should not contain oidc scopes in this grant type
2474
- const validBaseRequest = {
2475
- ...baseRequest,
2476
- scopes: baseRequest.scopes.filter(scope => !OIDC_DEFAULT_SCOPES.includes(scope))
2477
- };
2478
- const validRequest = {
2479
- ...request,
2480
- ...validBaseRequest,
2481
- clientAssertion
2482
- };
2483
- const azureRegionConfiguration = {
2484
- azureRegion: validRequest.azureRegion,
2485
- environmentRegion: process.env[REGION_ENVIRONMENT_VARIABLE]
2486
- };
2487
- const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByClientCredential, validRequest.correlationId, validRequest.skipCache);
2488
- try {
2489
- const clientCredentialConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, azureRegionConfiguration, request.azureCloudOptions);
2490
- const clientCredentialClient = new ClientCredentialClient(clientCredentialConfig, this.appTokenProvider);
2491
- this.logger.verbose("Client credential client created", validRequest.correlationId);
2492
- return clientCredentialClient.acquireToken(validRequest);
2493
- } catch (e) {
2494
- if (e instanceof AuthError) {
2495
- e.setCorrelationId(validRequest.correlationId);
2496
- }
2497
- serverTelemetryManager.cacheFailedRequest(e);
2498
- throw e;
2499
- }
2500
- }
2501
- /**
2502
- * Acquires tokens from the authority for the application.
2503
- *
2504
- * Used in scenarios where the current app is a middle-tier service which was called with a token
2505
- * representing an end user. The current app can use the token (oboAssertion) to request another
2506
- * token to access downstream web API, on behalf of that user.
2507
- *
2508
- * The current middle-tier app has no user interaction to obtain consent.
2509
- * See how to gain consent upfront for your middle-tier app from this article.
2510
- * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application
2511
- */
2512
- async acquireTokenOnBehalfOf(request) {
2513
- this.logger.info("acquireTokenOnBehalfOf called", request.correlationId);
2514
- const validRequest = {
2515
- ...request,
2516
- ...(await this.initializeBaseRequest(request))
2517
- };
2518
- try {
2519
- const onBehalfOfConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, undefined, undefined, request.azureCloudOptions);
2520
- const oboClient = new OnBehalfOfClient(onBehalfOfConfig);
2521
- this.logger.verbose("On behalf of client created", validRequest.correlationId);
2522
- return oboClient.acquireToken(validRequest);
2523
- } catch (e) {
2524
- if (e instanceof AuthError) {
2525
- e.setCorrelationId(validRequest.correlationId);
2526
- }
2527
- throw e;
2528
- }
2529
- }
2530
- setClientCredential(configuration) {
2531
- const clientSecretNotEmpty = !StringUtils.isEmpty(configuration.auth.clientSecret);
2532
- const clientAssertionNotEmpty = !StringUtils.isEmpty(configuration.auth.clientAssertion);
2533
- const certificate = configuration.auth.clientCertificate || {
2534
- thumbprint: Constants$1.EMPTY_STRING,
2535
- privateKey: Constants$1.EMPTY_STRING
2536
- };
2537
- const certificateNotEmpty = !StringUtils.isEmpty(certificate.thumbprint) || !StringUtils.isEmpty(certificate.privateKey);
2538
- /*
2539
- * If app developer configures this callback, they don't need a credential
2540
- * i.e. AzureSDK can get token from Managed Identity without a cert / secret
2541
- */
2542
- if (this.appTokenProvider) {
2543
- return;
2544
- }
2545
- // Check that at most one credential is set on the application
2546
- if (clientSecretNotEmpty && clientAssertionNotEmpty || clientAssertionNotEmpty && certificateNotEmpty || clientSecretNotEmpty && certificateNotEmpty) {
2547
- throw ClientAuthError.createInvalidCredentialError();
2548
- }
2549
- if (configuration.auth.clientSecret) {
2550
- this.clientSecret = configuration.auth.clientSecret;
2551
- return;
2552
- }
2553
- if (configuration.auth.clientAssertion) {
2554
- this.clientAssertion = ClientAssertion.fromAssertion(configuration.auth.clientAssertion);
2555
- return;
2556
- }
2557
- if (!certificateNotEmpty) {
2558
- throw ClientAuthError.createInvalidCredentialError();
2559
- } else {
2560
- var _configuration$auth$c;
2561
- this.clientAssertion = ClientAssertion.fromCertificate(certificate.thumbprint, certificate.privateKey, (_configuration$auth$c = configuration.auth.clientCertificate) == null ? void 0 : _configuration$auth$c.x5c);
2562
- }
2563
- }
2564
- }
2565
-
2566
- /*
2567
- * Copyright (c) Microsoft Corporation. All rights reserved.
2568
- * Licensed under the MIT License.
2569
- */
2570
- class DistributedCachePlugin {
2571
- constructor(client, partitionManager) {
2572
- this.client = client;
2573
- this.partitionManager = partitionManager;
2574
- }
2575
- async beforeCacheAccess(cacheContext) {
2576
- const partitionKey = await this.partitionManager.getKey();
2577
- const cacheData = await this.client.get(partitionKey);
2578
- cacheContext.tokenCache.deserialize(cacheData);
2579
- }
2580
- async afterCacheAccess(cacheContext) {
2581
- if (cacheContext.cacheHasChanged) {
2582
- const kvStore = cacheContext.tokenCache.getKVStore();
2583
- const accountEntities = Object.values(kvStore).filter(value => AccountEntity.isAccountEntity(value));
2584
- if (accountEntities.length > 0) {
2585
- const accountEntity = accountEntities[0];
2586
- const partitionKey = await this.partitionManager.extractKey(accountEntity);
2587
- await this.client.set(partitionKey, cacheContext.tokenCache.serialize());
2588
- }
2589
- }
2590
- }
2591
- }
2592
-
2593
- export { ClientApplication, ClientAssertion, ConfidentialClientApplication, CryptoProvider, DistributedCachePlugin, NodeStorage, PublicClientApplication, TokenCache, buildAppConfiguration, version };
2594
- //# sourceMappingURL=msal-node.esm.js.map