@hitchy/plugin-proxy
v0.4.1
Published
Hitchy plugin forwarding requests to remote servers
Downloads
132
Readme
@hitchy/plugin-proxy 
Hitchy plugin implementing reverse proxy for redirecting selected requests to remote servers
License
Installation
npm i @hitchy/plugin-proxyConfiguration
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:
prefixis 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/apior similar.targetprovides base URL of a remote service all processed requests are forwarded to.
In addition, either configuration object may include any of these optional properties:
aliasis providing one or more aliases. See below 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
responseFilterwas supported, only. It is calledfilters.response.header, now.filters.request.headeris 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.
The function may optionally adjust provided request or return a replacement for it. It may return a promise to delay this information, too.
filters.request.header = req => { if ( req.getHeader( "cookie" ) ) { req.removeHeader( "cookie" ); } }filters.request.pathis 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.
filters.request.path = segments => segments.map( encodeURIComponent );By default, all segments are passed with either segment encoded with encodeURI() plus encoding all literal forward slashes found in a segment.
filters.request.bodyis a function invoked on receiving request from client to be forwarded to some remote service. It is expected to return a transform stream instance to be injected into pipeline forwarding the request's body to the remote service.Provided argument is the optionally filtered request received from client.
It may return a transform stream instance to be inserted on forwarding the request's payload. It may return a readable stream instance which is used instead of actual request's payload. On returning any other value, request's payload is forwarded to remote service as-is.
filters.request.body = req => { return new Transform( { transform( chunk, encoding, doneFn ) { // TODO implement your transformation per chunk here doneFn( null, chunk ); } } ); }filters.response.headeris 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
- the response received from remote service,
- the optionally filtered request originally received from client and
- the request forwarded to the remote service.
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.
filters.response.header = res => { if ( res.headers["set-cookie"] ) { res.headers["set-cookie"] = undefined; } }The provided response is an IncomingMessage 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
undefinedis essentially removing it.filters.response.bodyis 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 to be injected into pipeline forwarding the response's body to the client.Provided arguments are
- the optionally filtered response received from remote service,
- the optionally filtered request originally received from client and
- the request forwarded to the remote service.
This function may return a transform stream instance 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 to apply changes to passing content without caching whole responses in memory, first.
Alternatively, a readable stream 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 for some tools.
On returning any other value, response's payload is forwarded to remote service as-is.
filters.response.body = res => { return new Transform( { transform( chunk, encoding, doneFn ) { // TODO implement your transformation per chunk here doneFn( null, chunk ); } } ); }
opaqueis a boolean switch. When set, forwarded requests do not contain headers exposing IP addresses of actual clients any request has been forwarded for. This includesForwarded-For,X-Forwarded-For,X-Forwarded-Host,X-Forwarded-ProtoandX-Real-IP.
Example
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.htmlwhich is translated back to redirecting to/ddg/index.htmlprior to returning it to the client. However, this translation fails when remote service redirects tohttps://ddg.com/index.htmlinstead 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.htmlproperly.
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-cookieheader 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:
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:
<!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():
export default function() {
const { AssetProvider } = this.services;
return {
proxy: [
...AssetProvider.googleFonts( "/font" ),
],
};
}The according line in an HTML document would look like this accordingly:
<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:
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:
<!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():
export default function() {
const { AssetProvider } = this.services;
return {
proxy: [
...AssetProvider.jsdelivr( "/extlib" ),
],
};
}The according line in an HTML document would look like this accordingly:
<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),ghto mirror files of https://github.com (more) orwpto mirror files of https://wordpress.org (more).
export default function() {
const { AssetProvider } = this.services;
return {
proxy: [
...AssetProvider.jsdelivr( "/extlib", { mode: "gh" } ),
],
};
}<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:
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:
<!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():
export default function() {
const { AssetProvider } = this.services;
return {
proxy: [
...AssetProvider.unpkg( "/extlib" ),
],
};
}The according line in an HTML document would look like this accordingly:
<script src="/extlib/@tailwindcss/browser@4"></script>