@azure/msal-node 3.8.4 → 5.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (313) hide show
  1. package/README.md +2 -1
  2. package/dist/cache/CacheHelpers.d.ts.map +1 -1
  3. package/dist/cache/CacheHelpers.mjs +4 -5
  4. package/dist/cache/CacheHelpers.mjs.map +1 -1
  5. package/dist/cache/NodeStorage.d.ts.map +1 -1
  6. package/dist/cache/NodeStorage.mjs +17 -18
  7. package/dist/cache/NodeStorage.mjs.map +1 -1
  8. package/dist/cache/TokenCache.d.ts.map +1 -1
  9. package/dist/cache/TokenCache.mjs +15 -15
  10. package/dist/cache/TokenCache.mjs.map +1 -1
  11. package/dist/cache/distributed/DistributedCachePlugin.d.ts.map +1 -1
  12. package/dist/cache/distributed/DistributedCachePlugin.mjs +3 -3
  13. package/dist/cache/distributed/DistributedCachePlugin.mjs.map +1 -1
  14. package/dist/cache/serializer/Deserializer.d.ts.map +1 -1
  15. package/dist/cache/serializer/Deserializer.mjs +3 -5
  16. package/dist/cache/serializer/Deserializer.mjs.map +1 -1
  17. package/dist/cache/serializer/Serializer.d.ts.map +1 -1
  18. package/dist/cache/serializer/Serializer.mjs +1 -3
  19. package/dist/cache/serializer/Serializer.mjs.map +1 -1
  20. package/dist/cache/serializer/SerializerTypes.d.ts +0 -2
  21. package/dist/cache/serializer/SerializerTypes.d.ts.map +1 -1
  22. package/dist/client/BaseClient.d.ts +42 -0
  23. package/dist/client/BaseClient.d.ts.map +1 -0
  24. package/dist/client/BaseClient.mjs +68 -0
  25. package/dist/client/BaseClient.mjs.map +1 -0
  26. package/dist/client/ClientApplication.d.ts.map +1 -1
  27. package/dist/client/ClientApplication.mjs +33 -43
  28. package/dist/client/ClientApplication.mjs.map +1 -1
  29. package/dist/client/ClientAssertion.d.ts.map +1 -1
  30. package/dist/client/ClientAssertion.mjs +6 -5
  31. package/dist/client/ClientAssertion.mjs.map +1 -1
  32. package/dist/client/ClientCredentialClient.d.ts +4 -2
  33. package/dist/client/ClientCredentialClient.d.ts.map +1 -1
  34. package/dist/client/ClientCredentialClient.mjs +23 -21
  35. package/dist/client/ClientCredentialClient.mjs.map +1 -1
  36. package/dist/client/ConfidentialClientApplication.d.ts.map +1 -1
  37. package/dist/client/ConfidentialClientApplication.mjs +10 -9
  38. package/dist/client/ConfidentialClientApplication.mjs.map +1 -1
  39. package/dist/client/DeviceCodeClient.d.ts +3 -1
  40. package/dist/client/DeviceCodeClient.d.ts.map +1 -1
  41. package/dist/client/DeviceCodeClient.mjs +21 -19
  42. package/dist/client/DeviceCodeClient.mjs.map +1 -1
  43. package/dist/client/ManagedIdentityApplication.d.ts.map +1 -1
  44. package/dist/client/ManagedIdentityApplication.mjs +7 -6
  45. package/dist/client/ManagedIdentityApplication.mjs.map +1 -1
  46. package/dist/client/ManagedIdentityClient.mjs +1 -1
  47. package/dist/client/ManagedIdentitySources/AppService.d.ts.map +1 -1
  48. package/dist/client/ManagedIdentitySources/AppService.mjs +3 -3
  49. package/dist/client/ManagedIdentitySources/AppService.mjs.map +1 -1
  50. package/dist/client/ManagedIdentitySources/AzureArc.d.ts.map +1 -1
  51. package/dist/client/ManagedIdentitySources/AzureArc.mjs +8 -8
  52. package/dist/client/ManagedIdentitySources/AzureArc.mjs.map +1 -1
  53. package/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.d.ts.map +1 -1
  54. package/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs +12 -11
  55. package/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs.map +1 -1
  56. package/dist/client/ManagedIdentitySources/CloudShell.d.ts.map +1 -1
  57. package/dist/client/ManagedIdentitySources/CloudShell.mjs +3 -3
  58. package/dist/client/ManagedIdentitySources/CloudShell.mjs.map +1 -1
  59. package/dist/client/ManagedIdentitySources/Imds.d.ts.map +1 -1
  60. package/dist/client/ManagedIdentitySources/Imds.mjs +3 -3
  61. package/dist/client/ManagedIdentitySources/Imds.mjs.map +1 -1
  62. package/dist/client/ManagedIdentitySources/MachineLearning.d.ts.map +1 -1
  63. package/dist/client/ManagedIdentitySources/MachineLearning.mjs +3 -3
  64. package/dist/client/ManagedIdentitySources/MachineLearning.mjs.map +1 -1
  65. package/dist/client/ManagedIdentitySources/ServiceFabric.d.ts.map +1 -1
  66. package/dist/client/ManagedIdentitySources/ServiceFabric.mjs +4 -4
  67. package/dist/client/ManagedIdentitySources/ServiceFabric.mjs.map +1 -1
  68. package/dist/client/OnBehalfOfClient.d.ts +3 -1
  69. package/dist/client/OnBehalfOfClient.d.ts.map +1 -1
  70. package/dist/client/OnBehalfOfClient.mjs +19 -18
  71. package/dist/client/OnBehalfOfClient.mjs.map +1 -1
  72. package/dist/client/PublicClientApplication.d.ts.map +1 -1
  73. package/dist/client/PublicClientApplication.mjs +15 -14
  74. package/dist/client/PublicClientApplication.mjs.map +1 -1
  75. package/dist/client/UsernamePasswordClient.d.ts +3 -1
  76. package/dist/client/UsernamePasswordClient.d.ts.map +1 -1
  77. package/dist/client/UsernamePasswordClient.mjs +8 -7
  78. package/dist/client/UsernamePasswordClient.mjs.map +1 -1
  79. package/dist/config/Configuration.d.ts +2 -19
  80. package/dist/config/Configuration.d.ts.map +1 -1
  81. package/dist/config/Configuration.mjs +18 -25
  82. package/dist/config/Configuration.mjs.map +1 -1
  83. package/dist/config/ManagedIdentityId.mjs +1 -1
  84. package/dist/config/ManagedIdentityRequestParameters.mjs +3 -3
  85. package/dist/config/ManagedIdentityRequestParameters.mjs.map +1 -1
  86. package/dist/crypto/CryptoProvider.d.ts.map +1 -1
  87. package/dist/crypto/CryptoProvider.mjs +5 -3
  88. package/dist/crypto/CryptoProvider.mjs.map +1 -1
  89. package/dist/crypto/GuidGenerator.mjs +1 -1
  90. package/dist/crypto/HashUtils.mjs +1 -1
  91. package/dist/crypto/PkceGenerator.d.ts.map +1 -1
  92. package/dist/crypto/PkceGenerator.mjs +6 -4
  93. package/dist/crypto/PkceGenerator.mjs.map +1 -1
  94. package/dist/error/ClientAuthErrorCodes.d.ts +8 -0
  95. package/dist/error/ClientAuthErrorCodes.d.ts.map +1 -0
  96. package/dist/error/ClientAuthErrorCodes.mjs +16 -0
  97. package/dist/error/ClientAuthErrorCodes.mjs.map +1 -0
  98. package/dist/error/ManagedIdentityError.mjs +1 -1
  99. package/dist/error/ManagedIdentityErrorCodes.mjs +1 -1
  100. package/dist/error/NodeAuthError.mjs +1 -1
  101. package/dist/index.d.ts +15 -11
  102. package/dist/index.d.ts.map +1 -1
  103. package/dist/index.mjs +20 -8
  104. package/dist/index.mjs.map +1 -1
  105. package/dist/internals.mjs +1 -1
  106. package/dist/network/HttpClient.d.ts +53 -40
  107. package/dist/network/HttpClient.d.ts.map +1 -1
  108. package/dist/network/HttpClient.mjs +149 -315
  109. package/dist/network/HttpClient.mjs.map +1 -1
  110. package/dist/network/HttpClientWithRetries.mjs +3 -3
  111. package/dist/network/HttpClientWithRetries.mjs.map +1 -1
  112. package/dist/network/LoopbackClient.d.ts.map +1 -1
  113. package/dist/network/LoopbackClient.mjs +3 -3
  114. package/dist/network/LoopbackClient.mjs.map +1 -1
  115. package/dist/packageMetadata.d.ts +1 -1
  116. package/dist/packageMetadata.d.ts.map +1 -1
  117. package/dist/packageMetadata.mjs +2 -2
  118. package/dist/protocol/Authorize.d.ts.map +1 -1
  119. package/dist/protocol/Authorize.mjs +6 -6
  120. package/dist/protocol/Authorize.mjs.map +1 -1
  121. package/dist/request/AuthorizationCodeRequest.d.ts +3 -2
  122. package/dist/request/AuthorizationCodeRequest.d.ts.map +1 -1
  123. package/dist/request/AuthorizationUrlRequest.d.ts +3 -3
  124. package/dist/request/AuthorizationUrlRequest.d.ts.map +1 -1
  125. package/dist/request/ClientCredentialRequest.d.ts +4 -4
  126. package/dist/request/ClientCredentialRequest.d.ts.map +1 -1
  127. package/dist/request/CommonClientCredentialRequest.d.ts +17 -0
  128. package/dist/request/CommonClientCredentialRequest.d.ts.map +1 -0
  129. package/dist/request/CommonDeviceCodeRequest.d.ts +21 -0
  130. package/dist/request/CommonDeviceCodeRequest.d.ts.map +1 -0
  131. package/dist/request/CommonOnBehalfOfRequest.d.ts +13 -0
  132. package/dist/request/CommonOnBehalfOfRequest.d.ts.map +1 -0
  133. package/dist/request/CommonUsernamePasswordRequest.d.ts +19 -0
  134. package/dist/request/CommonUsernamePasswordRequest.d.ts.map +1 -0
  135. package/dist/request/DeviceCodeRequest.d.ts +3 -2
  136. package/dist/request/DeviceCodeRequest.d.ts.map +1 -1
  137. package/dist/request/InteractiveRequest.d.ts +1 -1
  138. package/dist/request/InteractiveRequest.d.ts.map +1 -1
  139. package/dist/request/ManagedIdentityRequest.d.ts +1 -1
  140. package/dist/request/ManagedIdentityRequest.d.ts.map +1 -1
  141. package/dist/request/OnBehalfOfRequest.d.ts +2 -3
  142. package/dist/request/OnBehalfOfRequest.d.ts.map +1 -1
  143. package/dist/request/RefreshTokenRequest.d.ts +3 -2
  144. package/dist/request/RefreshTokenRequest.d.ts.map +1 -1
  145. package/dist/request/SilentFlowRequest.d.ts +3 -2
  146. package/dist/request/SilentFlowRequest.d.ts.map +1 -1
  147. package/dist/request/UsernamePasswordRequest.d.ts +4 -3
  148. package/dist/request/UsernamePasswordRequest.d.ts.map +1 -1
  149. package/dist/response/ManagedIdentityTokenResponse.d.ts +2 -2
  150. package/dist/response/ManagedIdentityTokenResponse.d.ts.map +1 -1
  151. package/dist/retry/DefaultManagedIdentityRetryPolicy.d.ts +1 -1
  152. package/dist/retry/DefaultManagedIdentityRetryPolicy.d.ts.map +1 -1
  153. package/dist/retry/DefaultManagedIdentityRetryPolicy.mjs +9 -9
  154. package/dist/retry/DefaultManagedIdentityRetryPolicy.mjs.map +1 -1
  155. package/dist/retry/ExponentialRetryStrategy.mjs +1 -1
  156. package/dist/retry/IHttpRetryPolicy.d.ts +1 -1
  157. package/dist/retry/IHttpRetryPolicy.d.ts.map +1 -1
  158. package/dist/retry/ImdsRetryPolicy.d.ts +1 -1
  159. package/dist/retry/ImdsRetryPolicy.d.ts.map +1 -1
  160. package/dist/retry/ImdsRetryPolicy.mjs +11 -11
  161. package/dist/retry/ImdsRetryPolicy.mjs.map +1 -1
  162. package/dist/retry/LinearRetryStrategy.mjs +1 -1
  163. package/dist/utils/Constants.d.ts +2 -9
  164. package/dist/utils/Constants.d.ts.map +1 -1
  165. package/dist/utils/Constants.mjs +4 -12
  166. package/dist/utils/Constants.mjs.map +1 -1
  167. package/dist/utils/EncodingUtils.d.ts.map +1 -1
  168. package/dist/utils/EncodingUtils.mjs +5 -5
  169. package/dist/utils/EncodingUtils.mjs.map +1 -1
  170. package/dist/utils/TimeUtils.mjs +1 -1
  171. package/lib/msal-node.cjs +5378 -6289
  172. package/lib/msal-node.cjs.map +1 -1
  173. package/lib/types/cache/CacheHelpers.d.ts.map +1 -1
  174. package/lib/types/cache/NodeStorage.d.ts.map +1 -1
  175. package/lib/types/cache/TokenCache.d.ts.map +1 -1
  176. package/lib/types/cache/distributed/DistributedCachePlugin.d.ts.map +1 -1
  177. package/lib/types/cache/serializer/Deserializer.d.ts.map +1 -1
  178. package/lib/types/cache/serializer/Serializer.d.ts.map +1 -1
  179. package/lib/types/cache/serializer/SerializerTypes.d.ts +0 -2
  180. package/lib/types/cache/serializer/SerializerTypes.d.ts.map +1 -1
  181. package/lib/types/client/BaseClient.d.ts +42 -0
  182. package/lib/types/client/BaseClient.d.ts.map +1 -0
  183. package/lib/types/client/ClientApplication.d.ts.map +1 -1
  184. package/lib/types/client/ClientAssertion.d.ts.map +1 -1
  185. package/lib/types/client/ClientCredentialClient.d.ts +4 -2
  186. package/lib/types/client/ClientCredentialClient.d.ts.map +1 -1
  187. package/lib/types/client/ConfidentialClientApplication.d.ts.map +1 -1
  188. package/lib/types/client/DeviceCodeClient.d.ts +3 -1
  189. package/lib/types/client/DeviceCodeClient.d.ts.map +1 -1
  190. package/lib/types/client/ManagedIdentityApplication.d.ts.map +1 -1
  191. package/lib/types/client/ManagedIdentitySources/AppService.d.ts.map +1 -1
  192. package/lib/types/client/ManagedIdentitySources/AzureArc.d.ts.map +1 -1
  193. package/lib/types/client/ManagedIdentitySources/BaseManagedIdentitySource.d.ts.map +1 -1
  194. package/lib/types/client/ManagedIdentitySources/CloudShell.d.ts.map +1 -1
  195. package/lib/types/client/ManagedIdentitySources/Imds.d.ts.map +1 -1
  196. package/lib/types/client/ManagedIdentitySources/MachineLearning.d.ts.map +1 -1
  197. package/lib/types/client/ManagedIdentitySources/ServiceFabric.d.ts.map +1 -1
  198. package/lib/types/client/OnBehalfOfClient.d.ts +3 -1
  199. package/lib/types/client/OnBehalfOfClient.d.ts.map +1 -1
  200. package/lib/types/client/PublicClientApplication.d.ts.map +1 -1
  201. package/lib/types/client/UsernamePasswordClient.d.ts +3 -1
  202. package/lib/types/client/UsernamePasswordClient.d.ts.map +1 -1
  203. package/lib/types/config/Configuration.d.ts +2 -19
  204. package/lib/types/config/Configuration.d.ts.map +1 -1
  205. package/lib/types/crypto/CryptoProvider.d.ts.map +1 -1
  206. package/lib/types/crypto/PkceGenerator.d.ts.map +1 -1
  207. package/lib/types/error/ClientAuthErrorCodes.d.ts +8 -0
  208. package/lib/types/error/ClientAuthErrorCodes.d.ts.map +1 -0
  209. package/lib/types/index.d.ts +15 -11
  210. package/lib/types/index.d.ts.map +1 -1
  211. package/lib/types/network/HttpClient.d.ts +53 -40
  212. package/lib/types/network/HttpClient.d.ts.map +1 -1
  213. package/lib/types/network/LoopbackClient.d.ts.map +1 -1
  214. package/lib/types/packageMetadata.d.ts +1 -1
  215. package/lib/types/packageMetadata.d.ts.map +1 -1
  216. package/lib/types/protocol/Authorize.d.ts.map +1 -1
  217. package/lib/types/request/AuthorizationCodeRequest.d.ts +3 -2
  218. package/lib/types/request/AuthorizationCodeRequest.d.ts.map +1 -1
  219. package/lib/types/request/AuthorizationUrlRequest.d.ts +3 -3
  220. package/lib/types/request/AuthorizationUrlRequest.d.ts.map +1 -1
  221. package/lib/types/request/ClientCredentialRequest.d.ts +4 -4
  222. package/lib/types/request/ClientCredentialRequest.d.ts.map +1 -1
  223. package/lib/types/request/CommonClientCredentialRequest.d.ts +17 -0
  224. package/lib/types/request/CommonClientCredentialRequest.d.ts.map +1 -0
  225. package/lib/types/request/CommonDeviceCodeRequest.d.ts +21 -0
  226. package/lib/types/request/CommonDeviceCodeRequest.d.ts.map +1 -0
  227. package/lib/types/request/CommonOnBehalfOfRequest.d.ts +13 -0
  228. package/lib/types/request/CommonOnBehalfOfRequest.d.ts.map +1 -0
  229. package/lib/types/request/CommonUsernamePasswordRequest.d.ts +19 -0
  230. package/lib/types/request/CommonUsernamePasswordRequest.d.ts.map +1 -0
  231. package/lib/types/request/DeviceCodeRequest.d.ts +3 -2
  232. package/lib/types/request/DeviceCodeRequest.d.ts.map +1 -1
  233. package/lib/types/request/InteractiveRequest.d.ts +1 -1
  234. package/lib/types/request/InteractiveRequest.d.ts.map +1 -1
  235. package/lib/types/request/ManagedIdentityRequest.d.ts +1 -1
  236. package/lib/types/request/ManagedIdentityRequest.d.ts.map +1 -1
  237. package/lib/types/request/OnBehalfOfRequest.d.ts +2 -3
  238. package/lib/types/request/OnBehalfOfRequest.d.ts.map +1 -1
  239. package/lib/types/request/RefreshTokenRequest.d.ts +3 -2
  240. package/lib/types/request/RefreshTokenRequest.d.ts.map +1 -1
  241. package/lib/types/request/SilentFlowRequest.d.ts +3 -2
  242. package/lib/types/request/SilentFlowRequest.d.ts.map +1 -1
  243. package/lib/types/request/UsernamePasswordRequest.d.ts +4 -3
  244. package/lib/types/request/UsernamePasswordRequest.d.ts.map +1 -1
  245. package/lib/types/response/ManagedIdentityTokenResponse.d.ts +2 -2
  246. package/lib/types/response/ManagedIdentityTokenResponse.d.ts.map +1 -1
  247. package/lib/types/retry/DefaultManagedIdentityRetryPolicy.d.ts +1 -1
  248. package/lib/types/retry/DefaultManagedIdentityRetryPolicy.d.ts.map +1 -1
  249. package/lib/types/retry/IHttpRetryPolicy.d.ts +1 -1
  250. package/lib/types/retry/IHttpRetryPolicy.d.ts.map +1 -1
  251. package/lib/types/retry/ImdsRetryPolicy.d.ts +1 -1
  252. package/lib/types/retry/ImdsRetryPolicy.d.ts.map +1 -1
  253. package/lib/types/utils/Constants.d.ts +2 -9
  254. package/lib/types/utils/Constants.d.ts.map +1 -1
  255. package/lib/types/utils/EncodingUtils.d.ts.map +1 -1
  256. package/package.json +4 -6
  257. package/src/cache/CacheHelpers.ts +3 -5
  258. package/src/cache/NodeStorage.ts +19 -16
  259. package/src/cache/TokenCache.ts +18 -14
  260. package/src/cache/distributed/DistributedCachePlugin.ts +2 -1
  261. package/src/cache/serializer/Deserializer.ts +7 -9
  262. package/src/cache/serializer/Serializer.ts +0 -2
  263. package/src/cache/serializer/SerializerTypes.ts +0 -2
  264. package/src/client/BaseClient.ts +158 -0
  265. package/src/client/ClientApplication.ts +50 -57
  266. package/src/client/ClientAssertion.ts +5 -6
  267. package/src/client/ClientCredentialClient.ts +32 -25
  268. package/src/client/ConfidentialClientApplication.ts +13 -13
  269. package/src/client/DeviceCodeClient.ts +33 -21
  270. package/src/client/ManagedIdentityApplication.ts +10 -7
  271. package/src/client/ManagedIdentitySources/AppService.ts +4 -2
  272. package/src/client/ManagedIdentitySources/AzureArc.ts +14 -8
  273. package/src/client/ManagedIdentitySources/BaseManagedIdentitySource.ts +18 -9
  274. package/src/client/ManagedIdentitySources/CloudShell.ts +4 -2
  275. package/src/client/ManagedIdentitySources/Imds.ts +4 -2
  276. package/src/client/ManagedIdentitySources/MachineLearning.ts +4 -2
  277. package/src/client/ManagedIdentitySources/ServiceFabric.ts +6 -3
  278. package/src/client/OnBehalfOfClient.ts +27 -21
  279. package/src/client/PublicClientApplication.ts +16 -16
  280. package/src/client/UsernamePasswordClient.ts +14 -8
  281. package/src/config/Configuration.ts +19 -48
  282. package/src/config/ManagedIdentityRequestParameters.ts +2 -2
  283. package/src/crypto/CryptoProvider.ts +5 -3
  284. package/src/crypto/PkceGenerator.ts +6 -4
  285. package/src/error/ClientAuthErrorCodes.ts +12 -0
  286. package/src/index.ts +5 -19
  287. package/src/network/HttpClient.ts +168 -457
  288. package/src/network/HttpClientWithRetries.ts +2 -2
  289. package/src/network/LoopbackClient.ts +2 -3
  290. package/src/packageMetadata.ts +1 -1
  291. package/src/protocol/Authorize.ts +8 -10
  292. package/src/request/AuthorizationCodeRequest.ts +2 -2
  293. package/src/request/AuthorizationUrlRequest.ts +2 -3
  294. package/src/request/ClientCredentialRequest.ts +3 -7
  295. package/src/request/CommonClientCredentialRequest.ts +29 -0
  296. package/src/request/CommonDeviceCodeRequest.ts +30 -0
  297. package/src/request/CommonOnBehalfOfRequest.ts +21 -0
  298. package/src/request/CommonUsernamePasswordRequest.ts +24 -0
  299. package/src/request/DeviceCodeRequest.ts +2 -5
  300. package/src/request/InteractiveRequest.ts +1 -4
  301. package/src/request/ManagedIdentityRequest.ts +1 -1
  302. package/src/request/OnBehalfOfRequest.ts +1 -3
  303. package/src/request/RefreshTokenRequest.ts +2 -2
  304. package/src/request/SilentFlowRequest.ts +3 -5
  305. package/src/request/UsernamePasswordRequest.ts +3 -3
  306. package/src/response/ManagedIdentityTokenResponse.ts +2 -2
  307. package/src/retry/DefaultManagedIdentityRetryPolicy.ts +9 -8
  308. package/src/retry/IHttpRetryPolicy.ts +1 -1
  309. package/src/retry/ImdsRetryPolicy.ts +11 -10
  310. package/src/utils/Constants.ts +2 -11
  311. package/src/utils/EncodingUtils.ts +8 -4
  312. package/dist/utils/NetworkUtils.mjs +0 -43
  313. package/dist/utils/NetworkUtils.mjs.map +0 -1
