npm package: @hitchy/plugin-proxy
Description: Hitchy plugin forwarding requests to remote servers
Author: cepharum GmbH
Latest version: 0.4.1

# @hitchy/plugin-proxy [![pipeline status](https://gitlab.com/hitchy/plugin-proxy/badges/master/pipeline.svg)](https://gitlab.com/hitchy/plugin-proxy/-/commits/master)

_Hitchy plugin implementing reverse proxy for redirecting selected requests to remote servers_

## License

[MIT](LICENSE)

---

- [Installation](#installation)
- [Configuration](#configuration)
- [Asset providers](#asset-providers)
  - [Google Fonts](#google-fonts)
  - [jsdelivr CDN](#jsdelivr-cdn)
  - [unpkg CDN](#unpkg-cdn)

---

## Installation

```bash
npm i @hitchy/plugin-proxy
```

## Configuration

Proxies are defined as part of your application's configuration under top-level name `proxy`. In compliance with Hitchy's conventions you should create a file **config/proxy.js** in your Hitchy-based application. The proxy configuration itself is an array of objects each one defining another reverse proxy.

Every such configuration object **must consist** of these mandatory properties:

* `prefix` is declaring a local a routing prefix. All incoming requests matching this prefix are processed as part of this proxy definition.

  Due to the way Hitchy is handling its routing table, other plugins or current application may define more specific prefixes used in preference over any prefix defined here. Thus, it is possible to use prefix `/` here and still have a local API with prefix `/api` or similar.
  
* `target` provides base URL of a remote service all processed requests are forwarded to.

In addition, either configuration object **may include** any of these optional properties:

* `alias` is providing one or more aliases. [See below](#aliases) for additional information.

* `filters` _(since v0.2.0)_ is optionally providing custom callbacks for adjusting header and body of request and/or response on the fly.

  > Prior to version v0.2.0, option `responseFilter` was supported, only. It is called `filters.response.header`, now.

  * `filters.request.header` is a function invoked early on receiving request from client to be forwarded to some remote service. It is designed to inspect and adjust client's request header. 

    Provided argument is the [request originally received from client](https://nodejs.org/dist/latest/docs/api/http.html#http_class_http_incomingmessage).  

    The function may optionally adjust provided request or return a replacement for it. It may return a promise to delay this information, too.
  
    ```javascript
    filters.request.header = req => {
        if ( req.getHeader( "cookie" ) ) {
            req.removeHeader( "cookie" );
        }
    }
    ```

  * `filters.request.path` is a function invoked to map the segments of a requested path name into another set of segments URI-encoded as necessary.

    Provided argument is the list of segments following configured prefix of proxy in client's request path.  

    The function is expected to return a list of optionally URI-encoded segments to pass to the proxied peer appending them to its configured base path. It may return a promise for that list of segments, too.
  
    ```javascript
    filters.request.path = segments => segments.map( encodeURIComponent );
    ```

    By default, all segments are passed with either segment encoded with [encodeURI()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) plus encoding all literal forward slashes found in a segment.

  * `filters.request.body` is a function invoked on receiving request from client to be forwarded to some remote service. It is expected to return a [transform stream instance](https://nodejs.org/dist/latest/docs/api/stream.html#class-streamtransform) to be injected into [pipeline](https://nodejs.org/dist/latest/docs/api/stream.html#streampipelinesource-transforms-destination-callback) forwarding the request's body to the remote service. 

    Provided argument is the [optionally filtered request received from client](https://nodejs.org/dist/latest/docs/api/http.html#http_class_http_incomingmessage).

    It _may_ return a [transform stream instance](https://nodejs.org/dist/latest/docs/api/stream.html#class-streamtransform) to be inserted on forwarding the request's payload. It _may_ return a [readable stream instance](https://nodejs.org/dist/latest/docs/api/stream.html#class-streamreadable) which is used instead of actual request's payload. On returning any other value, request's payload is forwarded to remote service as-is.
  
    ```javascript
    filters.request.body = req => {
        return new Transform( {
            transform( chunk, encoding, doneFn ) {
                // TODO implement your transformation per chunk here
                doneFn( null, chunk );
            }        
        } );
    }
    ```

  * `filters.response.header` is a function invoked early on receiving response from remote service. It is designed to adjust its headers prior to processing and forwarding it to the originally requesting client. 

    Provided arguments are 
  
    1. the [response received from remote service](https://nodejs.org/dist/latest/docs/api/http.html#class-httpserverresponse), 
    2. the [optionally filtered request originally received from client](https://nodejs.org/dist/latest/docs/api/http.html#http_class_http_incomingmessage) and 
    3. the [request forwarded to the remote service](https://nodejs.org/dist/latest/docs/api/http.html#http_class_http_clientrequest).  

    The function may optionally adjust response provided in first argument or return a replacement for it. It may return a promise to delay this information, too.
  
    ```javascript
    filters.response.header = res => {
        if ( res.headers["set-cookie"] ) {
            res.headers["set-cookie"] = undefined;
        }
    }
    ```
    
    The provided response is an [IncomingMessage](https://nodejs.org/docs/latest/api/http.html#class-httpincomingmessage) and thus does not provide an API for altering headers. **@hitchy/plugin-proxy** is processing every non-nullish header to response sent to requesting client, thus setting it to `undefined` is essentially removing it.

  * `filters.response.body` is a function invoked on receiving response from remote service to be forwarded to originally requesting client. It is expected to return a [transform stream instance](https://nodejs.org/dist/latest/docs/api/stream.html#class-streamtransform) to be injected into [pipeline](https://nodejs.org/dist/latest/docs/api/stream.html#streampipelinesource-transforms-destination-callback) forwarding the response's body to the client.

    Provided arguments are 
  
    1. the [optionally filtered response received from remote service](https://nodejs.org/dist/latest/docs/api/http.html#class-httpserverresponse), 
    2. the [optionally filtered request originally received from client](https://nodejs.org/dist/latest/docs/api/http.html#http_class_http_incomingmessage) and 
    3. the [request forwarded to the remote service](https://nodejs.org/dist/latest/docs/api/http.html#http_class_http_clientrequest).  
      
    This function _may_ return a [transform stream instance](https://nodejs.org/dist/latest/docs/api/stream.html#class-streamtransform) which will be inserted into the pipeline created by the proxy to forward response data from remote peer back to the requesting client.Prefer this option whenever larger response bodies are _probable_. Consider stream processing helpers such as [stream parsers](https://cepharum-foss.gitlab.io/parsing-stream/) to apply changes to passing content without caching whole responses in memory, first.
    
    Alternatively, a [readable stream](https://nodejs.org/dist/latest/docs/api/stream.html#class-streamreadable) may be returned. It will be used _instead_ of remote's response body providing content eventually sent to the requesting client. Based on your application, using this option may result in a larger memory footprint and thus should be considered for processing small response bodies, only. See [Hitchy's basic stream helpers](https://core.hitchy.org/api/service/stream.html) for some tools.
  
    On returning any other value, response's payload is forwarded to remote service as-is.

    ```javascript
    filters.response.body = res => {
        return new Transform( {
            transform( chunk, encoding, doneFn ) {
                // TODO implement your transformation per chunk here
                doneFn( null, chunk );
            }
        } );
    }
    ```

* `opaque` is a boolean switch. When set, forwarded requests do not contain headers exposing IP addresses of actual clients any request has been forwarded for. This includes `Forwarded-For`,`X-Forwarded-For`, `X-Forwarded-Host`, `X-Forwarded-Proto` and `X-Real-IP`.


### Example

```javascript
exports.proxy = [
    {
        prefix: "/ddg",
        target: "https://duckduckgo.com/",
        alias: "https://ddg.com/",
    },
    {
        prefix: "/denic",
        target: "https://www.denic.de",
    },
    {
        prefix: "/denic-alt",
        target: "https://www.denic.de",
        filters: {
            response: {
                header( backendResponse ) {
                    if ( backendResponse.statusCode === 401 ) {
                        backendResponse.statusCode = 403;
                        backendResponse.removeHeader( "WWW-Authenticate" );
                    }
                },
            },
        },
        opaque: true,
    },
];
```

This configuration file is defining three reverse proxies: 

* The first one is forwarding all requests for routes starting with **/ddg** to the base URL **https://duckduckgo.com** so that requesting **/ddg/assets/dax.svg** will eventually deliver the resource available at **https://duckduckgo.com/assets/dax.svg**.

* The second one is forwarding requests with prefix **/denic** to **http://www.denic.de**.

* The third one is basically working like second one. However, all responses with status 401 are transformed into responses with status 403.

### Aliases

Every proxy may declare one or more aliases used on mapping URls returned from target back into address space used in request sent to the proxy itself. Aliases are useful e.g. to test and develop backends prepared to run at different URL when in production setup.

> **Example**
>
> In first example above a forwarded request might cause response redirecting to URL `https://duckduckgo.com/index.html` which is translated back to redirecting to `/ddg/index.html` prior to returning it to the client. However, this translation fails when remote service redirects to `https://ddg.com/index.html` instead for it is assumed to be an alias for the same site. By adopting this alias in your configuration even this URL gets translated back to `/ddg/index.html` properly.

Use custom filters as described above for a more sophisticated address translation.


## Asset providers

Since v0.4.1, the plugin includes a service `AssetProvider` featuring methods for generating proxy configurations suitable for fetching remote assets via the local Hitchy instance e.g. to implement an application in compliance with EU GDPR by preventing the leak of personal user data to those remote service providers.

Every asset provider configuration generated by this service 

* prevents network address of requesting client being forwarded to the remote service,
* removes `set-cookie` header in responses of remote service and
* patches returned data when necessary so that follow-up requests use the local proxy as well.

### Google Fonts

In the plugin's configuration file **config/proxy.js** the result of method `AssetProvider.googleFonts()` must be inserted into the list of configured proxies:

```javascript
export default function() {
	const { AssetProvider } = this.services;

	return {
		proxy: [
			...AssetProvider.googleFonts(),
		],
	};
}
```

Clients (a.k.a. browsers) can then fetch Google Fonts from local URL **/ext/fonts/google** instead of https://fonts.googleapis.com/css like this:

```html
<!DOCTYPE html>
<html lang="en">
	<head>
		<!-- the following line is fetching a Google font via local reverse proxy -->
		<link rel="stylesheet" href="/ext/fonts/google?family=Rouge+Script">
		<style>
			h1 {
				font-family: "Rouge Script", serif;
			}
		</style>
	</head>
	<body>
		<h1>Hello world!</h1>
	</body>
</html>
```

The URL **/ext/fonts/google** is a default. A custom URL prefix can be provided as first argument to `AssetProvider.googleFonts()`:

```javascript
export default function() {
	const { AssetProvider } = this.services;

	return {
		proxy: [
			...AssetProvider.googleFonts( "/font" ),
		],
	};
}
```

The according line in an HTML document would look like this accordingly:

```html
<link rel="stylesheet" href="/font?family=Rouge+Script">
```

### jsdelivr CDN

In the plugin's configuration file **config/proxy.js** the result of method `AssetProvider.jsdelivr()` must be inserted into the list of configured proxies:

```javascript
export default function() {
	const { AssetProvider } = this.services;
	
	return {
		proxy: [
			...AssetProvider.jsdelivr(),
		],
	};
}
```

Clients (a.k.a. browsers) can then fetch files of npm packages from local URL **/ext/cdn/jsdelivr** instead of https://cdn.jsdelivr.net/npm like this:

```html
<!DOCTYPE html>
<html lang="en">
	<head>
		<!-- the following line is fetching Tailwind CSS from jsdelivr CDN via local reverse proxy -->
		<script src="/ext/cdn/jsdelivr/@tailwindcss/browser@4"></script>
	</head>
	<body>
		<h1 class="text-3xl font-bold underline">Hello world!</h1>
	</body>
</html>
```

The URL **/ext/cdn/jsdelivr** is a default. A custom URL prefix can be provided as first argument to `AssetProvider.jsdelivr()`:

```javascript
export default function() {
	const { AssetProvider } = this.services;
	
	return {
		proxy: [
			...AssetProvider.jsdelivr( "/extlib" ),
		],
	};
}
```

The according line in an HTML document would look like this accordingly:

```html
<script src="/extlib/@tailwindcss/browser@4"></script>
```

The jsdelivr CDN provides access on different source sites. Second argument to `AssetProvider.jsdelivr()` may be an object with options. Option `mode` can be

* `npm` (default) to mirror files of https://npmjs.com ([more](https://www.jsdelivr.com)),
* `gh` to mirror files of https://github.com ([more](https://www.jsdelivr.com/?docs=gh)) or
* `wp` to mirror files of https://wordpress.org ([more](https://www.jsdelivr.com/?docs=wp)).


```javascript
export default function() {
	const { AssetProvider } = this.services;
	
	return {
		proxy: [
			...AssetProvider.jsdelivr( "/extlib", { mode: "gh" } ),
		],
	};
}
```

```html
<script src="/extlib/jquery/jquery@3/dist/jquery.min.js"></script>
```

### unpkg CDN

In the plugin's configuration file **config/proxy.js** the result of method `AssetProvider.unpkg()` must be inserted into the list of configured proxies:

```javascript
export default function() {
	const { AssetProvider } = this.services;
	
	return {
		proxy: [
			...AssetProvider.unpkg(),
		],
	};
}
```

Clients (a.k.a. browsers) can then fetch files of npm packages from local URL **/ext/cdn/unpkg** instead of https://unpkg.com like this:

```html
<!DOCTYPE html>
<html lang="en">
	<head>
		<!-- the following line is fetching Tailwind CSS from unpkg CDN via local reverse proxy -->
		<script src="/ext/cdn/unpkg/@tailwindcss/browser@4"></script>
	</head>
	<body>
		<h1 class="text-3xl font-bold underline">Hello world!</h1>
	</body>
</html>
```

The URL **/ext/cdn/unpkg** is a default. A custom URL prefix can be provided as first argument to `AssetProvider.unpkg()`:

```javascript
export default function() {
	const { AssetProvider } = this.services;
	
	return {
		proxy: [
			...AssetProvider.unpkg( "/extlib" ),
		],
	};
}
```

The according line in an HTML document would look like this accordingly:

```html
<script src="/extlib/@tailwindcss/browser@4"></script>
```