The code below represents a sample proxy server that you can use to collect https requests from a source and rewrite them with different authentication fields to a destination server.
This is example code and is provided without warranty of any kind. It is NOT SUITABLE FOR PRODUCTION!
/**
* This script sets up a basic HTTPS server that proxies requests to a target server.
*
* It is provded without warranty of any kind and is NOT INTENDED FOR PRODUCTION USE.
*/
// Environment variables for proxy authentication
const CW_USERNAME = process.env.CW_USERNAME;
const CW_PASSWORD = process.env.CW_PASSWORD;
const CW_URL = process.env.CW_URL;
const BASE_USERNAME = process.env.BASE_USERNAME;
const BASE_PASSWORD = process.env.BASE_PASSWORD;
const express = require('express');
const https = require('https');
const fs = require('fs');
const basicAuth = require('express-basic-auth');
const httpProxy = require('http-proxy');
// Load credentials for HTTPS server
const httpsOptions = {
key: fs.readFileSync('path/to/your/server.key'),
cert: fs.readFileSync('path/to/your/server.cert')
};
// Set up the proxy server
const proxy = httpProxy.createProxyServer({
headers: {
'Authorization': 'Basic ' + Buffer.from(CW_USERNAME + ':' + CW_PASSWORD).toString('base64')
}
});
const app = express();
// Basic authentication middleware
app.use(basicAuth({
authorizer: (username, password) => {
const userMatches = basicAuth.safeCompare(username, BASE_USERNAME);
const passwordMatches = basicAuth.safeCompare(password, BASE_PASSWORD);
return userMatches & passwordMatches;
},
unauthorizedResponse: (req) => 'Unauthorized'
}));
// Proxy request handler
app.use((req, res) => {
delete req.headers.authorization
proxy.web(req, res, {
target: CW_URL,
changeOrigin: true
}, error => {
if (error) {
console.error('Proxy error:', error);
res.status(500).send('Proxy error');
}
});
});
// Create HTTPS server
https.createServer(httpsOptions, app).listen(3000, () => {
console.log('HTTPS server running on port 3000');
});