Files
9router/src/lib/tunnel/tunnelManager.js
T

196 lines
6.8 KiB
JavaScript
Raw Normal View History

2026-02-21 16:42:46 +07:00
import crypto from "crypto";
2026-04-10 18:16:14 +07:00
import { loadState, saveState, generateShortId } from "./state.js";
2026-03-19 23:47:13 +07:00
import { spawnQuickTunnel, killCloudflared, isCloudflaredRunning, setUnexpectedExitHandler } from "./cloudflared.js";
import { startFunnel, stopFunnel, isTailscaleRunning, isTailscaleLoggedIn, startLogin, startDaemonWithPassword } from "./tailscale.js";
2026-02-21 16:42:46 +07:00
import { getSettings, updateSettings } from "@/lib/localDb";
2026-04-10 18:16:14 +07:00
import { getCachedPassword, loadEncryptedPassword, initDbHooks } from "@/mitm/manager";
import { waitForHealth, probeUrlAlive } from "./networkProbe.js";
2026-04-10 18:16:14 +07:00
initDbHooks(getSettings, updateSettings);
2026-02-21 16:42:46 +07:00
2026-03-19 23:47:13 +07:00
const WORKER_URL = process.env.TUNNEL_WORKER_URL || "https://9router.com";
2026-02-21 16:42:46 +07:00
const MACHINE_ID_SALT = "9router-tunnel-salt";
2026-02-22 21:44:11 +07:00
// Per-service state (independent: tunnel ≠ tailscale)
const tunnelSvc = {
cancelToken: { cancelled: false },
spawnInProgress: false,
lastRestartAt: 0,
activeLocalPort: null,
};
const tailscaleSvc = {
cancelToken: { cancelled: false },
spawnInProgress: false,
lastRestartAt: 0,
activeLocalPort: null,
};
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; }
2026-02-21 16:42:46 +07:00
function getMachineId() {
try {
const { machineIdSync } = require("node-machine-id");
const raw = machineIdSync();
return crypto.createHash("sha256").update(raw + MACHINE_ID_SALT).digest("hex").substring(0, 16);
} catch (e) {
return crypto.randomUUID().replace(/-/g, "").substring(0, 16);
}
}
2026-04-10 18:16:14 +07:00
// ─── Cloudflare Tunnel ───────────────────────────────────────────────────────
2026-03-19 23:47:13 +07:00
async function registerTunnelUrl(shortId, tunnelUrl) {
await fetch(`${WORKER_URL}/api/tunnel/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ shortId, tunnelUrl })
2026-02-21 16:42:46 +07:00
});
}
function throwIfCancelled(token, label) {
if (token.cancelled) throw new Error(`${label} cancelled`);
2026-02-21 16:42:46 +07:00
}
export async function enableTunnel(localPort = 20128) {
tunnelSvc.cancelToken = { cancelled: false };
tunnelSvc.activeLocalPort = localPort;
tunnelSvc.spawnInProgress = true;
const token = tunnelSvc.cancelToken;
2026-02-22 21:44:11 +07:00
try {
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 };
}
2026-04-06 17:32:44 +07:00
}
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;
2026-02-22 21:44:11 +07:00
}
}
2026-02-21 16:42:46 +07:00
export async function disableTunnel() {
tunnelSvc.cancelToken.cancelled = true;
setUnexpectedExitHandler(null);
killCloudflared(tunnelSvc.activeLocalPort);
2026-02-21 16:42:46 +07:00
2026-03-19 23:47:13 +07:00
const state = loadState();
if (state) saveState({ shortId: state.shortId, machineId: state.machineId, tunnelUrl: null });
2026-02-21 16:42:46 +07:00
await updateSettings({ tunnelEnabled: false, tunnelUrl: "" });
return { success: true };
}
export async function getTunnelStatus() {
const state = loadState();
const running = isCloudflaredRunning();
const settings = await getSettings();
2026-03-19 23:47:13 +07:00
const shortId = state?.shortId || "";
const publicUrl = shortId ? `https://r${shortId}.9router.com` : "";
2026-02-21 16:42:46 +07:00
return {
enabled: settings.tunnelEnabled === true && running,
tunnelUrl: state?.tunnelUrl || "",
2026-03-19 23:47:13 +07:00
shortId,
publicUrl,
2026-02-21 16:42:46 +07:00
running
};
}
2026-04-10 18:16:14 +07:00
// ─── Tailscale Funnel ─────────────────────────────────────────────────────────
export async function enableTailscale(localPort = 20128) {
tailscaleSvc.cancelToken = { cancelled: false };
tailscaleSvc.activeLocalPort = localPort;
tailscaleSvc.spawnInProgress = true;
const token = tailscaleSvc.cancelToken;
2026-04-10 18:16:14 +07:00
try {
const sudoPass = getCachedPassword() || await loadEncryptedPassword() || "";
await startDaemonWithPassword(sudoPass);
throwIfCancelled(token, "tailscale");
2026-04-10 18:16:14 +07:00
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 };
2026-04-10 18:16:14 +07:00
}
throwIfCancelled(token, "tailscale");
2026-04-10 18:16:14 +07:00
stopFunnel();
const result = await startFunnel(localPort);
throwIfCancelled(token, "tailscale");
2026-04-10 18:16:14 +07:00
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;
}
2026-04-10 18:16:14 +07:00
}
export async function disableTailscale() {
tailscaleSvc.cancelToken.cancelled = true;
2026-04-10 18:16:14 +07:00
stopFunnel();
await updateSettings({ tailscaleEnabled: false, tailscaleUrl: "" });
return { success: true };
}
export async function getTailscaleStatus() {
const settings = await getSettings();
const running = isTailscaleRunning();
return {
enabled: settings.tailscaleEnabled === true && running,
tunnelUrl: settings.tailscaleUrl || "",
running
};
}