Fix : Tunnel

This commit is contained in:
decolua
2026-03-19 23:47:13 +07:00
parent f1c53a319e
commit 80583e203d
3 changed files with 124 additions and 67 deletions

View File

@@ -44,6 +44,7 @@ export default function APIPageClient({ machineId }) {
const [requireApiKey, setRequireApiKey] = useState(false); const [requireApiKey, setRequireApiKey] = useState(false);
const [tunnelEnabled, setTunnelEnabled] = useState(false); const [tunnelEnabled, setTunnelEnabled] = useState(false);
const [tunnelUrl, setTunnelUrl] = useState(""); const [tunnelUrl, setTunnelUrl] = useState("");
const [tunnelPublicUrl, setTunnelPublicUrl] = useState("");
const [tunnelShortId, setTunnelShortId] = useState(""); const [tunnelShortId, setTunnelShortId] = useState("");
const [tunnelLoading, setTunnelLoading] = useState(false); const [tunnelLoading, setTunnelLoading] = useState(false);
const [tunnelProgress, setTunnelProgress] = useState(""); const [tunnelProgress, setTunnelProgress] = useState("");
@@ -226,6 +227,7 @@ export default function APIPageClient({ machineId }) {
const data = await tunnelRes.json(); const data = await tunnelRes.json();
setTunnelEnabled(data.enabled || false); setTunnelEnabled(data.enabled || false);
setTunnelUrl(data.tunnelUrl || ""); setTunnelUrl(data.tunnelUrl || "");
setTunnelPublicUrl(data.publicUrl || "");
setTunnelShortId(data.shortId || ""); setTunnelShortId(data.shortId || "");
} }
} catch (error) { } catch (error) {
@@ -289,6 +291,7 @@ export default function APIPageClient({ machineId }) {
if (res.ok) { if (res.ok) {
setTunnelEnabled(true); setTunnelEnabled(true);
setTunnelUrl(data.tunnelUrl || ""); setTunnelUrl(data.tunnelUrl || "");
setTunnelPublicUrl(data.publicUrl || "");
setTunnelShortId(data.shortId || ""); setTunnelShortId(data.shortId || "");
setTunnelStatus({ type: "success", message: "Tunnel connected!" }); setTunnelStatus({ type: "success", message: "Tunnel connected!" });
} else { } else {
@@ -313,6 +316,7 @@ export default function APIPageClient({ machineId }) {
if (res.ok) { if (res.ok) {
setTunnelEnabled(false); setTunnelEnabled(false);
setTunnelUrl(""); setTunnelUrl("");
setTunnelPublicUrl("");
setTunnelStatus({ type: "success", message: "Tunnel disabled" }); setTunnelStatus({ type: "success", message: "Tunnel disabled" });
setShowDisableModal(false); setShowDisableModal(false);
} else { } else {
@@ -413,7 +417,7 @@ export default function APIPageClient({ machineId }) {
); );
} }
const currentEndpoint = tunnelEnabled && tunnelUrl ? `${tunnelUrl}/v1` : baseUrl; const currentEndpoint = tunnelEnabled && tunnelPublicUrl ? `${tunnelPublicUrl}/v1` : baseUrl;
return ( return (
<div className="flex flex-col gap-8"> <div className="flex flex-col gap-8">

View File

@@ -185,6 +185,87 @@ export async function spawnCloudflared(tunnelToken) {
}); });
} }
/**
* Spawn cloudflared quick tunnel (no account needed)
* Returns the generated trycloudflare.com URL
*/
export async function spawnQuickTunnel(localPort, onUrlUpdate) {
const binaryPath = await ensureCloudflared();
const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "cloudflared-quick-"));
const configPath = path.join(configDir, "config.yml");
// Avoid using default ~/.cloudflared/config.yml, which can conflict with quick tunnel behavior.
fs.writeFileSync(configPath, "# quick-tunnel config placeholder\n", "utf8");
let isCleaned = false;
const cleanup = () => {
if (isCleaned) return;
isCleaned = true;
try {
fs.rmSync(configDir, { recursive: true, force: true });
} catch (e) { /* ignore */ }
};
const child = spawn(binaryPath, ["tunnel", "--url", `http://localhost:${localPort}`, "--config", configPath, "--no-autoupdate"], {
detached: false,
windowsHide: true,
stdio: ["ignore", "pipe", "pipe"]
});
cloudflaredProcess = child;
savePid(child.pid);
return new Promise((resolve, reject) => {
let resolved = false;
const timeout = setTimeout(() => {
if (resolved) return;
resolved = true;
cleanup();
reject(new Error("Quick tunnel timed out"));
}, 90000);
const handleLog = (data) => {
const msg = data.toString();
// Parse trycloudflare.com URL from cloudflared output
const match = msg.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/);
if (match && !resolved) {
const tunnelUrl = match[0];
resolved = true;
clearTimeout(timeout);
cleanup();
resolve({ child, tunnelUrl });
// Notify caller of URL (for re-registration on URL change)
if (onUrlUpdate) onUrlUpdate(tunnelUrl);
}
};
child.stdout.on("data", handleLog);
child.stderr.on("data", handleLog);
child.on("error", (err) => {
if (resolved) return;
resolved = true;
clearTimeout(timeout);
cleanup();
reject(err);
});
child.on("exit", (code) => {
cloudflaredProcess = null;
clearPid();
if (!resolved) {
resolved = true;
clearTimeout(timeout);
cleanup();
reject(new Error(`cloudflared exited with code ${code}`));
return;
}
if (unexpectedExitHandler) unexpectedExitHandler();
cleanup();
});
});
}
export function killCloudflared() { export function killCloudflared() {
if (cloudflaredProcess) { if (cloudflaredProcess) {
try { try {

View File

@@ -1,11 +1,10 @@
import crypto from "crypto"; import crypto from "crypto";
import { loadState, saveState, clearState } from "./state.js"; import { loadState, saveState } from "./state.js";
import { spawnCloudflared, killCloudflared, isCloudflaredRunning, setUnexpectedExitHandler } from "./cloudflared.js"; import { spawnQuickTunnel, killCloudflared, isCloudflaredRunning, setUnexpectedExitHandler } from "./cloudflared.js";
import { getSettings, updateSettings } from "@/lib/localDb"; import { getSettings, updateSettings } from "@/lib/localDb";
const TUNNEL_WORKER_URL = process.env.TUNNEL_WORKER_URL || "https://tunnel.9router.com"; const WORKER_URL = process.env.TUNNEL_WORKER_URL || "https://9router.com";
const MACHINE_ID_SALT = "9router-tunnel-salt"; const MACHINE_ID_SALT = "9router-tunnel-salt";
const API_KEY_SECRET = "9router-tunnel-api-key-secret";
const SHORT_ID_LENGTH = 6; const SHORT_ID_LENGTH = 6;
const SHORT_ID_CHARS = "abcdefghijklmnpqrstuvwxyz23456789"; const SHORT_ID_CHARS = "abcdefghijklmnpqrstuvwxyz23456789";
const RECONNECT_DELAYS_MS = [5000, 10000, 20000, 30000, 60000]; const RECONNECT_DELAYS_MS = [5000, 10000, 20000, 30000, 60000];
@@ -31,65 +30,49 @@ function getMachineId() {
} }
} }
function generateApiKey(machineId) { /**
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"; * Register quick tunnel URL to worker (called on start and URL change)
let keyId = ""; */
for (let i = 0; i < 6; i++) { async function registerTunnelUrl(shortId, tunnelUrl) {
keyId += chars.charAt(Math.floor(Math.random() * chars.length)); await fetch(`${WORKER_URL}/api/tunnel/register`, {
} method: "POST",
const crc = crypto.createHmac("sha256", API_KEY_SECRET).update(machineId + keyId).digest("hex").slice(0, 8); headers: { "Content-Type": "application/json" },
return `sk-${machineId}-${keyId}-${crc}`; body: JSON.stringify({ shortId, tunnelUrl })
}
async function workerFetch(reqPath, options = {}) {
const url = `${TUNNEL_WORKER_URL}${reqPath}`;
const res = await fetch(url, {
...options,
headers: { "Content-Type": "application/json", ...options.headers }
}); });
return res.json();
} }
export async function enableTunnel() { export async function enableTunnel(localPort = 20128) {
const existing = loadState(); if (isCloudflaredRunning()) {
if (existing && existing.tunnelUrl && isCloudflaredRunning()) { const existing = loadState();
return { success: true, tunnelUrl: existing.tunnelUrl, shortId: existing.shortId, alreadyRunning: true }; if (existing?.tunnelUrl) {
return { success: true, tunnelUrl: existing.tunnelUrl, shortId: existing.shortId, alreadyRunning: true };
}
} }
killCloudflared(); killCloudflared();
const machineId = getMachineId(); const machineId = getMachineId();
const existing = loadState();
const shortId = existing?.shortId || generateShortId(); const shortId = existing?.shortId || generateShortId();
const apiKey = existing?.apiKey || generateApiKey(machineId);
await workerFetch("/api/session/create", { // Spawn quick tunnel, parse URL from cloudflared output
method: "POST", const { tunnelUrl } = await spawnQuickTunnel(localPort, async (url) => {
body: JSON.stringify({ apiKey, shortId }) // Called on URL change (restart) - re-register new URL
await registerTunnelUrl(shortId, url);
saveState({ shortId, machineId, tunnelUrl: url });
await updateSettings({ tunnelEnabled: true, tunnelUrl: url });
}); });
const tunnelResult = await workerFetch("/api/tunnel/create", { // Register initial URL
method: "POST", await registerTunnelUrl(shortId, tunnelUrl);
body: JSON.stringify({ apiKey }) saveState({ shortId, machineId, tunnelUrl });
}); await updateSettings({ tunnelEnabled: true, tunnelUrl });
if (tunnelResult.error) {
throw new Error(tunnelResult.error);
}
const { token, hostname } = tunnelResult;
await spawnCloudflared(token);
saveState({ shortId, apiKey, tunnelUrl: hostname, machineId });
await updateSettings({ tunnelEnabled: true, tunnelUrl: hostname });
// Re-register exit handler each time tunnel starts (handles reconnect scenario too)
setUnexpectedExitHandler(() => { setUnexpectedExitHandler(() => {
if (!isReconnecting) scheduleReconnect(0); if (!isReconnecting) scheduleReconnect(0);
}); });
return { success: true, tunnelUrl: hostname, shortId }; return { success: true, tunnelUrl, shortId };
} }
async function scheduleReconnect(attempt) { async function scheduleReconnect(attempt) {
@@ -97,14 +80,13 @@ async function scheduleReconnect(attempt) {
isReconnecting = true; isReconnecting = true;
const delay = RECONNECT_DELAYS_MS[Math.min(attempt, RECONNECT_DELAYS_MS.length - 1)]; const delay = RECONNECT_DELAYS_MS[Math.min(attempt, RECONNECT_DELAYS_MS.length - 1)];
console.log(`[Tunnel] Unexpected exit detected, reconnecting in ${delay / 1000}s (attempt ${attempt + 1})...`); console.log(`[Tunnel] Reconnecting in ${delay / 1000}s (attempt ${attempt + 1})...`);
await new Promise((r) => setTimeout(r, delay)); await new Promise((r) => setTimeout(r, delay));
try { try {
const settings = await getSettings(); const settings = await getSettings();
if (!settings.tunnelEnabled) { if (!settings.tunnelEnabled) {
console.log("[Tunnel] Tunnel disabled, skipping reconnect");
isReconnecting = false; isReconnecting = false;
return; return;
} }
@@ -115,30 +97,17 @@ async function scheduleReconnect(attempt) {
console.log(`[Tunnel] Reconnect attempt ${attempt + 1} failed:`, err.message); console.log(`[Tunnel] Reconnect attempt ${attempt + 1} failed:`, err.message);
isReconnecting = false; isReconnecting = false;
const nextAttempt = attempt + 1; const nextAttempt = attempt + 1;
if (nextAttempt < MAX_RECONNECT_ATTEMPTS) { if (nextAttempt < MAX_RECONNECT_ATTEMPTS) scheduleReconnect(nextAttempt);
scheduleReconnect(nextAttempt); else console.log("[Tunnel] All reconnect attempts exhausted");
} else {
console.log("[Tunnel] All reconnect attempts exhausted");
}
} }
} }
export async function disableTunnel() { export async function disableTunnel() {
const state = loadState();
killCloudflared(); killCloudflared();
if (state?.apiKey) { const state = loadState();
try {
await workerFetch("/api/tunnel/delete", {
method: "DELETE",
body: JSON.stringify({ apiKey: state.apiKey })
});
} catch (e) { /* ignore worker errors on disable */ }
}
if (state) { if (state) {
saveState({ shortId: state.shortId, apiKey: state.apiKey, machineId: state.machineId, tunnelUrl: null }); saveState({ shortId: state.shortId, machineId: state.machineId, tunnelUrl: null });
} }
await updateSettings({ tunnelEnabled: false, tunnelUrl: "" }); await updateSettings({ tunnelEnabled: false, tunnelUrl: "" });
@@ -150,11 +119,14 @@ export async function getTunnelStatus() {
const state = loadState(); const state = loadState();
const running = isCloudflaredRunning(); const running = isCloudflaredRunning();
const settings = await getSettings(); const settings = await getSettings();
const shortId = state?.shortId || "";
const publicUrl = shortId ? `https://r${shortId}.9router.com` : "";
return { return {
enabled: settings.tunnelEnabled === true && running, enabled: settings.tunnelEnabled === true && running,
tunnelUrl: state?.tunnelUrl || "", tunnelUrl: state?.tunnelUrl || "",
shortId: state?.shortId || "", shortId,
publicUrl,
running running
}; };
} }