|
|
#!/usr/bin/env node |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import http from 'http'; |
|
|
import net from 'net'; |
|
|
import { URL } from 'url'; |
|
|
import console from 'console'; |
|
|
|
|
|
const PROXY_PORT = 8877; |
|
|
const ALLOWED_DOMAINS = ['example.com', 'googleapis.com']; |
|
|
const ALLOWED_PORT = '443'; |
|
|
|
|
|
const server = http.createServer((req, res) => { |
|
|
|
|
|
console.log( |
|
|
`[PROXY] Denying non-CONNECT request for: ${req.method} ${req.url}`, |
|
|
); |
|
|
res.writeHead(405, { 'Content-Type': 'text/plain' }); |
|
|
res.end('Method Not Allowed'); |
|
|
}); |
|
|
|
|
|
server.on('connect', (req, clientSocket, head) => { |
|
|
|
|
|
const { port, hostname } = new URL(`http://${req.url}`); |
|
|
|
|
|
console.log(`[PROXY] Intercepted CONNECT request for: ${hostname}:${port}`); |
|
|
|
|
|
if ( |
|
|
ALLOWED_DOMAINS.some( |
|
|
(domain) => hostname == domain || hostname.endsWith(`.${domain}`), |
|
|
) && |
|
|
port === ALLOWED_PORT |
|
|
) { |
|
|
console.log(`[PROXY] Allowing connection to ${hostname}:${port}`); |
|
|
|
|
|
|
|
|
const serverSocket = net.connect(port, hostname, () => { |
|
|
clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n'); |
|
|
|
|
|
serverSocket.write(head); |
|
|
serverSocket.pipe(clientSocket); |
|
|
clientSocket.pipe(serverSocket); |
|
|
}); |
|
|
|
|
|
serverSocket.on('error', (err) => { |
|
|
console.error(`[PROXY] Error connecting to destination: ${err.message}`); |
|
|
clientSocket.end(`HTTP/1.1 502 Bad Gateway\r\n\r\n`); |
|
|
}); |
|
|
} else { |
|
|
console.log(`[PROXY] Denying connection to ${hostname}:${port}`); |
|
|
clientSocket.end('HTTP/1.1 403 Forbidden\r\n\r\n'); |
|
|
} |
|
|
|
|
|
clientSocket.on('error', (err) => { |
|
|
|
|
|
console.error(`[PROXY] Client socket error: ${err.message}`); |
|
|
}); |
|
|
}); |
|
|
|
|
|
server.listen(PROXY_PORT, () => { |
|
|
const address = server.address(); |
|
|
console.log(`[PROXY] Proxy listening on ${address.address}:${address.port}`); |
|
|
console.log( |
|
|
`[PROXY] Allowing HTTPS connections to domains: ${ALLOWED_DOMAINS.join(', ')}`, |
|
|
); |
|
|
}); |
|
|
|