index.d.mts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import httpNative, { IncomingMessage, ServerResponse } from "node:http";
  2. import http2, { Http2ServerRequest, Http2ServerResponse } from "node:http2";
  3. import { EventEmitter } from "node:events";
  4. import net, { Socket } from "node:net";
  5. import * as stream from "node:stream";
  6. import { Duplex } from "node:stream";
  7. interface ProxyTargetDetailed {
  8. host?: string;
  9. port?: number | string;
  10. protocol?: string;
  11. hostname?: string;
  12. pathname?: string;
  13. socketPath?: string;
  14. key?: string;
  15. passphrase?: string;
  16. pfx?: Buffer | string;
  17. cert?: string;
  18. ca?: string;
  19. ciphers?: string;
  20. secureProtocol?: string;
  21. }
  22. type ProxyTarget = string | URL | ProxyTargetDetailed;
  23. /** Resolved proxy address — either TCP (host + port) or Unix socket. */
  24. type ProxyAddr = {
  25. host?: string;
  26. port: number;
  27. socketPath?: undefined;
  28. } | {
  29. host?: undefined;
  30. port?: undefined;
  31. socketPath: string;
  32. };
  33. interface ProxyServerOptions {
  34. /** URL string to be parsed. */
  35. target?: ProxyTarget;
  36. /** URL string to be parsed. */
  37. forward?: ProxyTarget;
  38. /** Object to be passed to http(s).request. */
  39. agent?: any;
  40. /** Enable HTTP/2 listener, default is `false` */
  41. http2?: boolean;
  42. /** Object to be passed to https.createServer()
  43. * or http2.createSecureServer() if the `http2` option is enabled
  44. */
  45. ssl?: any;
  46. /** If you want to proxy websockets. */
  47. ws?: boolean;
  48. /** Adds x- forward headers. */
  49. xfwd?: boolean;
  50. /** Verify SSL certificate. */
  51. secure?: boolean;
  52. /** Explicitly specify if we are proxying to another proxy. */
  53. toProxy?: boolean;
  54. /** Specify whether you want to prepend the target's path to the proxy path. */
  55. prependPath?: boolean;
  56. /** Specify whether you want to ignore the proxy path of the incoming request. */
  57. ignorePath?: boolean;
  58. /** Local interface string to bind for outgoing connections. */
  59. localAddress?: string;
  60. /** Changes the origin of the host header to the target URL. */
  61. changeOrigin?: boolean;
  62. /** specify whether you want to keep letter case of response header key */
  63. preserveHeaderKeyCase?: boolean;
  64. /** Basic authentication i.e. 'user:password' to compute an Authorization header. */
  65. auth?: string;
  66. /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */
  67. hostRewrite?: string;
  68. /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */
  69. autoRewrite?: boolean;
  70. /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */
  71. protocolRewrite?: string;
  72. /** Rewrites domain of set-cookie headers. */
  73. cookieDomainRewrite?: false | string | {
  74. [oldDomain: string]: string;
  75. };
  76. /** Rewrites path of set-cookie headers. Default: false */
  77. cookiePathRewrite?: false | string | {
  78. [oldPath: string]: string;
  79. };
  80. /** Object with extra headers to be added to target requests. */
  81. headers?: {
  82. [header: string]: string;
  83. };
  84. /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */
  85. proxyTimeout?: number;
  86. /** Timeout (in milliseconds) for incoming requests */
  87. timeout?: number;
  88. /** If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event */
  89. selfHandleResponse?: boolean;
  90. /** Follow HTTP redirects from target. `true` = max 5 hops; number = custom max. */
  91. followRedirects?: boolean | number;
  92. /** Buffer */
  93. buffer?: stream.Stream;
  94. }
  95. type ResOfType<T extends "web" | "ws"> = T extends "ws" ? T extends "web" ? ServerResponse | Http2ServerResponse | Socket : Socket : T extends "web" ? ServerResponse | Http2ServerResponse : never;
  96. type ProxyMiddleware<T extends ServerResponse | Http2ServerResponse | Socket> = (req: IncomingMessage | Http2ServerRequest, res: T, opts: ProxyServerOptions & {
  97. target: URL | ProxyTargetDetailed;
  98. forward: URL;
  99. }, server: ProxyServer<IncomingMessage | Http2ServerRequest, ServerResponse | Http2ServerResponse>, head?: Buffer, callback?: (err: any, req: IncomingMessage | Http2ServerRequest, socket: T, url?: any) => void) => void | true;
  100. interface ProxyServerEventMap<Req extends httpNative.IncomingMessage | http2.Http2ServerRequest = httpNative.IncomingMessage, Res extends httpNative.ServerResponse | http2.Http2ServerResponse = httpNative.ServerResponse> {
  101. error: [err: Error, req?: Req, res?: Res | net.Socket, target?: URL | ProxyTarget];
  102. start: [req: Req, res: Res, target: URL | ProxyTarget];
  103. econnreset: [err: Error, req: Req, res: Res, target: URL | ProxyTarget];
  104. proxyReq: [proxyReq: httpNative.ClientRequest, req: Req, res: Res, options: ProxyServerOptions];
  105. proxyReqWs: [proxyReq: httpNative.ClientRequest, req: Req, socket: net.Socket, options: ProxyServerOptions, head: any];
  106. proxyRes: [proxyRes: httpNative.IncomingMessage, req: Req, res: Res];
  107. end: [req: Req, res: Res, proxyRes: httpNative.IncomingMessage];
  108. open: [proxySocket: net.Socket];
  109. /** @deprecated */
  110. proxySocket: [proxySocket: net.Socket];
  111. close: [proxyRes: Req, proxySocket: net.Socket, proxyHead: any];
  112. }
  113. declare class ProxyServer<Req extends httpNative.IncomingMessage | http2.Http2ServerRequest = httpNative.IncomingMessage, Res extends httpNative.ServerResponse | http2.Http2ServerResponse = httpNative.ServerResponse> extends EventEmitter<ProxyServerEventMap<Req, Res>> {
  114. private _server?;
  115. _webPasses: ProxyMiddleware<httpNative.ServerResponse>[];
  116. _wsPasses: ProxyMiddleware<net.Socket>[];
  117. options: ProxyServerOptions;
  118. web: (req: Req, res: Res, opts?: ProxyServerOptions, head?: any) => Promise<void>;
  119. ws: (req: Req, socket: net.Socket, opts: ProxyServerOptions, head?: any) => Promise<void>;
  120. /**
  121. * Creates the proxy server with specified options.
  122. * @param options - Config object passed to the proxy
  123. */
  124. constructor(options?: ProxyServerOptions);
  125. /**
  126. * A function that wraps the object in a webserver, for your convenience
  127. * @param port - Port to listen on
  128. * @param hostname - The hostname to listen on
  129. * @param listeningListener - A callback function that is called when the server starts listening
  130. */
  131. listen(port: number, hostname?: string, listeningListener?: () => void): this;
  132. /**
  133. * A function that closes the inner webserver and stops listening on given port
  134. */
  135. close(callback?: () => void): void;
  136. before<Type extends "ws" | "web">(type: Type, passName: string, pass: ProxyMiddleware<ResOfType<Type>>): void;
  137. after<Type extends "ws" | "web">(type: Type, passName: string, pass: ProxyMiddleware<ResOfType<Type>>): void;
  138. /** @internal */
  139. _getPasses<Type extends "ws" | "web">(type: Type): ProxyMiddleware<ResOfType<Type>>[];
  140. }
  141. /**
  142. * Creates the proxy server.
  143. *
  144. * Examples:
  145. *
  146. * httpProxy.createProxyServer({ .. }, 8000)
  147. * // => '{ web: [Function], ws: [Function] ... }'
  148. *
  149. * @param {Object} Options Config object passed to the proxy
  150. *
  151. * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
  152. *
  153. * @api public
  154. */
  155. declare function createProxyServer(options?: ProxyServerOptions): ProxyServer<httpNative.IncomingMessage, httpNative.ServerResponse>;
  156. /**
  157. * Options for {@link proxyFetch}.
  158. */
  159. interface ProxyFetchOptions {
  160. /**
  161. * Timeout in milliseconds for the upstream request.
  162. * Rejects with an error if the upstream does not respond within this time.
  163. */
  164. timeout?: number;
  165. /**
  166. * Add `x-forwarded-for`, `x-forwarded-port`, `x-forwarded-proto`, and
  167. * `x-forwarded-host` headers derived from the input URL.
  168. * Default: `false`.
  169. */
  170. xfwd?: boolean;
  171. /**
  172. * Rewrite the `Host` header to match the target address.
  173. * Default: `false` (original host from the input URL is kept).
  174. */
  175. changeOrigin?: boolean;
  176. /**
  177. * HTTP agent for connection pooling / reuse.
  178. * Default: `false` (no agent, no keep-alive).
  179. */
  180. agent?: any;
  181. /**
  182. * Follow HTTP redirects from the upstream.
  183. * `true` = max 5 hops; number = custom max.
  184. * Default: `false` (manual redirect, raw 3xx responses are returned).
  185. */
  186. followRedirects?: boolean | number;
  187. /**
  188. * TLS options forwarded to `https.request` (e.g. `{ rejectUnauthorized: false }`).
  189. * Also controls certificate verification — set `rejectUnauthorized: false` to skip.
  190. * Default: none.
  191. */
  192. ssl?: Record<string, unknown>;
  193. }
  194. /**
  195. * Proxy a request to a specific server address (TCP host/port or Unix socket)
  196. * using web standard {@link Request}/{@link Response} interfaces.
  197. *
  198. * Supports both HTTP and HTTPS upstream targets.
  199. *
  200. * @param addr - The target server address. Can be a URL string (`http://host:port`, `https://host:port`, `unix:/path`), or an object with `host`/`port` for TCP or `socketPath` for Unix sockets.
  201. * @param input - The request URL (string or URL) or a {@link Request} object.
  202. * @param inputInit - Optional {@link RequestInit} or {@link Request} to override method, headers, and body.
  203. * @param opts - Optional proxy options.
  204. */
  205. declare function proxyFetch(addr: string | ProxyAddr, input: string | URL | Request, inputInit?: RequestInit | Request, opts?: ProxyFetchOptions): Promise<Response>;
  206. /**
  207. * Options for {@link proxyUpgrade}.
  208. */
  209. interface ProxyUpgradeOptions {
  210. /**
  211. * Add `x-forwarded-for`, `x-forwarded-port`, and `x-forwarded-proto` headers.
  212. * Default: `true`.
  213. */
  214. xfwd?: boolean;
  215. /**
  216. * Rewrite the `Host` header to match the target.
  217. * Default: `false` (original host is kept).
  218. */
  219. changeOrigin?: boolean;
  220. /**
  221. * Extra headers to include in the upstream upgrade request.
  222. * Default: none.
  223. */
  224. headers?: Record<string, string>;
  225. /**
  226. * TLS options forwarded to `https.request`.
  227. * Default: none.
  228. */
  229. ssl?: Record<string, unknown>;
  230. /**
  231. * Whether to verify upstream TLS certificates.
  232. * Default: `true`.
  233. */
  234. secure?: boolean;
  235. /**
  236. * HTTP/HTTPS agent used for the upstream request.
  237. * Default: `false` (no keep-alive agent is used).
  238. */
  239. agent?: any;
  240. /**
  241. * Local interface address to bind for upstream connections.
  242. * Default: OS-selected local address.
  243. */
  244. localAddress?: string;
  245. /**
  246. * Basic auth credentials in `username:password` format.
  247. * Default: none.
  248. */
  249. auth?: string;
  250. /**
  251. * Prepend the target path to the proxied request path.
  252. * Default: `true`.
  253. */
  254. prependPath?: boolean;
  255. /**
  256. * Ignore the incoming request path when building the upstream path.
  257. * Default: `false` (incoming path is used).
  258. */
  259. ignorePath?: boolean;
  260. /**
  261. * Send absolute URL in request path when proxying to another proxy.
  262. * Default: `false` (path-only request target is used).
  263. */
  264. toProxy?: boolean;
  265. }
  266. /**
  267. * Proxy a WebSocket upgrade request to a target address without creating a
  268. * {@link ProxyServer} instance. Similar to {@link proxyFetch} but for
  269. * WebSocket upgrades.
  270. *
  271. * @param addr - Target server address. Can be a URL string (`http://host:port`, `ws://host:port`, `unix:/path`), or an object with `host`/`port` for TCP or `socketPath` for Unix sockets.
  272. * @param req - The incoming HTTP upgrade request.
  273. * @param socket - The network socket between the server and client.
  274. * @param head - The first packet of the upgraded stream (may be empty).
  275. * @param opts - Optional proxy options.
  276. * @returns A promise that resolves with the upstream proxy socket once the
  277. * WebSocket connection is established, or rejects on error.
  278. */
  279. declare function proxyUpgrade(addr: string | ProxyAddr, req: IncomingMessage, socket: Duplex, head?: Buffer, opts?: ProxyUpgradeOptions): Promise<Socket>;
  280. export { type ProxyAddr, type ProxyFetchOptions, ProxyServer, type ProxyServerEventMap, type ProxyServerOptions, type ProxyTarget, type ProxyTargetDetailed, type ProxyUpgradeOptions, createProxyServer, proxyFetch, proxyUpgrade };