forked from netptop/siteproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Proxy.js
355 lines (339 loc) · 14.4 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
var express = require('express');
var proxy = require('http-proxy-middleware');
const zlib = require("zlib")
const parse = require('url-parse')
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');
}
};
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'
var parsed = parse(req.headers['referer'])
if(parsed.hostname) {
host = parsed.hostname
httpType = parsed.protocol.replace(':', '')
} else {
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 = ({urlModify, 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 == '303' ||res.statusCode == '307' || res.statusCode == '308') {
location = locationReplaceMap302({location, serverName, httpprefix, host, httpType})
logSave(`after replacement, location=${location}`)
try {
res.setHeader('location', location)
} catch(e) {
logSave(`error: ${e}`)
return
}
// 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}.*?/`, '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')
}
// googlevideo.com manual redirection
if (typeof(body) === 'string' && body.startsWith(`${httpprefix}://${serverName}`) && body.indexOf('googlevideo.com') !== -1) {
// need to manually redirect it for youtube workaround.
console.log(`============== redirect googlevideo.com`)
try {
res.setHeader('location', body)
} catch(e) {
logSave(`error: ${e}`)
return
}
res.statusCode = '302'
}
body = zlib.gzipSync(body)
try {
res.setHeader('content-encoding', 'gzip');
logSave(`handleRespond: res.statusCode:${res.statusCode}, res.headers:${JSON.stringify(res.getHeaders())}`)
if (req.headers['debugflag']==='true') {
res.removeHeader('content-encoding')
res.setHeader('content-type','text/plain')
body=logGet()
}
res.end(body);
} catch(e) {
logSave(`error: ${e}`)
}
}
// only support https for now.
const router = (req) => { //return target
let myRe = new RegExp(`/${httpprefix}/${serverName}.*?/`, 'g') // match group
req.url = req.url.replace(myRe, '/')
let {host, httpType} = getHostFromReq(req)
let target = `${httpType}://${host}`
logSave(`router, target:${target}, req.url:${req.url}`)
return target
}
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) => {
logSave(`onerror: ${JSON.stringify(err)}`)
try {
if ((err.code && err.code === 'ECONNREFUSED') ||
(err.reason && err.reason.indexOf('Expected') === -1)) {
res.status(404).send(`{"error": "${err}"}`)
}
} catch(e) {
logSave(`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)}`)
let 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('urlencoded') !== -1 ||
proxyRes.headers["content-type"].indexOf('json') !== -1) {
if (!gunzipped) {
res.status(404).send(`{"error":"failed unzip"}`)
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()}`)
let key = "content-encoding"
if(key in proxyRes.headers) {
res.setHeader(key, proxyRes.headers[key]);
}
logSave(`2: res.headers:${JSON.stringify(res.getHeaders())}`)
if (req.headers['debugflag']==='true') {
res.removeHeader('content-encoding')
res.setHeader('content-type','text/plain')
body=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 {
logSave(`3========>${logGet()}`)
if (req.headers['debugflag']==='true') {
res.removeHeader('content-encoding')
res.setHeader('content-type','text/plain')
body=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 = `${serverName}`
}
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
}
try {
res.setHeader(key, proxyRes.headers[key]);
} catch(e) {
logSave(`error:${e}`)
return
}
});
res.statusCode = proxyRes.statusCode
logSave(`res.status:${res.statusCode} res.url:${res.url}, res.headers:${JSON.stringify(res.getHeaders())}`)
},
onProxyReq: (proxyReq, req, res) => {
let myRe = new RegExp(`/${httpprefix}/${serverName}.*?/`, 'g') // match group
req.url = req.url.replace(myRe, '/')
let fwdStr = req.headers['X-Forwarded-For'] || req.headers['x-forwarded-for']
let {host, httpType} = getHostFromReq(req)
if (host.indexOf(serverName) !== -1 || // we cannot request resource from proxy itself
host == '' || host.indexOf('.') === -1 || (fwdStr && fwdStr.split(',').length > 3)) { // too many forwardings
res.status(404).send("{}")
return
}
logClear()
req.headers['host'] = host
req.headers['referer'] = host
if ('origin' in req.headers) {
req.headers['origin'] = host
}
proxyReq.path = proxyReq.url = urlModify({httpType, host, url:req.url})
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) {
if (key.indexOf('x-') === 0) {
logSave(`remove key=${key},`)
proxyReq.removeHeader(key)
}
logSave(`set key=${key},`)
proxyReq.setHeader(key, req.headers[key])
})
proxyReq.setHeader('Accept-Encoding', 'gzip')
proxyReq.setHeader('referer', host)
logSave(`req host:${host}, req.url:${req.url}, proxyReq.query:${proxyReq.query} 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