mirror of
https://github.com/Nezumi-2711/9router.git
synced 2026-09-22 20:00:47 +00:00
+28
-11
@@ -22,7 +22,10 @@ function killMitmByPidFile() {
|
||||
if (!pid) return;
|
||||
|
||||
if (process.platform === "win32") {
|
||||
execSync(`taskkill /F /T /PID ${pid}`, { stdio: "ignore", windowsHide: true, timeout: 3000 });
|
||||
// taskkill first (works if same user); fallback to PowerShell Stop-Process which can kill admin process if our token allows
|
||||
try { execSync(`taskkill /F /T /PID ${pid}`, { stdio: "ignore", windowsHide: true, timeout: 3000 }); } catch {
|
||||
try { execSync(`powershell -NonInteractive -WindowStyle Hidden -Command "Stop-Process -Id ${pid} -Force"`, { stdio: "ignore", windowsHide: true, timeout: 3000 }); } catch { /* best effort */ }
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
execSync(`sudo -n kill -9 ${pid} 2>/dev/null`, { stdio: "ignore", timeout: 3000 });
|
||||
@@ -45,7 +48,13 @@ function collectAppPids() {
|
||||
const output = execSync(psCmd, { encoding: "utf8", windowsHide: true, timeout: KILL_TIMEOUT_MS });
|
||||
const lines = output.split("\n").slice(1).filter(l => l.trim());
|
||||
lines.forEach(line => {
|
||||
const isAppProcess = line.toLowerCase().includes("9router") || line.toLowerCase().includes("next-server");
|
||||
const lower = line.toLowerCase();
|
||||
// Match anything running from 9router install dir or wrapper cli.js
|
||||
const isAppProcess = lower.includes("9router") ||
|
||||
lower.includes("next-server") ||
|
||||
lower.includes("\\bin\\app\\") ||
|
||||
lower.includes("/bin/app/") ||
|
||||
lower.includes("cli.js");
|
||||
if (isAppProcess) {
|
||||
const match = line.match(/^"(\d+)"/);
|
||||
if (match && match[1] && match[1] !== process.pid.toString()) pids.push(match[1]);
|
||||
@@ -53,19 +62,27 @@ function collectAppPids() {
|
||||
});
|
||||
} catch { /* no processes */ }
|
||||
|
||||
try {
|
||||
const cfCmd = `powershell -NonInteractive -WindowStyle Hidden -Command "Get-Process cloudflared -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Id"`;
|
||||
const cfOut = execSync(cfCmd, { encoding: "utf8", windowsHide: true, timeout: KILL_TIMEOUT_MS });
|
||||
cfOut.split("\n").forEach(l => {
|
||||
const pid = l.trim();
|
||||
if (pid && !isNaN(pid)) pids.push(pid);
|
||||
});
|
||||
} catch { /* no cloudflared */ }
|
||||
// Kill cloudflared + tray binaries (giữ lock app dir)
|
||||
for (const procName of ["cloudflared", "tray_windows_release"]) {
|
||||
try {
|
||||
const cmd = `powershell -NonInteractive -WindowStyle Hidden -Command "Get-Process ${procName} -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Id"`;
|
||||
const out = execSync(cmd, { encoding: "utf8", windowsHide: true, timeout: KILL_TIMEOUT_MS });
|
||||
out.split("\n").forEach(l => {
|
||||
const pid = l.trim();
|
||||
if (pid && !isNaN(pid)) pids.push(pid);
|
||||
});
|
||||
} catch { /* not running */ }
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
const output = execSync("ps aux 2>/dev/null", { encoding: "utf8", timeout: KILL_TIMEOUT_MS });
|
||||
output.split("\n").forEach(line => {
|
||||
const isAppProcess = line.includes("9router") || line.includes("next-server") || line.includes("cloudflared");
|
||||
const isAppProcess = line.includes("9router") ||
|
||||
line.includes("next-server") ||
|
||||
line.includes("cloudflared") ||
|
||||
line.includes("/bin/app/") ||
|
||||
line.includes("tray_darwin") ||
|
||||
line.includes("tray_linux");
|
||||
if (isAppProcess) {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
const pid = parts[1];
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// Built-in node:sqlite adapter — available in Node >= 22.5.0.
|
||||
// No native build, no npm install. API mirrors betterSqliteAdapter.
|
||||
import { PRAGMA_SQL } from "../schema.js";
|
||||
|
||||
const CHECKPOINT_INTERVAL_MS = 60 * 1000;
|
||||
|
||||
export async function createNodeSqliteAdapter(filePath) {
|
||||
// Suppress "ExperimentalWarning: SQLite is an experimental feature" from node:sqlite.
|
||||
// Stable enough for production use as of Node 22.x (RC quality).
|
||||
const origEmit = process.emit;
|
||||
process.emit = function (name, data, ...rest) {
|
||||
if (name === "warning" && data?.name === "ExperimentalWarning" && /SQLite/i.test(data.message || "")) {
|
||||
return false;
|
||||
}
|
||||
return origEmit.call(process, name, data, ...rest);
|
||||
};
|
||||
|
||||
// Dynamic import — fails on Node < 22.5 → driver.js falls back to sql.js
|
||||
const sqlite = await import("node:sqlite");
|
||||
const Database = sqlite.DatabaseSync;
|
||||
const db = new Database(filePath);
|
||||
|
||||
db.exec(PRAGMA_SQL);
|
||||
|
||||
const stmtCache = new Map();
|
||||
function prepare(sql) {
|
||||
let stmt = stmtCache.get(sql);
|
||||
if (!stmt) {
|
||||
stmt = db.prepare(sql);
|
||||
stmtCache.set(sql, stmt);
|
||||
}
|
||||
return stmt;
|
||||
}
|
||||
|
||||
// Periodic WAL checkpoint to keep -wal/-shm small
|
||||
const checkpointTimer = setInterval(() => {
|
||||
try { db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); } catch {}
|
||||
}, CHECKPOINT_INTERVAL_MS);
|
||||
if (typeof checkpointTimer.unref === "function") checkpointTimer.unref();
|
||||
|
||||
function gracefulClose() {
|
||||
try { db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); } catch {}
|
||||
try { stmtCache.clear(); } catch {}
|
||||
try { db.close(); } catch {}
|
||||
}
|
||||
const onShutdown = () => gracefulClose();
|
||||
process.once("beforeExit", onShutdown);
|
||||
process.once("SIGINT", () => { onShutdown(); process.exit(0); });
|
||||
process.once("SIGTERM", () => { onShutdown(); process.exit(0); });
|
||||
|
||||
return {
|
||||
driver: "node:sqlite",
|
||||
run(sql, params = []) {
|
||||
const r = prepare(sql).run(...params);
|
||||
return { changes: Number(r.changes ?? 0), lastInsertRowid: Number(r.lastInsertRowid ?? 0) };
|
||||
},
|
||||
get(sql, params = []) {
|
||||
return prepare(sql).get(...params);
|
||||
},
|
||||
all(sql, params = []) {
|
||||
return prepare(sql).all(...params);
|
||||
},
|
||||
exec(sql) { return db.exec(sql); },
|
||||
transaction(fn) {
|
||||
// node:sqlite has no built-in transaction wrapper → manual BEGIN/COMMIT
|
||||
db.exec("BEGIN");
|
||||
try {
|
||||
const r = fn();
|
||||
db.exec("COMMIT");
|
||||
return r;
|
||||
} catch (e) {
|
||||
try { db.exec("ROLLBACK"); } catch {}
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
checkpoint() { try { db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); } catch {} },
|
||||
close() {
|
||||
clearInterval(checkpointTimer);
|
||||
gracefulClose();
|
||||
},
|
||||
raw: db,
|
||||
};
|
||||
}
|
||||
+16
-1
@@ -14,6 +14,19 @@ async function tryBetterSqlite() {
|
||||
}
|
||||
}
|
||||
|
||||
async function tryNodeSqlite() {
|
||||
// Built-in since Node 22.5.0 — no install needed.
|
||||
const [maj, min] = process.versions.node.split(".").map(Number);
|
||||
if (maj < 22 || (maj === 22 && min < 5)) return null;
|
||||
try {
|
||||
const { createNodeSqliteAdapter } = await import("./adapters/nodeSqliteAdapter.js");
|
||||
return await createNodeSqliteAdapter(DATA_FILE);
|
||||
} catch (e) {
|
||||
console.warn(`[DB] node:sqlite unavailable: ${e.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function trySqlJs() {
|
||||
try {
|
||||
const { createSqlJsAdapter } = await import("./adapters/sqljsAdapter.js");
|
||||
@@ -26,9 +39,11 @@ async function trySqlJs() {
|
||||
|
||||
async function initAdapter() {
|
||||
ensureDirs();
|
||||
// Order: native (fastest) → built-in (no install) → pure JS (universal)
|
||||
let adapter = await tryBetterSqlite();
|
||||
if (!adapter) adapter = await tryNodeSqlite();
|
||||
if (!adapter) adapter = await trySqlJs();
|
||||
if (!adapter) throw new Error("[DB] No SQLite driver available (better-sqlite3 + sql.js both failed)");
|
||||
if (!adapter) throw new Error("[DB] No SQLite driver available (better-sqlite3 + node:sqlite + sql.js all failed)");
|
||||
|
||||
if (!state.logged) {
|
||||
console.log(`[DB] Driver: ${adapter.driver} | file: ${DATA_FILE}`);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { getAdapter } from "../driver.js";
|
||||
import { parseJson, stringifyJson } from "../helpers/jsonCol.js";
|
||||
|
||||
const DEFAULT_MITM_ROUTER_BASE = "http://127.0.0.1:20128";
|
||||
const DEFAULT_MITM_ROUTER_BASE = "http://localhost:20128";
|
||||
|
||||
const DEFAULT_SETTINGS = {
|
||||
cloudEnabled: false,
|
||||
|
||||
@@ -197,6 +197,7 @@ export async function spawnCloudflared(tunnelToken) {
|
||||
const child = spawn(binaryPath, ["tunnel", "run", "--dns-resolver-addrs", "1.1.1.1:53", "--token", tunnelToken], {
|
||||
detached: false,
|
||||
windowsHide: true,
|
||||
cwd: os.tmpdir(),
|
||||
stdio: ["ignore", "pipe", "pipe"]
|
||||
});
|
||||
|
||||
@@ -291,6 +292,7 @@ export async function spawnQuickTunnel(localPort, onUrlUpdate) {
|
||||
const child = spawn(binaryPath, ["tunnel", "--url", `http://127.0.0.1:${localPort}`, "--config", configPath, "--no-autoupdate"], {
|
||||
detached: false,
|
||||
windowsHide: true,
|
||||
cwd: os.tmpdir(),
|
||||
env: {
|
||||
...process.env,
|
||||
TUNNEL_TRANSPORT_PROTOCOL: tunnelProtocol,
|
||||
@@ -340,12 +342,14 @@ export async function spawnQuickTunnel(localPort, onUrlUpdate) {
|
||||
lastUrl = tunnelUrl;
|
||||
clearTimeout(timeout);
|
||||
cleanup();
|
||||
console.log(`[Tunnel] cloudflared URL: ${tunnelUrl}`);
|
||||
resolve({ child, tunnelUrl });
|
||||
return;
|
||||
}
|
||||
|
||||
// URL changed after initial connect — notify caller to re-register
|
||||
if (tunnelUrl !== lastUrl) {
|
||||
console.log(`[Tunnel] cloudflared URL changed: ${tunnelUrl}`);
|
||||
lastUrl = tunnelUrl;
|
||||
if (onUrlUpdate) onUrlUpdate(tunnelUrl);
|
||||
}
|
||||
@@ -365,6 +369,7 @@ export async function spawnQuickTunnel(localPort, onUrlUpdate) {
|
||||
child.on("exit", (code, signal) => {
|
||||
cloudflaredProcess = null;
|
||||
clearPid();
|
||||
console.log(`[Tunnel] cloudflared exit code=${code} signal=${signal}`);
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
clearTimeout(timeout);
|
||||
|
||||
+86
-37
@@ -419,18 +419,26 @@ async function ensureUserOwnedDir(dir) {
|
||||
/** Start tailscaled in userspace-networking mode (no root, no sudo prompt). */
|
||||
export async function startDaemonWithPassword(_sudoPasswordUnused) {
|
||||
if (IS_WINDOWS) {
|
||||
// Windows: tailscale runs as a Windows Service, try to start it
|
||||
try {
|
||||
const bin = getTailscaleBin();
|
||||
if (bin) {
|
||||
execSync(`"${bin}" status --json`, { stdio: "ignore", windowsHide: true, timeout: 3000 });
|
||||
return; // Already running
|
||||
}
|
||||
} catch { /* not running */ }
|
||||
try {
|
||||
execSync("net start Tailscale", { stdio: "ignore", windowsHide: true, timeout: 10000 });
|
||||
await new Promise((r) => setTimeout(r, 3000));
|
||||
} catch { /* may need admin, or already running */ }
|
||||
// Windows: tailscale runs as a Windows Service. Start it then poll BackendState
|
||||
// until daemon finishes init (avoids "NoState" errors when calling funnel/up too early).
|
||||
const bin = getTailscaleBin();
|
||||
console.log("[Tailscale] win: net start Tailscale");
|
||||
try { execSync("net start Tailscale", { stdio: "ignore", windowsHide: true, timeout: 10000 }); }
|
||||
catch { /* may need admin, or already running */ }
|
||||
if (!bin) return;
|
||||
// Poll up to ~10s for backend to leave NoState
|
||||
for (let i = 0; i < 20; i++) {
|
||||
try {
|
||||
const out = execSync(`"${bin}" status --json`, { encoding: "utf8", windowsHide: true, timeout: 2000 });
|
||||
const j = JSON.parse(out);
|
||||
if (j.BackendState && j.BackendState !== "NoState") {
|
||||
console.log(`[Tailscale] win: BackendState=${j.BackendState} after ${i*500}ms`);
|
||||
return;
|
||||
}
|
||||
} catch { /* daemon not ready */ }
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
}
|
||||
console.log("[Tailscale] win: BackendState still NoState after poll");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -486,6 +494,7 @@ export async function startDaemonWithPassword(_sudoPasswordUnused) {
|
||||
const child = spawn(tailscaledBin, args, {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
cwd: os.tmpdir(),
|
||||
env: { ...process.env, PATH: EXTENDED_PATH },
|
||||
});
|
||||
child.unref();
|
||||
@@ -499,9 +508,24 @@ function ensureDaemon() {
|
||||
startDaemonWithPassword("").catch(() => {});
|
||||
}
|
||||
|
||||
/** Read AuthURL from `tailscale status --json` (Win exposes it there, not stdout). */
|
||||
function getAuthUrlFromStatus() {
|
||||
const bin = getTailscaleBin();
|
||||
if (!bin) return null;
|
||||
try {
|
||||
const out = execSync(`"${bin}" ${SOCKET_FLAG.join(" ")} status --json`, {
|
||||
encoding: "utf8", windowsHide: true, timeout: 2000
|
||||
});
|
||||
const j = JSON.parse(out);
|
||||
if (j.AuthURL) return j.AuthURL;
|
||||
return null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `tailscale up` and capture the auth URL for browser login.
|
||||
* Resolves with { authUrl } or { alreadyLoggedIn: true }.
|
||||
* On Windows, AuthURL comes from `status --json` (not stdout) — must poll status.
|
||||
*/
|
||||
export function startLogin(hostname) {
|
||||
const bin = getTailscaleBin();
|
||||
@@ -517,8 +541,8 @@ export function startLogin(hostname) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Spawn detached so process survives API request lifecycle
|
||||
const args = tsArgs("up", "--accept-routes");
|
||||
// Force re-auth on Win when device may have been removed from tailnet
|
||||
const args = tsArgs("up", "--accept-routes", "--force-reauth");
|
||||
if (hostname) args.push(`--hostname=${hostname}`);
|
||||
const child = spawn(bin, args, {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
@@ -529,31 +553,42 @@ export function startLogin(hostname) {
|
||||
let resolved = false;
|
||||
let output = "";
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
// Don't kill — let tailscale up keep waiting for auth
|
||||
child.unref();
|
||||
const url = parseAuthUrl(output);
|
||||
if (url) resolve({ authUrl: url });
|
||||
else reject(new Error("tailscale up timed out without auth URL"));
|
||||
}, 15000);
|
||||
|
||||
const parseAuthUrl = (text) => {
|
||||
const match = text.match(/https:\/\/login\.tailscale\.com\/a\/[a-zA-Z0-9]+/);
|
||||
return match ? match[0] : null;
|
||||
};
|
||||
|
||||
const finishWithUrl = (url, source) => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
clearTimeout(timeout);
|
||||
clearInterval(statusPoll);
|
||||
console.log(`[Tailscale] login authUrl detected (${source})`);
|
||||
child.unref();
|
||||
resolve({ authUrl: url });
|
||||
};
|
||||
|
||||
// Poll status --json every 500ms — Windows exposes AuthURL only there
|
||||
const statusPoll = setInterval(() => {
|
||||
if (resolved) return;
|
||||
const url = getAuthUrlFromStatus();
|
||||
if (url) finishWithUrl(url, "status");
|
||||
}, 500);
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
clearInterval(statusPoll);
|
||||
child.unref();
|
||||
const url = parseAuthUrl(output) || getAuthUrlFromStatus();
|
||||
if (url) resolve({ authUrl: url });
|
||||
else reject(new Error("tailscale up timed out without auth URL"));
|
||||
}, 15000);
|
||||
|
||||
const handleData = (data) => {
|
||||
output += data.toString();
|
||||
const url = parseAuthUrl(output);
|
||||
if (url && !resolved) {
|
||||
resolved = true;
|
||||
clearTimeout(timeout);
|
||||
// Keep process alive — unref so it doesn't block Node exit
|
||||
child.unref();
|
||||
resolve({ authUrl: url });
|
||||
}
|
||||
if (url) finishWithUrl(url, "stdout");
|
||||
};
|
||||
|
||||
child.stdout.on("data", handleData);
|
||||
@@ -563,17 +598,30 @@ export function startLogin(hostname) {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
clearTimeout(timeout);
|
||||
clearInterval(statusPoll);
|
||||
console.error(`[Tailscale] login spawn error: ${err.message}`);
|
||||
reject(err);
|
||||
});
|
||||
|
||||
child.on("exit", (code) => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
clearTimeout(timeout);
|
||||
const url = parseAuthUrl(output);
|
||||
if (url) resolve({ authUrl: url });
|
||||
else if (code === 0 || isTailscaleLoggedIn()) resolve({ alreadyLoggedIn: true });
|
||||
else reject(new Error(`tailscale up exited with code ${code}: ${output.trim() || "no output"}`));
|
||||
console.log(`[Tailscale] login exit code=${code}`);
|
||||
// Don't trust exit code alone — Win `tailscale up` exits 0 even when not logged in.
|
||||
// Let status poll continue until AuthURL appears or timeout.
|
||||
const url = parseAuthUrl(output) || getAuthUrlFromStatus();
|
||||
if (url) {
|
||||
finishWithUrl(url, "exit");
|
||||
return;
|
||||
}
|
||||
// Only resolve alreadyLoggedIn if status confirms BackendState=Running
|
||||
if (isTailscaleLoggedIn()) {
|
||||
resolved = true;
|
||||
clearTimeout(timeout);
|
||||
clearInterval(statusPoll);
|
||||
resolve({ alreadyLoggedIn: true });
|
||||
return;
|
||||
}
|
||||
// Otherwise keep polling — daemon may publish AuthURL shortly after exit
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -641,6 +689,7 @@ export async function startFunnel(port) {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
clearTimeout(timeout);
|
||||
console.log(`[Tailscale] funnel exit code=${code} output="${output.trim().slice(0, 200)}"`);
|
||||
const url = parseFunnelUrl(output) || getTailscaleFunnelUrl(port);
|
||||
if (url) resolve({ tunnelUrl: url });
|
||||
else reject(new Error(`tailscale funnel failed (code ${code}): ${output.trim()}`));
|
||||
|
||||
@@ -85,6 +85,7 @@ function throwIfCancelled(token, label) {
|
||||
}
|
||||
|
||||
export async function enableTunnel(localPort = 20128) {
|
||||
console.log(`[Tunnel] enable start (port=${localPort})`);
|
||||
tunnelSvc.cancelToken = { cancelled: false };
|
||||
tunnelSvc.activeLocalPort = localPort;
|
||||
tunnelSvc.spawnInProgress = true;
|
||||
@@ -95,11 +96,13 @@ export async function enableTunnel(localPort = 20128) {
|
||||
const existing = loadState();
|
||||
if (existing?.tunnelUrl && await probeUrlAlive(existing.tunnelUrl)) {
|
||||
const publicUrl = `https://r${existing.shortId}.9router.com`;
|
||||
console.log(`[Tunnel] already running, reuse: ${existing.tunnelUrl}`);
|
||||
return { success: true, tunnelUrl: existing.tunnelUrl, shortId: existing.shortId, publicUrl, alreadyRunning: true };
|
||||
}
|
||||
}
|
||||
|
||||
killCloudflared(localPort);
|
||||
console.log("[Tunnel] killed existing cloudflared");
|
||||
throwIfCancelled(token, "tunnel");
|
||||
|
||||
const machineId = getMachineId();
|
||||
@@ -108,36 +111,46 @@ export async function enableTunnel(localPort = 20128) {
|
||||
|
||||
const onUrlUpdate = async (url) => {
|
||||
if (token.cancelled) return;
|
||||
console.log(`[Tunnel] url updated: ${url}`);
|
||||
await registerTunnelUrl(shortId, url);
|
||||
saveState({ shortId, machineId, tunnelUrl: url });
|
||||
await updateSettings({ tunnelEnabled: true, tunnelUrl: url });
|
||||
};
|
||||
|
||||
const { tunnelUrl } = await spawnQuickTunnel(localPort, onUrlUpdate);
|
||||
console.log(`[Tunnel] spawned: ${tunnelUrl}`);
|
||||
throwIfCancelled(token, "tunnel");
|
||||
|
||||
const publicUrl = `https://r${shortId}.9router.com`;
|
||||
await registerTunnelUrl(shortId, tunnelUrl);
|
||||
saveState({ shortId, machineId, tunnelUrl });
|
||||
await updateSettings({ tunnelEnabled: true, tunnelUrl });
|
||||
console.log(`[Tunnel] registered shortId=${shortId} publicUrl=${publicUrl}`);
|
||||
|
||||
// Verify direct tunnel URL is reachable first (avoid CDN-cache false positive on publicUrl)
|
||||
await waitForHealth(tunnelUrl, token);
|
||||
console.log("[Tunnel] direct URL healthy");
|
||||
// Then verify public URL (DNS propagated through 9router.com worker)
|
||||
await waitForHealth(publicUrl, token);
|
||||
console.log("[Tunnel] public URL healthy");
|
||||
|
||||
// Prime reachable cache so UI shows correct state immediately
|
||||
tunnelReachable.value = true;
|
||||
tunnelReachable.url = tunnelUrl;
|
||||
tunnelReachable.fetchedAt = Date.now();
|
||||
|
||||
console.log("[Tunnel] enable success");
|
||||
return { success: true, tunnelUrl, shortId, publicUrl };
|
||||
} catch (e) {
|
||||
console.error(`[Tunnel] enable error: ${e.message}`);
|
||||
throw e;
|
||||
} finally {
|
||||
tunnelSvc.spawnInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function disableTunnel() {
|
||||
console.log("[Tunnel] disable");
|
||||
tunnelSvc.cancelToken.cancelled = true;
|
||||
setUnexpectedExitHandler(null);
|
||||
killCloudflared(tunnelSvc.activeLocalPort);
|
||||
@@ -177,6 +190,7 @@ export async function getTunnelStatus() {
|
||||
// ─── Tailscale Funnel ─────────────────────────────────────────────────────────
|
||||
|
||||
export async function enableTailscale(localPort = 20128) {
|
||||
console.log(`[Tailscale] enable start (port=${localPort})`);
|
||||
tailscaleSvc.cancelToken = { cancelled: false };
|
||||
tailscaleSvc.activeLocalPort = localPort;
|
||||
tailscaleSvc.spawnInProgress = true;
|
||||
@@ -185,36 +199,60 @@ export async function enableTailscale(localPort = 20128) {
|
||||
try {
|
||||
const sudoPass = getCachedPassword() || await loadEncryptedPassword() || "";
|
||||
await startDaemonWithPassword(sudoPass);
|
||||
console.log("[Tailscale] daemon ready");
|
||||
throwIfCancelled(token, "tailscale");
|
||||
|
||||
const existing = loadState();
|
||||
const shortId = existing?.shortId || generateShortId();
|
||||
const tsHostname = shortId;
|
||||
|
||||
if (!isTailscaleLoggedIn()) {
|
||||
const loggedIn = isTailscaleLoggedIn();
|
||||
console.log(`[Tailscale] loggedIn=${loggedIn}`);
|
||||
if (!loggedIn) {
|
||||
const loginResult = await startLogin(tsHostname);
|
||||
if (loginResult.authUrl) return { success: false, needsLogin: true, authUrl: loginResult.authUrl };
|
||||
if (loginResult.authUrl) {
|
||||
console.log(`[Tailscale] needs login, authUrl=${loginResult.authUrl}`);
|
||||
return { success: false, needsLogin: true, authUrl: loginResult.authUrl };
|
||||
}
|
||||
console.log("[Tailscale] login resolved alreadyLoggedIn");
|
||||
}
|
||||
throwIfCancelled(token, "tailscale");
|
||||
|
||||
stopFunnel();
|
||||
const result = await startFunnel(localPort);
|
||||
let result;
|
||||
try {
|
||||
console.log("[Tailscale] starting funnel");
|
||||
result = await startFunnel(localPort);
|
||||
} catch (e) {
|
||||
console.error(`[Tailscale] funnel error: ${e.message}`);
|
||||
// Daemon not logged in / not ready → auto-trigger login flow so user stays in-app
|
||||
if (/NoState|unexpected state|not logged in|Logged ?out|NeedsLogin/i.test(e.message || "")) {
|
||||
console.log("[Tailscale] retry via startLogin");
|
||||
const loginResult = await startLogin(tsHostname);
|
||||
if (loginResult.authUrl) return { success: false, needsLogin: true, authUrl: loginResult.authUrl };
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
throwIfCancelled(token, "tailscale");
|
||||
|
||||
if (result.funnelNotEnabled) {
|
||||
console.log(`[Tailscale] funnel not enabled, enableUrl=${result.enableUrl}`);
|
||||
return { success: false, funnelNotEnabled: true, enableUrl: result.enableUrl };
|
||||
}
|
||||
|
||||
// Strict probe: bypass cache so we don't false-negative on first invocation
|
||||
if (!isTailscaleLoggedIn() || !isTailscaleRunningStrict()) {
|
||||
console.error("[Tailscale] strict probe failed (device removed?)");
|
||||
stopFunnel();
|
||||
return { success: false, error: "Tailscale not connected. Device may have been removed. Please re-login." };
|
||||
}
|
||||
|
||||
await updateSettings({ tailscaleEnabled: true, tailscaleUrl: result.tunnelUrl });
|
||||
console.log(`[Tailscale] funnel up: ${result.tunnelUrl}`);
|
||||
|
||||
// Verify funnel actually serves /api/health
|
||||
await waitForHealth(result.tunnelUrl, token);
|
||||
console.log("[Tailscale] enable success");
|
||||
|
||||
// Prime reachable cache so UI shows correct state immediately
|
||||
tailscaleReachable.value = true;
|
||||
@@ -222,12 +260,16 @@ export async function enableTailscale(localPort = 20128) {
|
||||
tailscaleReachable.fetchedAt = Date.now();
|
||||
|
||||
return { success: true, tunnelUrl: result.tunnelUrl };
|
||||
} catch (e) {
|
||||
console.error(`[Tailscale] enable error: ${e.message}`);
|
||||
throw e;
|
||||
} finally {
|
||||
tailscaleSvc.spawnInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function disableTailscale() {
|
||||
console.log("[Tailscale] disable");
|
||||
tailscaleSvc.cancelToken.cancelled = true;
|
||||
stopFunnel();
|
||||
await updateSettings({ tailscaleEnabled: false, tailscaleUrl: "" });
|
||||
|
||||
@@ -172,6 +172,29 @@ function runInstall() {
|
||||
});
|
||||
}
|
||||
|
||||
function openBrowser(url) {
|
||||
const platform = process.platform;
|
||||
const cmd = platform === "darwin" ? `open "${url}"`
|
||||
: platform === "win32" ? `start "" "${url}"`
|
||||
: `xdg-open "${url}"`;
|
||||
try { spawn(cmd, { shell: true, detached: true, stdio: "ignore" }).unref(); } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// Wait until app port is listening (server alive again), then open dashboard
|
||||
async function waitForAppAndOpenBrowser() {
|
||||
const deadline = Date.now() + 30000;
|
||||
while (Date.now() < deadline) {
|
||||
const busy = await isAppPortBusy();
|
||||
if (busy) {
|
||||
openBrowser(`http://localhost:${appPort}/dashboard`);
|
||||
pushLog(`[updater] app ready, opened dashboard`);
|
||||
return;
|
||||
}
|
||||
await sleep(1000);
|
||||
}
|
||||
pushLog(`[updater] app not responding within 30s, skip browser open`);
|
||||
}
|
||||
|
||||
function relaunchApp() {
|
||||
if (process.env.UPDATER_RELAUNCH !== "1") return;
|
||||
const cmd = process.env.UPDATER_RELAUNCH_CMD;
|
||||
@@ -189,6 +212,8 @@ function relaunchApp() {
|
||||
});
|
||||
child.unref();
|
||||
pushLog(`[updater] relaunched: ${cmd} ${args.join(" ")} (pid=${child.pid})`);
|
||||
// Wait for new app to come up, then auto-open browser so user sees the result
|
||||
waitForAppAndOpenBrowser();
|
||||
} catch (e) {
|
||||
pushLog(`[updater] relaunch failed: ${e.message}`);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user