Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ tauri-plugin-deep-link = "2"
# 编出来的东西不一样;而更要紧的是,打进 `.app` 的那个 twcore 二进制
# 必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是从
# 这个 tag 去取二进制的(见 scripts/fetch-core.sh)。
tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.8.2" }
tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.9.0" }

anyhow = "1"
libc = "0.2"
Expand Down
73 changes: 65 additions & 8 deletions src-tauri/src/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -805,14 +805,71 @@ impl ControlClient {
.await
}

/// 生成一把新的网关密钥。**不写进配置** —— 只是拿一个值去填。
///
/// 在 core 里生成,不在界面里:字母表和长度是安全决定,两处各写
/// 一份的话迟早只有一处被改。
pub async fn new_key(&self) -> Result<String> {
let body = self.get("/keys/new").await?;
let k: tw_api::NewKey = serde_json::from_slice(&body)?;
Ok(k.key)
// ── 网关密钥。**规则全在 core**:默认密钥删不得、接管中的删不得、
// 改名带着规则一起改、更换同步给被接管的客户端

pub async fn keys(&self) -> Result<Vec<tw_api::ClientView>> {
Ok(serde_json::from_slice(&self.get("/keys").await?)?)
}

/// 一把密钥的明文。**只在用户点「复制」那一刻问**
pub async fn key_value(&self, name: &str) -> Result<tw_api::KeyValue> {
Ok(serde_json::from_slice(
&self.get(&format!("/keys/{}/value", segment(name))).await?,
)?)
}

pub async fn create_key(&self, req: &tw_api::KeySave) -> Result<tw_api::ConfigWritten> {
self.post_json("/keys", req).await
}

pub async fn update_key(
&self,
name: &str,
req: &tw_api::KeySave,
) -> Result<tw_api::ConfigWritten> {
self.send_json(hyper::Method::PUT, &format!("/keys/{}", segment(name)), req)
.await
}

pub async fn delete_key(
&self,
name: &str,
base_version: Option<&str>,
) -> Result<tw_api::ConfigWritten> {
let path = with_base(format!("/keys/{}", segment(name)), base_version);
self.send_json(hyper::Method::DELETE, &path, &()).await
}

/// 换一把新的,并同步给正在用它的客户端。**一次调用做完两件事**
pub async fn rotate_key(
&self,
name: &str,
base_version: Option<&str>,
) -> Result<tw_api::KeyRotated> {
self.post_json(
&format!("/keys/{}/rotate", segment(name)),
&tw_api::KeyRotate {
base_version: base_version.map(str::to_string),
},
)
.await
}

pub async fn set_default_key(
&self,
name: &str,
base_version: Option<&str>,
) -> Result<tw_api::ConfigWritten> {
self.send_json(
hyper::Method::PUT,
"/default_key",
&tw_api::DefaultKeySave {
name: name.to_string(),
base_version: base_version.map(str::to_string),
},
)
.await
}

/// 这台机器上有哪些网卡。
Expand Down
126 changes: 126 additions & 0 deletions src-tauri/src/keys.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
//! 密钥页的命令。
//!
//! **这一层只转发**,规则全在 core:默认密钥删不得、接管中的密钥删不得、
//! 改名要带着规则一起改、更换要同步给被接管的客户端。界面这边再判断一次,
//! 就多一处和 core 说法不一致的可能。
//!
//! 只有一件事在这里做:**把密钥放进剪贴板**。明文由这一层去问 core,
//! 不经过界面 —— 否则等于给 webview 开一个往剪贴板里写任意内容的口子。

use crate::AppState;

type Out<T> = Result<T, String>;

fn text(e: anyhow::Error) -> String {
format!("{e:#}")
}

#[tauri::command]
pub async fn list_keys(state: tauri::State<'_, AppState>) -> Out<Vec<tw_api::ClientView>> {
state.control.keys().await.map_err(text)
}

#[tauri::command]
pub async fn create_key(
state: tauri::State<'_, AppState>,
save: tw_api::KeySave,
) -> Out<tw_api::ConfigWritten> {
state.control.create_key(&save).await.map_err(text)
}

#[tauri::command]
pub async fn update_key(
state: tauri::State<'_, AppState>,
name: String,
save: tw_api::KeySave,
) -> Out<tw_api::ConfigWritten> {
state.control.update_key(&name, &save).await.map_err(text)
}

#[tauri::command]
pub async fn delete_key(
state: tauri::State<'_, AppState>,
name: String,
base_version: Option<String>,
) -> Out<tw_api::ConfigWritten> {
state
.control
.delete_key(&name, base_version.as_deref())
.await
.map_err(text)
}

/// 换一把新的。core 会把新值同步给正在用它的那个客户端。
#[tauri::command]
pub async fn rotate_key(
state: tauri::State<'_, AppState>,
name: String,
base_version: Option<String>,
) -> Out<tw_api::KeyRotated> {
state
.control
.rotate_key(&name, base_version.as_deref())
.await
.map_err(text)
}

#[tauri::command]
pub async fn set_default_key(
state: tauri::State<'_, AppState>,
name: String,
base_version: Option<String>,
) -> Out<tw_api::ConfigWritten> {
state
.control
.set_default_key(&name, base_version.as_deref())
.await
.map_err(text)
}

/// 把这把密钥放进剪贴板。
///
/// **明文不经过界面。**界面拿着它,就等于多了一个「界面传来一段文字、
/// 应用写进剪贴板」的口子;而在 Rust 这边写也不用看 webview 给不给剪贴板
/// 权限 —— 一个「复制」按钮唯一不能有的表现就是点了没反应。
#[tauri::command]
pub async fn copy_key(
app: tauri::AppHandle,
state: tauri::State<'_, AppState>,
name: String,
) -> Out<()> {
use tauri_plugin_clipboard_manager::ClipboardExt;
let v = state.control.key_value(&name).await.map_err(text)?;
app.clipboard().write_text(v.key).map_err(|e| e.to_string())
}

/// 客户端该连的网关地址。新建密钥之后那一屏要和密钥一起给出来。
#[tauri::command]
pub async fn gateway_base(state: tauri::State<'_, AppState>) -> Out<String> {
let clients = state.control.clients().await.map_err(text)?;
Ok(clients.gateway_base)
}

#[tauri::command]
pub async fn copy_gateway_base(
app: tauri::AppHandle,
state: tauri::State<'_, AppState>,
) -> Out<()> {
use tauri_plugin_clipboard_manager::ClipboardExt;
let clients = state.control.clients().await.map_err(text)?;
app.clipboard()
.write_text(clients.gateway_base)
.map_err(|e| e.to_string())
}

/// 每把密钥这段时间发了多少请求。**按密钥算,不是按客户端自报的标识**
#[tauri::command]
pub async fn key_usage(
state: tauri::State<'_, AppState>,
since_ms: i64,
) -> Out<Vec<tw_api::CostGroup>> {
Ok(state
.control
.cost_by("client", since_ms)
.await
.unwrap_or_default())
}
17 changes: 11 additions & 6 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use tauri::{Emitter, Manager, WebviewUrl, WebviewWindowBuilder};
pub mod autostart;
pub mod chatgpt;
pub mod control;
pub mod keys;
pub mod memcheck;
pub mod menubar;
pub mod notices;
Expand Down Expand Up @@ -159,11 +160,6 @@ pub fn locate_core(app: &tauri::AppHandle) -> anyhow::Result<PathBuf> {
)
}

