diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 5d66e151..941770f5 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4982,8 +4982,8 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "tw-api" -version = "0.8.2" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.8.2#afee6593ff539efac541a2fa52247d622cf17ab8" +version = "0.9.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.9.0#1a05e15a5dadc2b50372e42ff3b355ea6ee803ca" dependencies = [ "serde", "serde_json", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index bbcf7b1d..9727555b 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -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" diff --git a/src-tauri/src/control.rs b/src-tauri/src/control.rs index 54edc5cc..1de6d80d 100644 --- a/src-tauri/src/control.rs +++ b/src-tauri/src/control.rs @@ -805,14 +805,71 @@ impl ControlClient { .await } - /// 生成一把新的网关密钥。**不写进配置** —— 只是拿一个值去填。 - /// - /// 在 core 里生成,不在界面里:字母表和长度是安全决定,两处各写 - /// 一份的话迟早只有一处被改。 - pub async fn new_key(&self) -> Result { - 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> { + Ok(serde_json::from_slice(&self.get("/keys").await?)?) + } + + /// 一把密钥的明文。**只在用户点「复制」那一刻问** + pub async fn key_value(&self, name: &str) -> Result { + Ok(serde_json::from_slice( + &self.get(&format!("/keys/{}/value", segment(name))).await?, + )?) + } + + pub async fn create_key(&self, req: &tw_api::KeySave) -> Result { + self.post_json("/keys", req).await + } + + pub async fn update_key( + &self, + name: &str, + req: &tw_api::KeySave, + ) -> Result { + 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 { + 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 { + 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 { + self.send_json( + hyper::Method::PUT, + "/default_key", + &tw_api::DefaultKeySave { + name: name.to_string(), + base_version: base_version.map(str::to_string), + }, + ) + .await } /// 这台机器上有哪些网卡。 diff --git a/src-tauri/src/keys.rs b/src-tauri/src/keys.rs new file mode 100644 index 00000000..a23d8035 --- /dev/null +++ b/src-tauri/src/keys.rs @@ -0,0 +1,126 @@ +//! 密钥页的命令。 +//! +//! **这一层只转发**,规则全在 core:默认密钥删不得、接管中的密钥删不得、 +//! 改名要带着规则一起改、更换要同步给被接管的客户端。界面这边再判断一次, +//! 就多一处和 core 说法不一致的可能。 +//! +//! 只有一件事在这里做:**把密钥放进剪贴板**。明文由这一层去问 core, +//! 不经过界面 —— 否则等于给 webview 开一个往剪贴板里写任意内容的口子。 + +use crate::AppState; + +type Out = Result; + +fn text(e: anyhow::Error) -> String { + format!("{e:#}") +} + +#[tauri::command] +pub async fn list_keys(state: tauri::State<'_, AppState>) -> Out> { + state.control.keys().await.map_err(text) +} + +#[tauri::command] +pub async fn create_key( + state: tauri::State<'_, AppState>, + save: tw_api::KeySave, +) -> Out { + 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 { + 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, +) -> Out { + 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, +) -> Out { + 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, +) -> Out { + 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 { + 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> { + Ok(state + .control + .cost_by("client", since_ms) + .await + .unwrap_or_default()) +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index fab9cf73..304a9fa8 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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; @@ -159,11 +160,6 @@ pub fn locate_core(app: &tauri::AppHandle) -> anyhow::Result { ) } -#[tauri::command] -async fn new_key(state: tauri::State<'_, AppState>) -> Result { - state.control.new_key().await.map_err(|e| format!("{e:#}")) -} - #[tauri::command] async fn interfaces(state: tauri::State<'_, AppState>) -> Result, String> { state @@ -1227,7 +1223,6 @@ pub fn run() { .invoke_handler(tauri::generate_handler![ core_status, interfaces, - new_key, core_state, restart_core, overview, @@ -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, diff --git a/src/App.tsx b/src/App.tsx index c7bb1d5c..2b1ef10e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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"; @@ -1087,10 +1087,7 @@ export default function App() { ) : tab === "dashboard" ? ( ) : tab === "clients" ? ( - c.name)} - configVersion={configVersion} - /> + ) : tab === "security" ? ( ) : tab === "guard" ? ( @@ -1105,10 +1102,12 @@ export default function App() { ) ) : tab === "keys" ? ( ov ? ( - setNudge((n) => n + 1)} + onOpenConfigFile={(focus) => setConfigFile({ focus })} + onNavigate={(to) => setTab(to as Surface)} /> ) : (

