feat: add cloudflare tunnel feature with server version check (>=0.5.18) and bump version to v0.9.80

This commit is contained in:
haorwen
2026-06-12 10:56:14 +08:00
parent 351da6fa4d
commit 497e0f309e
7 changed files with 311 additions and 7 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "vocechat-web",
"version": "0.9.79",
"version": "0.9.80",
"homepage": "https://voce.chat",
"dependencies": {
"@metamask/onboarding": "^1.0.1",
+20 -2
View File
@@ -27,7 +27,8 @@
"api_doc": "API Documentation",
"version": "Version",
"video": "Video",
"notification": "Notifications"
"notification": "Notifications",
"cloudflared": "Cloudflare Tunnel"
},
"channel": {
"leave": "Leave Channel",
@@ -461,5 +462,22 @@
"update_error": "Failed to update channel type",
"delete_success": "Channel type deleted successfully",
"delete_error": "Failed to delete channel type"
},
"cloudflared": {
"title": "Cloudflare Tunnel",
"desc": "Expose this server to the public internet via a temporary trycloudflare.com tunnel — no Cloudflare account required.",
"start": "Start Tunnel",
"stop": "Stop Tunnel",
"stopping": "Stopping...",
"copy": "Copy",
"url_copied": "URL copied to clipboard",
"downloading_binary": "Downloading cloudflared binary...",
"status": {
"idle": "Idle",
"downloading": "Downloading",
"starting": "Starting",
"running": "Running",
"error": "Error"
}
}
}
}
+20 -4
View File
@@ -26,7 +26,8 @@
"version": "版本信息",
"feedback": "反馈",
"video": "音视频",
"notification": "通知设置"
"notification": "通知设置",
"cloudflared": "Cloudflare 隧道"
},
"channel": {
"leave": "离开",
@@ -58,7 +59,6 @@
"name": "服务器名",
"desc": "服务器描述",
"upload_desc": "图片最小 128x128,我们推荐上传 512x512 大小的图片,最大不要超过 5M。",
"sign_up": {
"title": "注册设置",
"desc": "允许什么方式注册",
@@ -201,7 +201,6 @@
"renew": "升级证书",
"update": "手动更新",
"update_placeholder": "请输入新的证书内容",
"renew_select": "请选择价格套餐",
"tip": {
"title": "一个获取免费升级的机会!",
@@ -460,5 +459,22 @@
"update_error": "渠道类型更新失败",
"delete_success": "渠道类型删除成功",
"delete_error": "渠道类型删除失败"
},
"cloudflared": {
"title": "Cloudflare 隧道",
"desc": "通过临时 trycloudflare.com 隧道将此服务器暴露到公网,无需 Cloudflare 账号。",
"start": "启动隧道",
"stop": "停止隧道",
"stopping": "停止中...",
"copy": "复制",
"url_copied": "链接已复制到剪贴板",
"downloading_binary": "正在下载 cloudflared 二进制文件...",
"status": {
"idle": "空闲",
"downloading": "下载中",
"starting": "启动中",
"running": "运行中",
"error": "错误"
}
}
}
}
+13
View File
@@ -7,6 +7,7 @@ import {
AgoraConfig,
AgoraTokenResponse,
AgoraVoicingListResponse,
CloudflaredStatus,
CreateAdminDTO,
FirebaseConfig,
GithubAuthConfig,
@@ -482,6 +483,16 @@ export const serverApi = createApi({
}),
invalidatesTags: (result, error, gid) => [{ type: "GroupAnnouncements", id: gid }],
}),
getCloudflaredStatus: builder.query<CloudflaredStatus, void>({
query: () => ({ url: `/admin/cloudflared/status` }),
}),
stopCloudflared: builder.mutation<string, void>({
query: () => ({
url: `/admin/cloudflared/stop`,
method: "POST",
responseHandler: "text",
}),
}),
}),
});
@@ -543,4 +554,6 @@ export const {
useGetGroupAnnouncementQuery,
useCreateOrUpdateGroupAnnouncementMutation,
useDeleteGroupAnnouncementMutation,
useLazyGetCloudflaredStatusQuery,
useStopCloudflaredMutation,
} = serverApi;
+245
View File
@@ -0,0 +1,245 @@
import { useEffect, useRef, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { BASE_ORIGIN, tokenHeader } from "@/app/config";
import { useLazyGetCloudflaredStatusQuery, useStopCloudflaredMutation } from "@/app/services/server";
import ServerVersionChecker from "@/components/ServerVersionChecker";
import Button from "@/components/styled/Button";
import { getLocalAuthData } from "@/utils";
type TunnelStatus = "idle" | "downloading" | "starting" | "running" | "error";
interface SseEvent {
event: string;
message: string;
url: string | null;
progress: number | null;
}
export default function Cloudflared() {
const { t } = useTranslation("setting", { keyPrefix: "cloudflared" });
const [status, setStatus] = useState<TunnelStatus>("idle");
const [tunnelUrl, setTunnelUrl] = useState<string | null>(null);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [downloadProgress, setDownloadProgress] = useState(0);
const [logs, setLogs] = useState<string[]>([]);
const [streaming, setStreaming] = useState(false);
const abortRef = useRef<AbortController | null>(null);
const [getStatus] = useLazyGetCloudflaredStatusQuery();
const [stopCloudflared, { isLoading: isStopping }] = useStopCloudflaredMutation();
useEffect(() => {
getStatus().then((res) => {
if (res.data) {
setStatus(res.data.status);
setTunnelUrl(res.data.url);
setErrorMsg(res.data.error);
}
});
}, []);
const addLog = (msg: string) =>
setLogs((prev) => [...prev.slice(-29), msg]);
const handleSseEvent = (evt: SseEvent) => {
addLog(evt.message);
switch (evt.event) {
case "downloading":
setStatus("downloading");
if (evt.progress != null) setDownloadProgress(evt.progress);
break;
case "progress":
setStatus("starting");
break;
case "url":
setStatus("running");
setTunnelUrl(evt.url);
break;
case "already_running":
setStatus("running");
setTunnelUrl(evt.url);
break;
case "error":
setStatus("error");
setErrorMsg(evt.message);
break;
case "stopped":
setStatus("idle");
break;
}
};
const startTunnel = async () => {
if (streaming) return;
setStreaming(true);
setStatus("starting");
setLogs([]);
setTunnelUrl(null);
setErrorMsg(null);
setDownloadProgress(0);
const ctrl = new AbortController();
abortRef.current = ctrl;
try {
const { token } = getLocalAuthData();
const resp = await fetch(`${BASE_ORIGIN}/api/admin/cloudflared/start`, {
method: "POST",
headers: { [tokenHeader]: token },
signal: ctrl.signal,
});
if (!resp.ok || !resp.body) {
setStatus("error");
setErrorMsg(`HTTP ${resp.status}`);
setStreaming(false);
return;
}
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buf = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
const parts = buf.split("\n\n");
buf = parts.pop() ?? "";
for (const part of parts) {
const line = part.trim();
if (!line.startsWith("data:")) continue;
try {
const evt: SseEvent = JSON.parse(line.slice("data:".length).trim());
handleSseEvent(evt);
if (["url", "error", "stopped", "already_running"].includes(evt.event)) {
reader.cancel();
setStreaming(false);
return;
}
} catch {
// ignore malformed lines
}
}
}
} catch (err: any) {
if (err?.name !== "AbortError") {
setStatus("error");
setErrorMsg(String(err));
}
} finally {
setStreaming(false);
abortRef.current = null;
}
};
const handleStop = async () => {
abortRef.current?.abort();
await stopCloudflared();
setStatus("idle");
setTunnelUrl(null);
setLogs([]);
};
const handleCopyUrl = () => {
if (!tunnelUrl) return;
navigator.clipboard.writeText(tunnelUrl);
toast.success(t("url_copied"));
};
const statusBadge: Record<TunnelStatus, string> = {
idle: "bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300",
downloading: "bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300",
starting: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/40 dark:text-yellow-300",
running: "bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300",
error: "bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",
};
const isActive = status === "running" || status === "downloading" || status === "starting";
return (
<ServerVersionChecker version="0.5.18">
<div className="setting-container max-md:w-full flex flex-col gap-6">
<div>
<h3 className="text-lg font-bold text-gray-800 dark:text-white">{t("title")}</h3>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">{t("desc")}</p>
</div>
<div className="flex items-center gap-2">
<span className={`px-2.5 py-0.5 rounded-full text-xs font-semibold ${statusBadge[status]}`}>
{t(`status.${status}`)}
</span>
</div>
{status === "downloading" && (
<div>
<div className="flex justify-between text-xs text-gray-500 dark:text-gray-400 mb-1">
<span>{t("downloading_binary")}</span>
<span>{downloadProgress}%</span>
</div>
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
<div
className="bg-blue-500 h-2 rounded-full transition-all duration-300"
style={{ width: `${downloadProgress}%` }}
/>
</div>
</div>
)}
{status === "running" && tunnelUrl && (
<div className="flex items-center gap-2 p-3 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-700 rounded-lg">
<a
href={tunnelUrl}
target="_blank"
rel="noreferrer"
className="text-sm text-green-700 dark:text-green-300 font-mono break-all flex-1 hover:underline"
>
{tunnelUrl}
</a>
<button
onClick={handleCopyUrl}
className="shrink-0 text-xs px-2 py-1 rounded bg-green-200 dark:bg-green-700 text-green-800 dark:text-green-100 hover:bg-green-300 dark:hover:bg-green-600 transition-colors"
>
{t("copy")}
</button>
</div>
)}
{status === "error" && errorMsg && (
<div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700 rounded-lg text-sm text-red-700 dark:text-red-300 break-all">
{errorMsg}
</div>
)}
{logs.length > 0 && (
<div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg font-mono text-xs text-gray-500 dark:text-gray-400 max-h-44 overflow-y-auto flex flex-col gap-0.5">
{logs.map((log, i) => (
<div key={i}>{log}</div>
))}
</div>
)}
<div className="flex gap-3">
{!isActive && (
<Button disabled={streaming} onClick={startTunnel}>
{t("start")}
</Button>
)}
{isActive && (
<button
onClick={handleStop}
disabled={isStopping}
className="px-4 py-2 rounded bg-red-500 hover:bg-red-600 disabled:opacity-50 text-white text-sm font-medium transition-colors"
>
{isStopping ? t("stopping") : t("stop")}
</button>
)}
</div>
</div>
</ServerVersionChecker>
);
}
+6
View File
@@ -6,6 +6,7 @@ import Version from "@/components/Version";
import APIConfig from "./APIConfig";
import APIDocument from "./APIDocument";
import BotConfig from "./BotConfig";
import Cloudflared from "./Cloudflared";
import ConfigAgora from "./config/Agora";
import ConfigFirebase from "./config/Firebase";
import Logins from "./config/Logins";
@@ -56,6 +57,11 @@ const navs = [
component: <BotConfig />,
admin: true,
},
{
name: "cloudflared",
component: <Cloudflared />,
admin: true,
},
{
name: "notification_channels",
component: <AdminNotificationChannels />,
+6
View File
@@ -144,3 +144,9 @@ export interface RenewLicenseResponse {
export interface CreateAdminDTO extends Pick<User, "email" | "name" | "gender"> {
password: string;
}
export interface CloudflaredStatus {
status: "idle" | "downloading" | "starting" | "running" | "error";
url: string | null;
error: string | null;
}