#[tauri::command]
async fn new_key(state: tauri::State<'_, AppState>) -> Result<String, String> {
state.control.new_key().await.map_err(|e| format!("{e:#}"))
}

#[tauri::command]
async fn interfaces(state: tauri::State<'_, AppState>) -> Result<Vec<tw_api::NicView>, String> {
state
Expand Down Expand Up @@ -1227,7 +1223,6 @@ pub fn run() {
.invoke_handler(tauri::generate_handler![
core_status,
interfaces,
new_key,
core_state,
restart_core,
overview,
Expand Down Expand Up @@ -1269,6 +1264,16 @@ pub fn run() {
notice_prefs,
set_notice_pref,
take_pending_view,
keys::list_keys,
keys::create_key,
keys::update_key,
keys::delete_key,
keys::rotate_key,
keys::set_default_key,
keys::copy_key,
keys::gateway_base,
keys::copy_gateway_base,
keys::key_usage,
chatgpt::start_chatgpt_login,
chatgpt::reopen_chatgpt_login,
chatgpt::copy_chatgpt_code,
Expand Down
11 changes: 5 additions & 6 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import Config from "./Config";
import { ConfigFileDialog, VersionHistoryDialog } from "./ConfigDialogs";
import UpstreamsPage from "./upstreams/UpstreamsPage";
import Clients from "./Clients";
import Keys from "./Keys";
import KeysPage from "./keys/KeysPage";
import RoutingPage from "./routing/RoutingPage";
import Security from "./Security";
import Guard from "./Guard";
Expand Down Expand Up @@ -1087,10 +1087,7 @@ export default function App() {
) : tab === "dashboard" ? (
<Dashboard tick={dashTick} ov={ov} />
) : tab === "clients" ? (
<Clients
clientKeys={(ov?.clients ?? []).map((c) => c.name)}
configVersion={configVersion}
/>
<Clients />
) : tab === "security" ? (
<Security alerts={alerts} onSeen={clearAlerts} />
) : tab === "guard" ? (
Expand All @@ -1105,10 +1102,12 @@ export default function App() {
)
) : tab === "keys" ? (
ov ? (
<Keys
<KeysPage
ov={ov}
configVersion={configVersion}
onChanged={() => setNudge((n) => n + 1)}
onOpenConfigFile={(focus) => setConfigFile({ focus })}
onNavigate={(to) => setTab(to as Surface)}
/>
) : (
<p className="p-5 tw-body text-muted-foreground">读取配置中…</p>
Expand Down
42 changes: 8 additions & 34 deletions src/Clients.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { Badge } from "@/ui/badge";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/ui/empty";
import { toast } from "sonner";
import { useCoreEvent } from "./useCoreEvent";
import { patchConfig } from "./patch";
import { FIELDS_ONLY_TEXT, takesEffectText } from "./labels";
import {
Dialog,
Expand All @@ -35,14 +34,7 @@ import {
* - 接管完成后**不宣布成功**,只说「已接管,等第一个请求」。
* 我们改了一个文件,但那个文件有没有被读到,只有请求能证明。
*/
export default function Clients({
clientKeys,
configVersion,
}: {
/** 配置里已有的密钥名。接管时用来判断「要不要先建一把」 */
clientKeys: string[];
configVersion: string | null;
}) {
export default function Clients() {
const [data, setData] = useState<ClientsResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const [plan, setPlan] = useState<{ p: PlanView; c: DetectedClient; restore: boolean } | null>(
Expand Down Expand Up @@ -106,34 +98,16 @@ export default function Clients({
setBusy(true);
try {
/*
**每个客户端用它自己那把密钥,不再共用第一把。**

在此之前这里不传 `key_name`,于是 core 一路落到
`cfg.clients.first()` —— 五个被接管的客户端拿到同一把密钥。
后果是连锁的:`RequestFacts.client` 永远是同一个值,所以按密钥
绑路由匹不到、每客户端并发上限形同虚设、流量和会话里也分不出
是谁发的。**整条「按客户端」的能力链因为末端少传一个参数而
全线失效。**

没有同名密钥就先建一把。建和用是两次写入,中间那一刻只是「多了
一把还未被引用的密钥」—— 一个无害的状态,而反过来(先接管再建)
那一刻客户端配的是一把不存在的密钥。
**密钥由 core 备好**:每个被接管的客户端有它自己的一把。

以前这一步在界面里做 —— 先生成一个值、再拼两行 YAML 写进配置、
再接管。三次调用之间任何一次失败,留下的都是「客户端配了一把
config.yaml 里没有的钥匙」。现在 core 在落盘那一步一并处理:
为这个客户端留着的那把(包括取消接管后留下的)直接复用,
一把也没有才新建。
*/
const keyName = plan.c.id;
if (!plan.restore && !clientKeys.includes(keyName)) {
// **类型查出来的。**这里原本直接把 `configVersion` 递进去,而它
// 可能还是 null(core 刚起来、第一次配置读回来之前)。那种时候
// 建密钥会失败,而接管照样往下走 —— 客户端配上一把不存在的密钥。
if (!configVersion) {
toast.error("配置版本尚未读取,请稍后重试");
return;
}
const key = await invoke<string>("new_key");
await patchConfig([{ op: "append", path: "/clients", item: `name: ${keyName}\nkey: ${key}` }], configVersion);
}
const r = await invoke<AdoptResponse>(plan.restore ? "restore_client" : "adopt_client", {
client: plan.c.id,
keyName: plan.restore ? null : keyName,
});
setPlan(null);
setDone(r);
Expand Down
Loading
Loading