fastify-http-proxy
Advanced tools
Comparing version 6.2.2 to 6.3.0
206
index.js
'use strict' | ||
const From = require('fastify-reply-from') | ||
const WebSocket = require('ws') | ||
const { convertUrlToWebSocket } = require('./utils') | ||
const httpMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS'] | ||
const urlPattern = /^https?:\/\// | ||
const warning = require('process-warning')() | ||
warning.create('FastifyWarning.fastify-http-proxy', 'FST_MODULE_DEP_fastify-http-proxy'.toUpperCase(), 'fastify-http-proxy has been deprecated. Use @fastify/http-proxy@7.0.0 instead.') | ||
warning.emit('FST_MODULE_DEP_fastify-http-proxy'.toUpperCase()) | ||
function liftErrorCode (code) { | ||
if (typeof code !== 'number') { | ||
// Sometimes "close" event emits with a non-numeric value | ||
return 1011 | ||
} else if (code === 1004 || code === 1005 || code === 1006) { | ||
// ws module forbid those error codes usage, lift to "application level" (4xxx) | ||
return 4000 + (code % 1000) | ||
} else { | ||
return code | ||
} | ||
} | ||
function closeWebSocket (socket, code, reason) { | ||
if (socket.readyState === WebSocket.OPEN) { | ||
socket.close(liftErrorCode(code), reason) | ||
} | ||
} | ||
function waitConnection (socket, write) { | ||
if (socket.readyState === WebSocket.CONNECTING) { | ||
socket.once('open', write) | ||
} else { | ||
write() | ||
} | ||
} | ||
function isExternalUrl (url = '') { | ||
return urlPattern.test(url) | ||
}; | ||
function proxyWebSockets (source, target) { | ||
function close (code, reason) { | ||
closeWebSocket(source, code, reason) | ||
closeWebSocket(target, code, reason) | ||
} | ||
source.on('message', data => waitConnection(target, () => target.send(data))) | ||
source.on('ping', data => waitConnection(target, () => target.ping(data))) | ||
source.on('pong', data => waitConnection(target, () => target.pong(data))) | ||
source.on('close', close) | ||
source.on('error', error => close(1011, error.message)) | ||
source.on('unexpected-response', () => close(1011, 'unexpected response')) | ||
// source WebSocket is already connected because it is created by ws server | ||
target.on('message', data => source.send(data)) | ||
target.on('ping', data => source.ping(data)) | ||
target.on('pong', data => source.pong(data)) | ||
target.on('close', close) | ||
target.on('error', error => close(1011, error.message)) | ||
target.on('unexpected-response', () => close(1011, 'unexpected response')) | ||
} | ||
function setupWebSocketProxy (fastify, options, rewritePrefix) { | ||
const server = new WebSocket.Server({ | ||
server: fastify.server, | ||
...options.wsServerOptions | ||
}) | ||
fastify.addHook('onClose', (instance, done) => server.close(done)) | ||
// To be able to close the HTTP server, | ||
// all WebSocket clients need to be disconnected. | ||
// Fastify is missing a pre-close event, or the ability to | ||
// add a hook before the server.close call. We need to resort | ||
// to monkeypatching for now. | ||
const oldClose = fastify.server.close | ||
fastify.server.close = function (done) { | ||
for (const client of server.clients) { | ||
client.close() | ||
} | ||
oldClose.call(this, done) | ||
} | ||
server.on('error', (err) => { | ||
fastify.log.error(err) | ||
}) | ||
server.on('connection', (source, request) => { | ||
if (fastify.prefix && !request.url.startsWith(fastify.prefix)) { | ||
fastify.log.debug({ url: request.url }, 'not matching prefix') | ||
source.close() | ||
return | ||
} | ||
const url = createWebSocketUrl(request) | ||
const target = new WebSocket(url, options.wsClientOptions) | ||
fastify.log.debug({ url: url.href }, 'proxy websocket') | ||
proxyWebSockets(source, target) | ||
}) | ||
function createWebSocketUrl (request) { | ||
const source = new URL(request.url, 'ws://127.0.0.1') | ||
const target = new URL( | ||
source.pathname.replace(fastify.prefix, rewritePrefix), | ||
convertUrlToWebSocket(options.upstream) | ||
) | ||
target.search = source.search | ||
return target | ||
} | ||
} | ||
function generateRewritePrefix (prefix, opts) { | ||
if (!prefix) { | ||
return '' | ||
} | ||
let rewritePrefix = opts.rewritePrefix || (opts.upstream ? new URL(opts.upstream).pathname : '/') | ||
if (!prefix.endsWith('/') && rewritePrefix.endsWith('/')) { | ||
rewritePrefix = rewritePrefix.slice(0, -1) | ||
} | ||
return rewritePrefix | ||
} | ||
async function httpProxy (fastify, opts) { | ||
if (!opts.upstream && !(opts.upstream === '' && opts.replyOptions && typeof opts.replyOptions.getUpstream === 'function')) { | ||
throw new Error('upstream must be specified') | ||
} | ||
const preHandler = opts.preHandler || opts.beforeHandler | ||
const rewritePrefix = generateRewritePrefix(fastify.prefix, opts) | ||
const fromOpts = Object.assign({}, opts) | ||
fromOpts.base = opts.upstream | ||
fromOpts.prefix = undefined | ||
const oldRewriteHeaders = (opts.replyOptions || {}).rewriteHeaders | ||
const replyOpts = Object.assign({}, opts.replyOptions, { | ||
rewriteHeaders | ||
}) | ||
fromOpts.rewriteHeaders = rewriteHeaders | ||
fastify.register(From, fromOpts) | ||
if (opts.proxyPayloads !== false) { | ||
fastify.addContentTypeParser('application/json', bodyParser) | ||
fastify.addContentTypeParser('*', bodyParser) | ||
} | ||
function rewriteHeaders (headers) { | ||
const location = headers.location | ||
if (location && !isExternalUrl(location)) { | ||
headers.location = location.replace(rewritePrefix, fastify.prefix) | ||
} | ||
if (oldRewriteHeaders) { | ||
headers = oldRewriteHeaders(headers) | ||
} | ||
return headers | ||
} | ||
function bodyParser (req, payload, done) { | ||
done(null, payload) | ||
} | ||
fastify.route({ | ||
url: '/', | ||
method: opts.httpMethods || httpMethods, | ||
preHandler, | ||
config: opts.config || {}, | ||
constraints: opts.constraints || {}, | ||
handler | ||
}) | ||
fastify.route({ | ||
url: '/*', | ||
method: opts.httpMethods || httpMethods, | ||
preHandler, | ||
config: opts.config || {}, | ||
constraints: opts.constraints || {}, | ||
handler | ||
}) | ||
function handler (request, reply) { | ||
const queryParamIndex = request.raw.url.indexOf('?') | ||
let dest = request.raw.url.slice(0, queryParamIndex !== -1 ? queryParamIndex : undefined) | ||
dest = dest.replace(this.prefix, rewritePrefix) | ||
reply.from(dest || '/', replyOpts) | ||
} | ||
if (opts.websocket) { | ||
setupWebSocketProxy(fastify, opts, rewritePrefix) | ||
} | ||
} | ||
httpProxy[Symbol.for('plugin-meta')] = { | ||
fastify: '^3.0.0', | ||
name: 'fastify-http-proxy' | ||
} | ||
module.exports = httpProxy | ||
module.exports.default = httpProxy | ||
module.exports.fastifyHttpProxy = httpProxy | ||
module.exports = require('fastify-http-proxy-deprecated') |
{ | ||
"name": "fastify-http-proxy", | ||
"version": "6.2.2", | ||
"description": "proxy http requests, for Fastify", | ||
"version": "6.3.0", | ||
"main": "index.js", | ||
"types": "index.d.ts", | ||
"scripts": { | ||
"lint": "standard | snazzy", | ||
"lint:fix": "standard --fix | snazzy", | ||
"lint:typescript": "npm run lint:fix - --parser @typescript-eslint/parser --plugin typescript \"test/types/*.ts\"", | ||
"test": "npm run lint && tap \"test/*.js\" && npm run typescript", | ||
"typescript": "tsd" | ||
}, | ||
"license": "MIT", | ||
"repository": { | ||
"type": "git", | ||
"url": "git+https://github.com/fastify/fastify-http-proxy.git" | ||
"url": "git://github.com/fastify/fastify-http-proxy.git" | ||
}, | ||
"keywords": [ | ||
"fastify", | ||
"http", | ||
"proxy" | ||
], | ||
"author": "Matteo Collina <hello@matteocollina.com>", | ||
"license": "MIT", | ||
"bugs": { | ||
"url": "https://github.com/fastify/fastify-http-proxy/issues" | ||
}, | ||
"homepage": "https://github.com/fastify/fastify-http-proxy#readme", | ||
"devDependencies": { | ||
"@fastify/pre-commit": "^2.0.2", | ||
"@types/node": "^17.0.8", | ||
"@types/ws": "^8.2.2", | ||
"@typescript-eslint/eslint-plugin": "^5.9.1", | ||
"@typescript-eslint/parser": "^5.9.1", | ||
"express": "^4.17.2", | ||
"express-http-proxy": "^1.6.3", | ||
"fast-proxy": "^2.1.0", | ||
"fastify": "^3.25.3", | ||
"fastify-websocket": "^4.0.0", | ||
"got": "^11.8.3", | ||
"http-errors": "^2.0.0", | ||
"http-proxy": "^1.18.1", | ||
"make-promises-safe": "^5.1.0", | ||
"simple-get": "^4.0.0", | ||
"snazzy": "^9.0.0", | ||
"socket.io": "^4.4.1", | ||
"socket.io-client": "^4.4.1", | ||
"standard": "^16.0.4", | ||
"tap": "^15.1.6", | ||
"tsd": "^0.19.1", | ||
"typescript": "^4.5.4" | ||
}, | ||
"homepage": "https://github.com/fastify/fastify-http-proxy", | ||
"dependencies": { | ||
"fastify-reply-from": "^6.4.1", | ||
"ws": "^8.4.2" | ||
}, | ||
"tsd": { | ||
"directory": "test/types" | ||
"process-warning": "^1.0.0", | ||
"fastify-http-proxy-deprecated": "npm:fastify-http-proxy@6.2.2" | ||
} | ||
} |
185
README.md
# fastify-http-proxy | ||
![CI](https://github.com/fastify/fastify-http-proxy/workflows/CI/badge.svg) | ||
[![NPM version](https://img.shields.io/npm/v/fastify-http-proxy.svg?style=flat)](https://www.npmjs.com/package/fastify-http-proxy) | ||
[![Known Vulnerabilities](https://snyk.io/test/github/fastify/fastify-http-proxy/badge.svg)](https://snyk.io/test/github/fastify/fastify-http-proxy) | ||
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/) | ||
Proxy your HTTP requests to another server, with hooks. | ||
This [`fastify`](https://www.fastify.io) plugin forwards all requests | ||
received with a given prefix (or none) to an upstream. All Fastify hooks are still applied. | ||
`fastify-http-proxy` is built on top of | ||
[`fastify-reply-from`](http://npm.im/fastify-reply-from), which enables single route proxying. | ||
This plugin can be used in a variety of circumstances, for example if you have to proxy an internal domain to an external domain (useful to avoid CORS problems) or to implement your own API gateway for a microservices architecture. | ||
## Requirements | ||
Fastify 3.x. See [this branch](https://github.com/fastify/fastify-http-proxy/tree/1.x) and related versions for Fastify 1.x compatibility and [this tag](https://github.com/fastify/fastify-http-proxy/tree/v3.2.0) for Fastify 2.x. | ||
## Install | ||
``` | ||
npm i fastify-http-proxy fastify | ||
``` | ||
## Example | ||
```js | ||
const Fastify = require('fastify') | ||
const server = Fastify() | ||
server.register(require('fastify-http-proxy'), { | ||
upstream: 'http://my-api.example.com', | ||
prefix: '/api', // optional | ||
http2: false // optional | ||
}) | ||
server.listen(3000) | ||
``` | ||
This will proxy any request starting with `/api` to `http://my-api.example.com`. For instance `http://localhost:3000/api/users` will be proxied to `http://my-api.example.com/users`. | ||
If you want to have different proxies on different prefixes you can register multiple instances of the plugin as shown in the following snippet: | ||
```js | ||
const Fastify = require('fastify') | ||
const server = Fastify() | ||
const proxy = require('fastify-http-proxy') | ||
// /api/x will be proxied to http://my-api.example.com/x | ||
server.register(proxy, { | ||
upstream: 'http://my-api.example.com', | ||
prefix: '/api', // optional | ||
http2: false // optional | ||
}) | ||
// /auth/user will be proxied to http://single-signon.example.com/signon/user | ||
server.register(proxy, { | ||
upstream: 'http://single-signon.example.com', | ||
prefix: '/auth', // optional | ||
rewritePrefix: '/signon', // optional | ||
http2: false // optional | ||
}) | ||
server.listen(3000) | ||
``` | ||
Notice that in this case it is important to use the `prefix` option to tell the proxy how to properly route the requests across different upstreams. | ||
Also notice paths in `upstream` are ignored, so you need to use `rewritePrefix` to specify the target base path. | ||
For other examples, see [`example.js`](examples/example.js). | ||
## Request tracking | ||
`fastify-http-proxy` can track and pipe the `request-id` across the upstreams. Using the [`hyperid`](https://www.npmjs.com/package/hyperid) module and the [`fastify-reply-from`](https://github.com/fastify/fastify-reply-from) built-in options a fairly simple example would look like this: | ||
```js | ||
const Fastify = require('fastify') | ||
const proxy = require('fastify-http-proxy') | ||
const hyperid = require('hyperid') | ||
const server = Fastify() | ||
const uuid = hyperid() | ||
server.register(proxy, { | ||
upstream: 'http://localhost:4001', | ||
replyOptions: { | ||
rewriteRequestHeaders: (originalReq, headers) => ({...headers, 'request-id': uuid()}) | ||
} | ||
}) | ||
server.listen(3000); | ||
``` | ||
## Options | ||
This `fastify` plugin supports _all_ the options of | ||
[`fastify-reply-from`](https://github.com/fastify/fastify-reply-from) plus the following. | ||
*Note that this plugin is fully encapsulated, and non-JSON payloads will | ||
be streamed directly to the destination.* | ||
### upstream | ||
An URL (including protocol) that represents the target server to use for proxying. | ||
### prefix | ||
The prefix to mount this plugin on. All the requests to the current server starting with the given prefix will be proxied to the provided upstream. | ||
The prefix will be removed from the URL when forwarding the HTTP | ||
request. | ||
### rewritePrefix | ||
Rewrite the prefix to the specified string. Default: `''`. | ||
### preHandler | ||
A `preHandler` to be applied on all routes. Useful for performing actions before the proxy is executed (e.g. check for authentication). | ||
### proxyPayloads | ||
When this option is `false`, you will be able to access the body but it will also disable direct pass through of the payload. As a result, it is left up to the implementation to properly parse and proxy the payload correctly. | ||
For example, if you are expecting a payload of type `application/xml`, then you would have to add a parser for it like so: | ||
```javascript | ||
fastify.addContentTypeParser('application/xml', (req, done) => { | ||
const parsedBody = parsingCode(req) | ||
done(null, parsedBody) | ||
}) | ||
``` | ||
### config | ||
An object accessible within the `preHandler` via `reply.context.config`. | ||
See [Config](https://www.fastify.io/docs/v2.1.x/Routes/#config) in the Fastify | ||
documentation for information on this option. Note: this is merged with other | ||
configuration passed to the route. | ||
### replyOptions | ||
Object with [reply options](https://github.com/fastify/fastify-reply-from#replyfromsource-opts) for `fastify-reply-from`. | ||
### httpMethods | ||
An array that contains the types of the methods. Default: `['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS']`. | ||
## websocket | ||
This module has _partial_ support for forwarding websockets by passing a | ||
`websocket` option. All those options are going to be forwarded to | ||
[`fastify-websocket`](https://github.com/fastify/fastify-websocket). | ||
A few things are missing: | ||
1. forwarding headers as well as `rewriteHeaders` | ||
2. request id logging | ||
3. support `ignoreTrailingSlash` | ||
Pull requests are welcome to finish this feature. | ||
## Benchmarks | ||
The following benchmarks where generated on a dedicated server with an Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz and 64GB of RAM: | ||
| __Framework__ | req/sec | | ||
| :----------------- | :------------------------- | | ||
| `express-http-proxy` | 2557 | | ||
| `http-proxy` | 9519 | | ||
| `fastify-http-proxy` | 15919 | | ||
The results were gathered on the second run of `autocannon -c 100 -d 5 | ||
URL`. | ||
## TODO | ||
* [ ] Perform validations for incoming data | ||
* [ ] Finish implementing websocket (follow TODO) | ||
## License | ||
MIT | ||
`fastify-http-proxy@6.3.0` has been deprecated. Please use | ||
`@fastify/http-proxy@7.0.0` instead. |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Deprecated
MaintenanceThe maintainer of the package marked it as deprecated. This could indicate that a single version should not be used, or that the package is no longer maintained and any new vulnerabilities will not be fixed.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Trivial Package
Supply chain riskPackages less than 10 lines of code are easily copied into your own project and may not warrant the additional supply chain risk of an external dependency.
Found 1 instance in 1 package
No contributors or author data
MaintenancePackage does not specify a list of contributors or an author in package.json.
Found 1 instance in 1 package
No bug tracker
MaintenancePackage does not have a linked bug tracker in package.json.
Found 1 instance in 1 package
No repository
Supply chain riskPackage does not have a linked source code repository. Without this field, a package will have no reference to the location of the source code use to generate the package.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 3 instances in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 2 instances in 1 package
0
1
2
857
3
5
2
1
5
+ Addedfastify-http-proxy-deprecated@npm:fastify-http-proxy@6.2.2
+ Addedprocess-warning@^1.0.0
+ Addedfastify-http-proxy@6.2.2(transitive)
- Removedfastify-reply-from@^6.4.1
- Removedws@^8.4.2