From a9df71a01b78057d0c6333e1a7c2adcadd1e9b42 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 23 Sep 2026 11:59:20 +0800 Subject: [PATCH] feat(zai): sign in to a Z.ai or BigModel account and get a key MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sign-in ends with an ordinary API key on the account, so the upstream it writes is a plain `anthropic` provider with a `key` — no `oauth` block, no refresh, no rotation. Z.ai's own client works the same way: a Coding Plan request carries nothing but that key, which is why the plan's quota follows the key and a direct call to the documented endpoint is enough. Three things about their protocol that the code has to know: - The authorization page belongs to their own client, because Z.ai does not let third parties register an OAuth app. The half we control is honest: our own User-Agent, a polling token we generate ourselves, and no field in the request where a client could claim to be someone else. - The browser lands on their page, not ours, so there is no callback server and no port to bind. Polling is the only way to learn the outcome. - Their business API answers HTTP 200 with a business error code in the body. Every call checks that code; otherwise a failure reads as a success and the real reason surfaces several steps later as something unrelated. Getting the key creates one on the account if there is none named `thinkwatch` — an existing one is reused. The UI has to say so before the sign-in starts. Also: GLM prices exist in the dataset only under a `zai/` prefix, so a bare `glm-5.2` resolved to nothing and every request through these upstreams had no cost at all. The prefixed key is now the last pricing candidate. `user_agent()` and `ORIGINATOR` move from the chatgpt module to the gateway root, since they are what we say about ourselves to any account API. Co-Authored-By: Claude Opus 5 --- bin/twcore/src/main.rs | 1 + crates/tw-api/src/lib.rs | 46 ++ crates/tw-config/src/lib.rs | 1 + crates/tw-control/src/lib.rs | 5 + crates/tw-control/src/zai.rs | 897 +++++++++++++++++++++++ crates/tw-control/tests/adopt.rs | 1 + crates/tw-control/tests/chatgpt.rs | 3 +- crates/tw-control/tests/dryrun.rs | 1 + crates/tw-control/tests/in_flight.rs | 1 + crates/tw-control/tests/keys.rs | 1 + crates/tw-control/tests/listen.rs | 1 + crates/tw-control/tests/live_state.rs | 1 + crates/tw-control/tests/m4_acceptance.rs | 1 + crates/tw-control/tests/models.rs | 1 + crates/tw-control/tests/pricing.rs | 1 + crates/tw-control/tests/resources.rs | 1 + crates/tw-control/tests/routes.rs | 1 + crates/tw-control/tests/security.rs | 1 + crates/tw-control/tests/sessions.rs | 1 + crates/tw-control/tests/speed.rs | 1 + crates/tw-control/tests/zai.rs | 547 ++++++++++++++ crates/tw-gateway/src/chatgpt.rs | 18 +- crates/tw-gateway/src/lib.rs | 30 + crates/tw-pricing/src/name.rs | 26 + 24 files changed, 1572 insertions(+), 16 deletions(-) create mode 100644 crates/tw-control/src/zai.rs create mode 100644 crates/tw-control/tests/zai.rs diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index b4cd3c38..df1e69d6 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -807,6 +807,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> store, price_updater: Default::default(), chatgpt: Default::default(), + zai: Default::default(), }; // 盯着客户端配置面。**只报告** —— 这条路径上没有任何 // 一处会改用户的文件。盯不住就只是少了「变更时告警」,页面上 diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 5f2a2c8b..92b841bd 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -2191,6 +2191,52 @@ pub struct ResetCreditUsed { pub windows_reset: i64, } +/// 用 Z.ai 或 BigModel 的账号登录(`POST /zai/login`)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ZaiLoginStart { + /// 登哪一家:`zai`(api.z.ai)或 `bigmodel`(open.bigmodel.cn)。不给是 `zai` + #[serde(default, skip_serializing_if = "Option::is_none")] + pub family: Option, + /// 登录后写进配置的上游名。不给就是那一家的名字;已经有同名的同一家账号上游时, + /// 换掉它的密钥(重新登录),其余设置不动 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + /// 登录期间调它们的接口走哪条路:`direct` / `system` / 代理名。不给是 `direct`。 + /// 新建上游时也写成它的出站方式 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub proxy: Option, +} + +/// 一次进行中的 Z.ai 登录。 +/// +/// **没有回到应用的地址**:授权完成后浏览器停在对方自己的页面上,那一页不是我们的, +/// 我们只能靠轮询知道登录成了。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ZaiLogin { + pub id: String, + /// 在浏览器里打开的授权地址 + pub authorize_url: String, + /// 多少秒内要完成 + pub expires_in_secs: u64, +} + +/// 登录进行到哪一步(`GET /zai/login/{id}`)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ZaiLoginStatus { + pub id: String, + /// `pending` / `done` / `failed` / `expired` / `cancelled` + pub status: String, + /// 写进配置的上游名。`done` 时有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider: Option, + /// 登的是哪个账号,邮箱或者昵称。`done` 时有,对方没给就没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub account: Option, + /// `failed` 时的原因 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, +} + /// L3 测速要花多少。 /// /// **这是「你确认要花钱吗」那个对话框的全部内容。**触发前必须显示它, diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index e2749d21..abaaf3e6 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -746,6 +746,7 @@ impl Provider { "api.deepseek.com", "api.moonshot.cn", "open.bigmodel.cn", + "api.z.ai", "dashscope.aliyuncs.com", "chatgpt.com", ]; diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index a0ca809a..ecbc7ec1 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -30,6 +30,7 @@ pub mod rotation; pub mod routes; pub mod scan; pub mod security; +pub mod zai; pub use config::{ApplyError, ConfigManager, resolve_path, spawn_watcher}; pub use tw_observe::EventBus; @@ -50,6 +51,9 @@ pub struct ControlState { pub price_updater: Arc, /// ChatGPT 账号的登录。**同一时刻只有一次**:回调端口只有一个 pub chatgpt: Arc, + /// Z.ai / BigModel 账号的登录。**同一时刻也只有一次** —— 理由不是端口,是 + /// 「一次登录」在界面上就是一件正在进行的事,两件同时进行没人说得清哪件成了 + pub zai: Arc, /// 用户的 home。接管要顺着它去找各客户端的配置。 /// /// **是个字段,不是每次现读 `$HOME`。**进程级的环境变量是全局可变 @@ -146,6 +150,7 @@ pub fn router(state: ControlState) -> Router { .merge(security::router()) .merge(pricing::router()) .merge(chatgpt::router()) + .merge(zai::router()) .with_state(state) } diff --git a/crates/tw-control/src/zai.rs b/crates/tw-control/src/zai.rs new file mode 100644 index 00000000..c025c58c --- /dev/null +++ b/crates/tw-control/src/zai.rs @@ -0,0 +1,897 @@ +//! Z.ai / BigModel 账号:登录换一把 API key。 +//! +//! # 这条路为什么比 ChatGPT 那条短 +//! +//! **登录的终点是账号下一把普通 API key**,不是一对会过期的 OAuth 令牌。Coding Plan +//! 的额度跟着 key 走 —— Z.ai 自己的客户端就是这么用的:套餐的每个请求只带这把 key, +//! 没有第二种凭据。所以写进 config.yaml 的是 `key`,不是 `oauth`:不需要刷新、不需要 +//! refresh token 轮换,[`tw_gateway::oauth`] 那一层完全不参与。 +//! +//! # 授权页上显示的是 Z.ai 自己的客户端 +//! +//! Z.ai 不开放第三方注册 OAuth 应用,授权地址由它的平台接口下发、`client_id` 是它自己 +//! 客户端的 —— 这一点和 ChatGPT 账号同源,界面上必须说明,不能让用户以为他授权的是 +//! ThinkWatch。**我们能控制的那一半如实写**:请求一律带 ThinkWatch 的 User-Agent +//! ([`tw_gateway::user_agent`]),轮询凭据由我们自己生成,登录接口的请求里没有任何 +//! 「我是谁」的字段可填,所以也没有一处需要冒充。 +//! +//! # 授权完成后浏览器停在对方的页面上 +//! +//! 回调回的是它平台自己的地址,不是本机 —— 所以没有回调服务、没有本机端口、也没有 +//! 「跳回应用」。登录成了没成,只有轮询知道。 +//! +//! # 它的业务接口用 HTTP 200 包业务错误码 +//! +//! `{"code":401,"msg":"token expired or incorrect"}` 会带着 200 回来(实测)。只看状态 +//! 码会把失败当成功,然后在后面某一步拿着一个空值报一句莫名其妙的错 —— 所以这里每一 +//! 次调用都要看回包里的 `code`(见 [`data`])。 + +use std::sync::Mutex; +use std::time::Duration; + +use axum::Json; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use axum::routing::{get, post}; +use serde_json::{Value, json}; +use tw_config::Protocol; +use tw_config::history::Origin; + +use crate::{ControlState, Fail, fail}; +use tw_types::msg; + +/// 登录要在多久之内完成。平台给的期限更短就按它的 +const LOGIN_TTL: Duration = Duration::from_secs(15 * 60); +/// 最快多久问一次「授权了没有」。平台给的间隔比它还短时按它来 —— 问得再勤,除了 +/// 被限流没有别的效果 +const POLL_MIN: Duration = Duration::from_secs(2); +/// 调它们的接口的超时 +const API_TIMEOUT: Duration = Duration::from_secs(15); +/// 我们在用户账号里建的那把 key 叫这个名字。 +/// +/// **不复用 Z.ai 客户端那把。**一把 key 是谁建的、能不能删,用户要在他自己的控制台 +/// 上看得出来;借用别人的名字会让他删错东西。 +const KEY_NAME: &str = "thinkwatch"; +/// 建 key 要指定机构和项目。名字里有这两个词的是它们给新账号的默认项,认不出来就用 +/// 第一个 —— 和 Z.ai 客户端的选法一致 +const DEFAULT_ORG: &str = "默认机构"; +const DEFAULT_PROJECT: &str = "默认项目"; + +pub fn router() -> axum::Router { + axum::Router::new() + .route("/zai/login", post(start)) + .route("/zai/login/{id}", get(status).delete(cancel)) +} + +// ---------------------------------------------------------------- 哪一家 + +/// 登哪一家。两家的登录流程一模一样,**换 key 那一步的鉴权方式不一样**。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Family { + /// api.z.ai + Zai, + /// open.bigmodel.cn + Bigmodel, +} + +impl Family { + fn parse(v: &str) -> Option { + match v { + "zai" => Some(Self::Zai), + "bigmodel" => Some(Self::Bigmodel), + _ => None, + } + } + pub fn slug(&self) -> &'static str { + match self { + Self::Zai => "zai", + Self::Bigmodel => "bigmodel", + } + } + /// 不指定名字时,上游叫这个 + fn default_name(&self) -> &'static str { + self.slug() + } +} + +/// 登录要用的地址。**平时是它们的**,测试里换成本机的假服务器 +#[derive(Debug, Clone)] +pub struct Endpoints { + /// 平台的命令行登录接口所在,形如 `https://zcode.z.ai/api/v1` + pub platform: String, + /// Z.ai 的业务接口:换平台令牌、建 key + pub zai_business: String, + /// BigModel 的业务接口 + pub bigmodel_business: String, + /// 登录成功后写进上游的接口地址 + pub zai_upstream: String, + pub bigmodel_upstream: String, +} + +impl Default for Endpoints { + fn default() -> Self { + Self { + platform: "https://zcode.z.ai/api/v1".to_string(), + zai_business: "https://api.z.ai".to_string(), + bigmodel_business: "https://bigmodel.cn".to_string(), + // **不带 `/v1`**:网关把客户端请求的路径原样接在后面 + zai_upstream: "https://api.z.ai/api/anthropic".to_string(), + bigmodel_upstream: "https://open.bigmodel.cn/api/anthropic".to_string(), + } + } +} + +impl Endpoints { + fn business(&self, family: Family) -> &str { + match family { + Family::Zai => &self.zai_business, + Family::Bigmodel => &self.bigmodel_business, + } + } + fn upstream(&self, family: Family) -> &str { + match family { + Family::Zai => &self.zai_upstream, + Family::Bigmodel => &self.bigmodel_upstream, + } + } +} + +/// 登录的状态。**进程里只有一份**:同一时刻只许一次登录,新的开始时把没完成的作废 +#[derive(Default)] +pub struct Accounts { + pub endpoints: Endpoints, + current: Mutex>, +} + +impl Accounts { + pub fn new(endpoints: Endpoints) -> Self { + Self { + endpoints, + current: Mutex::new(None), + } + } + + fn set_status(&self, status: tw_api::ZaiLoginStatus) { + if let Ok(mut g) = self.current.lock() + && let Some(c) = g.as_mut() + && c.status.id == status.id + { + c.status = status; + } + } +} + +struct Current { + status: tw_api::ZaiLoginStatus, + /// 等授权的那个任务。取消、或者新的登录开始时停掉它 + task: tokio::task::JoinHandle<()>, +} + +impl Current { + /// 停掉等授权的那个任务。**不用等它真的停下**:这条路上没有本机端口要让给下一次 + /// 登录,而在等的那一步只是一个带超时的 GET + fn stop(self, s: &ControlState) { + self.task.abort(); + if self.status.status == "pending" { + announce(s, &self.status.id, "cancelled", None, None); + } + } +} + +// ---------------------------------------------------------------- 登录 + +/// 这次要登成什么样。 +struct Want { + family: Family, + /// 登录后写进配置的上游名 + name: String, + /// 调它们的接口走哪条路 + proxy: String, +} + +impl Want { + /// 读一遍参数,有问题就直接回错 + fn read(s: &ControlState, req: &tw_api::ZaiLoginStart) -> Result { + let given = |v: &Option| { + v.as_deref() + .map(str::trim) + .filter(|x| !x.is_empty()) + .map(str::to_string) + }; + let family = match given(&req.family) { + None => Family::Zai, + Some(v) => Family::parse(&v).ok_or_else(|| { + fail( + StatusCode::BAD_REQUEST, + msg!("control.unknown_account_family", family = v => "`{family}` is not an account we can sign in to."), + ) + })?, + }; + let name = given(&req.name).unwrap_or_else(|| family.default_name().to_string()); + let proxy = given(&req.proxy).unwrap_or_else(|| tw_config::DIRECT.to_string()); + let cfg = s.config(); + if proxy != tw_config::DIRECT + && proxy != tw_config::SYSTEM + && !cfg.proxies.iter().any(|p| p.name == proxy) + { + return Err(fail( + StatusCode::BAD_REQUEST, + msg!("control.proxy_not_found", proxy = proxy => "There is no proxy named `{proxy}`."), + )); + } + // **同名的上游必须是同一家的账号**,否则重新登录会把一条别的上游的密钥换掉。 + // 认哪一家只能看接口地址:这类上游的协议是通用的 `anthropic`,分不出是谁 + let upstream = s.zai.endpoints.upstream(family); + if let Some(p) = cfg.providers.iter().find(|p| p.name == name) + && p.base_url.trim_end_matches('/') != upstream.trim_end_matches('/') + { + return Err(fail( + StatusCode::CONFLICT, + msg!( + "control.name_taken_not_zai", name = name => + "There is already an upstream named `{name}`, and it is not an account of this \ + service. Use a different name." + ), + )); + } + Ok(Self { + family, + name, + proxy, + }) + } +} + +/// 平台下发的这一次登录。 +struct Flow { + id: String, + /// 轮询要带上它 + poll_token: String, + flow_id: String, + authorize_url: String, + every: Duration, + /// 到这个时刻还没授权就作废 + deadline: tokio::time::Instant, +} + +async fn start( + State(s): State, + Json(req): Json, +) -> Result, Fail> { + let want = Want::read(&s, &req)?; + // 还没完成的上一次登录作废 + let prev = s.zai.current.lock().ok().and_then(|mut g| g.take()); + if let Some(prev) = prev { + prev.stop(&s); + } + let http = client_for(&s, &want)?; + let flow = init(&s, &want, &http).await?; + let login = tw_api::ZaiLogin { + id: flow.id.clone(), + authorize_url: flow.authorize_url.clone(), + expires_in_secs: flow + .deadline + .saturating_duration_since(tokio::time::Instant::now()) + .as_secs(), + }; + let current = Current { + status: pending(&flow.id), + task: tokio::spawn(await_login(s.clone(), want, http, flow)), + }; + // 两个登录同时开始时,后到的算数 + let raced = match s.zai.current.lock() { + Ok(mut g) => g.replace(current), + Err(_) => Some(current), + }; + if let Some(prev) = raced { + prev.stop(&s); + } + Ok(Json(login)) +} + +/// 问平台要一个授权地址。 +/// +/// 轮询凭据是**我们自己生成的**:平台只是记住它,所以这一次登录的结果只有拿着它的人 +/// 取得到。回包里也有一个 `poll_token`,那是它的回显,我们不用。 +async fn init(s: &ControlState, want: &Want, http: &reqwest::Client) -> Result { + let poll_token = tw_gateway::opaque_token(32); + let url = format!( + "{}/oauth/cli/init", + s.zai.endpoints.platform.trim_end_matches('/') + ); + let d = data( + http, + reqwest::Method::POST, + &url, + "asking for an authorization address", + Some(&format!("Bearer {poll_token}")), + Some(json!({ "provider": want.family.slug() })), + ) + .await + .map_err(|e| { + fail( + StatusCode::BAD_GATEWAY, + msg!("control.upstream_call_failed", detail = e => "{detail}"), + ) + })?; + let str_of = |k: &str| { + d.get(k) + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|v| !v.is_empty()) + .map(str::to_string) + }; + let bad = |what: &str| { + fail( + StatusCode::BAD_GATEWAY, + msg!( + "control.signin_response_unusable", detail = what.to_string() => + "The sign-in could not be started: {detail}" + ), + ) + }; + let flow_id = str_of("flow_id").ok_or_else(|| bad("the response has no flow id"))?; + let authorize_url = + str_of("authorize_url").ok_or_else(|| bad("the response has no authorization address"))?; + // **交给浏览器打开的地址必须是 https。**它是对方给的,一个 `file://` 或者 `javascript:` + // 就够我们替他打开一个不该打开的东西 + if !authorize_url.starts_with("https://") { + return Err(bad("the authorization address is not https")); + } + let every = d + .get("poll_interval_sec") + .and_then(|v| v.as_u64()) + .map(Duration::from_secs) + .unwrap_or(POLL_MIN) + .max(POLL_MIN); + // 平台给的是绝对时刻(秒)。给得比我们的上限还长时按我们的来 + let ttl = d + .get("expires_at") + .and_then(|v| v.as_u64()) + .map(|at| Duration::from_secs(at.saturating_sub(now_secs()))) + .filter(|d| !d.is_zero()) + .map_or(LOGIN_TTL, |d| d.min(LOGIN_TTL)); + Ok(Flow { + id: tw_gateway::opaque_token(16), + poll_token, + flow_id, + authorize_url, + every, + deadline: tokio::time::Instant::now() + ttl, + }) +} + +/// 等用户在浏览器里授权完。**`pending` 一直等,`failed` 立刻停** +async fn await_login(s: ControlState, want: Want, http: reqwest::Client, flow: Flow) { + let url = format!( + "{}/oauth/cli/poll/{}", + s.zai.endpoints.platform.trim_end_matches('/'), + flow.flow_id + ); + let auth = format!("Bearer {}", flow.poll_token); + while tokio::time::Instant::now() < flow.deadline { + let d = match data( + &http, + reqwest::Method::GET, + &url, + "waiting for the authorization", + Some(&auth), + None, + ) + .await + { + Ok(d) => d, + Err(why) => return settle(&s, &flow.id, Err(why)), + }; + match d.get("status").and_then(|v| v.as_str()) { + Some("pending") => { + tokio::time::sleep(flow.every).await; + continue; + } + Some("ready") => { + let done = finish(&s, &want, &http, &d).await; + return settle(&s, &flow.id, done); + } + Some("failed") => { + return settle(&s, &flow.id, Err("the authorization was refused".into())); + } + other => { + return settle( + &s, + &flow.id, + Err(format!( + "the authorization is in a state we do not know: {}", + other.unwrap_or("none") + )), + ); + } + } + } + s.zai.set_status(tw_api::ZaiLoginStatus { + id: flow.id.clone(), + status: "expired".into(), + provider: None, + account: None, + error: Some("the authorization was not completed in time".into()), + }); + announce(&s, &flow.id, "expired", None, None); +} + +/// 授权完了:换一把 key,写进配置。 +async fn finish( + s: &ControlState, + want: &Want, + http: &reqwest::Client, + ready: &Value, +) -> Result<(String, Option), String> { + // 这一家的令牌挂在以它自己命名的那个键下:`data.zai.access_token` + let access = ready + .get(want.family.slug()) + .and_then(|v| v.get("access_token").or_else(|| v.get("accessToken"))) + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|v| !v.is_empty()) + .ok_or("the authorization came back without an access token")?; + let account = ready + .get("user") + .and_then(|u| { + ["email", "name"] + .iter() + .find_map(|k| u.get(*k).and_then(|v| v.as_str())) + }) + .map(str::trim) + .filter(|v| !v.is_empty()) + .map(str::to_string); + let key = mint_key(http, &s.zai.endpoints, want.family, access).await?; + let name = save(s, want, key).await?; + Ok((name, account)) +} + +// ---------------------------------------------------------------- 换一把 key + +/// 从账号里取一把可用的 API key。 +/// +/// **这一步会在用户的账号里建东西**:名字是 [`KEY_NAME`] 的那把 key,已经有就复用。 +/// 套餐额度跟着账号的 key 走,所以拿到 key 才算登录完 —— 界面上必须在登录之前就把 +/// 这件事说清楚。 +async fn mint_key( + http: &reqwest::Client, + endpoints: &Endpoints, + family: Family, + access: &str, +) -> Result { + let host = endpoints.business(family).trim_end_matches('/'); + let auth = match family { + // Z.ai 的业务接口只认它自己换发的平台令牌,OAuth 那个 access token 在这儿用不了 + Family::Zai => { + let d = data( + http, + reqwest::Method::POST, + &format!("{host}/api/auth/z/login"), + "exchanging the sign-in for an account token", + None, + Some(json!({ "token": access })), + ) + .await?; + let token = d + .get("access_token") + .or_else(|| d.get("accessToken")) + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|v| !v.is_empty()) + .ok_or("the account token response has no token in it")?; + format!("Bearer {token}") + } + // BigModel 的业务接口直接认 OAuth 的 access token,**而且不带 `Bearer ` 前缀** + Family::Bigmodel => access.to_string(), + }; + let info = data( + http, + reqwest::Method::GET, + &format!("{host}/api/biz/customer/getCustomerInfo"), + "reading the account", + Some(&auth), + None, + ) + .await?; + let (org, project) = pick_place(&info) + .ok_or("the account has no organization and project an API key could go into")?; + let keys = format!("{host}/api/biz/v1/organization/{org}/projects/{project}/api_keys"); + let listed = data( + http, + reqwest::Method::GET, + &keys, + "listing the account's API keys", + Some(&auth), + None, + ) + .await?; + let mine = listed + .as_array() + .into_iter() + .flatten() + .find(|k| k.get("name").and_then(|v| v.as_str()) == Some(KEY_NAME)) + .and_then(|k| k.get("apiKey")) + .and_then(|v| v.as_str()) + .map(str::to_string); + let id = match mine { + Some(id) => id, + None => data( + http, + reqwest::Method::POST, + &keys, + "creating an API key", + Some(&auth), + Some(json!({ "name": KEY_NAME })), + ) + .await? + .get("apiKey") + .and_then(|v| v.as_str()) + .map(str::to_string) + .ok_or("the new API key came back without an id")?, + }; + // **id 要接进 URL 的路径里。**对方给什么我们就接什么的话,一个带 `/` 或 `?` 的值 + // 就能把请求发到另一个接口上 + if id.is_empty() + || !id + .chars() + .all(|c| c.is_ascii_alphanumeric() || ".-_".contains(c)) + { + return Err("the API key's id has characters we do not expect".into()); + } + let secret = data( + http, + reqwest::Method::GET, + &format!("{keys}/copy/{id}"), + "reading the API key", + Some(&auth), + None, + ) + .await? + .get("secretKey") + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|v| !v.is_empty()) + .map(str::to_string); + match (family, secret) { + (_, Some(secret)) => Ok(format!("{id}.{secret}")), + // Z.ai 的密钥是 `id.secret` 两段,少一段用不了 —— 宁可现在就说,不要写一把 + // 发出去就是 401 的密钥进配置 + (Family::Zai, None) => Err("the API key came back without its secret half".into()), + (Family::Bigmodel, None) => Ok(id), + } +} + +/// key 建在哪个机构的哪个项目下。名字认不出来就用第一个 +fn pick_place(info: &Value) -> Option<(String, String)> { + let orgs = info.get("organizations")?.as_array()?; + let named = |list: &[Value], key: &str, want: &str| -> Option { + list.iter() + .find(|o| { + o.get(key) + .and_then(|v| v.as_str()) + .is_some_and(|n| n.contains(want)) + }) + .or_else(|| list.first()) + .cloned() + }; + let org = named(orgs, "organizationName", DEFAULT_ORG)?; + let projects = org.get("projects")?.as_array()?.clone(); + let project = named(&projects, "projectName", DEFAULT_PROJECT)?; + let id = |v: &Value, k: &str| { + v.get(k) + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|v| !v.is_empty()) + .map(str::to_string) + }; + Some((id(&org, "organizationId")?, id(&project, "projectId")?)) +} + +/// 把登录得来的密钥写进 config.yaml。 +/// +/// **重新登录只换密钥**,出站方式、模型范围、停用状态这些都不动 —— 用户在上游页上 +/// 调过的东西不该因为换一次密钥就回到默认值。 +async fn save(s: &ControlState, want: &Want, key: String) -> Result { + let name = want.name.clone(); + let proxy = want.proxy.clone(); + let upstream = s.zai.endpoints.upstream(want.family).to_string(); + s.cfg + .transform(None, Origin::Ui, |text, cfg| { + let existing = cfg.providers.iter().find(|p| p.name == name); + if let Some(e) = existing + && e.base_url.trim_end_matches('/') != upstream.trim_end_matches('/') + { + return Err(crate::resources::invalid(format!( + "there is already an upstream named `{name}`, and it is not an account of this service" + ))); + } + let mut p = existing.cloned().unwrap_or_else(|| tw_config::Provider { + name: name.clone(), + base_url: upstream.clone(), + // 它的接口是 Anthropic 的 messages 协议。**写出来而不是让它去猜**: + // 这个域名不在猜得出来的那几个里 + protocol: Some(Protocol::Anthropic), + proxy: proxy.clone(), + ..Default::default() + }); + p.key = Some(tw_config::Secret::new(key.clone())); + // 这类上游从不用 OAuth。上一次登录留下的(不该有)也一并清掉 + p.oauth = None; + p.check_credential() + .map_err(|e| crate::resources::invalid(e.to_string()))?; + let current = existing.map(|_| name.as_str()); + Ok(tw_config::edit::upsert( + text, + tw_config::edit::PROVIDERS, + current, + &crate::resources::mapping(&p)?, + )?) + }) + .await + .map_err(|e| format!("the configuration could not be written: {e}"))?; + // 模型清单现在就问一次:不然要等到下一轮定时刷新,新上游的模型才出现 + let gateway = s.gateway.clone(); + let provider = name.clone(); + tokio::spawn(async move { + tw_gateway::models::refresh_one(&gateway, &provider).await; + }); + Ok(name) +} + +// ---------------------------------------------------------------- 状态 + +fn pending(id: &str) -> tw_api::ZaiLoginStatus { + tw_api::ZaiLoginStatus { + id: id.to_string(), + status: "pending".into(), + provider: None, + account: None, + error: None, + } +} + +/// 记下登录的结果,并告诉界面一声 +fn settle(s: &ControlState, id: &str, done: Result<(String, Option), String>) { + let status = match done { + Ok((provider, account)) => tw_api::ZaiLoginStatus { + id: id.to_string(), + status: "done".into(), + provider: Some(provider), + account, + error: None, + }, + Err(why) => { + tracing::warn!("the sign-in did not finish: {why}"); + tw_api::ZaiLoginStatus { + id: id.to_string(), + status: "failed".into(), + provider: None, + account: None, + error: Some(why), + } + } + }; + s.zai.set_status(status.clone()); + announce(s, id, &status.status, status.provider, status.error); +} + +async fn status( + State(s): State, + Path(id): Path, +) -> Result, Fail> { + s.zai + .current + .lock() + .ok() + .and_then(|g| { + g.as_ref() + .filter(|c| c.status.id == id) + .map(|c| c.status.clone()) + }) + .map(Json) + .ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + msg!( + "control.signin_gone" => + "There is no such sign-in, or a newer one replaced it." + ), + ) + }) +} + +async fn cancel( + State(s): State, + Path(id): Path, +) -> Result, Fail> { + let mut status = { + let g = s.zai.current.lock().map_err(|e| { + fail( + StatusCode::INTERNAL_SERVER_ERROR, + msg!("control.internal", detail = e => "{detail}"), + ) + })?; + let c = g.as_ref().filter(|c| c.status.id == id).ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + msg!( + "control.signin_gone" => + "There is no such sign-in, or a newer one replaced it." + ), + ) + })?; + if c.status.status != "pending" { + return Ok(Json(c.status.clone())); + } + c.task.abort(); + c.status.clone() + }; + status.status = "cancelled".into(); + s.zai.set_status(status.clone()); + announce(&s, &id, "cancelled", None, None); + Ok(Json(status)) +} + +// ---------------------------------------------------------------- 杂项 + +/// 调一次它们的接口,**把回包里的业务错误码当失败**。 +/// +/// 它们会用 HTTP 200 包一个 `{"code":401,"msg":"…"}` 回来。只看状态码的话,失败会被 +/// 当成成功,然后在后面某一步拿着一个空值报一句和真实原因无关的错。 +/// +/// 出错的话里只有**这一步在做什么**,没有地址:建 key 那几个地址的路径里带着密钥的 +/// id,而错误会进日志、也会显示给用户。 +async fn data( + http: &reqwest::Client, + method: reqwest::Method, + url: &str, + doing: &str, + auth: Option<&str>, + body: Option, +) -> Result { + let mut req = http + .request(method, url) + .timeout(API_TIMEOUT) + // 如实说自己是谁 + .header("user-agent", tw_gateway::user_agent()); + if let Some(auth) = auth { + req = req.header("authorization", auth); + } + if let Some(body) = body { + req = req.json(&body); + } + let resp = req.send().await.map_err(|e| { + format!( + "{doing} failed: {}", + tw_gateway::forward::map_reqwest_error(e).message() + ) + })?; + let status = resp.status(); + let text = resp.text().await.unwrap_or_default(); + if !status.is_success() { + return Err(format!( + "{doing} answered {}: {}", + status.as_u16(), + brief(&text) + )); + } + let v: Value = serde_json::from_str(&text) + .map_err(|_| format!("{doing} did not answer JSON: {}", brief(&text)))?; + if !business_ok(v.get("code")) { + let why = v + .get("msg") + .and_then(|m| m.as_str()) + .map(str::trim) + .filter(|m| !m.is_empty()) + .unwrap_or("no reason given"); + return Err(format!("{doing} was refused: {why}")); + } + Ok(v.get("data").cloned().unwrap_or(Value::Null)) +} + +/// 回包里的业务码算不算成功。**没有这一项也算** —— 有些接口成功时就不带它 +fn business_ok(code: Option<&Value>) -> bool { + match code { + None | Some(Value::Null) => true, + Some(Value::Number(n)) => matches!(n.as_i64(), Some(0) | Some(200)), + Some(Value::String(s)) => s == "0" || s == "200", + _ => false, + } +} + +/// 出错时给用户看的那一小段响应 +fn brief(text: &str) -> String { + tw_secret::mask_body(text).chars().take(200).collect() +} + +/// 按出站方式建一个客户端。**要代理才能访问它们的用户,直连会卡在第一步** +fn client_for(s: &ControlState, want: &Want) -> Result { + let route = tw_config::Provider { + name: want.name.clone(), + base_url: s.zai.endpoints.platform.clone(), + proxy: want.proxy.clone(), + ..Default::default() + }; + tw_gateway::client_for_provider(&s.config(), &route).map_err(|e| { + fail( + StatusCode::BAD_GATEWAY, + msg!("control.upstream_call_failed", detail = e.message().to_string() => "{detail}"), + ) + }) +} + +fn announce( + s: &ControlState, + login: &str, + status: &str, + provider: Option, + error: Option, +) { + s.bus().emit(tw_api::Event::LoginFinished { + id: s.bus().next_id(), + login: login.to_string(), + status: status.to_string(), + provider, + error, + at_ms: now_ms(), + }); +} + +fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +fn now_secs() -> u64 { + now_ms() / 1000 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_business_error_code_inside_a_200_is_a_failure() { + assert!(business_ok(None)); + assert!(business_ok(Some(&json!(0)))); + assert!(business_ok(Some(&json!(200)))); + assert!(business_ok(Some(&json!("0")))); + assert!(!business_ok(Some(&json!(401)))); + assert!(!business_ok(Some(&json!(3001)))); + assert!(!business_ok(Some(&json!("3001")))); + } + + #[test] + fn the_default_organization_and_project_win_over_the_first_one() { + let info = json!({"organizations": [ + {"organizationId": "o1", "organizationName": "别的机构", "projects": [ + {"projectId": "p1", "projectName": "别的项目"} + ]}, + {"organizationId": "o2", "organizationName": "我的默认机构", "projects": [ + {"projectId": "p2", "projectName": "别的项目"}, + {"projectId": "p3", "projectName": "默认项目"} + ]} + ]}); + assert_eq!( + pick_place(&info), + Some(("o2".to_string(), "p3".to_string())) + ); + } + + #[test] + fn the_first_organization_and_project_are_the_fallback() { + let info = json!({"organizations": [ + {"organizationId": "o1", "organizationName": "Acme", "projects": [ + {"projectId": "p1", "projectName": "Playground"} + ]} + ]}); + assert_eq!( + pick_place(&info), + Some(("o1".to_string(), "p1".to_string())) + ); + assert_eq!(pick_place(&json!({"organizations": []})), None); + } +} diff --git a/crates/tw-control/tests/adopt.rs b/crates/tw-control/tests/adopt.rs index c177e946..e58d97e4 100644 --- a/crates/tw-control/tests/adopt.rs +++ b/crates/tw-control/tests/adopt.rs @@ -40,6 +40,7 @@ fn bed_with_store(store: Option String) -> Bed { started: std::time::Instant::now(), price_updater: Default::default(), chatgpt: Arc::new(Accounts::new(endpoints.clone())), + zai: Default::default(), home: d.path().join("home"), }; Bed { @@ -856,7 +857,7 @@ async fn usage_shows_the_limits_without_personal_details() { assert_eq!(header("authorization"), "Bearer at-cfg"); assert_eq!(header("chatgpt-account-id"), "acct-1"); assert_eq!(header("originator"), "thinkwatch"); - assert_eq!(header("user-agent"), tw_gateway::chatgpt::user_agent()); + assert_eq!(header("user-agent"), tw_gateway::user_agent()); assert!(h.get("session-id").is_none()); assert!( b.openai.token_forms.lock().unwrap().is_empty(), diff --git a/crates/tw-control/tests/dryrun.rs b/crates/tw-control/tests/dryrun.rs index c62a551c..51734104 100644 --- a/crates/tw-control/tests/dryrun.rs +++ b/crates/tw-control/tests/dryrun.rs @@ -63,6 +63,7 @@ fn app_with(text: &str) -> (tempfile::TempDir, axum::Router) { started: std::time::Instant::now(), price_updater: Default::default(), chatgpt: Default::default(), + zai: Default::default(), home: d.path().join("home"), }; (d, tw_control::router(state)) diff --git a/crates/tw-control/tests/in_flight.rs b/crates/tw-control/tests/in_flight.rs index 45cbcf81..d061b656 100644 --- a/crates/tw-control/tests/in_flight.rs +++ b/crates/tw-control/tests/in_flight.rs @@ -26,6 +26,7 @@ fn app() -> (tempfile::TempDir, tw_observe::EventBus, axum::Router) { started: std::time::Instant::now(), price_updater: Default::default(), chatgpt: Default::default(), + zai: Default::default(), home: d.path().join("home"), }; (d, bus, tw_control::router(state)) diff --git a/crates/tw-control/tests/keys.rs b/crates/tw-control/tests/keys.rs index 11be2039..c8aca52d 100644 --- a/crates/tw-control/tests/keys.rs +++ b/crates/tw-control/tests/keys.rs @@ -60,6 +60,7 @@ fn bed(yaml: &str) -> Bed { started: std::time::Instant::now(), price_updater: Default::default(), chatgpt: Default::default(), + zai: Default::default(), // **测试里绝不能碰开发者自己的配置** home: d.path().join("home"), }; diff --git a/crates/tw-control/tests/listen.rs b/crates/tw-control/tests/listen.rs index 7c85bdef..fdea3198 100644 --- a/crates/tw-control/tests/listen.rs +++ b/crates/tw-control/tests/listen.rs @@ -40,6 +40,7 @@ fn bed(yaml: &str) -> Bed { started: std::time::Instant::now(), price_updater: Default::default(), chatgpt: Default::default(), + zai: Default::default(), // **测试里绝不能碰开发者自己的配置** home: d.path().join("home"), }; diff --git a/crates/tw-control/tests/live_state.rs b/crates/tw-control/tests/live_state.rs index b2fedb16..901338ba 100644 --- a/crates/tw-control/tests/live_state.rs +++ b/crates/tw-control/tests/live_state.rs @@ -30,6 +30,7 @@ fn control( started: std::time::Instant::now(), price_updater: Default::default(), chatgpt: Default::default(), + zai: Default::default(), home: d.path().join("home"), }; (gw, tw_control::router(state)) diff --git a/crates/tw-control/tests/m4_acceptance.rs b/crates/tw-control/tests/m4_acceptance.rs index 761b1854..bea06d1a 100644 --- a/crates/tw-control/tests/m4_acceptance.rs +++ b/crates/tw-control/tests/m4_acceptance.rs @@ -43,6 +43,7 @@ fn bed() -> Bed { started: std::time::Instant::now(), price_updater: Default::default(), chatgpt: Default::default(), + zai: Default::default(), // **测试里绝不能碰开发者自己的配置** home: home.clone(), }; diff --git a/crates/tw-control/tests/models.rs b/crates/tw-control/tests/models.rs index ca0fde6b..47f86f9d 100644 --- a/crates/tw-control/tests/models.rs +++ b/crates/tw-control/tests/models.rs @@ -36,6 +36,7 @@ fn bed(yaml: &str) -> Bed { started: std::time::Instant::now(), price_updater: Default::default(), chatgpt: Default::default(), + zai: Default::default(), // **测试里绝不能碰开发者自己的配置** home: d.path().join("home"), }; diff --git a/crates/tw-control/tests/pricing.rs b/crates/tw-control/tests/pricing.rs index 4c7a02f5..9f202704 100644 --- a/crates/tw-control/tests/pricing.rs +++ b/crates/tw-control/tests/pricing.rs @@ -58,6 +58,7 @@ fn bed_with(yaml: &str, updater: Updater) -> Bed { started: std::time::Instant::now(), price_updater: Arc::new(updater), chatgpt: Default::default(), + zai: Default::default(), // **测试里绝不能碰开发者自己的配置** home: d.path().join("home"), }; diff --git a/crates/tw-control/tests/resources.rs b/crates/tw-control/tests/resources.rs index 2d588d64..aa51663e 100644 --- a/crates/tw-control/tests/resources.rs +++ b/crates/tw-control/tests/resources.rs @@ -59,6 +59,7 @@ fn bed(yaml: &str) -> Bed { started: std::time::Instant::now(), price_updater: Default::default(), chatgpt: Default::default(), + zai: Default::default(), // **测试里绝不能碰开发者自己的配置** home: d.path().join("home"), }; diff --git a/crates/tw-control/tests/routes.rs b/crates/tw-control/tests/routes.rs index bec080ca..3cd47dcc 100644 --- a/crates/tw-control/tests/routes.rs +++ b/crates/tw-control/tests/routes.rs @@ -88,6 +88,7 @@ fn bed(yaml: &str) -> Bed { started: std::time::Instant::now(), price_updater: Default::default(), chatgpt: Default::default(), + zai: Default::default(), // **测试里绝不能碰开发者自己的配置** home: d.path().join("home"), }; diff --git a/crates/tw-control/tests/security.rs b/crates/tw-control/tests/security.rs index db879868..b88199f9 100644 --- a/crates/tw-control/tests/security.rs +++ b/crates/tw-control/tests/security.rs @@ -116,6 +116,7 @@ fn bed_with(yaml: &str, seed: impl FnOnce(&tw_store::Db)) -> Bed { started: std::time::Instant::now(), price_updater: Default::default(), chatgpt: Default::default(), + zai: Default::default(), // **测试里绝不能碰开发者自己的配置** home: d.path().join("home"), }; diff --git a/crates/tw-control/tests/sessions.rs b/crates/tw-control/tests/sessions.rs index 49b51dd7..b3e28224 100644 --- a/crates/tw-control/tests/sessions.rs +++ b/crates/tw-control/tests/sessions.rs @@ -70,6 +70,7 @@ fn app(rows: &[tw_store::db::RequestRow]) -> (tempfile::TempDir, axum::Router) { started: std::time::Instant::now(), price_updater: Default::default(), chatgpt: Default::default(), + zai: Default::default(), home: d.path().join("home"), }; (d, tw_control::router(state)) diff --git a/crates/tw-control/tests/speed.rs b/crates/tw-control/tests/speed.rs index 63abb060..9f1b7762 100644 --- a/crates/tw-control/tests/speed.rs +++ b/crates/tw-control/tests/speed.rs @@ -30,6 +30,7 @@ fn bed(yaml: &str) -> Bed { started: std::time::Instant::now(), price_updater: Default::default(), chatgpt: Default::default(), + zai: Default::default(), // **测试里绝不能碰开发者自己的配置** home: d.path().join("home"), }; diff --git a/crates/tw-control/tests/zai.rs b/crates/tw-control/tests/zai.rs new file mode 100644 index 00000000..087eae8d --- /dev/null +++ b/crates/tw-control/tests/zai.rs @@ -0,0 +1,547 @@ +//! Z.ai / BigModel 账号:登录换一把 API key,写成一条 anthropic 上游。 +//! +//! **全程只对本机的假 Z.ai**:登录接口、业务接口、建密钥的接口都是假的。浏览器那一步 +//! 不需要模拟 —— 授权回的是对方的服务端,这边只有轮询。 + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::body::Body; +use axum::extract::{Path, State}; +use axum::http::{HeaderMap, Request, StatusCode}; +use axum::routing::{get, post}; +use serde_json::{Value, json}; +use tower::ServiceExt; +use tw_control::zai::{Accounts, Endpoints}; +use tw_control::{ConfigManager, ControlState}; + +// ---------------------------------------------------------------- 假 Z.ai + +#[derive(Default)] +struct Zai { + /// 还要回几次 `pending` 才算授权完 + pending_left: Mutex, + /// 轮询回一个「HTTP 200 包着业务错误码」的回包 + poll_business_error: Mutex, + /// 账号下已经有的密钥 + keys: Mutex>, + /// `copy` 接口不给 secret 那一半 + no_secret: Mutex, + /// 各接口收到的 (路径, 请求头, 请求体) + seen: Mutex>, +} + +impl Zai { + fn note(&self, path: &str, headers: HeaderMap, body: Value) { + self.seen + .lock() + .unwrap() + .push((path.to_string(), headers, body)); + } + fn auth_of(&self, path: &str) -> Option { + self.seen + .lock() + .unwrap() + .iter() + .find(|(p, _, _)| p == path) + .and_then(|(_, h, _)| h.get("authorization").cloned()) + .and_then(|v| v.to_str().ok().map(str::to_string)) + } + fn hit(&self, path: &str) -> usize { + self.seen + .lock() + .unwrap() + .iter() + .filter(|(p, _, _)| p == path) + .count() + } + fn body_of(&self, path: &str) -> Option { + self.seen + .lock() + .unwrap() + .iter() + .find(|(p, _, _)| p == path) + .map(|(_, _, b)| b.clone()) + } +} + +/// 它们的回包外壳:业务码在 `code` 里,成功是 0 +fn wrapped(data: Value) -> axum::Json { + axum::Json(json!({ "code": 0, "msg": "", "data": data })) +} + +async fn init( + State(z): State>, + headers: HeaderMap, + axum::Json(body): axum::Json, +) -> axum::Json { + z.note("/api/v1/oauth/cli/init", headers, body); + wrapped(json!({ + "flow_id": "flow-1", + "authorize_url": "https://chat.example/api/oauth/authorize?client_id=theirs", + // 绝对时刻,秒 + "expires_at": 4_000_000_000u64, + "poll_interval_sec": 1, + "poll_token": "the-server-echo", + })) +} + +async fn poll( + State(z): State>, + Path(flow): Path, + headers: HeaderMap, +) -> axum::Json { + z.note("/api/v1/oauth/cli/poll", headers, json!({ "flow": flow })); + if *z.poll_business_error.lock().unwrap() { + // **HTTP 200,业务码是失败** —— 实测它们就是这么回的 + return axum::Json(json!({"code": 401, "msg": "token expired or incorrect"})); + } + { + let mut left = z.pending_left.lock().unwrap(); + if *left > 0 { + *left -= 1; + return wrapped(json!({ "status": "pending" })); + } + } + wrapped(json!({ + "status": "ready", + "token": "zcode-jwt", + "user": {"user_id": "u-1", "email": "someone@example.com", "name": "Someone"}, + "zai": {"access_token": "oauth-access", "refresh_token": "oauth-refresh"}, + "bigmodel": {"access_token": "oauth-access"}, + })) +} + +async fn business_login( + State(z): State>, + headers: HeaderMap, + axum::Json(body): axum::Json, +) -> axum::Json { + z.note("/api/auth/z/login", headers, body); + wrapped(json!({ "access_token": "biz-token" })) +} + +async fn customer(State(z): State>, headers: HeaderMap) -> axum::Json { + z.note("/api/biz/customer/getCustomerInfo", headers, Value::Null); + wrapped(json!({"organizations": [ + {"organizationId": "o1", "organizationName": "某个默认机构", "projects": [ + {"projectId": "p1", "projectName": "默认项目"} + ]} + ]})) +} + +async fn list_keys(State(z): State>, headers: HeaderMap) -> axum::Json { + z.note("/api_keys:list", headers, Value::Null); + let keys = z.keys.lock().unwrap().clone(); + wrapped(Value::Array(keys)) +} + +async fn create_key( + State(z): State>, + headers: HeaderMap, + axum::Json(body): axum::Json, +) -> axum::Json { + z.note("/api_keys:create", headers, body.clone()); + let name = body + .get("name") + .and_then(|v| v.as_str()) + .unwrap_or_default() + .to_string(); + let made = json!({"apiKey": "made-key", "name": name}); + z.keys.lock().unwrap().push(made.clone()); + wrapped(made) +} + +async fn copy_key( + State(z): State>, + Path((_org, _project, id)): Path<(String, String, String)>, + headers: HeaderMap, +) -> axum::Json { + z.note("/api_keys:copy", headers, json!({ "id": id })); + if *z.no_secret.lock().unwrap() { + return wrapped(json!({})); + } + wrapped(json!({ "secretKey": "the-secret" })) +} + +async fn start_zai(z: Arc) -> Endpoints { + let app = axum::Router::new() + .route("/api/v1/oauth/cli/init", post(init)) + .route("/api/v1/oauth/cli/poll/{flow}", get(poll)) + .route("/api/auth/z/login", post(business_login)) + .route("/api/biz/customer/getCustomerInfo", get(customer)) + .route( + "/api/biz/v1/organization/{org}/projects/{project}/api_keys", + get(list_keys).post(create_key), + ) + .route( + "/api/biz/v1/organization/{org}/projects/{project}/api_keys/copy/{id}", + get(copy_key), + ) + .with_state(z); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + Endpoints { + platform: format!("http://{addr}/api/v1"), + zai_business: format!("http://{addr}"), + bigmodel_business: format!("http://{addr}"), + zai_upstream: format!("http://{addr}/api/anthropic"), + bigmodel_upstream: format!("http://{addr}/api/bigmodel-anthropic"), + } +} + +// ---------------------------------------------------------------- 控制面 + +const BASE: &str = "version: 1 +clients: + - name: c + key: tw-k +providers: + - name: relay + base_url: https://relay.example + key: sk-relay + protocol: anthropic +"; + +struct Bed { + dir: tempfile::TempDir, + app: axum::Router, + events: tokio::sync::broadcast::Receiver, + zai: Arc, + endpoints: Endpoints, +} + +impl Bed { + fn file(&self) -> String { + std::fs::read_to_string(self.dir.path().join("config.yaml")).unwrap() + } + fn provider(&self, name: &str) -> Option { + tw_config::try_parse(&self.file()) + .unwrap() + .providers + .into_iter() + .find(|p| p.name == name) + } + async fn call(&self, method: &str, path: &str, body: Value) -> (StatusCode, Value) { + let r = self + .app + .clone() + .oneshot( + Request::builder() + .method(method) + .uri(path) + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + let st = r.status(); + let b = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); + let text = String::from_utf8_lossy(&b).to_string(); + ( + st, + serde_json::from_str(&text).unwrap_or(Value::String(text)), + ) + } + /// 等下一条登录结果事件 + async fn login_finished(&mut self) -> (String, Option, Option) { + tokio::time::timeout(Duration::from_secs(5), async { + loop { + if let Ok(tw_api::Event::LoginFinished { + status, + provider, + error, + .. + }) = self.events.recv().await + { + return (status, provider, error); + } + } + }) + .await + .expect("5 秒内应当收到登录结果") + } +} + +/// `extra` 追加在 providers 之下,拿得到假 Z.ai 的地址 +async fn bed(extra: impl FnOnce(&Endpoints) -> String) -> Bed { + let zai = Arc::new(Zai::default()); + let endpoints = start_zai(zai.clone()).await; + let yaml = format!("{BASE}{}", extra(&endpoints)); + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("config.yaml"); + std::fs::write(&p, &yaml).unwrap(); + let cfg = tw_config::try_parse(&yaml).unwrap(); + let gw = tw_gateway::AppState::new(cfg).unwrap(); + let bus = gw.bus.clone(); + let events = bus.subscribe(); + let state = ControlState { + cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), + gateway: gw, + store: None, + started: std::time::Instant::now(), + price_updater: Default::default(), + chatgpt: Default::default(), + zai: Arc::new(Accounts::new(endpoints.clone())), + home: d.path().join("home"), + }; + Bed { + app: tw_control::router(state), + dir: d, + events, + zai, + endpoints, + } +} + +// ---------------------------------------------------------------- 登录 + +#[tokio::test] +async fn a_login_writes_the_account_into_the_config_as_an_anthropic_upstream() { + let mut b = bed(|_| String::new()).await; + let (st, v) = b.call("POST", "/zai/login", json!({})).await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!( + v["authorize_url"], "https://chat.example/api/oauth/authorize?client_id=theirs", + "授权地址原样交给界面去打开" + ); + assert!( + v["expires_in_secs"].as_u64().unwrap() <= 15 * 60, + "平台给的期限再长也不超过我们的上限:{v}" + ); + + let (status, provider, error) = b.login_finished().await; + assert_eq!(status, "done", "{error:?}"); + assert_eq!(provider.as_deref(), Some("zai")); + + let p = b.provider("zai").expect("上游应当写进了配置"); + assert_eq!(p.base_url, b.endpoints.zai_upstream); + assert_eq!(p.protocol, Some(tw_config::Protocol::Anthropic)); + // **密钥是 `id.secret` 两段拼起来的** + assert_eq!( + p.key.as_ref().unwrap().resolve().unwrap(), + "made-key.the-secret" + ); + assert!(p.oauth.is_none(), "这类上游不用 OAuth,不该写 oauth 块"); + // 计费是默认那档:订阅账号也按价目表算费用 + assert_eq!(p.billing, tw_config::Billing::PerToken); + // 原有的上游一个都没动 + assert!(b.file().contains("sk-relay")); + + // 轮询凭据是我们自己生成的,不是平台回显的那个 + let init_auth = b.zai.auth_of("/api/v1/oauth/cli/init").unwrap(); + let poll_auth = b.zai.auth_of("/api/v1/oauth/cli/poll").unwrap(); + assert_eq!(init_auth, poll_auth); + assert!(!init_auth.contains("the-server-echo"), "{init_auth}"); + assert_eq!( + b.zai.body_of("/api/v1/oauth/cli/init").unwrap()["provider"], + "zai" + ); + // 建 key 那一步认的是业务令牌,不是 OAuth 的 access token + assert_eq!( + b.zai.auth_of("/api/biz/customer/getCustomerInfo").unwrap(), + "Bearer biz-token" + ); + assert_eq!( + b.zai.body_of("/api/auth/z/login").unwrap()["token"], + "oauth-access" + ); + // 建的那把 key 用我们自己的名字,不借用别人的 + assert_eq!( + b.zai.body_of("/api_keys:create").unwrap()["name"], + "thinkwatch" + ); +} + +#[tokio::test] +async fn every_request_says_who_it_is_from() { + let mut b = bed(|_| String::new()).await; + let (st, _) = b.call("POST", "/zai/login", json!({})).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(b.login_finished().await.0, "done"); + let seen = b.zai.seen.lock().unwrap(); + assert!(!seen.is_empty()); + for (path, headers, _) in seen.iter() { + let ua = headers + .get("user-agent") + .and_then(|v| v.to_str().ok()) + .unwrap_or_default(); + assert_eq!(ua, tw_gateway::user_agent(), "{path} 没有如实说自己是谁"); + } +} + +#[tokio::test] +async fn the_authorization_is_waited_for_until_it_is_ready() { + let mut b = bed(|_| String::new()).await; + *b.zai.pending_left.lock().unwrap() = 2; + let (st, v) = b.call("POST", "/zai/login", json!({})).await; + assert_eq!(st, StatusCode::OK); + let id = v["id"].as_str().unwrap().to_string(); + + let (st, v) = b.call("GET", &format!("/zai/login/{id}"), json!({})).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(v["status"], "pending"); + + assert_eq!(b.login_finished().await.0, "done"); + assert!(b.zai.hit("/api/v1/oauth/cli/poll") >= 3); + let (_, v) = b.call("GET", &format!("/zai/login/{id}"), json!({})).await; + assert_eq!(v["status"], "done"); + assert_eq!(v["account"], "someone@example.com"); +} + +#[tokio::test] +async fn a_business_error_code_inside_a_200_fails_the_login() { + // **这是它们真实的回法**:HTTP 200,错在正文里。只看状态码的话,这一步会被 + // 当成成功,然后在后面某一步报一句和真实原因无关的错。 + let mut b = bed(|_| String::new()).await; + *b.zai.poll_business_error.lock().unwrap() = true; + let (st, _) = b.call("POST", "/zai/login", json!({})).await; + assert_eq!(st, StatusCode::OK); + let (status, provider, error) = b.login_finished().await; + assert_eq!(status, "failed"); + assert!(provider.is_none()); + let why = error.unwrap(); + assert!(why.contains("token expired or incorrect"), "{why}"); + assert!(b.provider("zai").is_none(), "失败的登录不能写配置"); +} + +#[tokio::test] +async fn signing_in_again_only_replaces_the_key() { + let mut b = bed(|e| { + format!( + " - name: zai + base_url: {upstream} + protocol: anthropic + key: old-key.old-secret + proxy: system + models_only: + - glm-4.6 + disabled: true +", + upstream = e.zai_upstream + ) + }) + .await; + // 账号里已经有我们的那把 key 了:复用,不再建一把 + b.zai + .keys + .lock() + .unwrap() + .push(json!({"apiKey": "made-key", "name": "thinkwatch"})); + + let (st, _) = b + .call("POST", "/zai/login", json!({"proxy": "system"})) + .await; + assert_eq!(st, StatusCode::OK); + assert_eq!(b.login_finished().await.0, "done"); + + let p = b.provider("zai").unwrap(); + assert_eq!( + p.key.as_ref().unwrap().resolve().unwrap(), + "made-key.the-secret" + ); + // 用户调过的设置一个都不能动 + assert_eq!(p.proxy, "system"); + assert_eq!(p.models_only.as_deref(), Some(&["glm-4.6".to_string()][..])); + assert!(p.disabled); + assert_eq!(b.zai.hit("/api_keys:create"), 0, "已经有的 key 应当复用"); +} + +#[tokio::test] +async fn an_upstream_of_another_service_with_the_same_name_is_a_conflict() { + let b = bed(|_| { + " - name: zai + base_url: https://relay.example/anthropic + key: sk-someone-elses + protocol: anthropic +" + .to_string() + }) + .await; + let (st, v) = b.call("POST", "/zai/login", json!({})).await; + assert_eq!(st, StatusCode::CONFLICT, "{v}"); + assert!( + b.file().contains("sk-someone-elses"), + "别人的密钥不能被换掉" + ); + assert_eq!(b.zai.hit("/api/v1/oauth/cli/init"), 0, "拦在开始之前"); +} + +#[tokio::test] +async fn bigmodel_signs_in_with_the_oauth_token_itself_and_may_get_a_key_without_a_secret() { + let mut b = bed(|_| String::new()).await; + *b.zai.no_secret.lock().unwrap() = true; + let (st, v) = b + .call("POST", "/zai/login", json!({"family": "bigmodel"})) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + let (status, provider, error) = b.login_finished().await; + assert_eq!(status, "done", "{error:?}"); + assert_eq!(provider.as_deref(), Some("bigmodel")); + + let p = b.provider("bigmodel").unwrap(); + assert_eq!(p.base_url, b.endpoints.bigmodel_upstream); + // secret 那一半没有时,BigModel 的 key 就是它自己 + assert_eq!(p.key.as_ref().unwrap().resolve().unwrap(), "made-key"); + // 它的业务接口直接认 OAuth 的 access token,**不带 `Bearer ` 前缀** + assert_eq!( + b.zai.auth_of("/api/biz/customer/getCustomerInfo").unwrap(), + "oauth-access" + ); + assert_eq!(b.zai.hit("/api/auth/z/login"), 0, "这一家不需要换业务令牌"); +} + +#[tokio::test] +async fn z_ai_without_the_secret_half_is_a_failure_rather_than_an_unusable_key() { + let mut b = bed(|_| String::new()).await; + *b.zai.no_secret.lock().unwrap() = true; + let (st, _) = b.call("POST", "/zai/login", json!({})).await; + assert_eq!(st, StatusCode::OK); + let (status, _, error) = b.login_finished().await; + assert_eq!(status, "failed"); + assert!(error.unwrap().contains("secret"), "要说清缺的是哪一半"); + assert!(b.provider("zai").is_none()); +} + +#[tokio::test] +async fn an_unknown_family_and_an_unknown_proxy_are_both_refused() { + let b = bed(|_| String::new()).await; + let (st, _) = b + .call("POST", "/zai/login", json!({"family": "openai"})) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST); + let (st, _) = b.call("POST", "/zai/login", json!({"proxy": "nope"})).await; + assert_eq!(st, StatusCode::BAD_REQUEST); + assert_eq!(b.zai.hit("/api/v1/oauth/cli/init"), 0); +} + +#[tokio::test] +async fn a_login_can_be_cancelled_and_a_new_one_replaces_the_old() { + let mut b = bed(|_| String::new()).await; + // 一直 pending:不取消就不会结束 + *b.zai.pending_left.lock().unwrap() = u32::MAX; + let (_, first) = b.call("POST", "/zai/login", json!({})).await; + let id = first["id"].as_str().unwrap().to_string(); + + let (st, v) = b + .call("DELETE", &format!("/zai/login/{id}"), json!({})) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!(v["status"], "cancelled"); + assert_eq!(b.login_finished().await.0, "cancelled"); + assert!(b.provider("zai").is_none()); + + // 取消过的那次不再认 + let (st, _) = b.call("GET", &format!("/zai/login/{id}"), json!({})).await; + assert_eq!(st, StatusCode::OK, "取消后的状态还查得到"); + + // 新的一次登录顶掉旧的 + *b.zai.pending_left.lock().unwrap() = 0; + let (_, second) = b.call("POST", "/zai/login", json!({})).await; + assert_ne!(second["id"], first["id"]); + assert_eq!(b.login_finished().await.0, "done"); + let (st, _) = b.call("GET", &format!("/zai/login/{id}"), json!({})).await; + assert_eq!(st, StatusCode::NOT_FOUND, "旧的那次已经不在了"); +} diff --git a/crates/tw-gateway/src/chatgpt.rs b/crates/tw-gateway/src/chatgpt.rs index 0e4c9915..e90834e9 100644 --- a/crates/tw-gateway/src/chatgpt.rs +++ b/crates/tw-gateway/src/chatgpt.rs @@ -30,8 +30,6 @@ pub use tw_config::chatgpt::{ACCOUNT_HEADER, BASE_URL, CLIENT_ID, TOKEN_ENDPOINT pub const ISSUER: &str = "https://auth.openai.com"; /// 登出时吊销 refresh token pub const REVOKE_ENDPOINT: &str = "https://auth.openai.com/oauth/revoke"; -/// 请求来自谁。**如实写 ThinkWatch** -pub const ORIGINATOR: &str = "thinkwatch"; /// 模型清单要的 `client_version`。 /// /// 后端不带这个参数就回 400。ThinkWatch 不实现任何 Codex 客户端版本的特性,所以如实报 @@ -45,16 +43,6 @@ pub const SCOPE: &str = "openid profile email offline_access"; const RESIDENCY_HEADER: &str = "x-openai-internal-codex-residency"; -/// 发给 Codex 后端的 User-Agent:`thinkwatch/0.5.0 (macos; aarch64)` -pub fn user_agent() -> String { - format!( - "{ORIGINATOR}/{} ({}; {})", - env!("CARGO_PKG_VERSION"), - std::env::consts::OS, - std::env::consts::ARCH - ) -} - // ---------------------------------------------------------------- 请求 /// 客户端本来就说 Responses、这一跳直通时,把请求体改成 Codex 后端接受的样子。 @@ -124,8 +112,8 @@ pub fn identity_headers( .map(str::to_string) .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); let mut out = vec![ - ("originator".to_string(), ORIGINATOR.to_string()), - ("user-agent".to_string(), user_agent()), + ("originator".to_string(), crate::ORIGINATOR.to_string()), + ("user-agent".to_string(), crate::user_agent()), ("session-id".to_string(), session), ("accept".to_string(), "text/event-stream".to_string()), ]; @@ -270,7 +258,7 @@ pub fn authorize_url(issuer: &str, redirect_uri: &str, pkce: &Pkce, state: &str) .append_pair("code_challenge_method", "S256") .append_pair("id_token_add_organizations", "true") .append_pair("state", state) - .append_pair("originator", ORIGINATOR); + .append_pair("originator", crate::ORIGINATOR); url.to_string() } diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 586998ce..c1ba63e6 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -53,3 +53,33 @@ pub use quota::{Quota, from_headers as quota_from_headers}; pub use quote::Quote; pub use server::{AppState, Runtime, client_for_provider, router, serve}; pub use usage::{Sniffer, Usage}; + +/// 请求来自谁。**如实写 ThinkWatch** —— 我们从不把自己报成别的客户端。 +pub const ORIGINATOR: &str = "thinkwatch"; + +/// 如实说明自己是谁的 User-Agent:`thinkwatch/0.29.0 (macos; aarch64)`。 +/// +/// **账号类上游的接口也用它**(ChatGPT 的 Codex 后端、Z.ai 的业务接口)。对方认不认 +/// 我们是对方的事;冒充它们自己的客户端不在我们的选项里。 +pub fn user_agent() -> String { + format!( + "{ORIGINATOR}/{} ({}; {})", + env!("CARGO_PKG_VERSION"), + std::env::consts::OS, + std::env::consts::ARCH + ) +} + +/// 一串不可猜的十六进制令牌。 +/// +/// Z.ai 的命令行登录拿它当轮询凭据:**它由我们生成**,服务端只是记住它,所以这一次 +/// 登录的结果只有拿着它的人取得到。 +pub fn opaque_token(bytes: usize) -> String { + let mut buf = vec![0u8; bytes]; + rand::fill(buf.as_mut_slice()); + buf.iter().fold(String::new(), |mut out, b| { + use std::fmt::Write; + let _ = write!(out, "{b:02x}"); + out + }) +} diff --git a/crates/tw-pricing/src/name.rs b/crates/tw-pricing/src/name.rs index 1e0a25ca..8598836e 100644 --- a/crates/tw-pricing/src/name.rs +++ b/crates/tw-pricing/src/name.rs @@ -37,9 +37,24 @@ pub fn candidates(model: &str) -> Vec { if let Some(stripped) = strip_date_suffix(m) { push(stripped.rsplit('/').next().unwrap_or(stripped).to_string()); } + // GLM 在数据集里**只有带前缀的键**(`zai/glm-5.2`),而客户端发来的是裸名字 + // `glm-5.2` —— 不补这一个候选,走 Z.ai 和 BigModel 的每一条请求都是「价格未知」。 + // + // **放在最后一位**:第三方中转上的同名模型价格和官方不同,前面那几个候选(原名、 + // 剥掉前缀的名字)先命中的算数,官方价只是兜底。中转的真实价格本来就得靠自定义 + // 价目表 —— 那是第二层该管的事。 + if let Some(glm) = zai_key(bare) { + push(glm); + } out } +/// GLM 的官方价格在数据集里的键。**只认 `glm-` 开头** —— 别的名字没有这个规律, +/// 给它们凑一个前缀就是在猜 +fn zai_key(bare: &str) -> Option { + bare.starts_with("glm-").then(|| format!("zai/{bare}")) +} + /// 跨平台的最后一招:Bedrock 的写法。 /// /// 数据集里有些模型只有 `anthropic.<名字>-v1:0` 这个键,没有裸名字 —— @@ -125,6 +140,17 @@ mod tests { assert!(c.contains(&"claude-sonnet-4-5".to_string()), "{c:?}"); } + #[test] + fn a_glm_model_also_gets_looked_up_under_its_vendor_prefix() { + // 数据集里只有 `zai/glm-…`。客户端发来的是裸名字,**不补这一个候选, + // 走 Z.ai 的请求就全是「价格未知」**。 + let c = candidates("glm-4.6"); + assert_eq!(c[0], "glm-4.6", "先按原样查"); + assert_eq!(c.last().unwrap(), "zai/glm-4.6", "官方价只是兜底,排在最后"); + // 别的名字不凑前缀 + assert!(!candidates("kimi-k2").iter().any(|c| c.starts_with("zai/"))); + } + #[test] fn both_a_prefix_and_a_date_can_be_stripped_together() { let c = candidates("openrouter/anthropic/claude-sonnet-4-5-20250929");