From ebf7923c91cfc224e2250a5ed130dbb0502c6550 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 25 Sep 2026 11:36:49 +0800 Subject: [PATCH] feat(api): say who is signed in on a ChatGPT account upstream, read from its own token ProviderView.oauth (OAuthView) gains `account`: the signed-in account's email and plan, so the Upstreams page can label a ChatGPT account row without calling ChatgptUsage, which is a live call to the ChatGPT backend. Nothing new is stored and nothing goes online. The access token core already keeps with the credential (written to config.yaml at sign-in and after every refresh) is a JWT that names the account: the plan is in `https://api.openai.com/auth`, the email in `https://api.openai.com/profile` (the id_token has it at the top level; both are read). The view prefers the token in hand (just renewed, possibly not yet written back) and falls back to the configured one. It follows the credential: a re-login or a refresh that brings a new plan changes it, and the change arrives with the config reload the write-back already causes. After the credential expires it still names the last account. The account id and user id in the same token are not exposed. The plan is ChatgptPlan: KnownChatgptPlan (the words the Codex client knows, a closed slug set) or the backend's own word as is, since OpenAI keeps adding plans (go, prolite, ...). `hc` and `education` read as `enterprise` and `edu`. TypeScript: `KnownChatgptPlan | string`. ChatgptLoginStatus.plan uses the same type. ChatgptUsage drops `email` and `plan`: who is signed in now has one source, the credential, so the row and the quota dialog cannot disagree (the backend's rate limiter has been seen to report a different plan than the token). Control-plane protocol 21. Z.ai / BigModel account upstreams get no account block: that sign-in ends in a plain API key with no OAuth section, the key does not say whose it is, and the account name seen during sign-in is not kept with it. Tests use synthetic JWTs only and a fake OpenAI: the claims parser (email in either place, known / alias / unknown plans), the token-in-use choice, the overview after a browser sign-in and a re-login, a refresh that moves the plan along and survives a restart from the written config, and that none of it calls the token endpoint or the backend. Co-Authored-By: Claude Opus 5.5 --- crates/tw-api/src/lib.rs | 181 ++++++++++++++++++++++-- crates/tw-api/src/ts.rs | 16 +++ crates/tw-control/src/chatgpt.rs | 40 ++++-- crates/tw-control/src/lib.rs | 1 + crates/tw-control/tests/chatgpt.rs | 214 ++++++++++++++++++++++++++--- crates/tw-gateway/src/chatgpt.rs | 86 +++++++++++- crates/tw-gateway/src/oauth.rs | 47 +++++++ 7 files changed, 537 insertions(+), 48 deletions(-) diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 5b123bc0..2ba7c17e 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -288,6 +288,69 @@ slug_enum! { } } +slug_enum! { + /// ChatGPT 套餐里认得的那些词,和 Codex 客户端认的是同一份。 + /// + /// **这个集合不归我们定**:OpenAI 一直在加(`go`、`prolite` 都是后来才有的), + /// 认不出来的词见 [`ChatgptPlan::Other`]。 + pub enum KnownChatgptPlan { + Free = "free", + Go = "go", + Plus = "plus", + Pro = "pro", + ProLite = "prolite", + ProMax = "promax", + Team = "team", + Business = "business", + SelfServeBusinessProLite = "self_serve_business_prolite", + SelfServeBusinessUsageBased = "self_serve_business_usage_based", + /// 后端也写成 `hc` + Enterprise = "enterprise", + Ent26 = "ent26", + EnterpriseCbpAutomation = "enterprise_cbp_automation", + EnterpriseCbpUsageBased = "enterprise_cbp_usage_based", + /// 后端也写成 `education` + Edu = "edu", + EduPlus = "edu_plus", + EduPro = "edu_pro", + } +} + +/// ChatGPT 账号的套餐。 +/// +/// **线上就是后端给的那个词**:认得的是 [`KnownChatgptPlan`],认不出来的原样给。 +/// 集合是 OpenAI 的,它随时会多出一个新名字 —— 把新名字说成「未知」,比照原词 +/// 写出来更差。前端的类型是 `KnownChatgptPlan | string`。 +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(untagged)] +pub enum ChatgptPlan { + Known(KnownChatgptPlan), + /// 认不出来的词,原样 + Other(String), +} + +impl ChatgptPlan { + /// 读后端给的词。大小写不论,同一个套餐的另一种写法归到一个词上(`hc` 就是 + /// `enterprise`,`education` 就是 `edu`);空的是 `None` + pub fn from_raw(raw: &str) -> Option { + let raw = raw.trim(); + if raw.is_empty() { + return None; + } + let lower = raw.to_ascii_lowercase(); + let word = match lower.as_str() { + "hc" => "enterprise", + "education" => "edu", + w => w, + }; + Some(match KnownChatgptPlan::from_slug(word) { + Some(k) => Self::Known(k), + None => Self::Other(raw.to_string()), + }) + } +} + slug_enum! { /// 登哪一家的账号。 pub enum ZaiFamily { @@ -506,7 +569,12 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// (别的机器连网关用哪几个地址)。从远程端口进来的连接不能关 core、不能 /// 取诊断包、不能改 `listen.control` 这一节(403,`control.remote.*`)。 /// 照 19 写的客户端会缺这两个字段。 -pub const CONTROL_API_VERSION: u32 = 20; +/// +/// **21 起账号上游登的是谁在上游视图里**:`OAuthView.account`(邮箱、套餐)从凭据 +/// 自己的 access token 里读,不联网;`ChatgptUsage` 不再带 `email` 和 `plan`。套餐是 +/// [`ChatgptPlan`]:认得的词是枚举,认不出来的原样给,登录结果里的 `plan` 也换成了它。 +/// 照 20 写的界面会去用量里找邮箱和套餐,而那里已经没有了。 +pub const CONTROL_API_VERSION: u32 = 21; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -1456,6 +1524,33 @@ pub struct OAuthView { /// 凭据已经失效,只有重新登录能恢复 #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub needs_login: bool, + /// 登的是哪个账号。**ChatGPT 账号上游才有**,令牌里一项都读不出来时没有。 + /// + /// Z.ai / BigModel 的账号上游没有 `oauth` 这一节,也就没有它:那类登录的终点是一把 + /// 普通 API key,key 里读不出是谁,登录时读到的账号名只在那一次登录的结果里 + /// ([`ZaiLoginStatus::account`]),不随 key 保存 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub account: Option, +} + +/// 一个账号上游登的是哪个账号。 +/// +/// **从这份凭据自己的 access token 里读,不联网**:ChatGPT 的 access token 是 JWT,套餐 +/// 在 `https://api.openai.com/auth` 里,邮箱在 `https://api.openai.com/profile` 里。登录 +/// 和每一次刷新都换来一个新的、并且写回配置,所以它跟着凭据走:套餐变了,下一次换 +/// token 之后这里就是新的;凭据失效之后,这里仍是最后登着的那个账号。 +/// +/// 账户 ID、用户 ID 同在令牌里,**不往外带**:界面认账号靠邮箱,那两个读不出是谁, +/// 而它们一旦出去就会进日志 +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct AccountView { + /// 令牌里没写就没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub email: Option, + /// 令牌里没写就没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plan: Option, } /// 配置里引用了某个上游的一处。 @@ -2919,24 +3014,21 @@ pub struct ChatgptLoginStatus { /// 写进配置的上游名。`done` 时有 #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option, - /// 套餐:`plus` / `pro` / `team` …。`done` 时有,令牌里没写就没有 + /// 套餐。`done` 时有,令牌里没写就没有 #[serde(default, skip_serializing_if = "Option::is_none")] - pub plan: Option, + pub plan: Option, /// `failed` 时的原因 #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option, } /// ChatGPT 账号的用量(`GET /providers/{name}/chatgpt/usage`)。 +/// +/// **登的是谁不在这里**,在上游视图的 [`OAuthView::account`]:那一份从本机的凭据里读, +/// 不用为了给一行上游标上账号去问一次后端 #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ChatgptUsage { - /// 登的是哪个账号。**只有邮箱** —— 同一份回答里的用户 ID - /// 和账户 ID 不往外带:界面认账号靠邮箱,那两个读不出是谁 - #[serde(default, skip_serializing_if = "Option::is_none")] - pub email: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub plan: Option, /// 额度窗口,词表同 [`QuotaWindow`] pub windows: Vec, /// 可用的额度重置卡张数。账号没有这一项时没有 @@ -3882,6 +3974,11 @@ mod tests { ChatgptLoginMode::slug, ChatgptLoginMode::from_slug, ); + check( + KnownChatgptPlan::ALL, + KnownChatgptPlan::slug, + KnownChatgptPlan::from_slug, + ); check(ZaiFamily::ALL, ZaiFamily::slug, ZaiFamily::from_slug); check( ConfigOrigin::ALL, @@ -4077,6 +4174,72 @@ mod tests { let s: Status = serde_json::from_str(json).unwrap(); assert!(s.gateway_addr.is_none()); } + + /// 套餐的集合是 OpenAI 的:认得的归到一个词上,认不出来的原样过去,线上都是那个词。 + #[test] + fn a_plan_is_the_backends_word_known_or_not() { + use serde_json::json; + let plus = ChatgptPlan::from_raw("Plus").unwrap(); + assert_eq!(plus, ChatgptPlan::Known(KnownChatgptPlan::Plus)); + assert_eq!(serde_json::to_value(&plus).unwrap(), json!("plus")); + // 同一个套餐的另一种写法 + assert_eq!( + ChatgptPlan::from_raw("hc"), + Some(ChatgptPlan::Known(KnownChatgptPlan::Enterprise)) + ); + assert_eq!( + ChatgptPlan::from_raw(" education "), + Some(ChatgptPlan::Known(KnownChatgptPlan::Edu)) + ); + for &k in KnownChatgptPlan::ALL { + assert_eq!(ChatgptPlan::from_raw(k.slug()), Some(ChatgptPlan::Known(k))); + } + // 新名字不是「未知」,是它自己 + let new = ChatgptPlan::from_raw("pro_ultra").unwrap(); + assert_eq!(new, ChatgptPlan::Other("pro_ultra".into())); + assert_eq!(serde_json::to_value(&new).unwrap(), json!("pro_ultra")); + // 读回来:认得的是枚举,认不出来的仍是原词 + assert_eq!( + serde_json::from_value::(json!("team")).unwrap(), + ChatgptPlan::Known(KnownChatgptPlan::Team) + ); + assert_eq!( + serde_json::from_value::(json!("pro_ultra")).unwrap(), + new + ); + for blank in ["", " "] { + assert_eq!(ChatgptPlan::from_raw(blank), None, "{blank:?}"); + } + } + + /// 令牌里没写的项不出现;没有账号的凭据连这一块都没有。 + #[test] + fn an_account_says_only_what_the_token_said() { + use serde_json::json; + let a = AccountView { + email: Some("someone@example.com".into()), + plan: None, + }; + assert_eq!( + serde_json::to_value(&a).unwrap(), + json!({"email": "someone@example.com"}) + ); + let mut o = OAuthView { + endpoint: "https://auth.example/token".into(), + client_id: None, + expires_at: None, + failure: None, + needs_login: false, + account: None, + }; + assert!(serde_json::to_value(&o).unwrap().get("account").is_none()); + o.account = Some(AccountView { + email: None, + plan: ChatgptPlan::from_raw("pro"), + }); + let back: OAuthView = serde_json::from_value(serde_json::to_value(&o).unwrap()).unwrap(); + assert_eq!(back, o); + } } /// 数据目录在哪。 diff --git a/crates/tw-api/src/ts.rs b/crates/tw-api/src/ts.rs index e022a66a..8202a15c 100644 --- a/crates/tw-api/src/ts.rs +++ b/crates/tw-api/src/ts.rs @@ -194,6 +194,22 @@ mod tests { ); } + /// 集合不归我们定的字段:认得的词是字面量,其余照样是字符串。 + #[test] + fn an_open_set_is_its_known_words_or_any_string() { + let ts = typescript(); + assert_eq!( + decl_of(&ts, "ChatgptPlan"), + "export type ChatgptPlan = KnownChatgptPlan | string" + ); + let known = decl_of(&ts, "KnownChatgptPlan"); + assert!(known.contains("\"prolite\""), "{known}"); + let oauth = decl_of(&ts, "OAuthView"); + assert!(oauth.contains("account?: AccountView"), "{oauth}"); + let login = decl_of(&ts, "ChatgptLoginStatus"); + assert!(login.contains("plan?: ChatgptPlan"), "{login}"); + } + #[test] fn every_endpoint_is_in_the_table() { let ts = typescript(); diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs index 24a4d5c2..8b19b291 100644 --- a/crates/tw-control/src/chatgpt.rs +++ b/crates/tw-control/src/chatgpt.rs @@ -1,4 +1,4 @@ -//! ChatGPT 账号:登录、用量、额度重置卡。 +//! ChatGPT 账号:登录、登的是谁、用量、额度重置卡。 //! //! # 登录 //! @@ -486,7 +486,7 @@ fn not_in_time() -> Msg { } /// 记下登录的结果,并告诉界面一声 -fn settle(s: &ControlState, id: &str, done: Result<(String, Option), Msg>) { +fn settle(s: &ControlState, id: &str, done: Result<(String, Option), Msg>) { let status = match done { Ok((provider, plan)) => tw_api::ChatgptLoginStatus { id: id.to_string(), @@ -681,7 +681,7 @@ async fn exchange_and_save( code: &str, verifier: &str, redirect_uri: &str, -) -> Result<(String, Option), Msg> { +) -> Result<(String, Option), Msg> { let endpoints = &s.chatgpt.endpoints; let http = client_for(s, name, proxy)?; let tokens = @@ -759,6 +759,22 @@ async fn exchange_and_save( Ok((name, account.plan)) } +/// 这个上游登的是哪个账号:从它在用的 access token 里读(见 [`tw_api::AccountView`])。 +/// +/// **不联网。**界面每画一次上游列表都要它;为了给一行上游标上账号去问一次后端,就是 +/// 每打开一次上游页、每个账号一次真实调用 +pub(crate) fn account_view( + s: &ControlState, + p: &tw_config::Provider, + o: &tw_config::OAuth, +) -> Option { + if p.effective_protocol() != Some(Protocol::Chatgpt) { + return None; + } + let token = s.gateway.oauth.access_in_use(&p.name, o)?; + chatgpt::account(&token).view() +} + /// 按出站方式建一个客户端。**要代理才能访问 OpenAI 的用户,直连会卡在换 token 这一步** fn client_for(s: &ControlState, name: &str, proxy: &str) -> Result { let route = tw_config::Provider { @@ -987,9 +1003,9 @@ async fn usage( Ok(Json(usage)) } -/// `wham/usage` 的回答。**只取界面要用的几项**:额度、套餐,以及邮箱 -/// —— 账号不止一个时,邮箱是用户分得清哪个是哪个的唯一一项。同一份回答里 -/// 的用户 ID 和账户 ID 不往外带:界面用不上,而它们一旦出去就会进日志 +/// `wham/usage` 的回答。**只取额度和重置卡**:同一份回答里的邮箱、套餐由上游视图从 +/// 凭据里读([`account_view`]),用户 ID 和账户 ID 不往外带 —— 界面用不上,而它们一旦 +/// 出去就会进日志 /// /// `now_ms`:收到回答的时刻。「还有多少秒重置」要靠它换成时刻 fn parse_usage(v: &Value, now_ms: u64) -> tw_api::ChatgptUsage { @@ -1008,8 +1024,6 @@ fn parse_usage(v: &Value, now_ms: u64) -> tw_api::ChatgptUsage { }; let limits = &v["rate_limit"]; tw_api::ChatgptUsage { - email: v["email"].as_str().map(str::to_string), - plan: v["plan_type"].as_str().map(str::to_string), windows: [&limits["primary_window"], &limits["secondary_window"]] .into_iter() .filter_map(window) @@ -1119,7 +1133,7 @@ mod tests { } #[test] - fn usage_keeps_the_limits_and_who_is_signed_in() { + fn usage_keeps_the_limits_and_nothing_about_who() { let v = serde_json::json!({ "email": "someone@example.com", "user_id": "user-1", @@ -1133,8 +1147,6 @@ mod tests { "rate_limit_reset_credits": {"available_count": 2} }); let u = parse_usage(&v, 1_758_000_000_000); - assert_eq!(u.email.as_deref(), Some("someone@example.com")); - assert_eq!(u.plan.as_deref(), Some("plus")); assert_eq!(u.windows.len(), 1); assert_eq!(u.windows[0].window, "weekly"); assert_eq!(u.windows[0].used_percent, 21.0); @@ -1144,8 +1156,10 @@ mod tests { Some(1_758_000_000_000 + 410_907_000) ); assert_eq!(u.reset_credits, Some(2)); - // 用户 ID 不往外带:界面读不出是谁,而它一旦出去就会进日志 + // 登的是谁在上游视图里(从凭据读);用户 ID 更不往外带 let json = serde_json::to_string(&u).unwrap(); - assert!(!json.contains("user-1"), "{json}"); + for who in ["someone@example.com", "user-1", "plus"] { + assert!(!json.contains(who), "{json}"); + } } } diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 8d3674c8..ae32ebf3 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -447,6 +447,7 @@ fn provider_view( expires_at: o.expires_at.clone(), needs_login: failure.as_ref().is_some_and(|(_, relogin)| *relogin), failure: failure.map(|(why, _)| why), + account: chatgpt::account_view(s, p, o), } }), protocol: p.effective_protocol().map(Into::into), diff --git a/crates/tw-control/tests/chatgpt.rs b/crates/tw-control/tests/chatgpt.rs index 3b435965..a2e4e604 100644 --- a/crates/tw-control/tests/chatgpt.rs +++ b/crates/tw-control/tests/chatgpt.rs @@ -1,4 +1,4 @@ -//! ChatGPT 账号:浏览器登录、用量、额度重置卡、删除时吊销。 +//! ChatGPT 账号:浏览器登录、登的是谁、用量、额度重置卡、删除时吊销。 //! //! **全程只对本机的假 OpenAI**:登录页、token 端点、吊销接口和 ChatGPT 后端都是假的。 //! 重置卡用掉就回不来,测试绝不能碰真实账号。 @@ -52,6 +52,33 @@ fn jwt(claims: Value) -> String { ) } +/// OpenAI 发的 access token 的样子:账户、套餐在 auth 那一块,邮箱在 profile 那一块, +/// 顶层没有 `email`。**全是编的**,没有一个真令牌 +fn access_token(plan: &str) -> String { + jwt(json!({ + "aud": ["https://api.openai.com/v1"], + "client_id": CLIENT_ID, + "exp": 4_000_000_000u64, + "https://api.openai.com/auth": { + "chatgpt_account_id": "acct-1", + "chatgpt_user_id": "user-1", + "chatgpt_plan_type": plan + }, + "https://api.openai.com/profile": {"email": "someone@example.com", "email_verified": true}, + "sub": "auth0|someone" + })) +} + +/// 登录换来的 access token +fn at_login() -> String { + access_token("plus") +} + +/// 刷新换来的:这期间账号升级了套餐 +fn at_refreshed() -> String { + access_token("pro") +} + async fn token( State(o): State>, headers: HeaderMap, @@ -96,7 +123,7 @@ async fn token( } if refresh { return axum::Json(json!({ - "access_token": "at-refreshed", + "access_token": at_refreshed(), "refresh_token": "rt-rotated", "expires_in": 864000 })) @@ -107,7 +134,7 @@ async fn token( "email": "someone@example.com", "https://api.openai.com/auth": {"chatgpt_account_id": "acct-1", "chatgpt_plan_type": "plus"} })), - "access_token": "at-login", + "access_token": at_login(), "refresh_token": "rt-login", "expires_in": 864000 })) @@ -259,12 +286,17 @@ providers: /// 已经登录过的账号。access token 还有很久才过期,用它不用先换 fn logged_in(name: &str, e: &Endpoints, refresh: &str) -> String { + logged_in_with(name, e, refresh, "at-cfg") +} + +/// 同上,配置里写着的 access token 是 `access` +fn logged_in_with(name: &str, e: &Endpoints, refresh: &str, access: &str) -> String { format!( " - name: {name} base_url: {backend} protocol: chatgpt oauth: - access: at-cfg + access: {access} expires_at: 2099-01-01T00:00:00Z refresh: {refresh} endpoint: {token} @@ -280,6 +312,7 @@ fn logged_in(name: &str, e: &Endpoints, refresh: &str) -> String { struct Bed { dir: tempfile::TempDir, app: axum::Router, + state: ControlState, events: tokio::sync::broadcast::Receiver, openai: Arc, endpoints: Endpoints, @@ -289,6 +322,28 @@ impl Bed { fn file(&self) -> String { std::fs::read_to_string(self.dir.path().join("config.yaml")).unwrap() } + /// 重启:同一份配置文件、同一个假 OpenAI,内存里的一切(缓存的令牌、额度)从头来 + fn restart(self) -> Bed { + let Bed { + dir, + openai, + endpoints, + .. + } = self; + open(dir, openai, endpoints) + } + /// 概览里这个上游的 `oauth` 那一块 + async fn oauth_view(&self, name: &str) -> Value { + let (st, v) = self.call("GET", "/overview", Value::Null).await; + assert_eq!(st, StatusCode::OK, "{v}"); + v["providers"] + .as_array() + .unwrap() + .iter() + .find(|p| p["name"] == name) + .unwrap_or_else(|| panic!("概览里没有 {name}:{v}"))["oauth"] + .clone() + } fn provider(&self, name: &str) -> Option { tw_config::try_parse(&self.file()) .unwrap() @@ -344,9 +399,14 @@ async fn bed(extra: impl FnOnce(&Endpoints) -> String) -> Bed { let endpoints = start_openai(openai.clone()).await; let yaml = format!("{RELAY}{}", extra(&endpoints)); let d = tempfile::tempdir().unwrap(); + std::fs::write(d.path().join("config.yaml"), &yaml).unwrap(); + open(d, openai, endpoints) +} + +/// 按目录里的 config.yaml 起一个控制面 +fn open(d: tempfile::TempDir, openai: Arc, endpoints: Endpoints) -> Bed { let p = d.path().join("config.yaml"); - std::fs::write(&p, &yaml).unwrap(); - let cfg = tw_config::try_parse(&yaml).unwrap(); + let cfg = tw_config::try_parse(&std::fs::read_to_string(&p).unwrap()).unwrap(); let gw = tw_gateway::AppState::new(cfg).unwrap(); let bus = gw.bus.clone(); let events = bus.subscribe(); @@ -362,7 +422,8 @@ async fn bed(extra: impl FnOnce(&Endpoints) -> String) -> Bed { zai: Default::default(), }; Bed { - app: tw_control::router(state), + app: tw_control::router(state.clone()), + state, dir: d, events, openai, @@ -486,7 +547,7 @@ async fn a_browser_login_writes_the_account_into_the_config_and_hands_back_to_th assert!(!b.file().contains("billing"), "{}", b.file()); let o = p.oauth.as_ref().unwrap(); assert_eq!(o.refresh, "rt-login"); - assert_eq!(o.access.as_deref(), Some("at-login")); + assert_eq!(o.access.as_deref(), Some(at_login().as_str())); assert_eq!(o.endpoint, b.endpoints.token); assert_eq!(o.client_id.as_deref(), Some(CLIENT_ID)); let expires = chrono::DateTime::parse_from_rfc3339(o.expires_at.as_deref().unwrap()).unwrap(); @@ -501,6 +562,12 @@ async fn a_browser_login_writes_the_account_into_the_config_and_hands_back_to_th ); assert!(b.provider("relay").is_some(), "别的上游不动"); + // 上游页马上就知道登的是谁:从刚写进配置的 access token 里读 + assert_eq!( + b.oauth_view("chatgpt").await["account"], + json!({"email": "someone@example.com", "plan": "plus"}) + ); + // 模型清单马上就去问,不等下一轮 eventually("登录后获取模型清单", || { b.openai @@ -620,13 +687,22 @@ async fn a_rejected_code_fails_the_login_and_leaves_the_config_alone() { #[tokio::test] async fn logging_in_again_replaces_the_credentials_and_keeps_the_settings() { + // 上一次登的是另一个账号 + let before = jwt(json!({ + "https://api.openai.com/auth": {"chatgpt_plan_type": "free"}, + "https://api.openai.com/profile": {"email": "before@example.com"} + })); let b = bed(|e| { - logged_in("chatgpt", e, "rt-old").replace( + logged_in_with("chatgpt", e, "rt-old", &before).replace( " protocol: chatgpt\n", " protocol: chatgpt\n billing: free\n models_only: [gpt-5.5]\n", ) }) .await; + assert_eq!( + b.oauth_view("chatgpt").await["account"], + json!({"email": "before@example.com", "plan": "free"}) + ); let s = start_login(&b, json!({"name": "chatgpt"})).await; let (_, page) = browser(&format!("{}?code=code-1&state={}", s.redirect_uri, s.state)).await; assert!(page.contains("Signed in to ChatGPT"), "{page}"); @@ -634,7 +710,7 @@ async fn logging_in_again_replaces_the_credentials_and_keeps_the_settings() { let o = p.oauth.as_ref().unwrap(); assert_eq!( (o.refresh.as_str(), o.access.as_deref()), - ("rt-login", Some("at-login")) + ("rt-login", Some(at_login().as_str())) ); assert_eq!(p.models_only.as_deref(), Some(&["gpt-5.5".to_string()][..])); assert_eq!( @@ -647,6 +723,11 @@ async fn logging_in_again_replaces_the_credentials_and_keeps_the_settings() { p.headers.get("chatgpt-account-id").unwrap().value.raw(), "acct-1" ); + // 换了账号,上游页上跟着换 + assert_eq!( + b.oauth_view("chatgpt").await["account"], + json!({"email": "someone@example.com", "plan": "plus"}) + ); } #[tokio::test] @@ -831,7 +912,6 @@ async fn usage_shows_the_limits_without_personal_details() { .call("GET", "/providers/chatgpt/chatgpt/usage", Value::Null) .await; assert_eq!(st, StatusCode::OK, "{v}"); - assert_eq!(v["plan"], "plus"); assert_eq!(v["reset_credits"], 2); let windows = v["windows"].as_array().unwrap(); assert_eq!(windows.len(), 1, "长度为 0 的窗口不算:{v}"); @@ -844,14 +924,12 @@ async fn usage_shows_the_limits_without_personal_details() { (now + 410_907_000 - 60_000..=now + 410_907_000).contains(&at), "{at} vs {now}" ); - // 邮箱要给:账号不止一个时,它是用户分辨哪个是哪个的唯一一项 - assert_eq!(v["email"], "someone@example.com"); - // 用户 ID 和账户 ID 不给:界面读不出是谁,而它们一旦出去就会进日志 + // 登的是谁不在这里(在上游视图里,从凭据读);用户 ID 和账户 ID 更不给:界面读不出 + // 是谁,而它们一旦出去就会进日志 let text = v.to_string(); - assert!( - !text.contains("user-1") && !text.contains("acct-1"), - "{text}" - ); + for who in ["someone@example.com", "plus", "user-1", "acct-1"] { + assert!(!text.contains(who), "{text}"); + } // 问来的额度就是这个上游的额度:冷启动之后界面不用等第一次请求 let (_, q) = b.call("GET", "/quota", Value::Null).await; @@ -890,7 +968,13 @@ async fn a_revoked_access_token_is_renewed_once_and_the_call_goes_through() { .iter() .map(|(_, h)| h["authorization"].to_str().unwrap().to_string()) .collect(); - assert_eq!(auth, ["Bearer at-cfg", "Bearer at-refreshed"]); + assert_eq!( + auth, + [ + "Bearer at-cfg".to_string(), + format!("Bearer {}", at_refreshed()) + ] + ); let forms = b.openai.token_forms.lock().unwrap(); assert_eq!(forms.len(), 1); assert_eq!(forms[0]["grant_type"], "refresh_token"); @@ -978,6 +1062,98 @@ async fn reset_credits_are_listed_and_used_only_when_asked() { assert_eq!(h.get("originator").unwrap(), "thinkwatch"); } +// ---------------------------------------------------------------- 登的是谁 + +#[tokio::test] +async fn who_is_signed_in_is_read_from_the_stored_credential_without_asking_anyone() { + let access = at_login(); + let b = bed(|e| { + // 别家的 OAuth 上游,令牌里碰巧也有邮箱 + let sso = format!( + " - name: company-sso + base_url: https://llm.example + protocol: openai-chat + oauth: + access: {} + refresh: rt-sso + endpoint: {} +", + jwt(json!({"email": "worker@example.com"})), + e.token + ); + format!( + "{}{}{sso}", + logged_in_with("chatgpt", e, "rt-cfg", &access), + logged_in("opaque", e, "rt-opaque") + ) + }) + .await; + + // 邮箱和套餐,别的都不带(账户 ID、用户 ID 同在令牌里) + let o = b.oauth_view("chatgpt").await; + assert_eq!( + o["account"], + json!({"email": "someone@example.com", "plan": "plus"}) + ); + // 令牌本身不出这个进程 + let (_, all) = b.call("GET", "/overview", Value::Null).await; + let text = all.to_string(); + for secret in [access.as_str(), "rt-cfg", "rt-sso", "rt-opaque"] { + assert!(!text.contains(secret), "{secret} 出现在概览里"); + } + // 不是 ChatGPT 账号:套餐这个说法对它不成立,令牌里有邮箱也不读 + let sso = b.oauth_view("company-sso").await; + assert!(sso.get("account").is_none(), "{sso}"); + // 令牌里什么都读不出来:没有这一块,而不是一块空的 + let opaque = b.oauth_view("opaque").await; + assert!(opaque.get("account").is_none(), "{opaque}"); + + // 全是从本机读的:token 端点和后端一次都没被问过 + assert!(b.openai.token_forms.lock().unwrap().is_empty()); + assert!(b.openai.backend.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn a_renewed_token_moves_the_account_along_and_survives_a_restart() { + let b = bed(|e| logged_in_with("chatgpt", e, "rt-cfg", &at_login())).await; + tw_control::rotation::spawn(b.state.clone()); + assert_eq!(b.oauth_view("chatgpt").await["account"]["plan"], "plus"); + + // 后端不再认配置里的那个 access token:换一个。换回来的令牌说套餐已经是 pro + *b.openai.reject_access.lock().unwrap() = Some(at_login()); + let (st, v) = b + .call("GET", "/providers/chatgpt/chatgpt/usage", Value::Null) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!(b.openai.token_forms.lock().unwrap().len(), 1); + assert_eq!( + b.oauth_view("chatgpt").await["account"], + json!({"email": "someone@example.com", "plan": "pro"}) + ); + + // 新令牌写回了配置。重启之后内存里什么都没有,还是从配置里的令牌读出同一个账号 + eventually("新的 access token 写回配置", || { + b.provider("chatgpt") + .and_then(|p| p.oauth) + .and_then(|o| o.access) + == Some(at_refreshed()) + }) + .await; + let asked = |b: &Bed| { + ( + b.openai.token_forms.lock().unwrap().len(), + b.openai.backend.lock().unwrap().len(), + ) + }; + let before = asked(&b); + let b = b.restart(); + assert_eq!( + b.oauth_view("chatgpt").await["account"], + json!({"email": "someone@example.com", "plan": "pro"}) + ); + assert_eq!(asked(&b), before, "读账号不该联网"); +} + // ---------------------------------------------------------------- 删除时吊销 #[tokio::test] diff --git a/crates/tw-gateway/src/chatgpt.rs b/crates/tw-gateway/src/chatgpt.rs index 4cfcf8a9..8c52f107 100644 --- a/crates/tw-gateway/src/chatgpt.rs +++ b/crates/tw-gateway/src/chatgpt.rs @@ -142,16 +142,29 @@ pub fn keeps_client_header(name: &str) -> bool { #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Account { pub account_id: Option, - /// `plus` / `pro` / `team` … - pub plan: Option, + /// 邮箱。id_token 写在顶层,access token 写在 `https://api.openai.com/profile` 里 + pub email: Option, + pub plan: Option, /// 数据驻留。`no_constraint` 当成没有 pub residency: Option, } -/// 从 id_token 或 access token 里读账户信息。 +impl Account { + /// 给界面看的那一块:邮箱和套餐。**账户 ID 不在里面**(见 [`tw_api::AccountView`]); + /// 两项都读不出来时没有 + pub fn view(&self) -> Option { + (self.email.is_some() || self.plan.is_some()).then(|| tw_api::AccountView { + email: self.email.clone(), + plan: self.plan.clone(), + }) + } +} + +/// 从 id_token 或 access token 里读账户信息。两种令牌都是 JWT,账户和套餐都在 +/// `https://api.openai.com/auth` 里;邮箱的位置不一样(见 [`Account::email`])。 /// -/// **不验签。**令牌是我们自己经 TLS 从 OpenAI 换来的,读它只是为了拿要随请求带上的值, -/// 不拿它做任何授权判断。 +/// **不验签。**令牌是我们自己经 TLS 从 OpenAI 换来的,读它只是为了拿要随请求带上的值、 +/// 给界面看的账号,不拿它做任何授权判断。 pub fn account(jwt: &str) -> Account { let claims = jwt .split('.') @@ -164,7 +177,11 @@ pub fn account(jwt: &str) -> Account { Account { account_id: text(&auth["chatgpt_account_id"]) .or_else(|| text(&claims["chatgpt_account_id"])), - plan: text(&auth["chatgpt_plan_type"]), + email: text(&claims["email"]) + .or_else(|| text(&claims["https://api.openai.com/profile"]["email"])), + plan: auth["chatgpt_plan_type"] + .as_str() + .and_then(tw_api::ChatgptPlan::from_raw), residency: text(&auth["chatgpt_compute_residency"]) .or_else(|| text(&claims["chatgpt_compute_residency"])) .filter(|r| r != "no_constraint"), @@ -490,6 +507,7 @@ mod tests { #[test] fn account_fields_come_from_the_auth_claims() { let id = jwt(serde_json::json!({ + "email": "someone@example.com", "https://api.openai.com/auth": { "chatgpt_account_id": "acc-1", "chatgpt_plan_type": "plus", @@ -500,11 +518,65 @@ mod tests { account(&id), Account { account_id: Some("acc-1".into()), - plan: Some("plus".into()), + email: Some("someone@example.com".into()), + plan: tw_api::ChatgptPlan::from_raw("plus"), residency: None, } ); assert_eq!(account("not-a-jwt"), Account::default()); + assert_eq!(account("not-a-jwt").view(), None); + } + + /// access token 没有顶层的 `email`,邮箱在 profile 那一块里;界面那一块只有邮箱和套餐。 + #[test] + fn the_access_token_says_who_is_signed_in() { + let access = jwt(serde_json::json!({ + "https://api.openai.com/auth": { + "chatgpt_account_id": "acc-1", + "chatgpt_user_id": "user-1", + "chatgpt_plan_type": "prolite" + }, + "https://api.openai.com/profile": {"email": "someone@example.com", "email_verified": true} + })); + let a = account(&access); + assert_eq!( + a.view(), + Some(tw_api::AccountView { + email: Some("someone@example.com".into()), + plan: Some(tw_api::ChatgptPlan::Known( + tw_api::KnownChatgptPlan::ProLite + )), + }) + ); + let shown = serde_json::to_string(&a.view()).unwrap(); + assert!( + !shown.contains("acc-1") && !shown.contains("user-1"), + "{shown}" + ); + + // 后端的另一种写法归到同一个词上;新名字原样;只有一项也照样给 + let plan = |p: &str| { + account(&jwt(serde_json::json!({ + "https://api.openai.com/auth": {"chatgpt_plan_type": p} + }))) + .view() + }; + assert_eq!( + plan("hc").and_then(|v| v.plan), + Some(tw_api::ChatgptPlan::Known( + tw_api::KnownChatgptPlan::Enterprise + )) + ); + assert_eq!( + plan("pro_ultra"), + Some(tw_api::AccountView { + email: None, + plan: Some(tw_api::ChatgptPlan::Other("pro_ultra".into())), + }) + ); + // 什么都没写:没有这一块,而不是一块空的 + assert_eq!(plan(""), None); + assert_eq!(account(&jwt(serde_json::json!({"sub": "x"}))).view(), None); } #[test] diff --git a/crates/tw-gateway/src/oauth.rs b/crates/tw-gateway/src/oauth.rs index c651fb2a..0061b30f 100644 --- a/crates/tw-gateway/src/oauth.rs +++ b/crates/tw-gateway/src/oauth.rs @@ -305,6 +305,18 @@ impl Cache { self.refresh(provider, cfg, http).await } + /// 这家此刻在用的 access token:手里那个(可能刚换来、还没写回配置),没有就是配置里 + /// 写着的。**不联网、不换,也不记进缓存** —— 只是读,给「登的是谁」这类从令牌里读的 + /// 事实用。过没过期不管:过期的令牌说的仍是最后登着的那个账号 + pub fn access_in_use(&self, provider: &str, cfg: &OAuth) -> Option { + let g = self.inner.lock().expect("lock not poisoned"); + g.get(provider) + // 换 token 失败时留下的那一条可能没有 access token + .filter(|l| l.usable_for(cfg) && !l.access.is_empty()) + .map(|l| l.access.clone()) + .or_else(|| cfg.access.clone().filter(|a| !a.is_empty())) + } + /// 这家最近一次刷新失败的原因,和是不是要重新登录。没失败过、或者已经恢复,是 `None`。 pub fn failure(&self, provider: &str, cfg: &OAuth) -> Option<(Msg, bool)> { let g = self.inner.lock().expect("lock not poisoned"); @@ -663,6 +675,41 @@ mod tests { } } + #[test] + fn the_token_in_use_is_the_one_in_hand_then_the_configured_one() { + let c = Cache::new(); + let mut o = cfg("http://127.0.0.1:1/nope"); + // 没换过、配置里也没写:不知道 + assert_eq!(c.access_in_use("p", &o), None); + o.access = Some("a-cfg".into()); + assert_eq!(c.access_in_use("p", &o).as_deref(), Some("a-cfg")); + // 只是读:缓存里没有因此多出一条 + assert!(c.inner.lock().unwrap().is_empty()); + + // 刚换来、还没写回配置的那个优先 + let live = |access: &str| Live { + fp: fingerprint(&o), + access: access.into(), + renew_at: None, + refresh: o.refresh.clone(), + obtained: Some(Instant::now()), + failed: None, + }; + c.inner.lock().unwrap().insert("p".into(), live("a-live")); + assert_eq!(c.access_in_use("p", &o).as_deref(), Some("a-live")); + assert_eq!(c.access_in_use("q", &o).as_deref(), Some("a-cfg")); + + // 用户换了一份凭据:手里那个不再算数 + let mut other = o.clone(); + other.refresh = "r-someone-else".into(); + other.access = Some("a-other".into()); + assert_eq!(c.access_in_use("p", &other).as_deref(), Some("a-other")); + + // 换 token 失败时留下的空条目不算,退回配置里的 + c.inner.lock().unwrap().insert("p".into(), live("")); + assert_eq!(c.access_in_use("p", &o).as_deref(), Some("a-cfg")); + } + #[test] fn a_broken_endpoint_backs_off_instead_of_being_hammered() { // **没有退避,一个坏掉的 token 端点会被每个请求敲一次。**