Skip to content

Instantly share code, notes, and snippets.

@ranwahle
Created November 7, 2019 15:19
Show Gist options
  • Save ranwahle/a291554a1e37340b3415ef02244984ca to your computer and use it in GitHub Desktop.
Save ranwahle/a291554a1e37340b3415ef02244984ca to your computer and use it in GitHub Desktop.
Self Authenticating proxy in node.js
const getArguments = require('get-arguments-lib'); // Getting port & proxy hostname for arguments
const read = require('read'); // Use to silence password
const args = getArguments(process.argv);
const port = args.port || 8080;
const hostname = args.hostname
const http = require('http');
let {username, password} = {};
read({prompt: 'Username:'}, (err, answer) => {
username = answer;
// readline.question('Password', p => password = p);
read({prompt: 'password', silent: true, default: 'test-pass'}, (err, p) => {
password = p;
});
createServer();
});
const createServer = () => {
http.createServer((req, clientRes) => {
const options = {
hostname: hostname,
port: 8080,
timeout: 20000,
path: req.url,
method: req.method,
headers: req.headers,
// Authentication
auth: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`
};
const proxy = http.request(options, function (res) {
clientRes.writeHead(res.statusCode, res.headers)
res.pipe(clientRes, {
end: true
});
});
req.pipe(proxy, {
end: true
});
}).listen(port)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment