Refactor global styles and enhance MITM functionality

- Updated global CSS to implement a new brand color palette and improve light/dark theme consistency.
- Enhanced the MitmServerCard component to provide clearer user feedback regarding admin privileges.
- Filtered LLM combos in the CombosPage to ensure only relevant data is displayed.
- Improved APIPageClient layout for better usability and visual consistency.
- Added functionality to save and load DNS tool states in the MITM manager.
- Updated OAuth configuration URLs for Qwen to reflect the new endpoint structure.
- Refined tunnel management logic to improve reliability and user experience.
This commit is contained in:
decolua
2026-05-03 18:00:35 +07:00
parent 1686adc704
commit 6cdf40b44e
40 changed files with 1029 additions and 762 deletions
+5 -3
View File
@@ -152,8 +152,10 @@ export function spawnUpdaterAndExit(packageName = UPDATER_CONFIG.npmPackageName)
const updaterPath = ensureRuntimeUpdater(resolveBundledUpdaterPath());
const isTray = process.env.TRAY_MODE === "1";
const relaunch = resolveRelaunchCommand();
// Only relaunch in tray/background mode — foreground CLI loses TTY on exit
const relaunchArgs = isTray ? [...relaunch.args, "--tray", "--skip-update"] : [];
// Relaunch matching original env: tray stays tray, foreground stays foreground
const relaunchArgs = isTray
? [...relaunch.args, "--tray", "--skip-update"]
: [...relaunch.args, "--skip-update"];
spawn(process.execPath, [updaterPath], {
detached: true,
@@ -171,7 +173,7 @@ export function spawnUpdaterAndExit(packageName = UPDATER_CONFIG.npmPackageName)
UPDATER_WAIT_MAX_MS: String(UPDATER_CONFIG.waitForExitMaxMs),
UPDATER_WAIT_CHECK_MS: String(UPDATER_CONFIG.waitForExitCheckMs),
UPDATER_APP_PORT: String(UPDATER_CONFIG.appPort),
UPDATER_RELAUNCH: isTray ? "1" : "0",
UPDATER_RELAUNCH: "1",
UPDATER_RELAUNCH_CMD: relaunch.cmd,
UPDATER_RELAUNCH_ARGS: JSON.stringify(relaunchArgs),
},
+1
View File
@@ -36,6 +36,7 @@ const DEFAULT_SETTINGS = {
outboundProxyUrl: "",
outboundNoProxy: "",
mitmRouterBaseUrl: DEFAULT_MITM_ROUTER_BASE,
dnsToolEnabled: {},
rtkEnabled: true,
cavemanEnabled: false,
cavemanLevel: "full",
+2 -2
View File
@@ -57,8 +57,8 @@ export const GEMINI_CONFIG = {
// Qwen OAuth Configuration (Device Code Flow with PKCE)
export const QWEN_CONFIG = {
clientId: "f0304373b74a44d2b584a3fb70ca9e56",
deviceCodeUrl: "https://qwen.ai/api/v1/oauth2/device/code",
tokenUrl: "https://qwen.ai/api/v1/oauth2/token",
deviceCodeUrl: "https://chat.qwen.ai/api/v1/oauth2/device/code",
tokenUrl: "https://chat.qwen.ai/api/v1/oauth2/token",
scope: "openid profile email model.completion",
codeChallengeMethod: "S256",
};
+2 -4
View File
@@ -257,10 +257,8 @@ export async function spawnCloudflared(tunnelToken) {
}
return;
}
// Only notify on unexpected exit AFTER successful connection
if (wasConnected && unexpectedExitHandler) {
unexpectedExitHandler();
}
// Watchdog (initializeApp) handles recovery — no auto-reconnect here
if (wasConnected && unexpectedExitHandler) unexpectedExitHandler();
});
});
}
+67
View File
@@ -0,0 +1,67 @@
import net from "net";
import dns from "dns";
import { INTERNET_CHECK, HEALTH_CHECK } from "./tunnelConfig.js";
// Force public DNS to bypass OS negative cache (mDNSResponder holds NXDOMAIN)
const resolver = new dns.promises.Resolver();
resolver.setServers(["1.1.1.1", "1.0.0.1", "8.8.8.8"]);
export function checkInternet() {
return new Promise((resolve) => {
const socket = new net.Socket();
let done = false;
const finish = (ok) => {
if (done) return;
done = true;
try { socket.destroy(); } catch { /* ignore */ }
resolve(ok);
};
socket.setTimeout(INTERNET_CHECK.timeoutMs);
socket.once("connect", () => finish(true));
socket.once("timeout", () => finish(false));
socket.once("error", () => finish(false));
try { socket.connect(INTERNET_CHECK.port, INTERNET_CHECK.host); }
catch { finish(false); }
});
}
async function resolveDns(hostname, timeoutMs) {
try {
await Promise.race([
resolver.resolve4(hostname),
new Promise((_, rej) => setTimeout(() => rej(new Error("dns timeout")), timeoutMs)),
]);
return true;
} catch {
return false;
}
}
// Single health probe: DNS via 1.1.1.1 → fetch /api/health
export async function probeUrlAlive(url) {
if (!url) return false;
let hostname;
try { hostname = new URL(url).hostname; } catch { return false; }
if (!await resolveDns(hostname, HEALTH_CHECK.dnsTimeoutMs)) return false;
try {
const res = await fetch(`${url}/api/health`, {
signal: AbortSignal.timeout(HEALTH_CHECK.fetchTimeoutMs),
});
return res.ok;
} catch {
return false;
}
}
// Poll until tunnel responds /api/health, or timeout. Cancellable via token.
export async function waitForHealth(url, cancelToken = { cancelled: false }) {
const start = Date.now();
while (Date.now() - start < HEALTH_CHECK.timeoutMs) {
if (cancelToken.cancelled) throw new Error("cancelled");
if (await probeUrlAlive(url)) return true;
await new Promise((r) => setTimeout(r, HEALTH_CHECK.intervalMs));
}
throw new Error(`Health check timeout after ${HEALTH_CHECK.timeoutMs}ms`);
}
+18
View File
@@ -0,0 +1,18 @@
// Tunnel + Tailscale shared config (all values in ms)
export const HEALTH_CHECK = {
intervalMs: 2000,
timeoutMs: 180000,
fetchTimeoutMs: 5000,
dnsTimeoutMs: 2000,
};
export const INTERNET_CHECK = {
host: "1.1.1.1",
port: 443,
timeoutMs: 3000,
};
export const RESTART_COOLDOWN_MS = 60000;
export const NETWORK_SETTLE_MS = 2500;
export const WATCHDOG_INTERVAL_MS = 60000;
export const NETWORK_CHECK_INTERVAL_MS = 5000;
+102 -117
View File
@@ -4,27 +4,34 @@ import { spawnQuickTunnel, killCloudflared, isCloudflaredRunning, setUnexpectedE
import { startFunnel, stopFunnel, isTailscaleRunning, isTailscaleLoggedIn, startLogin, startDaemonWithPassword } from "./tailscale.js";
import { getSettings, updateSettings } from "@/lib/localDb";
import { getCachedPassword, loadEncryptedPassword, initDbHooks } from "@/mitm/manager";
import { waitForHealth, probeUrlAlive } from "./networkProbe.js";
initDbHooks(getSettings, updateSettings);
const WORKER_URL = process.env.TUNNEL_WORKER_URL || "https://9router.com";
const MACHINE_ID_SALT = "9router-tunnel-salt";
const RECONNECT_DELAYS_MS = [5000, 10000, 20000, 30000, 60000];
const MAX_RECONNECT_ATTEMPTS = RECONNECT_DELAYS_MS.length;
let isReconnecting = false;
let exitHandlerRegistered = false;
let reconnectTimeoutId = null;
let manualDisabled = false;
let activeLocalPort = null;
// Per-service state (independent: tunnel ≠ tailscale)
const tunnelSvc = {
cancelToken: { cancelled: false },
spawnInProgress: false,
lastRestartAt: 0,
activeLocalPort: null,
};
export function isTunnelManuallyDisabled() {
return manualDisabled;
}
const tailscaleSvc = {
cancelToken: { cancelled: false },
spawnInProgress: false,
lastRestartAt: 0,
activeLocalPort: null,
};
export function isTunnelReconnecting() {
return isReconnecting;
}
export function getTunnelService() { return tunnelSvc; }
export function getTailscaleService() { return tailscaleSvc; }
export function isTunnelManuallyDisabled() { return tunnelSvc.cancelToken.cancelled; }
export function isTunnelReconnecting() { return tunnelSvc.spawnInProgress; }
export function isTailscaleReconnecting() { return tailscaleSvc.spawnInProgress; }
function getMachineId() {
try {
@@ -46,96 +53,65 @@ async function registerTunnelUrl(shortId, tunnelUrl) {
});
}
export async function enableTunnel(localPort = 20128) {
manualDisabled = false;
activeLocalPort = localPort;
if (isCloudflaredRunning()) {
const existing = loadState();
if (existing?.tunnelUrl) {
const publicUrl = `https://r${existing.shortId}.9router.com`;
return { success: true, tunnelUrl: existing.tunnelUrl, shortId: existing.shortId, publicUrl, alreadyRunning: true };
}
}
killCloudflared(localPort);
const machineId = getMachineId();
const existing = loadState();
const shortId = existing?.shortId || generateShortId();
// onUrlUpdate: called when URL changes AFTER initial connect
const onUrlUpdate = async (url) => {
if (manualDisabled) return;
await registerTunnelUrl(shortId, url);
saveState({ shortId, machineId, tunnelUrl: url });
await updateSettings({ tunnelEnabled: true, tunnelUrl: url });
};
const { tunnelUrl } = await spawnQuickTunnel(localPort, onUrlUpdate);
await registerTunnelUrl(shortId, tunnelUrl);
saveState({ shortId, machineId, tunnelUrl });
await updateSettings({ tunnelEnabled: true, tunnelUrl });
if (!exitHandlerRegistered) {
setUnexpectedExitHandler(() => {
if (!isReconnecting) scheduleReconnect(0);
});
exitHandlerRegistered = true;
}
const publicUrl = `https://r${shortId}.9router.com`;
return { success: true, tunnelUrl, shortId, publicUrl };
function throwIfCancelled(token, label) {
if (token.cancelled) throw new Error(`${label} cancelled`);
}
async function scheduleReconnect(attempt) {
if (isReconnecting || manualDisabled) return;
isReconnecting = true;
const delay = RECONNECT_DELAYS_MS[Math.min(attempt, RECONNECT_DELAYS_MS.length - 1)];
console.log(`[Tunnel] Reconnecting in ${delay / 1000}s (attempt ${attempt + 1})...`);
await new Promise((r) => { reconnectTimeoutId = setTimeout(r, delay); });
export async function enableTunnel(localPort = 20128) {
tunnelSvc.cancelToken = { cancelled: false };
tunnelSvc.activeLocalPort = localPort;
tunnelSvc.spawnInProgress = true;
const token = tunnelSvc.cancelToken;
try {
if (manualDisabled) { isReconnecting = false; return; }
const settings = await getSettings();
if (!settings.tunnelEnabled) { isReconnecting = false; return; }
await enableTunnel();
console.log("[Tunnel] Reconnected successfully");
isReconnecting = false;
} catch (err) {
console.log(`[Tunnel] Reconnect attempt ${attempt + 1} failed:`, err.message);
isReconnecting = false;
const next = attempt + 1;
if (next < MAX_RECONNECT_ATTEMPTS) scheduleReconnect(next);
else {
console.log("[Tunnel] All reconnect attempts exhausted, disabling tunnel");
await updateSettings({ tunnelEnabled: false });
if (isCloudflaredRunning()) {
const existing = loadState();
if (existing?.tunnelUrl && await probeUrlAlive(existing.tunnelUrl)) {
const publicUrl = `https://r${existing.shortId}.9router.com`;
return { success: true, tunnelUrl: existing.tunnelUrl, shortId: existing.shortId, publicUrl, alreadyRunning: true };
}
}
killCloudflared(localPort);
throwIfCancelled(token, "tunnel");
const machineId = getMachineId();
const existing = loadState();
const shortId = existing?.shortId || generateShortId();
const onUrlUpdate = async (url) => {
if (token.cancelled) return;
await registerTunnelUrl(shortId, url);
saveState({ shortId, machineId, tunnelUrl: url });
await updateSettings({ tunnelEnabled: true, tunnelUrl: url });
};
const { tunnelUrl } = await spawnQuickTunnel(localPort, onUrlUpdate);
throwIfCancelled(token, "tunnel");
const publicUrl = `https://r${shortId}.9router.com`;
await registerTunnelUrl(shortId, tunnelUrl);
saveState({ shortId, machineId, tunnelUrl });
await updateSettings({ tunnelEnabled: true, tunnelUrl });
// Block until /api/health responds via public URL — proves DNS propagated + tunnel works
await waitForHealth(publicUrl, token);
return { success: true, tunnelUrl, shortId, publicUrl };
} finally {
tunnelSvc.spawnInProgress = false;
}
}
export async function disableTunnel() {
manualDisabled = true;
isReconnecting = true;
if (reconnectTimeoutId) {
clearTimeout(reconnectTimeoutId);
reconnectTimeoutId = null;
}
tunnelSvc.cancelToken.cancelled = true;
setUnexpectedExitHandler(null);
exitHandlerRegistered = false;
killCloudflared(activeLocalPort);
killCloudflared(tunnelSvc.activeLocalPort);
const state = loadState();
if (state) {
saveState({ shortId: state.shortId, machineId: state.machineId, tunnelUrl: null });
}
if (state) saveState({ shortId: state.shortId, machineId: state.machineId, tunnelUrl: null });
await updateSettings({ tunnelEnabled: false, tunnelUrl: "" });
isReconnecting = false;
return { success: true };
}
@@ -158,43 +134,52 @@ export async function getTunnelStatus() {
// ─── Tailscale Funnel ─────────────────────────────────────────────────────────
export async function enableTailscale(localPort = 20128) {
// Ensure daemon is running (needs sudo for TUN mode)
const sudoPass = getCachedPassword() || await loadEncryptedPassword() || "";
await startDaemonWithPassword(sudoPass);
tailscaleSvc.cancelToken = { cancelled: false };
tailscaleSvc.activeLocalPort = localPort;
tailscaleSvc.spawnInProgress = true;
const token = tailscaleSvc.cancelToken;
// Generate hostname from machine ID (same as tunnel shortId prefix)
const existing = loadState();
const shortId = existing?.shortId || generateShortId();
const tsHostname = shortId;
try {
const sudoPass = getCachedPassword() || await loadEncryptedPassword() || "";
await startDaemonWithPassword(sudoPass);
throwIfCancelled(token, "tailscale");
// If not logged in, return auth URL for user to authenticate
if (!isTailscaleLoggedIn()) {
const loginResult = await startLogin(tsHostname);
if (loginResult.authUrl) {
return { success: false, needsLogin: true, authUrl: loginResult.authUrl };
const existing = loadState();
const shortId = existing?.shortId || generateShortId();
const tsHostname = shortId;
if (!isTailscaleLoggedIn()) {
const loginResult = await startLogin(tsHostname);
if (loginResult.authUrl) return { success: false, needsLogin: true, authUrl: loginResult.authUrl };
}
}
throwIfCancelled(token, "tailscale");
stopFunnel();
const result = await startFunnel(localPort);
// Funnel not enabled on tailnet — return enable URL
if (result.funnelNotEnabled) {
return { success: false, funnelNotEnabled: true, enableUrl: result.enableUrl };
}
// Verify device is actually connected (BackendState=Running + funnel active)
if (!isTailscaleLoggedIn() || !isTailscaleRunning()) {
stopFunnel();
return { success: false, error: "Tailscale not connected. Device may have been removed. Please re-login." };
}
const result = await startFunnel(localPort);
throwIfCancelled(token, "tailscale");
await updateSettings({ tailscaleEnabled: true, tailscaleUrl: result.tunnelUrl });
return { success: true, tunnelUrl: result.tunnelUrl };
if (result.funnelNotEnabled) {
return { success: false, funnelNotEnabled: true, enableUrl: result.enableUrl };
}
if (!isTailscaleLoggedIn() || !isTailscaleRunning()) {
stopFunnel();
return { success: false, error: "Tailscale not connected. Device may have been removed. Please re-login." };
}
await updateSettings({ tailscaleEnabled: true, tailscaleUrl: result.tunnelUrl });
// Verify funnel actually serves /api/health
await waitForHealth(result.tunnelUrl, token);
return { success: true, tunnelUrl: result.tunnelUrl };
} finally {
tailscaleSvc.spawnInProgress = false;
}
}
export async function disableTailscale() {
// Only reset funnel — keep tailscaled daemon running to avoid breaking other apps using Tailscale
tailscaleSvc.cancelToken.cancelled = true;
stopFunnel();
await updateSettings({ tailscaleEnabled: false, tailscaleUrl: "" });
return { success: true };