Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
name: tests
on: [push, pull_request]

permissions:
contents: read

jobs:
testing:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node-version: [18.x, 20.x, 22.x, 24.x]
steps:
- uses: actions/checkout@v1
- name: Setup Environment (Using NodeJS 16.x)
uses: actions/setup-node@v1
- uses: actions/checkout@v4
- name: Setup Environment (Using NodeJS ${{ matrix.node-version }})
uses: actions/setup-node@v4
with:
node-version: 16.x
node-version: ${{ matrix.node-version }}

- name: Install dependencies
run: npm install
Expand All @@ -18,4 +25,4 @@ jobs:
run: npx standard

- name: Run tests
run: npm run test
run: npm run test
74 changes: 72 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,14 @@ Please see: https://github.com/jkyberneees/nodejs-proxy-benchmarks
### Options
#### `base`
Set the base URL for all the forwarded requests.
> When `base` is set, requests can only be forwarded to its origin (protocol + host + port). The path of `base` is not a restriction, see [Request target validation](#request-target-validation).

#### cacheURLs
The number of parsed URLs that will be cached. Default: 100.
> Use value = `0` to disable the caching mechanism

#### requests.http and requests.https
Allows to optionally overwrite the internal `http` and `https` client agents implementation. Defaults: [`http`](https://nodejs.org/api/http.html#http_http) and [`https`](https://nodejs.org/api/https.html#https_https).
Allows to optionally overwrite the internal `http` and `https` client implementation. Defaults: [`http`](https://nodejs.org/api/http.html#http_http) and [`https`](https://nodejs.org/api/https.html#https_https).

For example, this could be used to add support for following redirects, like so:

Expand Down Expand Up @@ -88,6 +89,15 @@ self-signed certificates.
#### Extended configurations
Other supported configurations in https://nodejs.org/api/http.html#http_new_agent_options can also be part of the `opts` object.

For example, `timeout` defines the maximum time (in milliseconds) the remote server connection can stay idle while a request is in flight:
```js
const { proxy, close } = require('fast-proxy-lite')({
base: 'http://127.0.0.1:3000',
timeout: 30000
})
```
> There is no timeout by default: a remote server that never responds keeps the client request open. Setting `timeout` here, or per request using `opts.request.timeout`, is strongly recommended.

### close
Optional _"on `close` resource release"_ strategy. You can link this to your application shutdown hook as an example.

Expand Down Expand Up @@ -119,6 +129,9 @@ if (!res.socket || res.socket.destroyed || res.writableEnded) {
return onClientConnectionTerminated(res, err, response)
}
```
- The request to the remote server is aborted as soon as the client connection is terminated. In such case `err.code` is `ECONNRESET` and `response` is `undefined`.
- If the remote server responded anyway, `response` is defined and `err` is `null`. The response stream is destroyed right after the callback returns, unless the callback starts consuming it.
- If the client connection was already terminated when `proxy` was invoked, nothing is sent to the remote server.

##### rewriteRequestHeaders(req, headers)
Called to rewrite the headers of the request, before them being sent to the downstream server.
Expand All @@ -134,7 +147,64 @@ Extended options supported by `http[s].request` method (https://nodejs.org/api/h
> The following options are dynamically assigned: `method, port, path, hostname, headers, agent`.

##### queryString
Replaces the original querystring of the request with what is specified.
Replaces the original querystring of the request with what is specified. Accepts a string or an object.
> If `source` has no querystring and this option is not set, the querystring of the original request (`req.url`) is forwarded.

## Behavior

### Request body
`GET` and `HEAD` requests are always forwarded without a payload. For any other method, the payload is taken from `req.body` when a body parser already consumed the request:

| `req.body` | Forwarded payload | Default `content-type` |
|---|---|---|
| `undefined` / `null` | the request stream | - |
| `Stream` | the given stream, using chunked transfer encoding | - |
| `string` | as is | `text/plain` |
| `Buffer` / typed array | as is | `application/octet-stream` |
| object, and the request `content-type` is `application/x-www-form-urlencoded` | URL encoded | `application/x-www-form-urlencoded` |
| anything else | JSON | `application/json` |

> An empty object (`{}`) on a request whose payload was not consumed is considered as "not parsed" (this is what `body-parser` assigns for content types it does not handle), the request stream is forwarded instead.

The `content-length`/`transfer-encoding` headers of the forwarded request are always (re)defined by the proxy, they are never copied blindly from the client request:
- A custom `Stream` is never framed using the `content-length` of the client request, as it does not describe it (e.g: a decompressed payload). If its length is known, `rewriteRequestHeaders` can replace `transfer-encoding` with `content-length`.
- If `rewriteRequestHeaders` returns both headers, `content-length` is dropped.
- `content-encoding` is not forwarded when the payload was decoded by a body parser.

A `req.body` that can't be serialized (cyclic structures, `BigInt` values...) is rejected with `400 Bad Request`.

### Headers
- Request: hop-by-hop headers (`connection`, `keep-alive`, `proxy-connection`, `proxy-authorization`, `te`, `trailer`, `transfer-encoding`, `upgrade`, `http2-settings`) and `expect` are not forwarded. `host` is set to the remote host, the original value is forwarded as `x-forwarded-host`.
- Response: hop-by-hop headers (`connection`, `keep-alive`, `proxy-connection`, `proxy-authenticate`, `te`, `trailer`, `transfer-encoding`, `upgrade`, `http2-settings`), the headers nominated by the remote `connection` header, and `host` are not forwarded.

> Protocol upgrades (e.g: WebSockets) are not supported.

### Request target validation
The request is rejected with `400 Bad Request`, and nothing is sent to the remote server, when:
- The `host` header is missing.
- The method is not upper case. HTTP/2 servers accept `delete` as a method, HTTP clients would send it as `DELETE`.
- The target URL can't be parsed, or its protocol is not `http:` or `https:`.
- `base` is set and the target resolves to a different origin.
- The target path starts with `//`, contains `.` or `..` segments (also in their `%2e` encoded form), backslashes or control characters, or the target starts/ends with a space. URL parsers rewrite those, the path sent to the remote server would be different than the one your router and access control logic have seen (e.g: `/public/../admin` matching a `/public/*` route, `//admin` not matching an `/admin` rule).
- The request can't be represented as a valid HTTP request (e.g: invalid header values returned by `rewriteRequestHeaders`).

`CONNECT` requests are rejected with `405 Method Not Allowed`.

> When `base` is not set, `source` must be an absolute URL and no origin restriction applies. Never build it from untrusted input.

> Anything else is forwarded as received: `/public/..;/admin`, `/public/..%2fadmin` or `/public//admin` are valid paths that reach the remote server untouched. If the remote server applies further normalization (matrix parameters, double decoding, slash merging...), access control has to take it into account.

### Errors
| Condition | Response |
|---|---|
| Remote server refused the connection (`ECONNREFUSED`) | `503 Service Unavailable` |
| Remote server timeout or connection reset (`ETIMEDOUT`, `ECONNRESET`) | `504 Gateway Timeout` |
| Any other failure, including invalid responses | `502 Bad Gateway` |
| `rewriteHeaders`, `onResponse` or `onClientConnectionTerminated` threw | `500 Internal Server Error` |

If the remote server fails after the response headers were sent to the client, the client connection (HTTP/2: the stream) is terminated so the response is not mistaken with a complete one.

Errors thrown by `rewriteHeaders`, `onResponse` and `onClientConnectionTerminated` can't be propagated to the caller, they are reported using [`process.emitWarning`](https://nodejs.org/api/process.html#processemitwarningwarning-options). Errors thrown by `rewriteRequestHeaders` are propagated to the caller of `proxy`.

## Related topics
- http-agent: https://nodejs.org/api/http.html#http_new_agent_options
Expand Down
53 changes: 37 additions & 16 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,66 @@
import * as Http from 'http';
import * as Http2 from 'http2';
import * as Https from 'https';
import { Stream } from 'pump';

export type Options = {
/**
* HTTP client implementation, e.g: the `http`/`https` core modules or
* `follow-redirects/http`/`follow-redirects/https`.
*/
export type RequestClient = {
request(options: Https.RequestOptions, ...args: any[]): any;
};

/**
* Besides the options described here, any option supported by the `http.Agent`
* and `https.Agent` constructors is accepted (`maxFreeSockets`, `timeout`...).
*/
export type Options = Https.AgentOptions & {
base?: string;
cacheURLs?: number;
requests?: {
http?: Http.Agent;
https?: Https.Agent;
http?: RequestClient;
https?: RequestClient;
};
keepAliveMsecs?: number;
maxSockets?: number;
rejectUnauthorized?: boolean;
};

export type ProxyRequest = Http.IncomingMessage | Http2.Http2ServerRequest;
export type ProxyResponse = Http.ServerResponse | Http2.Http2ServerResponse;

export type ProxyRequestResponse = {
statusCode: Number;
headers: Http.OutgoingHttpHeaders;
stream: Stream;
statusCode: number;
headers: Http.IncomingHttpHeaders;
stream: Http.IncomingMessage;
};

export type ProxyOptions = {
base?: string;
onClientConnectionTerminated?(res: Http.ServerResponse, err: Error, response: ProxyRequestResponse): void;
onResponse?(req: Http.IncomingMessage, res: Http.ServerResponse, stream: Stream): void;
rewriteRequestHeaders?(req: Http.IncomingMessage, headers: Http.IncomingHttpHeaders): Http.IncomingHttpHeaders;
/**
* Called when the client connection is terminated before the remote
* response could be delivered. `response` is only defined if the remote
* server responded, in such case its stream is destroyed after this callback
* returns, unless it is being consumed.
*/
onClientConnectionTerminated?(res: ProxyResponse, err: Error | null, response?: ProxyRequestResponse): void;
onResponse?(req: ProxyRequest, res: ProxyResponse, stream: Http.IncomingMessage): void;
rewriteRequestHeaders?(req: ProxyRequest, headers: Http.IncomingHttpHeaders): Http.IncomingHttpHeaders;
rewriteHeaders?(headers: Http.OutgoingHttpHeaders): Http.OutgoingHttpHeaders;
request?: Http.RequestOptions;
queryString?: string;
request?: Https.RequestOptions;
queryString?: string | URLSearchParams | Record<string, any>;
}

export type FastProxy = {
proxy(
originReq: Http.IncomingMessage,
originRes: Http.ServerResponse,
source: string,
originReq: ProxyRequest,
originRes: ProxyResponse,
source?: string | null,
opts?: ProxyOptions
): void;
close(): void;
}

declare function fastProxy(options?: Options): FastProxy
export declare function fastProxy(options?: Options): FastProxy

export default fastProxy
Loading
Loading