|
| 1 | +import type { INetworkModule, NetworkRequestOptions, NetworkResponse } from "@azure/msal-node"; |
| 2 | +import * as HttpsProxyAgent from "https-proxy-agent"; |
| 3 | +import fetch from "node-fetch"; |
| 4 | + |
| 5 | +/** |
| 6 | + * Placeholder for msal-node's network module which uses node-fetch to support |
| 7 | + * HTTP proxy configurations with authorization |
| 8 | + * |
| 9 | + * @see https://github.com/AzureAD/microsoft-authentication-library-for-js/issues/6527#issuecomment-2077953882 |
| 10 | + */ |
| 11 | +export class ProxyNetworkClient implements INetworkModule { |
| 12 | + private proxyAgent: HttpsProxyAgent; |
| 13 | + constructor(proxyUrl: string) { |
| 14 | + this.proxyAgent = new HttpsProxyAgent(proxyUrl); |
| 15 | + } |
| 16 | + |
| 17 | + sendGetRequestAsync<T>(url: string, options?: NetworkRequestOptions): Promise<NetworkResponse<T>> { |
| 18 | + return this.sendRequestAsync(url, "GET", options); |
| 19 | + } |
| 20 | + sendPostRequestAsync<T>(url: string, options?: NetworkRequestOptions): Promise<NetworkResponse<T>> { |
| 21 | + return this.sendRequestAsync(url, "POST", options); |
| 22 | + } |
| 23 | + |
| 24 | + private async sendRequestAsync<T>( |
| 25 | + url: string, |
| 26 | + method: "GET" | "POST", |
| 27 | + options: NetworkRequestOptions = {}, |
| 28 | + ): Promise<NetworkResponse<T>> { |
| 29 | + try { |
| 30 | + const requestOptions = { |
| 31 | + method: method, |
| 32 | + headers: options.headers, |
| 33 | + body: method === "POST" ? options.body : undefined, |
| 34 | + agent: this.proxyAgent, |
| 35 | + }; |
| 36 | + |
| 37 | + const response = await fetch(url, requestOptions); |
| 38 | + const data = await response.json() as any; |
| 39 | + |
| 40 | + const headersObj: Record<string, string> = {}; |
| 41 | + response.headers.forEach((value, key) => { |
| 42 | + headersObj[key] = value; |
| 43 | + }); |
| 44 | + |
| 45 | + return { |
| 46 | + headers: headersObj, |
| 47 | + body: data, |
| 48 | + status: response.status, |
| 49 | + }; |
| 50 | + } catch (err) { |
| 51 | + console.error("Proxy request error", err); |
| 52 | + throw err; |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments