Repository navigation
Expand file tree
/
Copy pathproxy.js
More file actions
78 lines (64 loc) · 2.18 KB
/
Copy pathproxy.js
File metadata and controls
78 lines (64 loc) · 2.18 KB
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
// proxy.js
const http = require('http');
const https = require('https');
// Bypass SSL certificate name mismatch verification
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const PORT = process.env.PORT || 3000;
const TARGET_HOST = process.env.TARGET_HOST || 'www.pinum.org.pk';
const TARGET_PORT = process.env.TARGET_PORT || 443;
const server = http.createServer((req, res) => {
console.log(`[Proxy] ${req.method} ${req.url}`);
// Set CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Accept');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
const options = {
hostname: TARGET_HOST,
port: TARGET_PORT,
path: req.url,
method: req.method,
headers: {
...req.headers,
host: TARGET_PORT === 443 ? TARGET_HOST : `${TARGET_HOST}:${TARGET_PORT}`,
},
rejectUnauthorized: false,
};
req.on('error', (err) => {
console.error('[Request Error]', err);
});
res.on('error', (err) => {
console.error('[Response Error]', err);
});
const proxyReq = https.request(options, (proxyRes) => {
proxyRes.on('error', (err) => {
console.error('[Proxy Response Error]', err);
});
// Forward headers and status
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
req.pipe(proxyReq, { end: true });
proxyReq.on('error', (err) => {
console.error('[Proxy Error]', err);
if (!res.headersSent) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
}
res.end('Proxy Error: ' + err.message);
});
});
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
console.warn(`[Proxy Warning] Port ${PORT} is already in use. Assuming proxy is already running.`);
} else {
console.error('[Proxy Server Error]', err);
}
});
server.listen(PORT, () => {
console.log(`Local PINUM API Proxy Server running at http://localhost:${PORT}`);
console.log(`Forwarding requests to https://${TARGET_HOST}:${TARGET_PORT} with SSL verification disabled.`);
});