I'm developing an Electron application that uses the http-mitm-proxy (https://github.com/joeferner/node-http-mitm-proxy) library for intercepting and handling web requests. My application is set up to create a custom proxy to intercept web traffic. So far, I've successfully managed to intercept HTTP traffic, but I'm encountering issues when trying to intercept HTTPS traffic.
The core problem seems to be that while HTTP requests are handled perfectly, HTTPS requests are not going through as expected. After some research and debugging, I've concluded that the likely culprit is the SSL certificate: it appears I need to install or trust the SSL certificate generated by http-mitm-proxy within the Electron browser for HTTPS interception to work correctly.
Below is the full code snippet of my current setup:
const { app, BrowserWindow, session } = require('electron');
const Proxy = require('http-mitm-proxy').Proxy;
const path = require('path');
const fs = require('fs');
const proxy = new Proxy();
const logFilePath = path.join(__dirname, 'requests.log'); // Path to the log file
app.on('ready', async () => {
// Start the MITM proxy
proxy.listen({ port: 8088, sslCaDir: path.join(__dirname, 'certs') }, () => {
console.log('MITM proxy listening on port 8080');
});
// Intercept and log all requests to a file
proxy.onRequest((ctx, callback) => {
const requestDetails = `Received request: ${ctx.clientToProxyRequest.method} ${ctx.clientToProxyRequest.headers.host}${ctx.clientToProxyRequest.url}\n`;
console.log('Request intercepted:', requestDetails);
// Append the request details to the log file
fs.appendFile(logFilePath, requestDetails, (err) => {
if (err) {
console.error('Error writing to log file:', err);
}
});
return callback();
});
// Ensure the default session is ready before setting the proxy
const proxyURL = 'http=127.0.0.1:8080;https=127.0.0.1:8088';
await session.defaultSession.setProxy({ proxyRules: proxyURL });
createWindow();
});
function createWindow() {
// Create a BrowserWindow instance
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
// Important: Use the default session for the proxy settings
}
});
// Load a specific website using the proxy
// mainWindow.loadURL('http://example.com'); //works
mainWindow.loadURL('https://example.com'); //dont work
}