Skip to content

Instantly share code, notes, and snippets.

@nondanee
Created March 22, 2020 07:57
Show Gist options
  • Save nondanee/b064d01dfeae20e418b32df1ef85a0ef to your computer and use it in GitHub Desktop.
Save nondanee/b064d01dfeae20e418b32df1ef85a0ef to your computer and use it in GitHub Desktop.
Simple Proxy Server
const net = require('net')
const http = require('http')
const parse = require('url').parse
const port = parseInt(process.argv[2]) || 8080
const server = http.createServer().listen(port)
// MITM Mode
server.on('request', (req, res) => {
if (!req.url.startsWith('http://')) return res.end('invalid')
const url = parse(req.url)
console.log('MITM', '>', url.hostname)
req.pipe(
http.request(Object.assign(url, { method: req.method, headers: req.headers }))
.on('response', proxyRes => {
res.writeHead(proxyRes.statusCode, proxyRes.headers)
proxyRes.pipe(res)
})
.on('error', () => res.end())
)
})
// Tunnel Mode
server.on('connect', (req, socket, head) => {
const url = parse('https://' + req.url)
console.log('TUNNEL', '>', url.hostname)
const proxySocket = net.connect(url.port, url.hostname)
.on('connect', () => {
socket.write('HTTP/1.1 200 Connection established\r\n\r\n')
proxySocket.write(head)
proxySocket.pipe(socket)
socket.pipe(proxySocket)
})
.on('error', () => socket.end())
socket.on('error', () => socket.end())
})
console.log(`HTTP Server running @ http://0.0.0.0:${port}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment