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";
|
2026-04-28 10:20:31 +07:00
|
|
|
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";
|
2026-05-03 18:00:35 +07:00
|
|
|
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
|
|
|
|
2026-05-03 18:00:35 +07:00
|
|
|
// Per-service state (independent: tunnel ≠ tailscale)
|
|
|
|
|
const tunnelSvc = {
|
|
|
|
|
cancelToken: { cancelled: false },
|
|
|
|
|
spawnInProgress: false,
|
|
|
|
|
lastRestartAt: 0,
|
|
|
|
|
activeLocalPort: null,
|
|
|
|
|
};
|
2026-03-20 12:44:20 +07:00
|
|
|
|
2026-05-03 18:00:35 +07:00
|
|
|
const tailscaleSvc = {
|
|
|
|
|
cancelToken: { cancelled: false },
|
|
|
|
|
spawnInProgress: false,
|
|
|
|
|
lastRestartAt: 0,
|
|
|
|
|
activeLocalPort: null,
|
|
|
|
|
};
|
2026-03-20 12:44:20 +07:00
|
|
|
|
2026-05-03 18:00:35 +07:00
|
|
|
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
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-03 18:00:35 +07:00
|
|
|
function throwIfCancelled(token, label) {
|
|
|
|
|
if (token.cancelled) throw new Error(`${label} cancelled`);
|
2026-02-21 16:42:46 +07:00
|
|
|
}
|
|
|
|
|
|
2026-05-03 18:00:35 +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 {
|
2026-05-03 18:00:35 +07:00
|
|
|
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
|
|
|
}
|
2026-05-03 18:00:35 +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() {
|
2026-05-03 18:00:35 +07:00
|
|
|
tunnelSvc.cancelToken.cancelled = true;
|
2026-03-20 12:44:20 +07:00
|
|
|
setUnexpectedExitHandler(null);
|
2026-05-03 18:00:35 +07:00
|
|
|
killCloudflared(tunnelSvc.activeLocalPort);
|
2026-02-21 16:42:46 +07:00
|
|
|
|
2026-03-19 23:47:13 +07:00
|
|
|
const state = loadState();
|
2026-05-03 18:00:35 +07:00
|
|
|
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,
|
2026-05-03 22:10:03 +07:00
|
|
|
settingsEnabled: settings.tunnelEnabled === true,
|
2026-02-21 16:42:46 +07:00
|
|
|
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) {
|
2026-05-03 18:00:35 +07:00
|
|
|
tailscaleSvc.cancelToken = { cancelled: false };
|
|
|
|
|
tailscaleSvc.activeLocalPort = localPort;
|
|
|
|
|
tailscaleSvc.spawnInProgress = true;
|
|
|
|
|
const token = tailscaleSvc.cancelToken;
|
2026-04-10 18:16:14 +07:00
|
|
|
|
2026-05-03 18:00:35 +07:00
|
|
|
try {
|
|
|
|
|
const sudoPass = getCachedPassword() || await loadEncryptedPassword() || "";
|
|
|
|
|
await startDaemonWithPassword(sudoPass);
|
|
|
|
|
throwIfCancelled(token, "tailscale");
|
2026-04-10 18:16:14 +07:00
|
|
|
|
2026-05-03 18:00:35 +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
|
|
|
}
|
2026-05-03 18:00:35 +07:00
|
|
|
throwIfCancelled(token, "tailscale");
|
2026-04-10 18:16:14 +07:00
|
|
|
|
|
|
|
|
stopFunnel();
|
2026-05-03 18:00:35 +07:00
|
|
|
const result = await startFunnel(localPort);
|
|
|
|
|
throwIfCancelled(token, "tailscale");
|
2026-04-10 18:16:14 +07:00
|
|
|
|
2026-05-03 18:00:35 +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() {
|
2026-05-03 18:00:35 +07:00
|
|
|
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,
|
2026-05-03 22:10:03 +07:00
|
|
|
settingsEnabled: settings.tailscaleEnabled === true,
|
2026-04-10 18:16:14 +07:00
|
|
|
tunnelUrl: settings.tailscaleUrl || "",
|
|
|
|
|
running
|
|
|
|
|
};
|
|
|
|
|
}
|