读取配置中…

diff --git a/src/Clients.tsx b/src/Clients.tsx index 1130272c..0e1ee3bc 100644 --- a/src/Clients.tsx +++ b/src/Clients.tsx @@ -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, @@ -35,14 +34,7 @@ import { * - 接管完成后**不宣布成功**,只说「已接管,等第一个请求」。 * 我们改了一个文件,但那个文件有没有被读到,只有请求能证明。 */ -export default function Clients({ - clientKeys, - configVersion, -}: { - /** 配置里已有的密钥名。接管时用来判断「要不要先建一把」 */ - clientKeys: string[]; - configVersion: string | null; -}) { +export default function Clients() { const [data, setData] = useState(null); const [error, setError] = useState(null); const [plan, setPlan] = useState<{ p: PlanView; c: DetectedClient; restore: boolean } | null>( @@ -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("new_key"); - await patchConfig([{ op: "append", path: "/clients", item: `name: ${keyName}\nkey: ${key}` }], configVersion); - } const r = await invoke(plan.restore ? "restore_client" : "adopt_client", { client: plan.c.id, - keyName: plan.restore ? null : keyName, }); setPlan(null); setDone(r); diff --git a/src/Keys.tsx b/src/Keys.tsx deleted file mode 100644 index 4b578809..00000000 --- a/src/Keys.tsx +++ /dev/null @@ -1,417 +0,0 @@ -import { useState } from "react"; -import { invoke } from "@tauri-apps/api/core"; -import { Tip } from "@/ui/tip"; -import type { Overview, PatchOp } from "./types"; -import { Button } from "@/ui/button"; -import { Input } from "@/ui/input"; -import { Badge } from "@/ui/badge"; -import { toast } from "sonner"; -import { patchConfig } from "./patch"; -import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from "@/ui/table"; -import { - AlertDialog, - AlertDialogCancel, - AlertDialogAction, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/ui/alert-dialog"; - -/** - * 网关密钥。 - * - * **这是访问控制的唯一入口。**端口决定谁能敲门,密钥决定谁能进来 —— - * 没有密钥,即使从 127.0.0.1 也连不上(core 里是硬行为,不分内外网)。 - * - * 在此之前这一整页不存在:密钥是「监听与访问」里的一行只读文本, - * 建不了、改不了、删不了、也绑不了路由。而下面每一件事都依赖它: - * - * · **区分客户端。**所有客户端共用一把密钥时,`RequestFacts.client` - * 永远是同一个值 —— 于是流量和会话里分不出是谁发的,每客户端并发 - * 上限形同虚设,按密钥绑路由也无从谈起。 - * · **绑路由。**一把密钥绑一条路由;没绑就走默认路由。 - * · **吊销。**某个客户端的配置泄露了,要能只换它那一把,而不是全换。 - */ -/** - * 这把密钥能看到哪些模型。 - * - * 三态,而且**第三态是「不允许任何模型」** —— 一个写成 `[]` 的空列表。 - * 那不是坏状态,是「临时停掉这个客户端」的正当用法,所以界面上要能 - * 明确选到它,而不是只能通过「删掉最后一条」意外抵达。 - * - * 三态之间**每个方向都要能走回去**。第一版只有「不限 → 限制」这一 - * 扇单向门:进了限制态就再也回不到不限,因为协议里当时没有「把这个 - * 键抹掉」的说法。回去的那条路是写 `null` —— 和路由解绑同一个做法。 - */ -function AllowCell({ - client, - allow, - busy, - onPatch, -}: { - client: string; - allow: string[] | null; - busy: boolean; - onPatch: (ops: PatchOp[]) => void; -}) { - const [adding, setAdding] = useState(""); - if (allow === null) { - return ( -
- 不限 - -
- ); - } - return ( -
- {allow.length === 0 && ( -不允许任何模型 - )} - - {allow.map((m, i) => ( - - {m} - - - ))} - setAdding(e.target.value)} - onKeyDown={(e) => { - if (e.key === "Enter" && adding.trim()) { - onPatch([ - { op: "append", path: `/clients/${client}/allow`, item: adding.trim() }, - ]); - setAdding(""); - } - }} - /> -
- ); -} - -export default function Keys({ - ov, - configVersion, - onChanged, -}: { - ov: Overview; - configVersion: string | null; - onChanged: () => void; -}) { - const [busy, setBusy] = useState(null); - const [adding, setAdding] = useState(false); - const [newName, setNewName] = useState(""); - const [confirmDelete, setConfirmDelete] = useState(null); - - const routes = ov.routes ?? []; - const defaultRoute = ov.default_route ?? "默认"; - - async function patch(ops: PatchOp[], tag: string) { - if (!configVersion) { - toast.error("配置版本尚未读取,请稍后重试"); - return false; - } - setBusy(tag); - try { - await patchConfig(ops, configVersion); - onChanged(); - return true; - } catch (e) { - toast.error(typeof e === "string" ? e : String(e)); - return false; - } finally { - setBusy(null); - } - } - - async function create() { - const name = newName.trim(); - if (!name) return; - if (ov.clients.some((c) => c.name === name)) { - toast.error(`密钥「${name}」已存在`); - return; - } - setBusy("new"); - try { - // **密钥由 core 生成。**字母表(去掉了 0/O、1/I/l)和长度是安全 - // 决定,在界面里再写一份的话,迟早只有一处被改。 - const key = await invoke("new_key"); - // 名字和密钥**一次写入**。分两次的话,中间那一刻配置里有一把 - // 没有密钥的 client —— 那是个加载不了的状态。 - const ok = await patch( - [{ op: "append", path: "/clients", item: `name: ${name}\nkey: ${key}` }], - "new", - ); - if (ok) { - setAdding(false); - setNewName(""); - } - } catch (e) { - toast.error(typeof e === "string" ? e : String(e)); - setBusy(null); - } - } - - async function regenerate(name: string) { - setBusy(name); - try { - const key = await invoke("new_key"); - await patch([{ op: "replace", path: `/clients/${name}/key`, value: key }], name); - } catch (e) { - toast.error(typeof e === "string" ? e : String(e)); - setBusy(null); - } - } - - return ( -
-
-
-

- 客户端须使用密钥连接网关,本机连接也不例外。 -

- -
- - {adding && ( -
- setNewName(e.target.value)} - onKeyDown={(e) => { - if (e.key === "Enter") void create(); - if (e.key === "Escape") setAdding(false); - }} - /> - - -
- )} - - - - - 名称 - 密钥 - 路由 - 并发上限 - 可见模型 - - - - - {ov.clients.map((c) => ( - - {c.name} - {c.key} - - {/* - 不绑就是走默认路由 —— 选项里把它写出来,而不是留一个 - 空白。**空白读起来是「还没配」,而它其实一直在生效。** - */} - - void patch( - [ - { - op: "replace", - path: `/clients/${c.name}/route`, - // 原生 option 收空串,「没绑」就是空串本身 - value: e.target.value || null, - }, - ], - c.name, - ) - } - > - - 默认({defaultRoute}) - - {routes - .filter((r) => !r.default) - .map((r) => ( - - {r.name} - - ))} - - - - { - const raw = e.target.value.trim(); - const v = raw === "" ? null : Number(raw); - if (v !== null && (!Number.isFinite(v) || v < 1)) { - toast.error("并发上限须为不小于 1 的整数,留空表示不限"); - return; - } - if ((c.max_concurrent ?? null) === v) return; - void patch( - [ - { - op: "replace", - path: `/clients/${c.name}/max_concurrent`, - value: v, - }, - ], - c.name, - ); - }} - /> - - - {/* - **三态,而且第三态是「不允许任何模型」。**留空 = 只按方言 - 过滤;写了 glob = 再按它保留;写一个空列表 = 这把密钥 - 看不到任何模型,也就用不了 —— 那是「临时停掉这个客户端」 - 的正当用法,而不是一个坏状态。 - */} - void patch(ops, c.name)} - /> - - - - - - {/* - **最后一把不给删。**删光之后谁也连不上,而且配置会 - 加载失败(`validate` 要求至少一把)—— 那时网关起不来, - 用户看到的是「core 连续失败」,而原因在三步之前。 - */} - - - - - - ))} - -
- -
- - !o && setConfirmDelete(null)} - > - - - 删除密钥「{confirmDelete}」 - - 删除后,使用此密钥的客户端将立即无法连接,需重新配置密钥。可在版本历史中恢复。 - - - - 取消 - { - const name = confirmDelete; - setConfirmDelete(null); - if (name) void patch([{ op: "remove", path: `/clients/${name}` }], name); - }} - > - 删除 - - - - -
- ); -} diff --git a/src/keys/KeyDialog.tsx b/src/keys/KeyDialog.tsx new file mode 100644 index 00000000..2725a708 --- /dev/null +++ b/src/keys/KeyDialog.tsx @@ -0,0 +1,276 @@ +import { useState } from "react"; +import { CopyIcon, RotateCwIcon } from "lucide-react"; +import { Button } from "@/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/ui/dialog"; +import { Input } from "@/ui/input"; +import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; +import { Spinner } from "@/ui/spinner"; +import { Switch } from "@/ui/switch"; +import { when } from "@/format"; +import type { ClientView, CostGroup, DetectedClient, RouteView } from "@/types"; +import { api } from "./api"; +import { errorText, routeLabel, useLabel } from "./labels"; + +/** 可见模型的三态。第三态是「一个都不给」——「临时停掉」的正当用法 */ +type Scope = "all" | "some" | "none"; + +function scopeOf(allow: string[] | null | undefined): Scope { + if (allow == null) return "all"; + return allow.length === 0 ? "none" : "some"; +} + +/** + * 新建与编辑一把密钥。 + * + * 密钥的值不是一个可填的字段:它由 core 生成,要换走「更换」—— + * 那条路会把新值同步给正在用它的客户端。 + */ +export function KeyDialog({ + editing, + keys, + clients, + usage, + routes, + defaultRoute, + configVersion, + onClose, + onSaved, + onRotate, +}: { + /** 编辑哪一把。不给就是新建 */ + editing: ClientView | null; + keys: ClientView[]; + clients: DetectedClient[]; + usage: CostGroup[]; + routes: RouteView[]; + defaultRoute: string; + configVersion: string | null; + onClose: () => void; + onSaved: (name: string) => void; + onRotate: (name: string) => void; +}) { + const [name, setName] = useState(editing?.name ?? ""); + const [route, setRoute] = useState(editing?.route ?? ""); + const [scope, setScope] = useState(scopeOf(editing?.allow)); + const [globs, setGlobs] = useState((editing?.allow ?? []).join("\n")); + const [limit, setLimit] = useState( + editing?.max_concurrent != null ? String(editing.max_concurrent) : "", + ); + const [enabled, setEnabled] = useState(!editing?.disabled); + const [saving, setSaving] = useState(false); + const [copied, setCopied] = useState(false); + const [error, setError] = useState(null); + + const used = usage.find((u) => u.name === editing?.name); + const taken = keys.some((k) => k.name === name.trim() && k.name !== editing?.name); + const missing = + name.trim().length === 0 + ? "请填写名称" + : taken + ? "这个名称已被占用" + : scope === "some" && globs.trim().length === 0 + ? "请至少填写一条模型范围" + : null; + + async function save() { + setSaving(true); + setError(null); + const allow = + scope === "all" + ? null + : scope === "none" + ? [] + : globs + .split("\n") + .map((g) => g.trim()) + .filter(Boolean); + const body = { + key: { + name: name.trim(), + route: route || null, + allow, + max_concurrent: limit.trim() ? Number(limit.trim()) : null, + disabled: !enabled, + }, + base_version: configVersion ?? undefined, + }; + try { + if (editing) await api.updateKey(editing.name, body); + else await api.createKey(body); + onSaved(name.trim()); + } catch (e) { + setError(errorText(e)); + } finally { + setSaving(false); + } + } + + return ( + !o && onClose()}> + + + {editing ? "编辑密钥" : "新建密钥"} + + {editing ? ( + <> + {editing.name} ·{" "} + {useLabel(editing, clients)} + + ) : ( + "新密钥立即可用。客户端把它填进请求头即可连接网关。" + )} + + + +
+ {editing && ( +
+
+

{editing.key}

+

+ {editing.last_seen_ms ? `最后使用 ${when(editing.last_seen_ms)}` : "从未使用"} + {used && used.requests > 0 && ` · 24 小时 ${used.requests.toLocaleString()} 次`} +

+
+
+ + +
+
+ )} + +
+
+ + setName(e.target.value)} + placeholder="例如 codex" + aria-invalid={taken} + /> +

流量与会话里按它区分客户端

+
+
+ + setRoute(e.target.value)}> + {/* 不绑就是走默认路由 —— 写出来,而不是留一个空白 */} + {routeLabel(null, defaultRoute)} + {routes + .filter((r) => r.name !== defaultRoute) + .map((r) => ( + + {r.name} + + ))} + +

决定这把密钥的请求发往哪些上游

+
+
+ +
+
+ + setScope(e.target.value as Scope)} + > + 不限 + 指定范围 + 一个都不给 + +
+
+ + setLimit(e.target.value.replace(/[^0-9]/g, ""))} + /> +
+
+ + {scope === "some" && ( +
+ +