Fix MITM on window

This commit is contained in:
decolua
2026-02-28 10:04:57 +07:00
parent 49a56612bf
commit 833069caac
22 changed files with 650 additions and 199 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
const path = require("path");
const fs = require("fs");
const os = require("os");
const { MITM_DIR } = require("../paths");
const TARGET_HOST = "daily-cloudcode-pa.googleapis.com";
@@ -8,7 +8,7 @@ const TARGET_HOST = "daily-cloudcode-pa.googleapis.com";
* Generate self-signed SSL certificate using selfsigned (pure JS, no openssl needed)
*/
async function generateCert() {
const certDir = path.join(os.homedir(), ".9router", "mitm");
const certDir = MITM_DIR;
const keyPath = path.join(certDir, "server.key");
const certPath = path.join(certDir, "server.crt");
+17 -17
View File
@@ -80,17 +80,17 @@ async function installCertMac(sudoPassword, certPath) {
}
async function installCertWindows(certPath) {
// Use PowerShell elevated to add cert to Root store
const psCommand = `Start-Process certutil -ArgumentList '-addstore','Root','${certPath.replace(/'/g, "''")}' -Verb RunAs -Wait`;
const escaped = certPath.replace(/'/g, "''");
const psCommand = `Start-Process certutil -ArgumentList '-addstore','Root','${escaped}' -Verb RunAs -Wait -WindowStyle Hidden`;
return new Promise((resolve, reject) => {
exec(`powershell -Command "${psCommand}"`, (error) => {
if (error) {
reject(new Error(`Failed to install certificate: ${error.message}`));
} else {
console.log(`✅ Installed certificate to Windows Root store`);
resolve();
exec(
`powershell -NonInteractive -WindowStyle Hidden -Command "${psCommand}"`,
{ windowsHide: true },
(error) => {
if (error) reject(new Error(`Failed to install certificate: ${error.message}`));
else { console.log("✅ Installed certificate to Windows Root store"); resolve(); }
}
});
);
});
}
@@ -125,16 +125,16 @@ async function uninstallCertMac(sudoPassword, certPath) {
}
async function uninstallCertWindows() {
const psCommand = `Start-Process certutil -ArgumentList '-delstore','Root','daily-cloudcode-pa.googleapis.com' -Verb RunAs -Wait`;
const psCommand = `Start-Process certutil -ArgumentList '-delstore','Root','daily-cloudcode-pa.googleapis.com' -Verb RunAs -Wait -WindowStyle Hidden`;
return new Promise((resolve, reject) => {
exec(`powershell -Command "${psCommand}"`, (error) => {
if (error) {
reject(new Error(`Failed to uninstall certificate: ${error.message}`));
} else {
console.log("✅ Uninstalled certificate from Windows Root store");
resolve();
exec(
`powershell -NonInteractive -WindowStyle Hidden -Command "${psCommand}"`,
{ windowsHide: true },
(error) => {
if (error) reject(new Error(`Failed to uninstall certificate: ${error.message}`));
else { console.log("✅ Uninstalled certificate from Windows Root store"); resolve(); }
}
});
);
});
}
+43 -25
View File
@@ -38,18 +38,20 @@ function execWithPassword(command, password) {
}
/**
* Execute elevated command on Windows via PowerShell RunAs
* Execute elevated command on Windows via PowerShell RunAs (hidden window)
*/
function execElevatedWindows(command) {
return new Promise((resolve, reject) => {
const psCommand = `Start-Process cmd -ArgumentList '/c','${command.replace(/'/g, "''")}' -Verb RunAs -Wait`;
exec(`powershell -Command "${psCommand}"`, (error, stdout, stderr) => {
if (error) {
reject(new Error(`Elevated command failed: ${error.message}\n${stderr}`));
} else {
resolve(stdout);
const escaped = command.replace(/'/g, "''");
const psCommand = `Start-Process cmd -ArgumentList '/c','${escaped}' -Verb RunAs -Wait -WindowStyle Hidden`;
exec(
`powershell -NonInteractive -WindowStyle Hidden -Command "${psCommand}"`,
{ windowsHide: true },
(error, stdout, stderr) => {
if (error) reject(new Error(`Elevated command failed: ${error.message}\n${stderr}`));
else resolve(stdout);
}
});
);
});
}
@@ -84,17 +86,26 @@ async function addDNSEntry(sudoPassword) {
try {
if (IS_WIN) {
// Windows: add each entry separately
for (const host of entriesToAdd) {
const entry = `127.0.0.1 ${host}`;
await execElevatedWindows(`echo ${entry} >> "${HOSTS_FILE}"`);
}
// Windows: add all entries + flush in one elevated PowerShell call (single UAC)
const hostsPath = HOSTS_FILE.replace(/'/g, "''");
const addLines = entriesToAdd.map(host =>
`$hc = Get-Content -Path '${hostsPath}' -Raw -ErrorAction SilentlyContinue; if ($hc -notmatch '${host}') { Add-Content -Path '${hostsPath}' -Value '127.0.0.1 ${host}' -Encoding UTF8 }`
).join("; ");
const psScript = `${addLines}; ipconfig /flushdns | Out-Null`;
await new Promise((resolve, reject) => {
const escaped = psScript.replace(/"/g, '\\"');
exec(
`powershell -NonInteractive -WindowStyle Hidden -Command "Start-Process powershell -ArgumentList '-NonInteractive -WindowStyle Hidden -Command \\"${escaped}\\"' -Verb RunAs -Wait"`,
{ windowsHide: true },
(error) => { if (error) reject(new Error(`Failed to add DNS: ${error.message}`)); else resolve(); }
);
});
} else {
await execWithPassword(`echo "${entries}" >> ${HOSTS_FILE}`, sudoPassword);
}
// Flush DNS cache
// Flush DNS cache (non-Windows)
if (IS_WIN) {
await execElevatedWindows("ipconfig /flushdns");
// already flushed above
} else if (IS_MAC) {
await execWithPassword("dscacheutil -flushcache && killall -HUP mDNSResponder", sudoPassword);
} else {
@@ -121,7 +132,7 @@ async function removeDNSEntry(sudoPassword) {
try {
if (IS_WIN) {
// Read in Node, filter, write to temp file, then elevated-copy over hosts
// Read in Node, filter, write to temp file, then single elevated-copy + flush (1 UAC)
const content = fs.readFileSync(HOSTS_FILE, "utf8");
const filtered = content.split(/\r?\n/).filter(l => !TARGET_HOSTS.some(host => l.includes(host))).join("\r\n");
if (!filtered.trim() && content.trim()) {
@@ -129,14 +140,21 @@ async function removeDNSEntry(sudoPassword) {
}
const tmpFile = path.join(os.tmpdir(), "hosts_filtered.tmp");
fs.writeFileSync(tmpFile, filtered, "utf8");
// Use elevated cmd to copy temp file over hosts (safe: original untouched until copy succeeds)
const psCommand = `Start-Process cmd -ArgumentList '/c','copy /Y "${tmpFile}" "${HOSTS_FILE}"' -Verb RunAs -Wait`;
const tmpEsc = tmpFile.replace(/'/g, "''");
const hostsEsc = HOSTS_FILE.replace(/'/g, "''");
// Single UAC: copy temp file over hosts + flush DNS
const psScript = `Copy-Item -Path '${tmpEsc}' -Destination '${hostsEsc}' -Force; ipconfig /flushdns | Out-Null; Remove-Item '${tmpEsc}' -ErrorAction SilentlyContinue`;
await new Promise((resolve, reject) => {
exec(`powershell -Command "${psCommand}"`, (error) => {
try { fs.unlinkSync(tmpFile); } catch { /* ignore */ }
if (error) reject(new Error(`Failed to remove DNS entry: ${error.message}`));
else resolve();
});
const escaped = psScript.replace(/"/g, '\\"');
exec(
`powershell -NonInteractive -WindowStyle Hidden -Command "Start-Process powershell -ArgumentList '-NonInteractive -WindowStyle Hidden -Command \\"${escaped}\\"' -Verb RunAs -Wait"`,
{ windowsHide: true },
(error) => {
try { fs.unlinkSync(tmpFile); } catch { /* ignore */ }
if (error) reject(new Error(`Failed to remove DNS entry: ${error.message}`));
else resolve();
}
);
});
} else {
// Remove all target hosts using sed
@@ -147,9 +165,9 @@ async function removeDNSEntry(sudoPassword) {
await execWithPassword(sedCmd, sudoPassword);
}
}
// Flush DNS cache
// Flush DNS cache (non-Windows, already flushed above for Windows)
if (IS_WIN) {
await execElevatedWindows("ipconfig /flushdns");
// already flushed above
} else if (IS_MAC) {
await execWithPassword("dscacheutil -flushcache && killall -HUP mDNSResponder", sudoPassword);
} else {
+201 -88
View File
@@ -10,9 +10,12 @@ const { addDNSEntry, removeDNSEntry, checkDNSEntry } = require("./dns/dnsConfig"
const IS_WIN = process.platform === "win32";
const { generateCert } = require("./cert/generate");
const { installCert } = require("./cert/install");
const { MITM_DIR } = require("./paths");
const MITM_PORT = 443;
const PID_FILE = path.join(os.homedir(), ".9router", "mitm", ".mitm.pid");
// Windows: node listens on 8443, netsh portproxy forwards 443→8443
const MITM_WIN_NODE_PORT = 8443;
const PID_FILE = path.join(MITM_DIR, ".mitm.pid");
// Resolve server.js path robustly:
// __dirname is unreliable inside Next.js bundles, so we use DATA_DIR env or
@@ -48,20 +51,15 @@ const ENCRYPT_SALT = "9router-mitm-pwd";
function getProcessUsingPort443() {
try {
if (IS_WIN) {
// Windows: use netstat to find PID, then tasklist to get process name
const netstatResult = execSync("netstat -ano | findstr :443", { encoding: "utf8" });
const lines = netstatResult.trim().split("\n");
if (lines.length > 0) {
// Extract PID from last column (format: TCP 0.0.0.0:443 0.0.0.0:0 LISTENING 1234)
const pidMatch = lines[0].match(/\s+(\d+)\s*$/);
if (pidMatch) {
const pid = pidMatch[1];
const tasklistResult = execSync(`tasklist /FI "PID eq ${pid}" /FO CSV /NH`, { encoding: "utf8" });
const processMatch = tasklistResult.match(/"([^"]+)"/);
if (processMatch) {
return processMatch[1].replace(".exe", "");
}
}
// Use PowerShell for precise port 443 owner lookup
const psCmd = `powershell -NonInteractive -WindowStyle Hidden -Command ` +
`"$c = Get-NetTCPConnection -LocalPort 443 -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1; if ($c) { $c.OwningProcess } else { 0 }"`;
const pidStr = execSync(psCmd, { encoding: "utf8", windowsHide: true }).trim();
const pid = parseInt(pidStr, 10);
if (pid && pid > 4) {
const tasklistResult = execSync(`tasklist /FI "PID eq ${pid}" /FO CSV /NH`, { encoding: "utf8", windowsHide: true });
const processMatch = tasklistResult.match(/"([^"]+)"/);
if (processMatch) return processMatch[1].replace(".exe", "");
}
} else {
// macOS/Linux: use lsof
@@ -208,20 +206,19 @@ function checkPort443Free() {
function getPort443Owner(sudoPassword) {
return new Promise((resolve) => {
if (IS_WIN) {
exec(`netstat -ano | findstr ":443 "`, (err, stdout) => {
if (err || !stdout.trim()) return resolve(null);
for (const line of stdout.split("\n")) {
const match = line.match(/LISTENING\s+(\d+)/i);
if (match) {
const pid = parseInt(match[1], 10);
exec(`tasklist /FI "PID eq ${pid}" /FO CSV /NH`, (e2, out2) => {
const m = out2?.match(/"([^"]+)"/);
resolve({ pid, name: m ? m[1] : "unknown" });
});
return;
}
}
resolve(null);
// Use PowerShell Get-NetTCPConnection for precise port 443 owner lookup
const psCmd = `powershell -NonInteractive -WindowStyle Hidden -Command "` +
`$c = Get-NetTCPConnection -LocalPort 443 -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1; ` +
`if ($c) { $c.OwningProcess } else { 0 }"`;
exec(psCmd, { windowsHide: true }, (err, stdout) => {
if (err) return resolve(null);
const pid = parseInt(stdout.trim(), 10);
// 0 = no owner, <=4 = System/Idle — not real port owners
if (!pid || pid <= 4) return resolve(null);
exec(`tasklist /FI "PID eq ${pid}" /FO CSV /NH`, { windowsHide: true }, (e2, out2) => {
const m = out2?.match(/"([^"]+)"/);
resolve({ pid, name: m ? m[1] : "unknown" });
});
});
} else {
// Use ps to find node process running server.js (no sudo needed)
@@ -281,12 +278,12 @@ async function killLeftoverMitm(sudoPassword) {
* Poll MITM health endpoint until server is up or timeout.
* Returns { ok, pid } on success, null on timeout.
*/
function pollMitmHealth(timeoutMs) {
function pollMitmHealth(timeoutMs, port = MITM_PORT) {
return new Promise((resolve) => {
const deadline = Date.now() + timeoutMs;
const check = () => {
const req = https.request(
{ hostname: "127.0.0.1", port: 443, path: "/_mitm_health", method: "GET", rejectUnauthorized: false },
{ hostname: "127.0.0.1", port, path: "/_mitm_health", method: "GET", rejectUnauthorized: false },
(res) => {
let body = "";
res.on("data", (d) => { body += d; });
@@ -332,8 +329,7 @@ async function getMitmStatus() {
}
const dnsConfigured = checkDNSEntry();
const certDir = path.join(os.homedir(), ".9router", "mitm");
const certExists = fs.existsSync(path.join(certDir, "server.crt"));
const certExists = fs.existsSync(path.join(MITM_DIR, "server.crt"));
return { running, pid, dnsConfigured, certExists };
}
@@ -372,71 +368,132 @@ async function startMitm(apiKey, sudoPassword) {
// Kill any leftover MITM server from a previous failed start attempt
await killLeftoverMitm(sudoPassword);
// Check port 443 availability BEFORE modifying system
// "no-permission" = EACCES: port may be held by a root process, check via lsof/netstat
const portStatus = await checkPort443Free();
if (portStatus === "in-use" || portStatus === "no-permission") {
const owner = await getPort443Owner(sudoPassword);
if (owner && owner.name === "node") {
// Orphan MITM node process — kill it and continue
console.log(`[MITM] Killing orphan node process on port 443 (PID ${owner.pid})...`);
try {
if (IS_WIN) {
await new Promise((resolve) => exec(`taskkill /F /PID ${owner.pid}`, resolve));
} else {
if (!IS_WIN) {
// Check port 443 availability — Windows handles this inside elevated script
const portStatus = await checkPort443Free();
if (portStatus === "in-use" || portStatus === "no-permission") {
const owner = await getPort443Owner(sudoPassword);
if (owner && owner.name === "node") {
// Orphan MITM node process — kill it and continue
console.log(`[MITM] Killing orphan node process on port 443 (PID ${owner.pid})...`);
try {
const { execWithPassword } = require("./dns/dnsConfig");
await execWithPassword(`kill -9 ${owner.pid}`, sudoPassword);
}
await new Promise(r => setTimeout(r, 800));
} catch {
// best effort — continue anyway
await new Promise(r => setTimeout(r, 800));
} catch { /* best effort */ }
} else if (owner) {
const shortName = owner.name.includes("/")
? owner.name.split("/").filter(Boolean).pop()
: owner.name;
throw new Error(
`Port 443 is already in use by "${shortName}" (PID ${owner.pid}). Stop that process first, then retry.`
);
}
} else if (owner) {
const shortName = owner.name.includes("/")
? owner.name.split("/").filter(Boolean).pop()
: owner.name;
throw new Error(
`Port 443 is already in use by "${shortName}" (PID ${owner.pid}). Stop that process first, then retry.`
);
}
// owner === null + no-permission → likely just needs sudo, proceed
}
// 1. Generate SSL certificate if not exists
const certPath = path.join(os.homedir(), ".9router", "mitm", "server.crt");
// 1. Generate SSL certificate if not exists (no elevation needed)
const certPath = path.join(MITM_DIR, "server.crt");
if (!fs.existsSync(certPath)) {
console.log("Generating SSL certificate...");
await generateCert();
}
// 2. Install certificate to system keychain
// Skip if db flag says installed AND cert file still exists (same cert in keychain)
const settings = _getSettings ? await _getSettings().catch(() => ({})) : {};
const certAlreadyInstalled = settings.mitmCertInstalled && fs.existsSync(certPath);
if (!certAlreadyInstalled) {
await installCert(sudoPassword, certPath);
if (_updateSettings) await _updateSettings({ mitmCertInstalled: true }).catch(() => { });
}
// 3. Add DNS entry
console.log("Adding DNS entry...");
await addDNSEntry(sudoPassword);
// 4. Spawn MITM server with sudo (port 443 requires root on macOS/Linux)
// 4. Spawn MITM server
console.log("Starting MITM server...");
if (IS_WIN) {
// Use cmd /c to set env vars inline before launching node (env vars survive RunAs)
const nodePath = process.execPath.replace(/"/g, '\\"');
const serverPath = SERVER_PATH.replace(/"/g, '\\"');
const cmdLine = `set ROUTER_API_KEY=${apiKey}&& set NODE_ENV=production&& "${nodePath}" "${serverPath}"`;
serverProcess = spawn("powershell", [
"-NoProfile", "-Command",
`Start-Process cmd -ArgumentList '/c','${cmdLine.replace(/'/g, "''")}' -Verb RunAs -WindowStyle Hidden`
], { stdio: "ignore" });
// Windows: single UAC via VBScript → elevated PowerShell script that:
// 1. Installs SSL cert 2. Adds DNS entries 3. Starts node server.js (elevated → can bind 443) 4. Writes flag
// Node polls flag file to know when server is ready, then health-checks port 443
const hostsFile = path.join(process.env.SystemRoot || "C:\\Windows", "System32", "drivers", "etc", "hosts");
const TARGET_HOSTS_WIN = ["daily-cloudcode-pa.googleapis.com", "cloudcode-pa.googleapis.com"];
// Use Chr(34) in VBScript for quotes — avoid escaping issues
const flagFile = path.join(os.tmpdir(), `mitm_ready_${Date.now()}.flag`);
// PowerShell uses single-quoted strings — escape single quotes only
const psSQ = (s) => s.replace(/'/g, "''");
const certPs = psSQ(certPath);
const hostsPs = psSQ(hostsFile);
const nodePs = psSQ(process.execPath);
const serverPs = psSQ(SERVER_PATH);
const flagPs = psSQ(flagFile);
const dnsLines = TARGET_HOSTS_WIN.map(h =>
`$hc = Get-Content -Path '${hostsPs}' -Raw -ErrorAction SilentlyContinue\n` +
`if ($hc -notmatch [regex]::Escape('${h}')) { Add-Content -Path '${hostsPs}' -Value '127.0.0.1 ${h}' -Encoding UTF8 }`
).join("\n");
const psScript = [
`# 0. Kill any orphan node process on port 443`,
`$conn = Get-NetTCPConnection -LocalPort 443 -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1`,
`if ($conn -and $conn.OwningProcess -gt 4) { Stop-Process -Id $conn.OwningProcess -Force -ErrorAction SilentlyContinue }`,
`Start-Sleep -Milliseconds 500`,
``,
`# 1. Install SSL cert to Windows Root store (always run to ensure trust)`,
`& certutil -addstore Root '${certPs}' | Out-Null`,
``,
`# 2. Add DNS entries to hosts file`,
dnsLines,
`& ipconfig /flushdns | Out-Null`,
``,
`# 3. Start node MITM server elevated (required to bind port 443)`,
`# Use cmd /c to pass env vars inline — Start-Process does not inherit current env`,
`$nodeCmd = 'set ROUTER_API_KEY=${psSQ(apiKey)}&& set NODE_ENV=production&& "${nodePs}" "${serverPs}"'`,
`Start-Process cmd -ArgumentList '/c',$nodeCmd -WindowStyle Hidden`,
``,
`# 4. Signal ready`,
`Start-Sleep -Milliseconds 500`,
`Set-Content -Path '${flagPs}' -Value 'ready' -Encoding UTF8`,
].join("\n");
const tmpPs1 = path.join(os.tmpdir(), `mitm_start_${Date.now()}.ps1`);
fs.writeFileSync(tmpPs1, psScript, "utf8");
// VBScript uses Shell.Application.ShellExecute to trigger UAC from any context
// Chr(34) = double-quote, avoids VBScript string escaping issues
const vbs = [
`Set oShell = CreateObject("Shell.Application")`,
`Dim ps`,
`ps = Chr(34) & "powershell.exe" & Chr(34)`,
`Dim args`,
`args = "-NoProfile -ExecutionPolicy Bypass -File " & Chr(34) & "${tmpPs1}" & Chr(34)`,
`oShell.ShellExecute ps, args, "", "runas", 1`,
].join("\r\n");
const tmpVbs = path.join(os.tmpdir(), `mitm_uac_${Date.now()}.vbs`);
fs.writeFileSync(tmpVbs, vbs, "utf8");
// Launch VBScript — shows UAC dialog, user confirms, script runs elevated
spawn("wscript.exe", [tmpVbs], { stdio: "ignore", windowsHide: false, detached: true }).unref();
// Poll flag file — resolves when elevated script completes
await new Promise((resolve, reject) => {
const deadline = Date.now() + 90000; // 90s: UAC wait + cert install + node start
const poll = () => {
if (fs.existsSync(flagFile)) {
try { fs.unlinkSync(flagFile); fs.unlinkSync(tmpPs1); fs.unlinkSync(tmpVbs); } catch { /* ignore */ }
return resolve();
}
if (Date.now() > deadline) return reject(new Error("Timed out waiting for UAC confirmation. Please try again."));
setTimeout(poll, 500);
};
poll();
});
if (_updateSettings) await _updateSettings({ mitmCertInstalled: true }).catch(() => { });
} else {
// macOS/Linux: install cert + add DNS (requires sudo), then spawn server
const settings = _getSettings ? await _getSettings().catch(() => ({})) : {};
const certAlreadyInstalled = settings.mitmCertInstalled && fs.existsSync(certPath);
if (!certAlreadyInstalled) {
await installCert(sudoPassword, certPath);
if (_updateSettings) await _updateSettings({ mitmCertInstalled: true }).catch(() => { });
}
console.log("Adding DNS entry...");
await addDNSEntry(sudoPassword);
// sudo -S: read password from stdin, -E: preserve env vars
// Pass ROUTER_API_KEY inline via env=... wrapper to avoid sudo stripping env
const inlineCmd = `ROUTER_API_KEY='${apiKey}' NODE_ENV='production' '${process.execPath}' '${SERVER_PATH}'`;
serverProcess = spawn(
"sudo", ["-S", "-E", "sh", "-c", inlineCmd],
@@ -447,8 +504,11 @@ async function startMitm(apiKey, sudoPassword) {
serverProcess.stdin.end();
}
serverPid = serverProcess.pid;
fs.writeFileSync(PID_FILE, String(serverPid));
// Windows: node was started by elevated script — PID comes from health check later
if (!IS_WIN && serverProcess) {
serverPid = serverProcess.pid;
fs.writeFileSync(PID_FILE, String(serverPid));
}
let startError = null;
if (!IS_WIN) {
@@ -471,8 +531,8 @@ async function startMitm(apiKey, sudoPassword) {
});
}
// Wait for server to be ready by polling health endpoint
const health = await pollMitmHealth(IS_WIN ? 12000 : 8000);
// Wait for server to be ready by polling health endpoint on port 443
const health = await pollMitmHealth(IS_WIN ? 15000 : 8000, MITM_PORT);
if (!health) {
if (IS_WIN) serverProcess = null;
@@ -483,6 +543,9 @@ async function startMitm(apiKey, sudoPassword) {
throw new Error(`MITM server failed to start. ${reason}`);
}
// On Windows, mark cert as installed after successful start
if (IS_WIN && _updateSettings) await _updateSettings({ mitmCertInstalled: true }).catch(() => { });
// On Windows, use real PID from health check (launcher exits immediately after UAC)
if (IS_WIN && health.pid) {
serverPid = health.pid;
@@ -524,8 +587,58 @@ async function stopMitm(sudoPassword) {
serverPid = null;
}
console.log("Removing DNS entry...");
await removeDNSEntry(sudoPassword);
if (IS_WIN) {
// Windows stop: remove DNS entries via elevated VBScript (1 UAC)
const hostsFile = path.join(process.env.SystemRoot || "C:\\Windows", "System32", "drivers", "etc", "hosts");
const TARGET_HOSTS_WIN = ["daily-cloudcode-pa.googleapis.com", "cloudcode-pa.googleapis.com"];
const psSQ = (s) => s.replace(/'/g, "''");
// Filter hosts content in Node (read doesn't need elevation)
let hostsContent = "";
try { hostsContent = fs.readFileSync(hostsFile, "utf8"); } catch { /* ignore */ }
const filtered = hostsContent.split(/\r?\n/)
.filter(l => !TARGET_HOSTS_WIN.some(h => l.includes(h)))
.join("\r\n");
const tmpHosts = path.join(os.tmpdir(), "mitm_hosts_clean.tmp");
fs.writeFileSync(tmpHosts, filtered, "utf8");
const flagFile = path.join(os.tmpdir(), "mitm_stop_done.flag");
const psScript = [
`Copy-Item -Path '${psSQ(tmpHosts)}' -Destination '${psSQ(hostsFile)}' -Force`,
`& ipconfig /flushdns | Out-Null`,
`Remove-Item '${psSQ(tmpHosts)}' -ErrorAction SilentlyContinue`,
`Set-Content -Path '${psSQ(flagFile)}' -Value 'done' -Encoding UTF8`,
].join("\n");
const tmpPs1 = path.join(os.tmpdir(), "mitm_stop.ps1");
fs.writeFileSync(tmpPs1, psScript, "utf8");
const vbs = [
`Set oShell = CreateObject("Shell.Application")`,
`Dim args`,
`args = "-NoProfile -ExecutionPolicy Bypass -File " & Chr(34) & "${tmpPs1}" & Chr(34)`,
`oShell.ShellExecute "powershell.exe", args, "", "runas", 1`,
].join("\r\n");
const tmpVbs = path.join(os.tmpdir(), "mitm_stop_uac.vbs");
fs.writeFileSync(tmpVbs, vbs, "utf8");
spawn("wscript.exe", [tmpVbs], { stdio: "ignore", windowsHide: false, detached: true }).unref();
// Poll flag — best effort, don't block UI if user cancels UAC
await new Promise((resolve) => {
const deadline = Date.now() + 30000;
const poll = () => {
if (fs.existsSync(flagFile)) {
try { fs.unlinkSync(flagFile); fs.unlinkSync(tmpPs1); fs.unlinkSync(tmpVbs); } catch { /* ignore */ }
return resolve();
}
if (Date.now() > deadline) return resolve();
setTimeout(poll, 500);
};
poll();
});
} else {
console.log("Removing DNS entry...");
await removeDNSEntry(sudoPassword);
}
try { fs.unlinkSync(PID_FILE); } catch { /* ignore */ }
+16
View File
@@ -0,0 +1,16 @@
const path = require("path");
const os = require("os");
// Single source of truth for data directory — matches localDb.js logic
function getDataDir() {
if (process.env.DATA_DIR) return process.env.DATA_DIR;
if (process.platform === "win32") {
return path.join(process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming"), "9router");
}
return path.join(os.homedir(), ".9router");
}
const DATA_DIR = getDataDir();
const MITM_DIR = path.join(DATA_DIR, "mitm");
module.exports = { DATA_DIR, MITM_DIR };
+12 -12
View File
@@ -3,8 +3,6 @@ const fs = require("fs");
const path = require("path");
const dns = require("dns");
const { promisify } = require("util");
const os = require("os");
// Configuration
const INTERNAL_REQUEST_HEADER = { name: "x-request-source", value: "local" };
const TARGET_HOSTS = [
@@ -14,7 +12,8 @@ const TARGET_HOSTS = [
const LOCAL_PORT = 443;
const ROUTER_URL = "http://localhost:20128/v1/chat/completions";
const API_KEY = process.env.ROUTER_API_KEY;
const DB_FILE = path.join(os.homedir(), ".9router", "db.json");
const { DATA_DIR, MITM_DIR } = require("./paths");
const DB_FILE = path.join(DATA_DIR, "db.json");
// Toggle logging (set true to enable file logging for debugging)
const ENABLE_FILE_LOG = false;
@@ -25,7 +24,7 @@ if (!API_KEY) {
}
// Load SSL certificates
const certDir = path.join(os.homedir(), ".9router", "mitm");
const certDir = MITM_DIR;
let sslOptions;
try {
sslOptions = {
@@ -92,17 +91,18 @@ function collectBodyRaw(req) {
});
}
function extractModel(body) {
try {
return JSON.parse(body.toString()).model || null;
} catch {
return null;
}
// Extract model from URL path (Gemini format: /v1beta/models/gemini-2.0-flash:generateContent)
// Fallback to body.model (OpenAI format)
function extractModel(url, body) {
const urlMatch = url.match(/\/models\/([^/:]+)/);
if (urlMatch) return urlMatch[1];
try { return JSON.parse(body.toString()).model || null; } catch { return null; }
}
function getMappedModel(model) {
if (!model) return null;
try {
if (!fs.existsSync(DB_FILE)) return null;
const db = JSON.parse(fs.readFileSync(DB_FILE, "utf-8"));
return db.mitmAlias?.antigravity?.[model] || null;
} catch {
@@ -200,8 +200,8 @@ const server = https.createServer(sslOptions, async (req, res) => {
return passthrough(req, res, bodyBuffer);
}
const model = extractModel(bodyBuffer);
console.log(`📡 ${model} (passthrough)`);
const model = extractModel(req.url, bodyBuffer);
console.log(`📡 intercepted: ${req.url} | model: ${model}`);
const mappedModel = getMappedModel(model);
if (!mappedModel) {