-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlocal-cf.js
74 lines (63 loc) · 2.04 KB
/
local-cf.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
var httpProxy = require('http-proxy');
const http = require('http');
const conf = require('./config.json')
const staticLookup = (ip, v) => (hostname, opts, cb) => cb(null, ip, v || 4);
function encryptUrl(str) {
const a = str.split('').reverse().join('');
return encodeURIComponent(a);
}
const httpAgent = new http.Agent({
keepAlive: true,
keepAliveMsecs: 50 * 1000,
// lookup: staticLookup(conf.cfip, 4),
lookup: staticLookup(conf.cfip6, 6),
});
const proxy = httpProxy.createProxyServer({
target: conf.cfOrigin1,
agent: httpAgent,
changeOrigin: true,
toProxy: true
}); // See (†)
const server = http.createServer(function (req, res) {
if (req.method.toLowerCase() === 'options') {
let allowHeaders = "*";
const accessHeaders = req.headers['Access-Control-Request-Headers']
if (accessHeaders) {
allowHeaders = accessHeaders
}
res.setHeader('access-control-allow-origin', '*')
res.setHeader('Access-Control-Allow-Headers', allowHeaders)
res.setHeader('access-control-allow-methods', "GET,POST,PUT,PATCH,TRACE,DELETE,HEAD,OPTIONS")
res.setHeader('access-control-max-age', '1728000')
res.statusCode = 204
res.end('')
return
}
let url1 = req.url.replace(/^\//, '')
url1 = url1.replace(/(^https:)\/([^/])/, 'https://$2')
const url2 = encryptUrl(url1)
req.url = '/' +url2
res.setHeader('access-control-allow-origin', '*')
proxy.web(req, res, {
target: conf.cfOrigin1,
agent: httpAgent,
changeOrigin: true,
toProxy: true,
}, function (err) {
// Now you can get the err
// and handle it by your self
// if (err) throw err;
// res.writeHead(502);
res.end("There was an error proxying your request");
});
});
server.on('upgrade', function (req, socket, head) {
let url1 = req.url.replace(/^\//, '')
url1 = url1.replace(/(^https:)\/([^/])/, 'https://$2')
req.headers['X-Forwarded-For'] = conf.cfip6
const url2 = encryptUrl(url1)
req.url = '/' + url2
proxy.ws(req, socket, head);
});
server.listen(conf.cfPort);
console.log('listen ' + conf.cfPort)