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