More documentation and options.

This commit is contained in:
Rob W
2013-01-03 20:02:43 +01:00
parent b7ba441712
commit 2cf2300afb
3 changed files with 173 additions and 106 deletions

View File

@@ -12,12 +12,15 @@ The package also includes a Procfile, to run the app on Heroku. More information
Heroku can be found at https://devcenter.heroku.com/articles/nodejs.
## Example
```javascript
var host = '127.0.0.1';
var port = 8080;
var cors_proxy = require("cors-anywhere");
cors_proxy.createServer().listen(port, host, function() {
cors_proxy.createServer({
xRequestedWith: true
}).listen(port, host, function() {
console.log('Running CORS Anywhere on ' + host + ':' + port);
});
```
@@ -30,7 +33,36 @@ Request examples:
* http://localhost:8080/favicon.ico - Replies 404 Not found
## Documentation
The module exports two properties: `getHandler` and `createServer`.
* `getHandler(options)` returns a handler which implements the routing logic.
This handler is used by [http-proxy](https://github.com/nodejitsu/node-http-proxy).
* `createServer(options)` creates a server with the default handler.
The following options are recognized by both methods:
* boolean `withCredentials` - If true, [user credentials](http://www.w3.org/TR/cors/#user-credentials)
such as cookies are accepted in the request. It's recommended to set this flag to `false`, because
cookies ought not to be leaked to other domains. If you want to use `withCredentials`, make sure that
you implement cookie parsing and transforming so that the `path` flag of the cookie is set correctly.
* string `requireHeader`` - If set, the request must include this header or the API will refuse to proxy.
Recommended if you want to prevent users from using the proxy for browsing. Example: `X-Requested-With`
* array of lowercase strings `removeHeaders` - Exclude certain headers from being included in the request.
Example: `["cookie"]`
`createServer` recognizes the following option as well:
* `httpProxyOptions` - Options for http-proxy. The documentation for these options can be found [here](https://github.com/nodejitsu/node-http-proxy#options).
## Dependencies
- NodeJitsu's [http-proxy](https://github.com/nodejitsu/node-http-proxy)
## License
Copyright (C) 2013 Rob W <gwnRob@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of

View File

@@ -35,133 +35,164 @@ function hasNoContent(hostname) {
}
function handleCookies(isAllowed, headers) {
// Assumed that all headers' names are lowercase
if (!isAllowed) {
delete headers['set-cookie'];
delete headers['set-cookie2'];
return;
}
// TODO: Parse cookies, and change Domain and Secure flag to match the API domain,
// and change Path to /<website>/....
//if (headers['set-cookie']) headers['set-cookie'] = _parseCookie(headers['set-cookie']);
//if (headers['set-cookie2']) headers['set-cookie2'] = _parseCookie(headers['set-cookie']);
// Assumed that all headers' names are lowercase
if (!isAllowed) {
delete headers['set-cookie'];
delete headers['set-cookie2'];
return;
}
// TODO: Parse cookies, and change Domain and Secure flag to match the API domain,
// and change Path to /<website>/....
//if (headers['set-cookie']) headers['set-cookie'] = _parseCookie(headers['set-cookie']);
//if (headers['set-cookie2']) headers['set-cookie2'] = _parseCookie(headers['set-cookie']);
}
// Called on every request
var handler = exports.handler = function(req, res, proxy) {
var cors_headers = {
'access-control-allow-origin': req.headers.origin || '*'
var getHandler = exports.getHandler = function(options) {
var corsAnywhere = {
withCredentials: false, // Toggle credentials/cookies
requireHeader: null, // Require a header to be set?
removeHeaders: [] // Strip these request headers
};
if (proxy.withCredentials) {
// Allow sending of credentials ONLY if it's explicitly allowed on creation of the proxy.
cors_headers['access-control-allow-credentials'] = 'true';
if (options) {
Object.keys(corsAnywhere).forEach(function(option) {
if (Object.prototype.hasOwnProperty.call(options, option)) {
corsAnywhere[option] = options[option];
}
});
}
if (req.headers['access-control-request-method']) {
cors_headers['access-control-allow-methods'] = req.headers['access-control-request-method'];
}
if (req.headers['access-control-request-headers']) {
cors_headers['access-control-allow-headers'] = req.headers['access-control-request-headers'];
}
if (req.method == 'OPTIONS') {
// Pre-flight request. Reply successfully:
res.writeHead(200, cors_headers);
res.end();
return;
} else {
// Actual request. First, extract the desired URL from the request:
var host, hostname, port, path, match;
match = req.url.match(/^\/(?:(https?:)?\/\/)?(([^\/?]+?)(?::(\d{0,5})(?=[\/?]|$))?)([\/?][\S\s]*|$)/i);
// ^^^^^^^ ^^^^^^^^ ^^^^^^^ ^^^^^^^^^^^^
// 1:protocol 3:hostname 4:port 5:path + query string
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// 2:host
if (!match || (match[2].indexOf('.') === -1 && match[2].indexOf(':') === -1) || match[4] > 65535) {
// Incorrect usage. Show how to do it correctly.
showUsage(res);
return;
} else if (match[2] === 'iscorsneeded') {
// Is CORS needed? This path is provided so that API consumers can test whether it's necessary
// to use CORS. The server's reply is always No, because if they can read it, then CORS headers
// are not necessary.
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('no');
return;
} else if (match[4] > 65535) {
// Port is higher than 65535
res.writeHead(400, 'Invalid port', cors_headers);
res.end();
return;
} else if ( hasNoContent(match[3]) ) {
// Don't even try to proxy invalid hosts
res.writeHead(404, cors_headers);
return function(req, res, proxy) {
var cors_headers = {
'access-control-allow-origin': req.headers.origin || '*'
};
if (corsAnywhere.withCredentials) { // <-- If the corsAnywhere property does not exists, throw an error.
// Allow sending of credentials ONLY if it's explicitly allowed on creation of the proxy.
cors_headers['access-control-allow-credentials'] = 'true';
}
if (req.headers['access-control-request-method']) {
cors_headers['access-control-allow-methods'] = req.headers['access-control-request-method'];
}
if (req.headers['access-control-request-headers']) {
cors_headers['access-control-allow-headers'] = req.headers['access-control-request-headers'];
}
if (req.method == 'OPTIONS') {
// Pre-flight request. Reply successfully:
res.writeHead(200, cors_headers);
res.end();
return;
} else {
host = match[2];
hostname = match[3];
// Read port from input: :<port> / 443 if https / 80 by default
port = match[4] ? +match[4] : (match[1] && match[1].toLowerCase() === 'https:' ? 443 : 80);
path = match[5];
}
// Change the requested path:
req.url = path;
// Hook res.writeHead method to set the correct header
var res_writeHead = res.writeHead;
res.writeHead = function(statusCode, reasonPhrase, headers) {
if (typeof reasonPhrase === 'object') {
headers = reasonPhrase;
// Actual request. First, extract the desired URL from the request:
var host, hostname, port, path, match;
match = req.url.match(/^\/(?:(https?:)?\/\/)?(([^\/?]+?)(?::(\d{0,5})(?=[\/?]|$))?)([\/?][\S\s]*|$)/i);
// ^^^^^^^ ^^^^^^^^ ^^^^^^^ ^^^^^^^^^^^^
// 1:protocol 3:hostname 4:port 5:path + query string
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// 2:host
if (!match || (match[2].indexOf('.') === -1 && match[2].indexOf(':') === -1) || match[4] > 65535) {
// Incorrect usage. Show how to do it correctly.
showUsage(res);
return;
} else if (match[2] === 'iscorsneeded') {
// Is CORS needed? This path is provided so that API consumers can test whether it's necessary
// to use CORS. The server's reply is always No, because if they can read it, then CORS headers
// are not necessary.
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('no');
return;
} else if (match[4] > 65535) {
// Port is higher than 65535
res.writeHead(400, 'Invalid port', cors_headers);
res.end();
return;
} else if ( hasNoContent(match[3]) ) {
// Don't even try to proxy invalid hosts
res.writeHead(404, cors_headers);
res.end();
return;
} else if (corsAnywhere.requireHeader != null && req.headers[corsAnywhere.requireHeader.toLowerCase()] == null) {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end('Missing ' + corsAnywhere.requireHeader + ' header!');
return;
} else {
host = match[2];
hostname = match[3];
// Read port from input: :<port> / 443 if https / 80 by default
port = match[4] ? +match[4] : (match[1] && match[1].toLowerCase() === 'https:' ? 443 : 80);
path = match[5];
}
if (!headers) headers = cors_headers;
else {
var header;
for (header in cors_headers) {
// We define the cors_headers object, so we can be damn sure that hasOwnProperty is not a key of it.
// and therefor we can use hOP directly instead of Object.prototype.hOP.call(...)
if (cors_headers.hasOwnProperty(header)) {
headers[header] = cors_headers[header];
}
}
// Change the requested path:
req.url = path;
if ((statusCode === 301 || statusCode === 302) && headers.location) {
corsAnywhere.removeHeaders.forEach(function(header) {
delete req.headers[header];
});
// Hook res.writeHead method to set the correct header
var res_writeHead = res.writeHead;
res.writeHead = function(statusCode, reasonPhrase, headers) {
if (typeof reasonPhrase === 'object') {
headers = reasonPhrase;
}
if (!headers) headers = cors_headers;
else {
var header;
for (header in cors_headers) {
// We define the cors_headers object, so we can be damn sure that hasOwnProperty is not a key of it.
// and therefor we can use hOP directly instead of Object.prototype.hOP.call(...)
if (cors_headers.hasOwnProperty(header)) {
headers[header] = cors_headers[header];
}
}
if ((statusCode === 301 || statusCode === 302) && headers.location) {
// Handle redirects
// The X-Forwarded-Proto header is set by Heroku, and also by the http-proxy library when xforward is true)
var proxy_base_url = (req.headers['x-forwarded-proto'] || 'http') + '://' + req.headers['host'];
headers.location = proxy_base_url + '/' + headers.location;
}
handleCookies(proxy.withCredentials, headers);
}
handleCookies(proxy.withCredentials, headers);
}
return res_writeHead.apply(this, arguments); // headers are magically updated when variables are modified
};
// Finally, proxy the request
proxy.proxyRequest(req, res, {
host: hostname,
port: port
});
}
return res_writeHead.apply(this, arguments); // headers are magically updated when variables are modified
};
// Finally, proxy the request
proxy.proxyRequest(req, res, {
host: hostname,
port: port
});
}
};
};
// Create server with default/recommended values
// Create server with default and given values
// Creator still needs to call .listen()
var createServer = exports.createServer = function() {
if (arguments.length) {
console.log('Warning: corsproxy.createServer ignores all arguments.');
}
var options = {
changeOrigin: true,
xforward: true
var createServer = exports.createServer = function(options) {
if (!options) options = {};
// Default options:
var httpProxyOptions = {
changeOrigin: true, // Change Host request header to match the requested URL instead of the proxy's URL.
xforward: {
enable: true // Append X-Forwarded-* headers
}
};
var server = httpProxy.createServer(options, handler);
// Allow user to override defaults and add own options
if (options.httpProxyOptions) {
Object.keys(options.httpProxyOptions).forEach(function(option) {
httpProxyOptions[option] = options.httpProxyOptions[option];
});
}
var handler = getHandler(options);
var server = httpProxy.createServer(httpProxyOptions, handler);
// When the server fails, just show a 404 instead of Internal server error
server.proxy.on('proxyError', function(err, req, res) {
res.writeHead(404, {});
res.end();
});
// Disable Cookies etc. If you want to enable cookies, please implement a cookie parser which
// correctly uses the Path flag to separate cookies.
server.proxy.withCredentials = false;
return server;
};

View File

@@ -2,6 +2,10 @@ var host = '127.0.0.1';
var port = 8080;
var cors_proxy = require("./lib/cors-anywhere");
cors_proxy.createServer().listen(port, host, function() {
cors_proxy.createServer({
requireHeader: 'x-requested-with',
withCredentials: false,
removeHeaders: ['cookie', 'cookie2']
}).listen(port, host, function() {
console.log('Running CORS Anywhere on ' + host + ':' + port);
});