-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.js
100 lines (81 loc) · 2.47 KB
/
proxy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
var http = require('http');
var httpProxy = require('http-proxy');
var config = require("./config");
var URI = require("url");
require("./app");
var bufferRequest = function (obj, cb) {
var events = [],
onData,
onEnd;
obj.on('data', onData = function (data, encoding) {
cb(data, encoding, function(processedData) {
events.push(['data', processedData, encoding]);
});
});
obj.on('end', onEnd = function (data, encoding) {
events.push(['end', data, encoding]);
});
return {
end: function () {
obj.removeListener('data', onData);
obj.removeListener('end', onEnd);
},
destroy: function () {
this.end();
this.resume = function () {
console.error("Cannot resume buffer after destroying it.");
};
onData = onEnd = events = obj = null;
},
resume: function () {
this.end();
for (var i = 0, len = events.length; i < len; ++i) {
obj.emit.apply(obj, events[i]);
}
}
};
};
var appProxy = new httpProxy.HttpProxy({target: {
host: config.ip,
port: config.port - 10,
}});
var accessToken = "AAADnV3jJYoIBAJnqo8eJBCBMMB8GduPsbQ4JZADmvnCZCafIXDj0ubNZCgDM2Pw3wVgYbr8tBlZCNZCVSlKQk6vRM0wi0LuhyZChsbn3dYDwZDZD";
var handleRequest = module.exports = function (req, res) {
if (req.url.indexOf("?proxy=") < 0) {
appProxy.proxyRequest(req, res);
return;
}
var url = (req.url || "").replace("/?proxy=", "");
var requestURI = URI.parse(url);
req.url = requestURI.pathname;
req.headers.host = requestURI.host;
console.log(req.url);
var buffer = bufferRequest(req, function(data, encoding, cb) {
console.log("here");
var dataStr = data.toString(encoding);
if (dataStr.indexOf("token_fb_access") >= 0) {
dataStr = dataStr.replace("token_fb_access", accessToken);
}
var modifiedBuffer = new Buffer(dataStr, encoding);
console.log(modifiedBuffer.toString(encoding));
cb(modifiedBuffer);
});
req.once("end", function() {
console.log("ended");
var target = {
host: requestURI.host,
port: requestURI.protocol === "https:" ? 443 : 80,
https: requestURI.protocol === "https:",
}
console.log(target);
var proxy = new httpProxy.HttpProxy({
"target": target});
proxy.proxyRequest(req, res, buffer);
req.on("end", function() {
console.log("real end");
});
});
};
http.createServer(function (req, res) {
handleRequest(req, res);
}).listen(config.port, config.ip);