http-server: update module to latest

This commit is contained in:
Josh Tynjala
2023-05-16 12:53:26 -07:00
parent 571c2bd181
commit a0c6f92136
1540 changed files with 85700 additions and 7281 deletions

View File

@@ -0,0 +1,6 @@
{
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": true,
"commitLimit": false
}

View File

@@ -0,0 +1 @@
package-lock.json binary

View File

@@ -1,7 +0,0 @@
test
examples
doc
benchmark
.travis.yml
CHANGELOG.md
UPGRADING.md

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,74 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at <https://github.com/http-party/node-http-proxy>. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -0,0 +1,568 @@
<p align="center">
<img src="https://raw.github.com/http-party/node-http-proxy/master/doc/logo.png"/>
</p>
# node-http-proxy [![Build Status](https://travis-ci.org/http-party/node-http-proxy.svg?branch=master)](https://travis-ci.org/http-party/node-http-proxy) [![codecov](https://codecov.io/gh/http-party/node-http-proxy/branch/master/graph/badge.svg)](https://codecov.io/gh/http-party/node-http-proxy)
`node-http-proxy` is an HTTP programmable proxying library that supports
websockets. It is suitable for implementing components such as reverse
proxies and load balancers.
### Table of Contents
* [Installation](#installation)
* [Upgrading from 0.8.x ?](#upgrading-from-08x-)
* [Core Concept](#core-concept)
* [Use Cases](#use-cases)
* [Setup a basic stand-alone proxy server](#setup-a-basic-stand-alone-proxy-server)
* [Setup a stand-alone proxy server with custom server logic](#setup-a-stand-alone-proxy-server-with-custom-server-logic)
* [Setup a stand-alone proxy server with proxy request header re-writing](#setup-a-stand-alone-proxy-server-with-proxy-request-header-re-writing)
* [Modify a response from a proxied server](#modify-a-response-from-a-proxied-server)
* [Setup a stand-alone proxy server with latency](#setup-a-stand-alone-proxy-server-with-latency)
* [Using HTTPS](#using-https)
* [Proxying WebSockets](#proxying-websockets)
* [Options](#options)
* [Listening for proxy events](#listening-for-proxy-events)
* [Shutdown](#shutdown)
* [Miscellaneous](#miscellaneous)
* [Test](#test)
* [ProxyTable API](#proxytable-api)
* [Logo](#logo)
* [Contributing and Issues](#contributing-and-issues)
* [License](#license)
### Installation
`npm install http-proxy --save`
**[Back to top](#table-of-contents)**
### Upgrading from 0.8.x ?
Click [here](UPGRADING.md)
**[Back to top](#table-of-contents)**
### Core Concept
A new proxy is created by calling `createProxyServer` and passing
an `options` object as argument ([valid properties are available here](lib/http-proxy.js#L26-L42))
```javascript
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer(options); // See (†)
```
†Unless listen(..) is invoked on the object, this does not create a webserver. See below.
An object will be returned with four methods:
* web `req, res, [options]` (used for proxying regular HTTP(S) requests)
* ws `req, socket, head, [options]` (used for proxying WS(S) requests)
* listen `port` (a function that wraps the object in a webserver, for your convenience)
* close `[callback]` (a function that closes the inner webserver and stops listening on given port)
It is then possible to proxy requests by calling these functions
```javascript
http.createServer(function(req, res) {
proxy.web(req, res, { target: 'http://mytarget.com:8080' });
});
```
Errors can be listened on either using the Event Emitter API
```javascript
proxy.on('error', function(e) {
...
});
```
or using the callback API
```javascript
proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... });
```
When a request is proxied it follows two different pipelines ([available here](lib/http-proxy/passes))
which apply transformations to both the `req` and `res` object.
The first pipeline (incoming) is responsible for the creation and manipulation of the stream that connects your client to the target.
The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data
to the client.
**[Back to top](#table-of-contents)**
### Use Cases
#### Setup a basic stand-alone proxy server
```js
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create your proxy server and set the target in the options.
//
httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000); // See (†)
//
// Create your target server
//
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
```
†Invoking listen(..) triggers the creation of a web server. Otherwise, just the proxy instance is created.
**[Back to top](#table-of-contents)**
#### Setup a stand-alone proxy server with custom server logic
This example shows how you can proxy a request using your own HTTP server
and also you can put your own logic to handle the request.
```js
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});
//
// Create your custom server and just call `proxy.web()` to proxy
// a web request to the target passed in the options
// also you can use `proxy.ws()` to proxy a websockets request
//
var server = http.createServer(function(req, res) {
// You can define here your custom logic to handle the request
// and then proxy the request.
proxy.web(req, res, { target: 'http://127.0.0.1:5050' });
});
console.log("listening on port 5050")
server.listen(5050);
```
**[Back to top](#table-of-contents)**
#### Setup a stand-alone proxy server with proxy request header re-writing
This example shows how you can proxy a request using your own HTTP server that
modifies the outgoing proxy request by adding a special header.
```js
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});
// To modify the proxy connection before data is sent, you can listen
// for the 'proxyReq' event. When the event is fired, you will receive
// the following arguments:
// (http.ClientRequest proxyReq, http.IncomingMessage req,
// http.ServerResponse res, Object options). This mechanism is useful when
// you need to modify the proxy request before the proxy connection
// is made to the target.
//
proxy.on('proxyReq', function(proxyReq, req, res, options) {
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
});
var server = http.createServer(function(req, res) {
// You can define here your custom logic to handle the request
// and then proxy the request.
proxy.web(req, res, {
target: 'http://127.0.0.1:5050'
});
});
console.log("listening on port 5050")
server.listen(5050);
```
**[Back to top](#table-of-contents)**
#### Modify a response from a proxied server
Sometimes when you have received a HTML/XML document from the server of origin you would like to modify it before forwarding it on.
[Harmon](https://github.com/No9/harmon) allows you to do this in a streaming style so as to keep the pressure on the proxy to a minimum.
**[Back to top](#table-of-contents)**
#### Setup a stand-alone proxy server with latency
```js
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create a proxy server with latency
//
var proxy = httpProxy.createProxyServer();
//
// Create your server that makes an operation that waits a while
// and then proxies the request
//
http.createServer(function (req, res) {
// This simulates an operation that takes 500ms to execute
setTimeout(function () {
proxy.web(req, res, {
target: 'http://localhost:9008'
});
}, 500);
}).listen(8008);
//
// Create your target server
//
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9008);
```
**[Back to top](#table-of-contents)**
#### Using HTTPS
You can activate the validation of a secure SSL certificate to the target connection (avoid self-signed certs), just set `secure: true` in the options.
##### HTTPS -> HTTP
```js
//
// Create the HTTPS proxy server in front of a HTTP server
//
httpProxy.createServer({
target: {
host: 'localhost',
port: 9009
},
ssl: {
key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
}
}).listen(8009);
```
##### HTTPS -> HTTPS
```js
//
// Create the proxy server listening on port 443
//
httpProxy.createServer({
ssl: {
key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
},
target: 'https://localhost:9010',
secure: true // Depends on your needs, could be false.
}).listen(443);
```
##### HTTP -> HTTPS (using a PKCS12 client certificate)
```js
//
// Create an HTTP proxy server with an HTTPS target
//
httpProxy.createProxyServer({
target: {
protocol: 'https:',
host: 'my-domain-name',
port: 443,
pfx: fs.readFileSync('path/to/certificate.p12'),
passphrase: 'password',
},
changeOrigin: true,
}).listen(8000);
```
**[Back to top](#table-of-contents)**
#### Proxying WebSockets
You can activate the websocket support for the proxy using `ws:true` in the options.
```js
//
// Create a proxy server for websockets
//
httpProxy.createServer({
target: 'ws://localhost:9014',
ws: true
}).listen(8014);
```
Also you can proxy the websocket requests just calling the `ws(req, socket, head)` method.
```js
//
// Setup our server to proxy standard HTTP requests
//
var proxy = new httpProxy.createProxyServer({
target: {
host: 'localhost',
port: 9015
}
});
var proxyServer = http.createServer(function (req, res) {
proxy.web(req, res);
});
//
// Listen to the `upgrade` event and proxy the
// WebSocket requests as well.
//
proxyServer.on('upgrade', function (req, socket, head) {
proxy.ws(req, socket, head);
});
proxyServer.listen(8015);
```
**[Back to top](#table-of-contents)**
### Options
`httpProxy.createProxyServer` supports the following options:
* **target**: url string to be parsed with the url module
* **forward**: url string to be parsed with the url module
* **agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects)
* **ssl**: object to be passed to https.createServer()
* **ws**: true/false, if you want to proxy websockets
* **xfwd**: true/false, adds x-forward headers
* **secure**: true/false, if you want to verify the SSL Certs
* **toProxy**: true/false, passes the absolute URL as the `path` (useful for proxying to proxies)
* **prependPath**: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path
* **ignorePath**: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required).
* **localAddress**: Local interface string to bind for outgoing connections
* **changeOrigin**: true/false, Default: false - changes the origin of the host header to the target URL
* **preserveHeaderKeyCase**: true/false, Default: false - specify whether you want to keep letter case of response header key
* **auth**: Basic authentication i.e. 'user:password' to compute an Authorization header.
* **hostRewrite**: rewrites the location hostname on (201/301/302/307/308) redirects.
* **autoRewrite**: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
* **protocolRewrite**: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
* **cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values:
* `false` (default): disable cookie rewriting
* String: new domain, for example `cookieDomainRewrite: "new.domain"`. To remove the domain, use `cookieDomainRewrite: ""`.
* Object: mapping of domains to new domains, use `"*"` to match all domains.
For example keep one domain unchanged, rewrite one domain and remove other domains:
```
cookieDomainRewrite: {
"unchanged.domain": "unchanged.domain",
"old.domain": "new.domain",
"*": ""
}
```
* **cookiePathRewrite**: rewrites path of `set-cookie` headers. Possible values:
* `false` (default): disable cookie rewriting
* String: new path, for example `cookiePathRewrite: "/newPath/"`. To remove the path, use `cookiePathRewrite: ""`. To set path to root use `cookiePathRewrite: "/"`.
* Object: mapping of paths to new paths, use `"*"` to match all paths.
For example, to keep one path unchanged, rewrite one path and remove other paths:
```
cookiePathRewrite: {
"/unchanged.path/": "/unchanged.path/",
"/old.path/": "/new.path/",
"*": ""
}
```
* **headers**: object with extra headers to be added to target requests.
* **proxyTimeout**: timeout (in millis) for outgoing proxy requests
* **timeout**: timeout (in millis) for incoming requests
* **followRedirects**: true/false, Default: false - specify whether you want to follow redirects
* **selfHandleResponse** true/false, 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
* **buffer**: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e.g. If you read the body of a request into a field called 'req.rawbody' you could restream this field in the buffer option:
```
'use strict';
const streamify = require('stream-array');
const HttpProxy = require('http-proxy');
const proxy = new HttpProxy();
module.exports = (req, res, next) => {
proxy.web(req, res, {
target: 'http://localhost:4003/',
buffer: streamify(req.rawBody)
}, next);
};
```
**NOTE:**
`options.ws` and `options.ssl` are optional.
`options.target` and `options.forward` cannot both be missing
If you are using the `proxyServer.listen` method, the following options are also applicable:
* **ssl**: object to be passed to https.createServer()
* **ws**: true/false, if you want to proxy websockets
**[Back to top](#table-of-contents)**
### Listening for proxy events
* `error`: The error event is emitted if the request to the target fail. **We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.**
* `proxyReq`: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "web" connections
* `proxyReqWs`: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "websocket" connections
* `proxyRes`: This event is emitted if the request to the target got a response.
* `open`: This event is emitted once the proxy websocket was created and piped into the target websocket.
* `close`: This event is emitted once the proxy websocket was closed.
* (DEPRECATED) `proxySocket`: Deprecated in favor of `open`.
```js
var httpProxy = require('http-proxy');
// Error example
//
// Http Proxy Server with bad target
//
var proxy = httpProxy.createServer({
target:'http://localhost:9005'
});
proxy.listen(8005);
//
// Listen for the `error` event on `proxy`.
proxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.');
});
//
// Listen for the `proxyRes` event on `proxy`.
//
proxy.on('proxyRes', function (proxyRes, req, res) {
console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});
//
// Listen for the `open` event on `proxy`.
//
proxy.on('open', function (proxySocket) {
// listen for messages coming FROM the target here
proxySocket.on('data', hybiParseAndLogMessage);
});
//
// Listen for the `close` event on `proxy`.
//
proxy.on('close', function (res, socket, head) {
// view disconnected websocket connections
console.log('Client disconnected');
});
```
**[Back to top](#table-of-contents)**
### Shutdown
* When testing or running server within another program it may be necessary to close the proxy.
* This will stop the proxy from accepting new connections.
```js
var proxy = new httpProxy.createProxyServer({
target: {
host: 'localhost',
port: 1337
}
});
proxy.close();
```
**[Back to top](#table-of-contents)**
### Miscellaneous
If you want to handle your own response after receiving the `proxyRes`, you can do
so with `selfHandleResponse`. As you can see below, if you use this option, you
are able to intercept and read the `proxyRes` but you must also make sure to
reply to the `res` itself otherwise the original client will never receive any
data.
### Modify response
```js
var option = {
target: target,
selfHandleResponse : true
};
proxy.on('proxyRes', function (proxyRes, req, res) {
var body = [];
proxyRes.on('data', function (chunk) {
body.push(chunk);
});
proxyRes.on('end', function () {
body = Buffer.concat(body).toString();
console.log("res from proxied server:", body);
res.end("my response to cli");
});
});
proxy.web(req, res, option);
```
#### ProxyTable API
A proxy table API is available through this add-on [module](https://github.com/donasaur/http-proxy-rules), which lets you define a set of rules to translate matching routes to target routes that the reverse proxy will talk to.
#### Test
```
$ npm test
```
#### Logo
Logo created by [Diego Pasquali](http://dribbble.com/diegopq)
**[Back to top](#table-of-contents)**
### Contributing and Issues
* Read carefully our [Code Of Conduct](https://github.com/http-party/node-http-proxy/blob/master/CODE_OF_CONDUCT.md)
* Search on Google/Github
* If you can't find anything, open an issue
* If you feel comfortable about fixing the issue, fork the repo
* Commit to your local branch (which must be different from `master`)
* Submit your Pull Request (be sure to include tests and update documentation)
**[Back to top](#table-of-contents)**
### License
>The MIT License (MIT)
>
>Copyright (c) 2010 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
>
>Permission is hereby granted, free of charge, to any person obtaining a copy
>of this software and associated documentation files (the "Software"), to deal
>in the Software without restriction, including without limitation the rights
>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
>copies of the Software, and to permit persons to whom the Software is
>furnished to do so, subject to the following conditions:
>
>The above copyright notice and this permission notice shall be included in
>all copies or substantial portions of the Software.
>
>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
>AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
>LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
>OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
>THE SOFTWARE.

View File

@@ -0,0 +1,10 @@
coverage:
parsers:
javascript:
enable_partials: yes
status:
project:
default:
target: "70%"
patch:
enabled: false

View File

@@ -37,9 +37,9 @@ function createProxyServer(options) {
* changeOrigin: <true/false, Default: false - changes the origin of the host header to the target URL>
* preserveHeaderKeyCase: <true/false, Default: false - specify whether you want to keep letter case of response header key >
* auth : Basic authentication i.e. 'user:password' to compute an Authorization header.
* hostRewrite: rewrites the location hostname on (301/302/307/308) redirects, Default: null.
* autoRewrite: rewrites the location host/port on (301/302/307/308) redirects based on requested host/port. Default: false.
* protocolRewrite: rewrites the location protocol on (301/302/307/308) redirects to 'http' or 'https'. Default: null.
* hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null.
* autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
* protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
* }
*
* NOTE: `options.ws` and `options.ssl` are optional.

View File

@@ -4,8 +4,7 @@ var common = exports,
required = require('requires-port');
var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i,
isSSL = /^https|wss/,
cookieDomainRegex = /(;\s*domain=)([^;]+)/i;
isSSL = /^https|wss/;
/**
* Simple Regex for testing if protocol is https
@@ -40,7 +39,7 @@ common.setupOutgoing = function(outgoing, options, req, forward) {
function(e) { outgoing[e] = options[forward || 'target'][e]; }
);
outgoing.method = req.method;
outgoing.method = options.method || req.method;
outgoing.headers = extend({}, req.headers);
if (options.headers){
@@ -211,27 +210,27 @@ common.urlJoin = function() {
*
* @api private
*/
common.rewriteCookieDomain = function rewriteCookieDomain(header, config) {
common.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) {
if (Array.isArray(header)) {
return header.map(function (headerElement) {
return rewriteCookieDomain(headerElement, config);
return rewriteCookieProperty(headerElement, config, property);
});
}
return header.replace(cookieDomainRegex, function(match, prefix, previousDomain) {
var newDomain;
if (previousDomain in config) {
newDomain = config[previousDomain];
return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", 'i'), function(match, prefix, previousValue) {
var newValue;
if (previousValue in config) {
newValue = config[previousValue];
} else if ('*' in config) {
newDomain = config['*'];
newValue = config['*'];
} else {
//no match, return previous domain
//no match, return previous value
return match;
}
if (newDomain) {
//replace domain
return prefix + newDomain;
if (newValue) {
//replace value
return prefix + newValue;
} else {
//remove domain
//remove value
return '';
}
});

View File

@@ -41,14 +41,15 @@ function createRightProxy(type) {
cntr--;
}
var requestOptions = options;
if(
!(args[cntr] instanceof Buffer) &&
args[cntr] !== res
) {
//Copy global options
options = extend({}, options);
requestOptions = extend({}, options);
//Overwrite with request options
extend(options, args[cntr]);
extend(requestOptions, args[cntr]);
cntr--;
}
@@ -60,11 +61,11 @@ function createRightProxy(type) {
/* optional args parse end */
['target', 'forward'].forEach(function(e) {
if (typeof options[e] === 'string')
options[e] = parse_url(options[e]);
if (typeof requestOptions[e] === 'string')
requestOptions[e] = parse_url(requestOptions[e]);
});
if (!options.target && !options.forward) {
if (!requestOptions.target && !requestOptions.forward) {
return this.emit('error', new Error('Must provide a proper URL as target'));
}
@@ -77,7 +78,7 @@ function createRightProxy(type) {
* refer to the connection socket
* pass(req, socket, options, head)
*/
if(passes[i](req, res, options, head, this, cbl)) { // passes can return a truthy value to halt the loop
if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop
break;
}
}

View File

@@ -1,12 +1,15 @@
var http = require('http'),
https = require('https'),
var httpNative = require('http'),
httpsNative = require('https'),
web_o = require('./web-outgoing'),
common = require('../common');
common = require('../common'),
followRedirects = require('follow-redirects');
web_o = Object.keys(web_o).map(function(pass) {
return web_o[pass];
});
var nativeAgents = { http: httpNative, https: httpsNative };
/*!
* Array of passes.
*
@@ -79,7 +82,7 @@ module.exports = {
values[header];
});
req.headers['x-forwarded-host'] = req.headers['host'] || '';
req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || '';
},
/**
@@ -99,6 +102,10 @@ module.exports = {
// And we begin!
server.emit('start', req, res, options.target || options.forward);
var agents = options.followRedirects ? followRedirects : nativeAgents;
var http = agents.http;
var https = agents.https;
if(options.forward) {
// If forward enable, so just pipe the request
var forwardReq = (options.forward.protocol === 'https:' ? https : http).request(
@@ -122,7 +129,9 @@ module.exports = {
// Enable developers to modify the proxyReq before headers are sent
proxyReq.on('socket', function(socket) {
if(server) { server.emit('proxyReq', proxyReq, req, res, options); }
if(server && !proxyReq.getHeader('expect')) {
server.emit('proxyReq', proxyReq, req, res, options);
}
});
// allow outgoing socket to timeout so that we could
@@ -162,19 +171,24 @@ module.exports = {
proxyReq.on('response', function(proxyRes) {
if(server) { server.emit('proxyRes', proxyRes, req, res); }
for(var i=0; i < web_o.length; i++) {
if(web_o[i](req, res, proxyRes, options)) { break; }
if(!res.headersSent && !options.selfHandleResponse) {
for(var i=0; i < web_o.length; i++) {
if(web_o[i](req, res, proxyRes, options)) { break; }
}
}
// Allow us to listen when the proxy has completed
proxyRes.on('end', function () {
server.emit('end', req, res, proxyRes);
});
proxyRes.pipe(res);
if (!res.finished) {
// Allow us to listen when the proxy has completed
proxyRes.on('end', function () {
if (server) server.emit('end', req, res, proxyRes);
});
// We pipe to the response unless its expected to be handled by the user
if (!options.selfHandleResponse) proxyRes.pipe(res);
} else {
if (server) server.emit('end', req, res, proxyRes);
}
});
//proxyReq.end();
}
};

View File

@@ -84,12 +84,16 @@ module.exports = { // <--
*/
writeHeaders: function writeHeaders(req, res, proxyRes, options) {
var rewriteCookieDomainConfig = options.cookieDomainRewrite,
rewriteCookiePathConfig = options.cookiePathRewrite,
preserveHeaderKeyCase = options.preserveHeaderKeyCase,
rawHeaderKeyMap,
setHeader = function(key, header) {
if (header == undefined) return;
if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') {
header = common.rewriteCookieDomain(header, rewriteCookieDomainConfig);
header = common.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain');
}
if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') {
header = common.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path');
}
res.setHeader(String(key).trim(), header);
};
@@ -98,6 +102,10 @@ module.exports = { // <--
rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig };
}
if (typeof rewriteCookiePathConfig === 'string') { //also test for ''
rewriteCookiePathConfig = { '*': rewriteCookiePathConfig };
}
// message.rawHeaders is added in: v0.11.6
// https://nodejs.org/api/http.html#http_message_rawheaders
if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) {
@@ -129,9 +137,10 @@ module.exports = { // <--
writeStatusCode: function writeStatusCode(req, res, proxyRes) {
// From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers])
if(proxyRes.statusMessage) {
res.writeHead(proxyRes.statusCode, proxyRes.statusMessage);
res.statusCode = proxyRes.statusCode;
res.statusMessage = proxyRes.statusMessage;
} else {
res.writeHead(proxyRes.statusCode);
res.statusCode = proxyRes.statusCode;
}
}

View File

@@ -77,6 +77,24 @@ module.exports = {
* @api private
*/
stream : function stream(req, socket, options, head, server, clb) {
var createHttpHeader = function(line, headers) {
return Object.keys(headers).reduce(function (head, key) {
var value = headers[key];
if (!Array.isArray(value)) {
head.push(key + ': ' + value);
return head;
}
for (var i = 0; i < value.length; i++) {
head.push(key + ': ' + value[i]);
}
return head;
}, [line])
.join('\r\n') + '\r\n\r\n';
}
common.setupSocket(socket);
if (head && head.length) socket.unshift(head);
@@ -93,7 +111,10 @@ module.exports = {
proxyReq.on('error', onOutgoingError);
proxyReq.on('response', function (res) {
// if upgrade event isn't going to happen, close the socket
if (!res.upgrade) socket.end();
if (!res.upgrade) {
socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers));
res.pipe(socket);
}
});
proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {
@@ -119,22 +140,7 @@ module.exports = {
// Remark: Handle writing the headers to the socket when switching protocols
// Also handles when a header is an array
//
socket.write(
Object.keys(proxyRes.headers).reduce(function (head, key) {
var value = proxyRes.headers[key];
if (!Array.isArray(value)) {
head.push(key + ': ' + value);
return head;
}
for (var i = 0; i < value.length; i++) {
head.push(key + ': ' + value[i]);
}
return head;
}, ['HTTP/1.1 101 Switching Protocols'])
.join('\r\n') + '\r\n\r\n'
);
socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers));
proxySocket.pipe(socket).pipe(proxySocket);

View File

@@ -1,109 +1,41 @@
{
"_args": [
[
"http-proxy@^1.8.1",
"/home/joshua/Development/Haxe/test/node_modules/http-server"
]
],
"_from": "http-proxy@>=1.8.1 <2.0.0",
"_id": "http-proxy@1.16.2",
"_inCache": true,
"_installable": true,
"_location": "/http-proxy",
"_nodeVersion": "6.9.1",
"_npmOperationalInternal": {
"host": "packages-18-east.internal.npmjs.com",
"tmp": "tmp/http-proxy-1.16.2.tgz_1481039349196_0.5866330966819078"
},
"_npmUser": {
"email": "jcrugzz@gmail.com",
"name": "jcrugzz"
},
"_npmVersion": "3.10.8",
"_phantomChildren": {},
"_requested": {
"name": "http-proxy",
"raw": "http-proxy@^1.8.1",
"rawSpec": "^1.8.1",
"scope": null,
"spec": ">=1.8.1 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/http-server"
],
"_resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.16.2.tgz",
"_shasum": "06dff292952bf64dbe8471fa9df73066d4f37742",
"_shrinkwrap": null,
"_spec": "http-proxy@^1.8.1",
"_where": "/home/joshua/Development/Haxe/test/node_modules/http-server",
"author": {
"email": "charlie.robbins@gmail.com",
"name": "Charlie Robbins"
},
"bugs": {
"url": "https://github.com/nodejitsu/node-http-proxy/issues"
},
"dependencies": {
"eventemitter3": "1.x.x",
"requires-port": "1.x.x"
},
"description": "HTTP proxying for the masses",
"devDependencies": {
"async": "*",
"blanket": "*",
"coveralls": "*",
"dox": "*",
"expect.js": "*",
"mocha": "*",
"mocha-lcov-reporter": "*",
"semver": "^5.0.3",
"socket.io": "*",
"socket.io-client": "*",
"sse": "0.0.6",
"ws": "^0.8.0"
},
"directories": {},
"dist": {
"shasum": "06dff292952bf64dbe8471fa9df73066d4f37742",
"tarball": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.16.2.tgz"
},
"engines": {
"node": ">=0.10.0"
},
"gitHead": "c1fb596b856df971d291585ccf105233f7deca51",
"homepage": "https://github.com/nodejitsu/node-http-proxy#readme",
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"name": "indexzero",
"email": "charlie.robbins@gmail.com"
},
{
"name": "cronopio",
"email": "aristizabal.daniel@gmail.com"
},
{
"name": "yawnt",
"email": "yawn.localhost@gmail.com"
},
{
"name": "jcrugzz",
"email": "jcrugzz@gmail.com"
}
],
"name": "http-proxy",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"version": "1.18.1",
"repository": {
"type": "git",
"url": "git+https://github.com/nodejitsu/node-http-proxy.git"
"url": "https://github.com/http-party/node-http-proxy.git"
},
"description": "HTTP proxying for the masses",
"author": "Charlie Robbins <charlie.robbins@gmail.com>",
"maintainers": [
"jcrugzz <jcrugzz@gmail.com>"
],
"main": "index.js",
"dependencies": {
"eventemitter3": "^4.0.0",
"requires-port": "^1.0.0",
"follow-redirects": "^1.0.0"
},
"devDependencies": {
"async": "^3.0.0",
"auto-changelog": "^1.15.0",
"concat-stream": "^2.0.0",
"expect.js": "~0.3.1",
"mocha": "^3.5.3",
"nyc": "^14.0.0",
"semver": "^5.0.3",
"socket.io": "^2.1.0",
"socket.io-client": "^2.1.0",
"sse": "0.0.8",
"ws": "^3.0.0"
},
"scripts": {
"coveralls": "mocha --require blanket --reporter mocha-lcov-reporter | ./node_modules/coveralls/bin/coveralls.js",
"test": "mocha test/*-test.js",
"test-cov": "mocha --require blanket -R html-cov > cov/coverage.html"
"mocha": "mocha test/*-test.js",
"test": "nyc --reporter=text --reporter=lcov npm run mocha",
"version": "auto-changelog -p && git add CHANGELOG.md"
},
"version": "1.16.2"
"engines": {
"node": ">=8.0.0"
},
"license": "MIT"
}

View File

@@ -0,0 +1,19 @@
{
"platform": "github",
"autodiscover": false,
"requireConfig": true,
"ignoreNpmrcFile": true,
"rangeStrategy": "replace",
"packageRules": [
{
"packagePatterns": [
"*"
],
"minor": {
"groupName": "all non-major dependencies",
"groupSlug": "all-minor-patch"
}
}
],
"commitMessagePrefix": "[dist]"
}