This repository has been archived by the owner on Nov 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproxy.js
111 lines (86 loc) · 2.73 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
101
102
103
104
105
106
107
108
109
110
111
var http = require('http');
var https = require('https');
var zlib = require('zlib');
var Transform = function (res, remoteRes, protocol, host) {
this.callback = function (error, data) {
if (error) {
console.log(error);
res.end();
return;
}
delete remoteRes.headers['content-length'];
delete remoteRes.headers['content-encoding'];
delete remoteRes.headers['transfer-encoding'];
data = data.toString();
data = data.replace(new RegExp(protocol + '://' + host, 'g'), '');
data = data.replace(new RegExp(' target="', 'g'), ' _target="');
remoteRes.headers['content-length'] = data.length;
res.writeHead(remoteRes.statusCode, remoteRes.headers);
res.end(data, 'utf8');
};
return this;
};
exports.Transform = Transform;
var Proxy = function (host, transform, protocol, auth) {
var client = (protocol === "https") ? https : http;
protocol = protocol || "http";
this.request = function (req, res) {
req.headers.host = host;
// scrub proxy basic auth headers from upstream
delete req.headers.authorization;
var options = {
host: host,
method: req.method,
headers: req.headers,
path: req.url
};
if (auth) {
options.auth = auth;
}
var remoteReq = client.request(options);
remoteReq.on('error', console.error);
remoteReq.on('response', function (remoteRes) {
if (remoteRes.headers.location) {
remoteRes.headers.location = remoteRes.headers.location.replace(new RegExp("^" + protocol + "://" + host, "g"), '');
}
if (transform && (remoteRes.headers['content-type'] || "").match(/^text\/html/)) {
var buffer = [];
delete remoteRes.headers['content-length'];
remoteRes.on('data', function (data) {
buffer.push(data);
});
remoteRes.on('end', function () {
var data = Buffer.concat(buffer);
var transform = new Transform(res, remoteRes, protocol, host);
switch (remoteRes.headers['content-encoding']) {
case 'gzip':
zlib.gunzip(data, transform.callback);
break;
case 'deflate':
zlib.deflate(data, transform.callback);
break;
default:
transform.callback(null, data);
break;
}
});
} else {
res.writeHead(remoteRes.statusCode, remoteRes.headers);
remoteRes.on('data', function (data) {
res.write(data);
});
remoteRes.on('end', function () {
res.end();
});
}
});
req.on('data', function (data) {
remoteReq.write(data);
});
req.on('end', function () {
remoteReq.end();
});
};
return this;
};
exports.Proxy = Proxy;