forked from netptop/siteproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Proxy.js
288 lines (275 loc) · 11.5 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
var express = require('express');
var proxy = require('http-proxy-middleware');
const https = require('https')
const zlib = require("zlib")
const cookiejar = require('cookiejar')
const iconv = require('iconv-lite')
const {logSave, logGet, logClear} = require('./logger')
const {CookieAccessInfo, CookieJar, Cookie} = cookiejar
function countUtf8Bytes(s) {
var b = 0, i = 0, c
for(;c=s.charCodeAt(i++);b+=c>>11?3:c>>7?2:1);
return b
}
var enableCors = function(req, res) {
if (req.headers['access-control-request-method']) {
res.setHeader('access-control-allow-methods', req.headers['access-control-request-method']);
}
if (req.headers['access-control-request-headers']) {
res.setHeader('access-control-allow-headers', req.headers['access-control-request-headers']);
}
if (req.headers.origin) {
res.setHeader('access-control-allow-origin', req.headers.origin);
res.setHeader('access-control-allow-credentials', 'true');
}
};
// only support https for now.
let router = (req) => { //return target
let {host, httpType} = getHostFromReq(req)
let target = `${httpType}://${host}`
logSave(`router, target:${target}, req.url:${req.url}`)
return target
}
let getHostFromReq = (req) => { //return target
// url: http://127.0.0.1:8011/https/www.youtube.com/xxx/xxx/...
let https_prefix = '/https/'
let http_prefix = '/http/'
let host = ''
let httpType = 'https'
if (req.url.startsWith(https_prefix)) {
host = req.url.slice(https_prefix.length, req.url.length)
if (host.indexOf('/') !== -1) {
host = host.slice(0, host.indexOf('/'))
}
} else if (req.url.startsWith(http_prefix)) {
host = req.url.slice(http_prefix.length, req.url.length)
if (host.indexOf('/') !== -1) {
host = host.slice(0, host.indexOf('/'))
}
httpType = 'http'
} else if (req.headers['referer'] && req.headers['referer'].indexOf('https/') !== -1) {
let start = req.headers['referer'].indexOf('https/') + 6
host = req.headers['referer'].slice(start, req.headers['referer'].length)
let end = host.indexOf('/')
if (end === -1) {
end = host.length
}
host = host.slice(0, end)
logSave(`============= host:${host}, req referer:${req.headers['referer']}`)
} else if (req.headers['referer'] && req.headers['referer'].indexOf('http/') !== -1) {
let start = req.headers['referer'].indexOf('http/') + 5
host = req.headers['referer'].slice(start, req.headers['referer'].length)
let end = host.indexOf('/')
if (end === -1) {
end = host.length
}
host = host.slice(0, end)
httpType = 'http'
logSave(`============= host:${host}, req referer:${req.headers['referer']}`)
} else if (req.headers['referer']) { // 'zh.wikipedia.org'
host = req.headers['referer']
httpType = 'https'
}
logSave(`getHostFromReq, req.url:${req.url}, referer:${req.headers['referer']}, host:${host}, httpType:${httpType}`)
return {host, httpType}
}
let Proxy = ({httpprefix, serverName, port, cookieDomainRewrite, locationReplaceMap302, regReplaceMap, siteSpecificReplace, pathReplace}) => {
let handleRespond = ({req, res, body, gbFlag}) => {
// logSave("res from proxied server:", body);
let myRe
let {host, httpType} = getHostFromReq(req)
let location = res.getHeaders()['location']
if (res.statusCode == '301' || res.statusCode == '302' || res.statusCode == '307' || res.statusCode == '308') {
location = locationReplaceMap302({location, serverName, httpprefix, host, httpType})
logSave(`after replacement, location=${location}`)
res.setHeader('location', location)
// return
}
// logSave(`HandleRespond(), req.url:${req.url}, req.headers:${JSON.stringify(req.headers)}`)
for(let key in regReplaceMap) {
myRe = new RegExp(key, 'g') // match group
body = body.replace(myRe, regReplaceMap[key])
}
logSave(`##### host:${host}`)
if (host) {
body = pathReplace({host, httpType, body})
}
// remove duplicate /https/siteproxylocal.now.sh:443
myRe = new RegExp(`/${httpprefix}/${serverName}:${port}`, 'g') // match group
body = body.replace(myRe, '')
// put siteSpecificReplace at end
Object.keys(siteSpecificReplace).forEach( (site) => {
if (req.url.indexOf(site) !== -1 || req.headers['referer'].indexOf(site) !== -1) {
keys = Object.keys(siteSpecificReplace[site])
keys.forEach( key => {
myRe = new RegExp(key, 'g') // match group
body = body.replace(myRe, siteSpecificReplace[site][key])
})
}
})
if (gbFlag) {
body = iconv.encode(body, 'gbk')
}
body = zlib.gzipSync(body)
res.setHeader('content-encoding', 'gzip');
logSave(`handleRespond: res.headers:${JSON.stringify(res.getHeaders())}`)
// console.log(`1=================${logGet()}`)
res.end(body);
}
let p = proxy({
target: `https://www.google.com`,
router,
/*
pathRewrite: (path, req) => {
let {host, httpType} = getHostFromReq(req)
let newpath = path.replace(`/https/${host}`, '') || '/'
logSave(`newpath:${newpath}`)
return newpath
},
*/
// hostRewrite: true,
// autoRewrite: true,
protocolRewrite: true,
// followRedirects: true,
cookieDomainRewrite,
secure: false,
changeOrigin: true,
debug:true,
onError: (err, req, res) => {
console.log(`onerror: ${err}`)
try {
res.status(404).send(`onError: ${err}`)
} catch(e) {
console.log(`error of sending 404: ${e}`)
}
},
selfHandleResponse: true, // so that the onProxyRes takes care of sending the response
onProxyRes: (proxyRes, req, res) => {
let {host, httpType} = getHostFromReq(req)
logSave(`proxyRes.status:${proxyRes.statusCode} proxyRes.headers:${JSON.stringify(proxyRes.headers)}`)
var body = Buffer.from('');
proxyRes.on('data', function(data) {
body = Buffer.concat([body, data]);
})
proxyRes.on('end', function() {
let gbFlag = false
if (proxyRes.headers["content-encoding"] === 'gzip' ||
proxyRes.headers["content-encoding"] === 'br') {
let gunzipped
try {
if (proxyRes.headers["content-encoding"] === 'br') {
gunzipped = zlib.brotliDecompressSync(body)
logSave(`zlib.brotli...`)
} else { //gzip
gunzipped = zlib.gunzipSync(body)
logSave(`zlib.gunzip...`)
}
} catch(e) {
res.status(404).send(`error:${e}`)
return
}
if (proxyRes.headers["content-type"].indexOf('text/') !== -1 ||
proxyRes.headers["content-type"].indexOf('javascript') !== -1 ||
proxyRes.headers["content-type"].indexOf('json') !== -1) {
if (!gunzipped) {
res.status(404).send()
return
}
logSave(`utf-8 text...`)
let originBody = gunzipped
body = gunzipped.toString('utf-8');
if (body.indexOf('="text/html; charset=gb') !== -1 ||
body.indexOf(' charset="gb') !== -1 ||
body.indexOf('=\'text/html; charset=gb') !== -1) {
logSave(`gb2312 found...`)
body = iconv.decode(originBody, 'gbk')
gbFlag = true
}
handleRespond({req, res, body, gbFlag})
} else {
// console.log(`2========>${logGet()}`)
res.end(body)
}
} else if (proxyRes.statusCode === 301 || proxyRes.statusCode === 302 || proxyRes.statusCode === 307 || proxyRes.statusCode === 308 ||
(proxyRes.headers["content-type"] &&
(proxyRes.headers["content-type"].indexOf('text/') !== -1 ||
proxyRes.headers["content-type"].indexOf('javascript') !== -1 ||
proxyRes.headers["content-type"].indexOf('json') !== -1))) {
logSave(`utf-8 text...`)
let originBody = body
body = body.toString('utf-8');
if (body.indexOf('="text/html; charset=gb') !== -1 ||
body.indexOf(' charset="gb') !== -1 ||
body.indexOf('=\'text/html; charset=gb') !== -1) {
logSave(`gb2312 found...`)
body = iconv.decode(originBody, 'gbk')
gbFlag = true
}
handleRespond({req, res, body, gbFlag})
} else {
// console.log(`3========>${logGet()}`)
res.end(body)
}
})
const setCookieHeaders = proxyRes.headers['set-cookie'] || []
const modifiedSetCookieHeaders = setCookieHeaders
.map(str => new cookiejar.Cookie(str))
.map(cookie => {
logSave(`cookie:${JSON.stringify(cookie)}`)
if (cookie.path && cookie.path[0] === '/') {
cookie.domain = `127.0.0.1`
cookie.path = `${req.url}`
}
cookie.secure = false
return cookie
})
.map(cookie => cookie.toString())
proxyRes.headers['set-cookie'] = modifiedSetCookieHeaders
Object.keys(proxyRes.headers).forEach(function (key) {
if (key === 'content-encoding' ||
key === 'content-security-policy' ||
key === 'x-frame-options' ||
(key === 'content-length' && proxyRes.headers["content-type"] &&
(proxyRes.headers["content-type"].indexOf('text/') !== -1 ||
proxyRes.headers["content-type"].indexOf('javascript') !== -1 ||
proxyRes.headers["content-type"].indexOf('json') !== -1))) {
logSave(`skip header:${key}`)
return
}
// res.append(key, proxyRes.headers[key]);
res.setHeader(key, proxyRes.headers[key]);
});
res.statusCode = proxyRes.statusCode
logSave(`res.status:${res.statusCode} res.url:${res.url}, res.headers:${JSON.stringify(res.getHeaders())}`)
},
onProxyReq: (proxyReq, req, res) => {
let {host, httpType} = getHostFromReq(req)
if (host == '' || host.indexOf('.') === -1) {
res.status(404).send()
return
}
logClear()
req.headers['host'] = host
req.headers['referer'] = host
if ('origin' in req.headers) {
req.headers['origin'] = host
}
let newpath = req.url.replace(`/${httpType}/${host}`, '') || '/'
logSave(`httpType:${httpType}, host:${host}, req.url:${req.url}, req.headers:${JSON.stringify(req.headers)}`)
Object.keys(req.headers).forEach(function (key) {
proxyReq.setHeader(key, req.headers[key]);
});
proxyReq.setHeader('Accept-Encoding', 'gzip')
proxyReq.setHeader('referer', host)
proxyReq.path = newpath
logSave(`req host:${host}, req.url:${req.url}, proxyReq.path:${proxyReq.path}, proxyReq.url:${proxyReq.url} proxyReq headers:${JSON.stringify(proxyReq.getHeaders())}`)
if(host === '' || !host) {
logSave(`------------------ sending status 404`)
res.status(404).send()
res.end()
}
},
})
return p
}
module.exports = Proxy