@@ -4,507 +4,218 @@
4
4
  */
5
5
 
6
6
  import {
7
+ AuthError,
8
+ ClientAuthErrorCodes,
7
9
  INetworkModule,
8
10
  NetworkRequestOptions,
9
11
  NetworkResponse,
10
- HttpStatus,
11
- Logger,
12
- LoggerOptions,
12
+ createAuthError,
13
+ createNetworkError,
13
14
  } from "@azure/msal-common/node";
14
- import { HttpMethod, Constants, ProxyStatus } from "../utils/Constants.js";
15
- import { NetworkUtils } from "../utils/NetworkUtils.js";
16
- import { name, version } from "../packageMetadata.js";
17
- import http from "http";
18
- import https from "https";
15
+ import { HttpMethod } from "../utils/Constants.js";
19
16
 
20
17
  /**
21
- * This class implements the API for network requests.
18
+ * HTTP client implementation using Node.js native fetch API.
19
+ *
20
+ * This class provides a clean interface for making HTTP requests using the modern
21
+ * fetch API available in Node.js 18+. It replaces the previous implementation that
22
+ * relied on custom proxy handling and the legacy http/https modules.
22
23
  */
23
24
  export class HttpClient implements INetworkModule {
24
- private proxyUrl: string;
25
- private customAgentOptions: http.AgentOptions | https.AgentOptions;
26
- private logger: Logger;
27
- private isPiiEnabled: boolean;
28
-
29
- constructor(
30
- proxyUrl?: string,
31
- customAgentOptions?: http.AgentOptions | https.AgentOptions,
32
- loggerOptions?: LoggerOptions
33
- ) {
34
- this.proxyUrl = proxyUrl || "";
35
- this.customAgentOptions = customAgentOptions || {};
36
-
37
- this.logger = new Logger(loggerOptions || {}, name, version);
38
- this.isPiiEnabled = this.logger.isPiiLoggingEnabled();
39
- }
40
-
41
25
  /**
42
- * Http Get request
43
- * @param url
44
- * @param options
26
+ * Sends an HTTP GET request to the specified URL.
27
+ *
28
+ * This method handles GET requests with optional timeout support. The timeout
29
+ * is implemented using AbortController, which provides a clean way to cancel
30
+ * fetch requests that take too long to complete.
31
+ *
32
+ * @param url - The target URL for the GET request
33
+ * @param options - Optional request configuration including headers
34
+ * @param timeout - Optional timeout in milliseconds. If specified, the request
35
+ * will be aborted if it doesn't complete within this time
36
+ * @returns Promise that resolves to a NetworkResponse containing headers, body, and status
37
+ * @throws {AuthError} When the request times out or response parsing fails
38
+ * @throws {NetworkError} When the network request fails
45
39
  */
46
- public async sendGetRequestAsync<T>(
40
+ async sendGetRequestAsync<T>(
47
41
  url: string,
48
42
  options?: NetworkRequestOptions,
49
43
  timeout?: number
50
44
  ): Promise<NetworkResponse<T>> {
51
- if (this.proxyUrl) {
52
- return this.networkRequestViaProxy(
53
- HttpMethod.GET,
54
- url,
55
- options,
56
- timeout
57
- );
58
- } else {
59
- return this.networkRequestViaHttps(
60
- HttpMethod.GET,
61
- url,
62
- options,
63
- timeout
64
- );
65
- }
45
+ return this.sendRequest<T>(url, HttpMethod.GET, options, timeout);
66
46
  }
67
47
 
68
48
  /**
69
- * Http Post request
70
- * @param url
71
- * @param options
49
+ * Sends an HTTP POST request to the specified URL.
50
+ *
51
+ * This method handles POST requests with request body support. Currently,
52
+ * timeout functionality is not exposed for POST requests, but the underlying
53
+ * implementation supports it through the shared sendRequest method.
54
+ *
55
+ * @param url - The target URL for the POST request
56
+ * @param options - Optional request configuration including headers and body
57
+ * @returns Promise that resolves to a NetworkResponse containing headers, body, and status
58
+ * @throws {AuthError} When the request times out or response parsing fails
59
+ * @throws {NetworkError} When the network request fails
72
60
  */
73
- public async sendPostRequestAsync<T>(
61
+ async sendPostRequestAsync<T>(
74
62
  url: string,
75
63
  options?: NetworkRequestOptions
76
64
  ): Promise<NetworkResponse<T>> {
77
- if (this.proxyUrl) {
78
- return this.networkRequestViaProxy(HttpMethod.POST, url, options);
79
- } else {
80
- return this.networkRequestViaHttps(HttpMethod.POST, url, options);
81
- }
65
+ return this.sendRequest<T>(url, HttpMethod.POST, options);
82
66
  }
83
67
 
84
- private networkRequestViaProxy = <T>(
85
- httpMethod: string,
86
- destinationUrlString: string,
68
+ /**
69
+ * Core HTTP request implementation using native fetch API.
70
+ *
71
+ * This method handles GET and POST HTTP requests with comprehensive
72
+ * timeout support and error handling. The timeout mechanism works as follows:
73
+ *
74
+ * 1. An AbortController is created for each request
75
+ * 2. If a timeout is specified, setTimeout is used to call abort() after the delay
76
+ * 3. The abort signal is passed to fetch, which will reject the promise if aborted
77
+ * 4. Cleanup occurs in both success and error cases to prevent timer leaks
78
+ *
79
+ * Error handling priority:
80
+ * 1. Timeout errors (AbortError) are converted to "Request timeout" messages
81
+ * 2. Network/connection errors are wrapped with "Network request failed" prefix
82
+ * 3. JSON parsing errors are wrapped with "Failed to parse response" prefix
83
+ *
84
+ * @param url - The target URL for the request
85
+ * @param method - HTTP method (GET or POST)
86
+ * @param options - Optional request configuration (headers, body)
87
+ * @param timeout - Optional timeout in milliseconds for request cancellation
88
+ * @returns Promise resolving to NetworkResponse with parsed JSON body
89
+ * @throws {AuthError} For timeouts or JSON parsing errors
90
+ * @throws {NetworkError} For network failures
91
+ */
92
+ private async sendRequest<T>(
93
+ url: string,
94
+ method: string,
87
95
  options?: NetworkRequestOptions,
88
96
  timeout?: number
89
- ): Promise<NetworkResponse<T>> => {
90
- const destinationUrl = new URL(destinationUrlString);
91
- const proxyUrl = new URL(this.proxyUrl);
92
-
93
- // "method: connect" must be used to establish a connection to the proxy
94
- const headers = options?.headers || ({} as Record<string, string>);
95
- const tunnelRequestOptions: https.RequestOptions = {
96
- host: proxyUrl.hostname,
97
- port: proxyUrl.port,
98
- method: "CONNECT",
99
- path: destinationUrl.hostname,
100
- headers: headers,
101
- };
102
-
103
- if (
104
- this.customAgentOptions &&
105
- Object.keys(this.customAgentOptions).length
106
- ) {
107
- tunnelRequestOptions.agent = new http.Agent(
108
- this.customAgentOptions
109
- );
110
- }
97
+ ): Promise<NetworkResponse<T>> {
98
+ /*
99
+ * Setup timeout mechanism using AbortController
100
+ * This provides a standard way to cancel fetch requests
101
+ */
102
+ const controller = new AbortController();
103
+ let timeoutId: NodeJS.Timeout | undefined;
111
104
 
112
- // compose a request string for the socket
113
- let postRequestStringContent: string = "";
114
- if (httpMethod === HttpMethod.POST) {
115
- const body = options?.body || "";
116
- postRequestStringContent =
117
- "Content-Type: application/x-www-form-urlencoded\r\n" +
118
- `Content-Length: ${body.length}\r\n` +
119
- `\r\n${body}`;
120
- } else {
121
- // optional timeout is only for get requests (regionDiscovery, for example)
122
- if (timeout) {
123
- tunnelRequestOptions.timeout = timeout;
124
- }
105
+ /*
106
+ * Configure timeout if specified
107
+ * The setTimeout will trigger abort() if the request takes too long
108
+ */
109
+ if (timeout) {
110
+ timeoutId = setTimeout(() => {
111
+ // Calling abort() will cause fetch to reject with AbortError
112
+ controller.abort();
113
+ }, timeout);
125
114
  }
126
- const outgoingRequestString =
127
- `${httpMethod.toUpperCase()} ${destinationUrl.href} HTTP/1.1\r\n` +
128
- `Host: ${destinationUrl.host}\r\n` +
129
- "Connection: close\r\n" +
130
- postRequestStringContent +
131
- "\r\n";
132
115
 
133
- return new Promise<NetworkResponse<T>>((resolve, reject) => {
134
- const request = http.request(tunnelRequestOptions);
116
+ const fetchOptions: RequestInit = {
117
+ method: method,
118
+ headers: getFetchHeaders(options),
119
+ signal: controller.signal, // Enable cancellation via AbortController
120
+ };
135
121
 
136
- if (timeout) {
137
- request.on("timeout", () => {
138
- this.logUrlWithPiiAwareness(
139
- `Request timeout after ${timeout}ms for URL`,
140
- destinationUrlString
141
- );
122
+ if (method === HttpMethod.POST) {
123
+ fetchOptions.body = options?.body || "";
124
+ }
142
125
 
143
- request.destroy();
144
- reject(new Error(`Request time out after ${timeout}ms`));
145
- });
126
+ let response: Response;
127
+ try {
128
+ response = await fetch(url, fetchOptions);
129
+ } catch (error) {
130
+ // Clean up timeout to prevent memory leaks
131
+ if (timeoutId) {
132
+ clearTimeout(timeoutId);
146
133
  }
147
134
 
148
- request.end();
149
-
150
- // establish connection to the proxy
151
- request.on("connect", (response, socket) => {
152
- const proxyStatusCode =
153
- response?.statusCode || ProxyStatus.SERVER_ERROR;
154
- if (
155
- proxyStatusCode < ProxyStatus.SUCCESS_RANGE_START ||
156
- proxyStatusCode > ProxyStatus.SUCCESS_RANGE_END
157
- ) {
158
- request.destroy();
159
- socket.destroy();
160
- reject(
161
- new Error(
162
- `Error connecting to proxy. Http status code: ${
163
- response.statusCode
164
- }. Http status message: ${
165
- response?.statusMessage || "Unknown"
166
- }`
167
- )
168
- );
169
- }
170
-
171
- // make a request over an HTTP tunnel
172
- socket.write(outgoingRequestString);
173
-
174
- const data: Buffer[] = [];
175
- socket.on("data", (chunk) => {
176
- data.push(chunk);
177
- });
178
-
179
- socket.on("end", () => {
180
- // combine all received buffer streams into one buffer, and then into a string
181
- const dataString = Buffer.concat([...data]).toString();
182
-
183
- // separate each line into it's own entry in an arry
184
- const dataStringArray = dataString.split("\r\n");
185
- // the first entry will contain the statusCode and statusMessage
186
- const httpStatusCode = parseInt(
187
- dataStringArray[0].split(" ")[1]
188
- );
189
- // remove "HTTP/1.1" and the status code to get the status message
190
- const statusMessage = dataStringArray[0]
191
- .split(" ")
192
- .slice(2)
193
- .join(" ");
194
- // the last entry will contain the body
195
- const body = dataStringArray[dataStringArray.length - 1];
196
-
197
- // everything in between the first and last entries are the headers
198
- const headersArray = dataStringArray.slice(
199
- 1,
200
- dataStringArray.length - 2
201
- );
202
-
203
- // build an object out of all the headers
204
- const entries = new Map();
205
- headersArray.forEach((header) => {
206
- /**
207
- * the header might look like "Content-Length: 1531", but that is just a string
208
- * it needs to be converted to a key/value pair
209
- * split the string at the first instance of ":"
210
- * there may be more than one ":" if the value of the header is supposed to be a JSON object
211
- */
212
- const headerKeyValue = header.split(
213
- new RegExp(/:\s(.*)/s)
214
- );
215
- const headerKey = headerKeyValue[0];
216
- let headerValue = headerKeyValue[1];
217
-
218
- // check if the value of the header is supposed to be a JSON object
219
- try {
220
- const object = JSON.parse(headerValue);
221
-
222
- // if it is, then convert it from a string to a JSON object
223
- if (object && typeof object === "object") {
224
- headerValue = object;
225
- }
226
- } catch (e) {
227
- // otherwise, leave it as a string
228
- }
229
-
230
- entries.set(headerKey, headerValue);
231
- });
232
- const headers = Object.fromEntries(entries);
233
-
234
- const parsedHeaders = headers as Record<string, string>;
235
- const networkResponse = NetworkUtils.getNetworkResponse(
236
- parsedHeaders,
237
- this.parseBody(
238
- httpStatusCode,
239
- statusMessage,
240
- parsedHeaders,
241
- body
242
- ) as T,
243
- httpStatusCode
244
- );
245
-
246
- if (
247
- this.shouldDestroyRequest(
248
- httpStatusCode,
249
- networkResponse
250
- )
251
- ) {
252
- request.destroy();
253
- }
254
- resolve(networkResponse);
255
- });
256
-
257
- socket.on("error", (chunk) => {
258
- request.destroy();
259
- socket.destroy();
260
- reject(new Error(chunk.toString()));
261
- });
262
- });
263
-
264
- request.on("error", (chunk) => {
265
- this.logger.error(
266
- `HttpClient - Proxy request error: ${chunk.toString()}`,
267
- ""
268
- );
269
- this.logUrlWithPiiAwareness(
270
- "Destination URL",
271
- destinationUrlString
272
- );
273
- this.logUrlWithPiiAwareness("Proxy URL", this.proxyUrl);
274
- this.logger.error(`HttpClient - Method: ${httpMethod}`, "");
275
- this.logger.errorPii(
276
- `HttpClient - Headers: ${JSON.stringify(headers)}`,
277
- ""
135
+ if (error instanceof Error && error.name === "AbortError") {
136
+ throw createAuthError(
137
+ ClientAuthErrorCodes.networkError,
138
+ "Request timeout"
278
139
  );
140
+ }
279
141
 
280
- request.destroy();
281
- reject(new Error(chunk.toString()));
282
- });
283
- });
284
- };
285
-
286
- private networkRequestViaHttps = <T>(
287
- httpMethod: string,
288
- urlString: string,
289
- options?: NetworkRequestOptions,
290
- timeout?: number
291
- ): Promise<NetworkResponse<T>> => {
292
- const isPostRequest = httpMethod === HttpMethod.POST;
293
- const body: string = options?.body || "";
294
-
295
- const url = new URL(urlString);
296
- const headers = options?.headers || ({} as Record<string, string>);
297
- const customOptions: https.RequestOptions = {
298
- method: httpMethod,
299
- headers: headers,
300
- ...NetworkUtils.urlToHttpOptions(url),
301
- };
142
+ const baseAuthError: AuthError = createAuthError(
143
+ ClientAuthErrorCodes.networkError,
144
+ `Network request failed: ${
145
+ error instanceof Error ? error.message : "unknown"
146
+ }`
147
+ );
148
+ throw createNetworkError(
149
+ baseAuthError,
150
+ undefined,
151
+ undefined,
152
+ error instanceof Error ? error : undefined
153
+ );
154
+ }
302
155
 
303
- if (
304
- this.customAgentOptions &&
305
- Object.keys(this.customAgentOptions).length
306
- ) {
307
- customOptions.agent = new https.Agent(this.customAgentOptions);
156
+ // Clean up timeout to prevent memory leaks
157
+ if (timeoutId) {
158
+ clearTimeout(timeoutId);
308
159
  }
309
160
 
310
- if (isPostRequest) {
311
- // needed for post request to work
312
- customOptions.headers = {
313
- ...customOptions.headers,
314
- "Content-Length": body.length,
161
+ try {
162
+ return {
163
+ headers: getHeaderDict(response.headers),
164
+ body: (await response.json()) as T,
165
+ status: response.status,
315
166
  };
316
- } else {
317
- // optional timeout is only for get requests (regionDiscovery, for example)
318
- if (timeout) {
319
- customOptions.timeout = timeout;
320
- }
167
+ } catch (error) {
168
+ throw createAuthError(
169
+ ClientAuthErrorCodes.tokenParsingError,
170
+ `Failed to parse response: ${
171
+ error instanceof Error ? error.message : "unknown"
172
+ }`
173
+ );
321
174
  }
175
+ }
176
+ }
322
177
 
323
- return new Promise<NetworkResponse<T>>((resolve, reject) => {
324
- let request: http.ClientRequest;
325
- // managed identity sources use http instead of https
326
- if (customOptions.protocol === "http:") {
327
- request = http.request(customOptions);
328
- } else {
329
- request = https.request(customOptions);
330
- }
331
-
332
- if (isPostRequest) {
333
- request.write(body);
334
- }
335
-
336
- if (timeout) {
337
- request.on("timeout", () => {
338
- this.logUrlWithPiiAwareness(
339
- `HTTPS request timeout after ${timeout}ms for URL`,
340
- urlString
341
- );
342
-
343
- request.destroy();
344
- reject(new Error(`Request time out after ${timeout}ms`));
345
- });
346
- }
347
-
348
- request.end();
349
-
350
- request.on("response", (response) => {
351
- const headers = response.headers;
352
- const statusCode = response.statusCode as number;
353
- const statusMessage = response.statusMessage;
354
-
355
- const data: Buffer[] = [];
356
- response.on("data", (chunk) => {
357
- data.push(chunk);
358
- });
359
-
360
- response.on("end", () => {
361
- // combine all received buffer streams into one buffer, and then into a string
362
- const body = Buffer.concat([...data]).toString();
363
-
364
- const parsedHeaders = headers as Record<string, string>;
365
- const networkResponse = NetworkUtils.getNetworkResponse(
366
- parsedHeaders,
367
- this.parseBody(
368
- statusCode,
369
- statusMessage,
370
- parsedHeaders,
371
- body
372
- ) as T,
373
- statusCode
374
- );
375
-
376
- if (
377
- this.shouldDestroyRequest(statusCode, networkResponse)
378
- ) {
379
- request.destroy();
380
- }
381
- resolve(networkResponse);
382
- });
383
- });
384
-
385
- request.on("error", (chunk) => {
386
- this.logger.error(
387
- `HttpClient - HTTPS request error: ${chunk.toString()}`,
388
- ""
389
- );
390
- this.logUrlWithPiiAwareness("URL", urlString);
391
- this.logger.error(`HttpClient - Method: ${httpMethod}`, "");
392
- this.logger.errorPii(
393
- `HttpClient - Headers: ${JSON.stringify(headers)}`,
394
- ""
395
- );
396
-
397
- request.destroy();
398
- reject(new Error(chunk.toString()));
399
- });
400
- });
401
- };
402
-
403
- /**
404
- * Check if extra parsing is needed on the repsonse from the server
405
- * @param statusCode {number} the status code of the response from the server
406
- * @param statusMessage {string | undefined} the status message of the response from the server
407
- * @param headers {Record<string, string>} the headers of the response from the server
408
- * @param body {string} the body from the response of the server
409
- * @returns {Object} JSON parsed body or error object
410
- */
411
- private parseBody = (
412
- statusCode: number,
413
- statusMessage: string | undefined,
414
- headers: Record<string, string>,
415
- body: string
416
- ) => {
417
- /*
418
- * Informational responses (100 – 199)
419
- * Successful responses (200 – 299)
420
- * Redirection messages (300 – 399)
421
- * Client error responses (400 – 499)
422
- * Server error responses (500 – 599)
423
- */
178
+ /**
179
+ * Converts a fetch Headers object to a plain JavaScript object.
180
+ *
181
+ * The fetch API returns headers as a Headers object with methods like get(), has(),
182
+ * etc. However, the rest of the MSAL codebase expects headers as a simple key-value
183
+ * object. This function performs that conversion.
184
+ *
185
+ * @param headers - The Headers object returned by fetch response
186
+ * @returns A plain object with header names as keys and values as strings
187
+ */
188
+ function getHeaderDict(headers: Headers): Record<string, string> {
189
+ const headerDict: Record<string, string> = {};
424
190
 
425
- let parsedBody;
426
- try {
427
- parsedBody = JSON.parse(body);
428
- } catch (error) {
429
- let errorType;
430
- let errorDescriptionHelper;
431
- if (
432
- statusCode >= HttpStatus.CLIENT_ERROR_RANGE_START &&
433
- statusCode <= HttpStatus.CLIENT_ERROR_RANGE_END
434
- ) {
435
- errorType = "client_error";
436
- errorDescriptionHelper = "A client";
437
- } else if (
438
- statusCode >= HttpStatus.SERVER_ERROR_RANGE_START &&
439
- statusCode <= HttpStatus.SERVER_ERROR_RANGE_END
440
- ) {
441
- errorType = "server_error";
442
- errorDescriptionHelper = "A server";
443
- } else {
444
- errorType = "unknown_error";
445
- errorDescriptionHelper = "An unknown";
446
- }
191
+ headers.forEach((value: string, key: string) => {
192
+ headerDict[key] = value;
193
+ });
447
194
 
448
- parsedBody = {
449
- error: errorType,
450
- error_description: `${errorDescriptionHelper} error occured.\nHttp status code: ${statusCode}\nHttp status message: ${
451
- statusMessage || "Unknown"
452
- }\nHeaders: ${JSON.stringify(headers)}`,
453
- };
454
- }
195
+ return headerDict;
196
+ }
455
197
 
456
- return parsedBody;
457
- };
198
+ /**
199
+ * Converts NetworkRequestOptions headers to a fetch-compatible Headers object.
200
+ *
201
+ * The MSAL library uses plain objects for headers in NetworkRequestOptions,
202
+ * but the fetch API expects either a Headers object, plain object, or array
203
+ * of arrays. Using the Headers constructor provides better compatibility
204
+ * and validation.
205
+ *
206
+ * @param options - Optional NetworkRequestOptions containing headers
207
+ * @returns A Headers object ready for use with fetch API
208
+ */
209
+ function getFetchHeaders(options?: NetworkRequestOptions): Headers {
210
+ const headers = new Headers();
458
211
 
459
- /**
460
- * Helper function to log a formatted message containing URLs, with PII-aware sanitization
461
- * @param label {string} the label for the log message
462
- * @param urlString {string} the URL to log
463
- */
464
- private logUrlWithPiiAwareness = (
465
- label: string,
466
- urlString: string
467
- ): void => {
468
- if (this.isPiiEnabled) {
469
- this.logger.errorPii(`HttpClient - ${label}: ${urlString}`, "");
470
- } else {
471
- let urlHelper: string;
472
- try {
473
- const url = new URL(urlString);
474
- urlHelper = `${url.protocol}//${url.host}${url.pathname}`;
475
- } catch {
476
- urlHelper = urlString.split("?")[0] || "unknown";
477
- }
212
+ if (!(options && options.headers)) {
213
+ return headers;
214
+ }
478
215
 
479
- this.logger.error(
480
- `HttpClient - ${label}: ${urlHelper} [Enable PII logging to see additional details]`,
481
- ""
482
- );
483
- }
484
- };
216
+ Object.entries(options.headers).forEach(([key, value]) => {
217
+ headers.append(key, value);
218
+ });
485
219
 
486
- /**
487
- * Helper function to determine if a request should be destroyed based on status code and response body.
488
- * Checks if the response is an error and not part of the device code flow (authorization_pending).
489
- * @param statusCode {number} the status code of the response
490
- * @param networkResponse {NetworkResponse<T>} the network response object
491
- * @returns {boolean} true if the request should be destroyed, false otherwise
492
- */
493
- private shouldDestroyRequest = <T>(
494
- statusCode: number,
495
- networkResponse: NetworkResponse<T>
496
- ): boolean => {
497
- return (
498
- (statusCode < HttpStatus.SUCCESS_RANGE_START ||
499
- statusCode > HttpStatus.SUCCESS_RANGE_END) &&
500
- // do not destroy the request for the device code flow
501
- !(
502
- networkResponse.body &&
503
- typeof networkResponse.body === "object" &&
504
- "error" in networkResponse.body &&
505
- (networkResponse.body as { error: string }).error ===
506
- Constants.AUTHORIZATION_PENDING
507
- )
508
- );
509
- };
220
+ return headers;
510
221
  }