module.exports = function spawnReverseProxy(cb) { // Set up proxy rules instance var proxyRules = new HttpProxyRules({ rules: { '.*/test': 'http://localhost:8080/cool', // Rule (1) '.*/test2/': 'http://localhost:8080/cool2/' // Rule (2) }, default: 'http://localhost:8080' // default target }); // Create reverse proxy instance var proxy = httpProxy.createProxy(); // Create http server that leverages reverse proxy instance // and proxy rules to proxy requests to different targets http.createServer(function(req, res) { // a match method is exposed on the proxy rules instance // to test a request to see if it matches against one of the specified rules var target = proxyRules.match(req); if (target) { return proxy.web(req, res, { target: target }); } res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('The request url and path did not match any of the listed rules!'); }).listen(6010, cb); };
module.exports = function( settings ) { const proxy = httpProxy.createProxy( { secure: false } ); proxy.on('proxyReq', function(proxyReq, req, res, options) { if( settings.username ) { proxyReq.setHeader( "Authorization", "Basic " + new Buffer(settings.username + ":" + settings.password).toString("base64") ); } }); function request( req, res ) { proxy.web( req, res, { target: settings.target } ); }; function close() { proxy.close(); } console.log( `\tremote: ${settings.target}` ); return new Promise( function( resolve, reject ) { resolve( { request: request, close: close } ); } ); };
/** * @param config */ function launch(config) { // clear filters filter.clear(); //var agent = new http.Agent({keepAlive: true}); //var proxy = httpProxy.createProxy({agent: agent}); var proxy = httpProxy.createProxy(); proxy.on('error', function (err, req, res) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('proxied Service could probably not be reached.'); }); var server = http.createServer(function (req, res) { var options = {target: `http://${config.hostname}:${config.port}`, shadow: []}; var cookieJar = new cookies(req, res); var sessionId = null; if (cookieJar.get(BIFROST_SESSION_ID_COOKIE) === undefined) { sessionId = sessionStore.generate(); cookieJar.set(BIFROST_SESSION_ID_COOKIE, sessionId); log.debug(`new session ${sessionId}`); } else { sessionId = cookieJar.get(BIFROST_SESSION_ID_COOKIE); if (!sessionStore.exists(sessionId)) { log.debug(`${sessionId} is old - reissue.`); sessionId = sessionStore.generate(); cookieJar.set(BIFROST_SESSION_ID_COOKIE, sessionId); } log.debug(`session identified or re-issued as ${sessionId}`); } if (filter.hasFilters()) { routeRequest(req, filter.listFilters(), options, sessionId); log.debug(`proxying request...`); log.debug(options); } // default: redirect everything to target service options.shadow.forEach(function(shadowTarget) { request({method: req.method, uri: shadowTarget + req.url, headers: req.headers}); }); proxy.web(req, res, options); }); log.debug(`proxy setup for http://${config.hostname}:${config.port}`); return server.listen(config.proxyPort); }
module.exports = function( settings ) { const proxy = httpProxy.createProxy( { secure: false } ); console.log( `\tremote: ${settings.target}` ); return function( req, res ) { proxy.web( req, res, { target: settings.target } ); }; };
exports = module.exports = function(config) { var httpProxy = require('http-proxy'); var proxy = httpProxy.createProxy(); proxy.on('error', function (err, req, res) { console.log("[proxyError]", err); }); return function(req, res, next) { if (!req.user) { res.send(403, 'Forbidden!'); return; } delete req.headers.cookie; proxy.web(req, res, { target: config.elasticsearch.url }); }; };
function proxy(endpoint, region, service) { var proxy = httpProxy.createProxy({ secure: true, changeOrigin: true, target: endpoint.href }); proxy.on('proxyReq', function(proxyReq, req, res, options) { var awsReq = new AWS.HttpRequest(endpoint); awsReq.method = proxyReq.method; awsReq.path = proxyReq.path; awsReq.headers['Host'] = endpoint.host; awsReq.headers['presigned-expires'] = false; awsReq.region = region; if (Buffer.isBuffer(req.body)) { awsReq.body = req.body; } var signer = new AWS.Signers.V4(awsReq, service); signer.addAuthorization({ accessKeyId: req.accessKeyId, secretAccessKey: req.secretAccessKey }, new Date()); proxyReq.setHeader('Host', awsReq.headers['Host']); proxyReq.setHeader('X-Amz-Date', awsReq.headers['X-Amz-Date']); proxyReq.setHeader('Authorization', awsReq.headers['Authorization']); }); return function(req, res) { var opts = {}; if (Buffer.isBuffer(req.body)) { opts.buffer = AWS.util.buffer.toStream(req.body); } proxy.web(req, res, opts); }; }
var http = require('http'); var finalhandler = require('finalhandler'); var morgan = require('morgan'); var httpProxy = require('http-proxy'); var accessLogStream = FileStreamRotator.getStream({ filename: __dirname + '/log/access.%DATE%.log', frequency: 'daily', verbose: false, date_format: "YYYY-MM-DD" }); var logger = morgan('combined', { stream: accessLogStream }); var proxy = httpProxy.createProxy(); http.createServer(function(req, res) { var done = finalhandler(req, res); logger(req, res, function(err) { var host = req.headers.host; var url; switch (host) { case "tlks.io": case 'www.tlks.io': url = 'http://localhost:9001'; proxy.web(req, res, { target: url }); break; case 'api.tlks.io':
function setup(_support_server) { support_server = _support_server; var config = opt; var control_port = opt.control_port; var support_port = undefined; if (support_server) { support_port = config.support_port = support_server.port; } // TODO start support server // currently happens within user_server var bouncer_port = 0; if (config.local && parseInt(config.local)) { bouncer_port = config.local; } if (config.phantom && parseInt(config.phantom)) { bouncer_port = config.phantom; } var proxy = httpProxy.createProxy(); proxy.on('proxyReq', on_proxy_req); bouncer = http.createServer(); bouncer.on('request', on_request(proxy.web)); bouncer.on('upgrade', on_request(proxy.ws)); function on_request(bounce) { return function(req, res) { var args = [].slice.call(arguments); if (is_control_req(req)) { args.push({ target: 'http://localhost:' + control_port }); bounce.apply(proxy, args); return; } args.push({ target: 'http://localhost:' + support_port }, on_support_server_proxy_done); bounce.apply(proxy, args); }; } function on_proxy_req(proxyReq, req, res, options) { if (is_control_req(req) || (req.headers.connection && req.headers.connection.toLowerCase().indexOf('upgrade') === -1)) { proxyReq.setHeader('connection', 'close'); } } function on_support_server_proxy_done(err, req, res) { if (err.code === 'ECONNRESET' && res && res.socket && res.socket.destroyed === true) { debug('Request to support-server:%s was canceled by the client, ignoring the proxy error'); } } function is_control_req(req) { var url = req.url.split('?')[0]; return !support_port || url.split('/')[1] === '__zuul'; } bouncer.listen(bouncer_port, bouncer_active); function bouncer_active() { var app_port = bouncer.address().port; debug('bouncer active on port %d', app_port); if (!config.tunnel) { return cb(null, 'http://localhost:' + app_port + '/__zuul'); } tunnel.connect(app_port, cb); }; }
console.log('\x1b[31m', 'NODE_ENV is not defined! Using default development environment'); } process.env.NODE_ENV = 'development'; } else { console.log('\x1b[7m', 'Application loaded using the "' + process.env.NODE_ENV + '" environment configuration'); } console.log('\x1b[0m'); }); // Get production or development config var config = require('./config/env/' + process.env.NODE_ENV); if (config.startHttpProxy) { // Create http proxy var proxy = httpProxy.createProxy({target: { protocol: 'http:'}}); // Start http server var httpServer = http.createServer(function(req, res) { // proxy requests to the target url that matches the current request url proxy.web(req, res, { target: config.options[req.headers.host] }); }); proxy.on('error', function (err, req, res) { // check previous time error was sent by email var currentErrorTime = new Date(); var diff = currentErrorTime - previousErrorTime; if (diff > 3600000) {
module.exports.init = function (app) { // get config info var port = app.config.get('port'); // we have to create a "proxy table": https://blog.nodejitsu.com/node-http-proxy-1dot0/ var options = app.config.proxyOptions(); // debug logger var morgan = require('morgan'); morgan.token('remote-user', function (req, res) { if (req.user) return req.user.id; return 'null'; }); morgan.token('message', function (req, res) { return res.logMessage; }); var morganFormat = ':remote-addr - :remote-user ":method fhir.' + app.config.get('domain') + ':url" :status ":message"'; var morganOptions = { stream: app.logger.stream, skip: function (req, res) { // only log requests that were made to the FHIR server return !req.logThis; } }; // create an Express server so we can use middleware with our reverse proxy var server = express() // allow CORS // TODO: edit to limit domains instead of using a wildcard .use(function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Auth-Token, X-Requested-With, Content-Type, Accept,Destroy'); res.header('Access-Control-Allow-Methods', 'DELETE, GET, POST, PUT'); // don't need HEAD, OPTIONS, or TRACE next(); }) .use(morgan(morganFormat, morganOptions)) .use(onBeforeProxy) .use(doProxy); var tls = app.config.get('use_tls') == 'true'; var serverCB = function () { app.logger.info('HTTP%s proxy server listening on port %d, proxy table: %s', tls ? 'S' : '', port, JSON.stringify(options, null, 2)); }; // start the Express server reverse proxy if (tls) { var https = require('https'); var tlsOptions = app.config.get('tls_options'); var tlsServer = https.createServer(tlsOptions, server); tlsServer.listen(port, serverCB); if (port == '443') { // we're listening on the standard HTTPS port (443) // redirect from the standard HTTP port (80) to HTTPS var http = require('http'); http.createServer(function (req, res) { res.writeHead(301, {"Location": "https://" + req.headers['host'] + req.url}); res.end(); }).listen(80); } } else { server.listen(port, serverCB); } // middleware to check tokens for connections to the FHIR server var regex = new RegExp("^fhir"); function onBeforeProxy(req, res, next) { // use compiled regex to check if this client is trying to access the FHIR server if (req.method === "OPTIONS") { // respond OK to all options requests // this is needed so browsers don't puke on themselves when doing ajax/XHR preflight requests for CORS respond(res, 200); } else if (regex.test(req.headers.host)) { // they are trying to access the FHIR server, instruct Morgan to log this request req.logThis = true; // now let's authenticate their token auth.checkTokenWeb(req, res, function () { var user = req.user; // TODO: Should we look up the user in the database? Otherwise an old token may not have correct roles... probably a non-issue var url = req.originalUrl.split('?')[0]; var resource = url.split('/').slice(0, 2).join('/'); // so "/Medication/foo/bar/baz" will result in "/Medication" //app.acl.areAnyRolesAllowed(user.roles, resource, req.method.toLowerCase(), function (err, result) { // if (err) { // app.logger.error('FHIR authorization- failed when trying to authorize user "%s" with roles %s to access resource "%s": %s', user.id, JSON.stringify(user.roles), resource, err.message); // respond(res, 500); // } else if (!result) { // app.logger.verbose('FHIR authorization- user "%s" has roles %s and is unauthorized to access resource "%s"', user.id, JSON.stringify(user.roles), resource); // respond(res, 403); // } else { // forward this request to our nomination proxy var split = req.headers.host.split(':'); var urlPrefix = options[split[0]]; // trim off port if it's present, before looking up target req.url = urlPrefix + req.url; var target = 'http://localhost:3002'; app.logger.silly('Proxying request from "%s" to "%s"', req.headers.host, target); Q.ninvoke(proxy, 'web', req, res, {target: target, toProxy: true, prependPath: false}) .catch(function (err) { app.logger.error('Failed to proxy request from "%s" to "%s": %s', req.headers.host, target, err.message); respond(res, 500); }).done(); // } //}) }); } else { // they aren't trying to access the FHIR server, just proxy the request through next(); } } // middleware to actually perform reverse proxying var proxy = httpProxy.createProxy(); function doProxy(req, res) { var split = req.headers.host.split(':'); var target = options[split[0]]; // trim off port if it's present, before looking up target //app.logger.silly('Proxying request from "%s" to "%s"', req.headers.host, target); Q.ninvoke(proxy, 'web', req, res, {target: target}) .catch(function (err) { app.logger.error('Failed to proxy request from "%s" to "%s": %s', req.headers.host, target, err.message); respond(res, 500); }).done(); } };
run = function() { if (server) { server.close(); } configApp(args[0]); function forward(req, res) { var port = getPort(req); if (req.url.indexOf("/xena") == 0) { // console.log("xena directing to port", port, "mapping url", req.url, "to", req.url.replace("/xena","/")); req.url = req.url.replace("/xena",""); } proxy.web(req, res, { target: "http://localhost:"+port, },function(e){ log_error(e,req); console.log("web error", e); launch(getApp(req), res); res.writeHead(500, { 'Content-Type': 'text/html' }); res.write(reloadFile, "binary"); res.end(); }); } function signIn(req, res) { var host = null; if (config.server.ssl) host = "https://" + config.server.host + ":"+ config.server.ssl; else host = "http://" + config.server.host + ":"+ config.server.nonssl; var url = host + "/sign-in?RETURNTO="+encodeURI(req.url); res.writeHead(307, { location: url}); res.end(); } function mustLogin(firstPart, req, res) { var cookies = new Cookies(req, res); function checkCredentials(cache, gateway_token) { if (gateway_token) try { var gateway_credentials = JSON.parse(gateway_token); var obj = JSON.parse(gateway_credentials.json); if ( obj.collaborations.indexOf(firstPart) >= 0) { var signature = hash( gateway_credentials.json ); if ( signature == gateway_credentials.signature ) { if (cache) console.log("credentials cached"); return true; } } } catch (err) { console.log("credential failure" , err); console.log("gateway_token" , gateway_token); console.log("gateway_credentials" , gateway_credentials); } return false; } function requestCredentials() { var options = { method: 'GET', path: '/medbookUser', port: final, headers: { 'cookie': req.headers.cookie, }, keepAlive: true, keepAliveMsecs: 3600000, // an hour }; var medbookUserReq = http.request(options, function(medbookUserRes) { medbookUserRes.setEncoding('utf8'); var all = ""; medbookUserRes.on("data", function(data) { all += data; }); medbookUserRes.on("end", function(data) { if (data != null) all += data; var gateway_credentials = { signature: hash( all ), json: all, } var gateway_token = JSON.stringify(gateway_credentials); cookies.set("gateway_token", gateway_token); if (checkCredentials(false, gateway_token)) forward(req, res); else signIn(req, res); }); }); medbookUserReq.on("error", function(err) { signIn(req, res); }); medbookUserReq.end(); }; // requestCredentials() if (checkCredentials(true, cookies.get("gateway_token"))) forward(req, res); else requestCredentials(); } // mustLogin function main(req, res) { var hostname = req.headers.host if (req.url == "/menu") return serveMenu(req, res); if (req.url.indexOf( "/postScript") == 0) return serveScript(req, res, postScript); if (req.url.indexOf(hostname.indexOf("tumormap")) == 0 ) { var red = "https://" + config.server.host + ":" + config.server.ssl + "/hex/" + req.url; res.writeHead(307, {'Location': red}); res.end(); } if (req.url.indexOf("/swat") == 0 ) { req.url = req.url.replace("/swat", ""); if (req.url.indexOf("/..") >=0 ) { console.log(".. not allowed: " + req.url); res.writeHead(404, {'Content-Type': 'text/plain'}); res.end(); } return serveFile(req, res, '/data/home/galaxy/hexProxy/'); } /*if (req.url.indexOf("/public") == 0) return serveFile(req, res, '/data/public/');*/ var urlPath = req.url.split("/"); var firstPart = "never match"; if (urlPath && urlPath.length >= 2 && urlPath[1].length > 0) firstPart = urlPath[1]; var sla = "/" + firstPart; if (sla in auth && auth[sla]) { mustLogin(firstPart, req, res); } else forward(req, res); } // main if (config.server.ssl) server = require('https').createServer(readSSLcredentials(), main); else server = require('http').createServer(main); var httpProxy = require('http-proxy') var proxy = httpProxy.createProxy({ ws : true }); server.on('upgrade',function(req,res){ var port = getPort(req); proxy.ws(req, res, { target: "http://localhost:" + port, },function(e){ log_error(e, req); launch(getApp(req)); console.log("WS ERROR", e); /* res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Something went wrong. And we are reporting a custom error message.'); */ }); }) if (config.server.ssl) { console.log("ssl listening on", config.server.ssl); server.listen(config.server.ssl) } else { console.log("nonssl listening on", config.server.nonssl); server.listen(config.server.nonssl) } };
var _ = require('lodash'); var httpProxy = require('http-proxy'); var routingProxy = httpProxy.createProxy(); var logger = require('../logger'); var config = require('../config'); var cache = null; var buildProxyCache = function() { // once the cache is hydrated with configs just return it if (cache) { return; } cache = []; if (config.options.user) { config.headers = { 'RemoteUser': config.options.user }; } // for each server configuration... _.each(config.options.servers, function(server) { // if proxy flag is not true just continue if (!server.proxy) {
/************************************************************ * * Express routes for: * - app.js * - app-terminal.js * - index.html * * Proxy requests to: * - /api -> :4040/api * ************************************************************/ // Proxy to backend var backendProxy = httpProxy.createProxy({ ws: true, target: 'http://' + BACKEND_HOST + ':4040' }); backendProxy.on('error', function(err) { console.error('Proxy error', err); }); app.all('/api*', backendProxy.web.bind(backendProxy)); // Serve application file depending on environment if (process.env.NODE_ENV === 'production') { // serve all precompiled content from build/ app.use(express.static('build')); } else { // redirect the JS bundles app.get(/.*js/, function(req, res) { res.redirect('//' + WEBPACK_SERVER_HOST + ':4041' + req.originalUrl);
var url = require('url'); var app = express(); var BACKEND_HOST = process.env.BACKEND_HOST || 'localhost'; var WEBPACK_SERVER_HOST = process.env.WEBPACK_SERVER_HOST || 'localhost'; /************************************************************ * * Proxy requests to: * - /api -> :4040/api * ************************************************************/ var backendProxy = httpProxy.createProxy({ ws: true, target: 'http://' + BACKEND_HOST + ':4040' }); backendProxy.on('error', function(err) { console.error('Proxy error', err); }); app.all('/api*', backendProxy.web.bind(backendProxy)); /************************************************************ * * Production env serves precompiled content from build/ * ************************************************************/ if (process.env.NODE_ENV === 'production') { app.use(express.static('build')); }
.alias('u', 'url') .describe('u', 'URL to test') .alias('r', 'require') .describe('r', 'Required analytics tools. One or more of: "omniture", "googleanalytics", "nielsen" separated by commas.') .alias('d', 'debug') .describe('d','Enable debugging output to console.') .argv; if (argv.debug) { console.log('Proxy: '.red.bold + 'localhost:' + proxyPort); } /* Proxy server looks at all requests and works out which are interesting beacon requests. */ var proxyServer = httpProxy.createProxy(); var outboundServer = require('http').createServer(function(req, res) { if (argv.debug) { console.log('Request: '.blue.bold + req.url); } var beacon = beaconTests(req); if (beacon) { beacon.url = req.url; beacons.push(beacon); } if (beacon && beacon.isBeacon) { if (argv.debug) { console.log("Not proxying: ".blue.bold + req.url); } proxyServer.web(req, res, {