chore: release v0.4.27

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
decoluaandCursor committed 2026-05-09 22:48:07 +07:00
1 parent b184444f34
commit b39eb61c33
24 files changed
+517 -229

No files matched your search

+5
View File
@@ -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
View File
@@ -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()}`));
+45 -3
View File
@@ -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: "" });