From 5a6732e7e176c7de782fd638ee8ac3c36aca3566 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 18 Sep 2026 23:11:30 +0800 Subject: [PATCH 1/2] feat: sign in to ChatGPT from another device MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Some machines cannot open the browser that OAuth needs: a headless box, a remote shell, a work laptop where the account lives on a phone. The device flow covers those — core asks OpenAI for a one-time code, the user types it on whatever device is already signed in, and core waits for the approval. `POST /chatgpt/login` takes `mode`: `browser` (the default, unchanged) or `device`, which answers with `user_code` and `verification_url` instead of `authorize_url`. Both paths end in the same place, so a device login writes the same provider, the same credentials and the same account header as a browser login; `authorize_url` is now optional in the reply. Not every account can use it. When the server has not enabled the flow the code request 404s, and we say so with the one thing the user can do about it: sign in on this computer instead. Asking for usage now records the quota too. It lives only in memory, so after a cold start the upstreams page had nothing to show until the account saw its first request — one lazy fetch when the page opens now fills it. Co-Authored-By: Claude Opus 5 --- crates/tw-api/src/lib.rs | 17 +- crates/tw-control/src/chatgpt.rs | 498 +++++++++++++++++++++-------- crates/tw-control/tests/chatgpt.rs | 155 +++++++++ crates/tw-gateway/src/chatgpt.rs | 26 ++ crates/tw-gateway/src/server.rs | 7 +- 5 files changed, 567 insertions(+), 136 deletions(-) diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index d4cf4ae7..8d5ba9e7 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -1704,17 +1704,28 @@ pub struct ChatgptLoginStart { #[serde(default, skip_serializing_if = "Option::is_none")] pub proxy: Option, /// 登录完成后,浏览器页面跳到哪里。**只接受应用自己的协议**(`thinkwatch://…`), - /// 不接受网页地址 + /// 不接受网页地址。设备码登录没有浏览器页面,给了也不用 #[serde(default, skip_serializing_if = "Option::is_none")] pub return_to: Option, + /// 在哪台设备上授权:`browser`(默认,在这台机器上开浏览器)或 `device`(拿一个 + /// 一次性码,去别的设备上输) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mode: Option, } /// 一次进行中的登录。 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ChatgptLogin { pub id: String, - /// 在浏览器里打开的授权地址 - pub authorize_url: String, + /// 在浏览器里打开的授权地址。`browser` 登录才有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub authorize_url: Option, + /// 要用户输进去的一次性码。`device` 登录才有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub user_code: Option, + /// 用户在另一台设备上打开、输码的地址。`device` 登录才有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub verification_url: Option, /// 多少秒内要完成 pub expires_in_secs: u64, } diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs index 29a69808..98860b89 100644 --- a/crates/tw-control/src/chatgpt.rs +++ b/crates/tw-control/src/chatgpt.rs @@ -1,11 +1,17 @@ -//! ChatGPT 账号:浏览器登录、用量、额度重置卡。 +//! ChatGPT 账号:登录、用量、额度重置卡。 //! //! # 登录 //! -//! 在浏览器里完成 OAuth 授权(PKCE)。**回调只能回本机的 1455 或 1457 端口**:那是登记在 -//! Codex 客户端上的回调地址,OpenAI 不开放第三方登记自己的地址。core 在其中一个端口上等 -//! 回调,用授权码换 token,把上游写进 config.yaml —— refresh token、access token、过期时间和 -//! 账户 ID 都在配置里,和别的上游一起管理。桌面版只负责打开浏览器。 +//! 两条路,都是 OAuth(PKCE),最后都落到同一处:用授权码换 token,把上游写进 +//! config.yaml —— refresh token、access token、过期时间和账户 ID 都在配置里,和别的上游 +//! 一起管理。 +//! +//! - **在这台机器上开浏览器**(`browser`)。**回调只能回本机的 1455 或 1457 端口**:那是 +//! 登记在 Codex 客户端上的回调地址,OpenAI 不开放第三方登记自己的地址。core 在其中一个 +//! 端口上等回调,桌面版只负责打开浏览器。 +//! - **去另一台设备上输码**(`device`)。这台机器上没有浏览器、或者浏览器登录不了的时候 +//! 用。core 换一个一次性码,之后自己去问「批准了没有」。**不是所有账号都开放这条路**, +//! 服务端没开时换码直接 404,只能改用浏览器登录。 //! //! **同一时刻只有一次登录**:回调端口只有一个。新的登录开始时,还没完成的那次作废。 //! @@ -32,6 +38,9 @@ use crate::{ControlState, Fail, fail}; /// 登录要在多久之内完成。和 Codex 一样是 15 分钟 const LOGIN_TTL: Duration = Duration::from_secs(15 * 60); +/// 设备码最快多久问一次「批准了没有」。服务端给的间隔比它还短就按它来 —— 问得再勤, +/// 除了被限流没有别的效果 +const DEVICE_POLL_MIN: Duration = Duration::from_secs(3); /// 不指定名字时,上游叫这个 const DEFAULT_NAME: &str = "chatgpt"; /// 调 ChatGPT 后端接口(用量、重置卡)的超时 @@ -138,63 +147,113 @@ struct Flow { // ---------------------------------------------------------------- 登录 -async fn start( - State(s): State, - Json(req): Json, -) -> Result, Fail> { - let name = req - .name - .as_deref() - .map(str::trim) - .filter(|n| !n.is_empty()) - .unwrap_or(DEFAULT_NAME) - .to_string(); - let proxy = req - .proxy - .as_deref() - .map(str::trim) - .filter(|p| !p.is_empty()) - .unwrap_or(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, - format!("代理「{proxy}」不存在"), - )); - } - if let Some(p) = cfg.providers.iter().find(|p| p.name == name) - && p.effective_protocol() != Some(Protocol::Chatgpt) - { - return Err(fail( - StatusCode::CONFLICT, - format!("已有名为「{name}」的上游,且不是 ChatGPT 账号上游,请使用其他名称"), - )); - } - let return_to = match req - .return_to - .as_deref() - .map(str::trim) - .filter(|v| !v.is_empty()) - { - Some(v) if app_link(v) => Some(v.to_string()), - Some(_) => { +/// 在哪台设备上授权 +enum Mode { + /// 在这台机器上开浏览器 + Browser, + /// 去另一台设备上输码 + Device, +} + +/// 这次要登成什么样。两条登录路共用的那几项参数 +struct Want { + mode: Mode, + /// 登录后写进配置的上游名 + name: String, + /// 换 token 走哪条路 + proxy: String, + /// 浏览器登录完成后跳回应用。设备码登录没有这一步 + return_to: Option, +} + +impl Want { + /// 读一遍参数,有问题就直接回错 + fn read(s: &ControlState, req: &tw_api::ChatgptLoginStart) -> Result { + let given = |v: &Option| { + v.as_deref() + .map(str::trim) + .filter(|x| !x.is_empty()) + .map(str::to_string) + }; + let mode = match given(&req.mode).as_deref() { + None | Some("browser") => Mode::Browser, + Some("device") => Mode::Device, + Some(other) => { + return Err(fail( + StatusCode::BAD_REQUEST, + format!("登录方式「{other}」不认识"), + )); + } + }; + let name = given(&req.name).unwrap_or_else(|| 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, - "登录完成后的跳转地址只能使用应用自己的协议,不能是网页地址", + format!("代理「{proxy}」不存在"), )); } - None => None, - }; + if let Some(p) = cfg.providers.iter().find(|p| p.name == name) + && p.effective_protocol() != Some(Protocol::Chatgpt) + { + return Err(fail( + StatusCode::CONFLICT, + format!("已有名为「{name}」的上游,且不是 ChatGPT 账号上游,请使用其他名称"), + )); + } + let return_to = match given(&req.return_to) { + Some(v) if app_link(&v) => Some(v), + Some(_) => { + return Err(fail( + StatusCode::BAD_REQUEST, + "登录完成后的跳转地址只能使用应用自己的协议,不能是网页地址", + )); + } + None => None, + }; + Ok(Self { + mode, + name, + proxy, + return_to, + }) + } +} +async fn start( + State(s): State, + Json(req): Json, +) -> Result, Fail> { + let want = Want::read(&s, &req)?; // 还没完成的上一次登录作废:回调端口要让出来 let prev = s.chatgpt.current.lock().ok().and_then(|mut g| g.take()); if let Some(prev) = prev { prev.stop(&s).await; } + let (current, login) = match want.mode { + Mode::Browser => start_browser(&s, want).await?, + Mode::Device => start_device(&s, want).await?, + }; + // 两个登录同时开始时,后到的算数 + let raced = match s.chatgpt.current.lock() { + Ok(mut g) => g.replace(current), + Err(_) => Some(current), + }; + if let Some(prev) = raced { + prev.stop(&s).await; + } + Ok(Json(login)) +} + +/// 在这台机器上开浏览器:占住一个回调端口,等浏览器带着授权码回来 +async fn start_browser( + s: &ControlState, + want: Want, +) -> Result<(Current, tw_api::ChatgptLogin), Fail> { let (listener, port) = bind_callback(&s.chatgpt.endpoints.ports) .await .ok_or_else(|| { @@ -221,9 +280,9 @@ async fn start( let flow = Arc::new(Flow { s: s.clone(), id: id.clone(), - name, - proxy, - return_to, + name: want.name, + proxy: want.proxy, + return_to: want.return_to, redirect_uri, verifier: pkce.verifier, state, @@ -231,29 +290,192 @@ async fn start( settled: AtomicBool::new(false), done: tokio::sync::Notify::new(), }); - let current = Current { - status: tw_api::ChatgptLoginStatus { - id: id.clone(), - status: "pending".into(), - provider: None, - plan: None, + Ok(( + Current { + status: pending(&id), + task: tokio::spawn(serve_callback(flow, listener)), + }, + tw_api::ChatgptLogin { + id, + authorize_url: Some(authorize_url), + user_code: None, + verification_url: None, + expires_in_secs: LOGIN_TTL.as_secs(), + }, + )) +} + +/// 去另一台设备上输码:先换一个一次性码,再自己去问「批准了没有」。 +/// +/// **PKCE 的两段都在服务端**:challenge 是它生成的,批准之后连 verifier 一起给我们, +/// 我们只负责原样带进换 token 那一步。 +async fn start_device( + s: &ControlState, + want: Want, +) -> Result<(Current, tw_api::ChatgptLogin), Fail> { + let issuer = s.chatgpt.endpoints.issuer.clone(); + let http = + client_for(s, &want.name, &want.proxy).map_err(|e| fail(StatusCode::BAD_GATEWAY, e))?; + let asked = serde_json::json!({ "client_id": chatgpt::CLIENT_ID }); + let resp = send( + &http, + reqwest::Method::POST, + &chatgpt::device_code_url(&issuer), + &[], + Some(&asked), + ) + .await?; + let status = resp.status(); + if status == StatusCode::NOT_FOUND { + return Err(fail( + StatusCode::CONFLICT, + "这个账号还不能用设备码登录,请改用在这台电脑上登录", + )); + } + let text = resp.text().await.unwrap_or_default(); + if !status.is_success() { + return Err(fail( + StatusCode::BAD_GATEWAY, + format!("换设备码时返回 {}:{}", status.as_u16(), brief(&text)), + )); + } + let code: DeviceCode = + serde_json::from_str(&text).map_err(|e| fail(StatusCode::BAD_GATEWAY, e))?; + let id = chatgpt::new_state(); + let user_code = code.user_code.clone(); + Ok(( + Current { + status: pending(&id), + task: tokio::spawn(await_device(s.clone(), id.clone(), want, http, code)), + }, + tw_api::ChatgptLogin { + id, + authorize_url: None, + user_code: Some(user_code), + verification_url: Some(chatgpt::device_page_url(&issuer)), + expires_in_secs: LOGIN_TTL.as_secs(), + }, + )) +} + +fn pending(id: &str) -> tw_api::ChatgptLoginStatus { + tw_api::ChatgptLoginStatus { + id: id.to_string(), + status: "pending".into(), + provider: None, + plan: None, + error: None, + } +} + +/// 换来的设备码 +#[derive(Debug, Clone, serde::Deserialize)] +struct DeviceCode { + /// 问「批准了没有」时要带上它 + device_auth_id: String, + /// 给用户看、让他输进去的码 + user_code: String, + /// 服务端让我们隔多少秒问一次 + #[serde(default)] + interval: u64, +} + +/// 用户批准之后拿到的东西。verifier 是服务端生成的,原样带进换 token +#[derive(Debug, serde::Deserialize)] +struct Approved { + authorization_code: String, + code_verifier: String, +} + +/// 等用户在另一台设备上批准。**403 和 404 都是「还没批」**,一直问到 15 分钟为止 +async fn await_device( + s: ControlState, + id: String, + want: Want, + http: reqwest::Client, + code: DeviceCode, +) { + let issuer = s.chatgpt.endpoints.issuer.clone(); + let url = chatgpt::device_token_url(&issuer); + let asked = serde_json::json!({ + "device_auth_id": code.device_auth_id, + "user_code": code.user_code, + }); + let every = Duration::from_secs(code.interval).max(DEVICE_POLL_MIN); + let deadline = tokio::time::Instant::now() + LOGIN_TTL; + while tokio::time::Instant::now() < deadline { + let resp = match send(&http, reqwest::Method::POST, &url, &[], Some(&asked)).await { + Ok(r) => r, + Err((_, why)) => return settle(&s, &id, Err(why)), + }; + let status = resp.status(); + // 还没批:接着等 + if status == StatusCode::FORBIDDEN || status == StatusCode::NOT_FOUND { + tokio::time::sleep(every).await; + continue; + } + let text = resp.text().await.unwrap_or_default(); + if !status.is_success() { + return settle( + &s, + &id, + Err(format!("登录时返回 {}:{}", status.as_u16(), brief(&text))), + ); + } + let done = match serde_json::from_str::(&text) { + Ok(a) => { + exchange_and_save( + &s, + &want.name, + &want.proxy, + &a.authorization_code, + &a.code_verifier, + &chatgpt::device_redirect_uri(&issuer), + ) + .await + } + Err(e) => Err(format!("批准登录的响应看不懂:{e}")), + }; + return settle(&s, &id, done); + } + s.chatgpt.set_status(tw_api::ChatgptLoginStatus { + id: id.clone(), + status: "expired".into(), + provider: None, + plan: None, + error: Some("15 分钟内没有完成授权".into()), + }); + announce(&s, &id, "expired", None, None); +} + +/// 记下登录的结果,并告诉界面一声 +fn settle(s: &ControlState, id: &str, done: Result<(String, Option), String>) { + let status = match done { + Ok((provider, plan)) => tw_api::ChatgptLoginStatus { + id: id.to_string(), + status: "done".into(), + provider: Some(provider), + plan, error: None, }, - task: tokio::spawn(serve_callback(flow, listener)), - }; - // 两个登录同时开始时,后到的算数 - let raced = match s.chatgpt.current.lock() { - Ok(mut g) => g.replace(current), - Err(_) => Some(current), + Err(why) => { + tracing::warn!("ChatGPT 登录未完成:{why}"); + tw_api::ChatgptLoginStatus { + id: id.to_string(), + status: "failed".into(), + provider: None, + plan: None, + error: Some(why), + } + } }; - if let Some(prev) = raced { - prev.stop(&s).await; - } - Ok(Json(tw_api::ChatgptLogin { - id, - authorize_url, - expires_in_secs: LOGIN_TTL.as_secs(), - })) + s.chatgpt.set_status(status.clone()); + announce(s, id, &status.status, status.provider, status.error); +} + +/// 出错时给用户看的那一小段响应 +fn brief(text: &str) -> String { + tw_secret::mask_body(text).chars().take(200).collect() } async fn status( @@ -375,43 +597,32 @@ async fn callback( detail.chars().take(200).collect::() )) } - (None, Some(code)) => complete(&flow, code).await, - (None, None) => Err("回调中缺少授权码".to_string()), - }; - let html = match result { - Ok((provider, plan)) => { - flow.s.chatgpt.set_status(tw_api::ChatgptLoginStatus { - id: flow.id.clone(), - status: "done".into(), - provider: Some(provider.clone()), - plan, - error: None, - }); - announce(&flow.s, &flow.id, "done", Some(provider), None); - page( - "ChatGPT 登录已完成", - "此页可以关闭。", - flow.return_to.as_deref(), + (None, Some(code)) => { + exchange_and_save( + &flow.s, + &flow.name, + &flow.proxy, + code, + &flow.verifier, + &flow.redirect_uri, ) + .await } - Err(why) => { - tracing::warn!("ChatGPT 登录未完成:{why}"); - let html = page( - "ChatGPT 登录未完成", - &format!("{why}。请回到 ThinkWatch 重新发起登录。"), - flow.return_to.as_deref(), - ); - flow.s.chatgpt.set_status(tw_api::ChatgptLoginStatus { - id: flow.id.clone(), - status: "failed".into(), - provider: None, - plan: None, - error: Some(why.clone()), - }); - announce(&flow.s, &flow.id, "failed", None, Some(why)); - html - } + (None, None) => Err("回调中缺少授权码".to_string()), }; + let html = match &result { + Ok(_) => page( + "ChatGPT 登录已完成", + "此页可以关闭。", + flow.return_to.as_deref(), + ), + Err(why) => page( + "ChatGPT 登录未完成", + &format!("{why}。请回到 ThinkWatch 重新发起登录。"), + flow.return_to.as_deref(), + ), + }; + settle(&flow.s, &flow.id, result); *outcome = Some(html.clone()); flow.settled.store(true, Ordering::SeqCst); // 这一页先发出去,服务再停 @@ -420,25 +631,18 @@ async fn callback( } /// 用授权码换 token,写进配置。返回上游名和套餐。 -async fn complete(flow: &Flow, code: &str) -> Result<(String, Option), String> { - let s = &flow.s; +async fn exchange_and_save( + s: &ControlState, + name: &str, + proxy: &str, + code: &str, + verifier: &str, + redirect_uri: &str, +) -> Result<(String, Option), String> { let endpoints = &s.chatgpt.endpoints; - // 换 token 走选定的出站方式:需要代理才能访问 OpenAI 的用户,直连会卡在这一步 - let route = tw_config::Provider { - name: flow.name.clone(), - base_url: endpoints.backend.clone(), - proxy: flow.proxy.clone(), - ..Default::default() - }; - let http = tw_gateway::client_for_provider(&s.config(), &route).map_err(|e| e.message)?; - let tokens = chatgpt::exchange_code( - &http, - &endpoints.token, - code, - &flow.verifier, - &flow.redirect_uri, - ) - .await?; + let http = client_for(s, name, proxy)?; + let tokens = + chatgpt::exchange_code(&http, &endpoints.token, code, verifier, redirect_uri).await?; let account = chatgpt::account(&tokens.id_token); let oauth = tw_config::OAuth { access: Some(tokens.access.clone()), @@ -452,8 +656,8 @@ async fn complete(flow: &Flow, code: &str) -> Result<(String, Option), S client_secret: None, refresh_before: None, }; - let name = flow.name.clone(); - let proxy = flow.proxy.clone(); + let name = name.to_string(); + let proxy = proxy.to_string(); let backend = endpoints.backend.clone(); let account_id = account.account_id.clone(); s.cfg @@ -504,11 +708,22 @@ async fn complete(flow: &Flow, code: &str) -> Result<(String, Option), S .map_err(|e| format!("无法写入配置:{e}"))?; // 模型清单现在就问一次:不然要等到下一轮定时刷新,新上游的模型才出现 let gateway = s.gateway.clone(); - let provider = flow.name.clone(); + let provider = name.clone(); tokio::spawn(async move { tw_gateway::models::refresh_one(&gateway, &provider).await; }); - Ok((flow.name.clone(), account.plan)) + Ok((name, account.plan)) +} + +/// 按出站方式建一个客户端。**要代理才能访问 OpenAI 的用户,直连会卡在换 token 这一步** +fn client_for(s: &ControlState, name: &str, proxy: &str) -> Result { + let route = tw_config::Provider { + name: name.to_string(), + base_url: s.chatgpt.endpoints.backend.clone(), + proxy: proxy.to_string(), + ..Default::default() + }; + tw_gateway::client_for_provider(&s.config(), &route).map_err(|e| e.message) } fn announce( @@ -691,7 +906,26 @@ async fn usage( Path(name): Path, ) -> Result, Fail> { let v = account_call(&s, &name, reqwest::Method::GET, "usage", None).await?; - Ok(Json(parse_usage(&v))) + let usage = parse_usage(&v); + // 问来的额度和响应头里读到的一样记下来:**额度只在内存里**,冷启动之后要等这个账号 + // 第一次有请求才会有,而界面一打开就该看得见 + s.gateway.record_quota( + s.bus().next_id(), + &name, + tw_gateway::quota::Quota { + windows: usage + .windows + .iter() + .map(|w| tw_gateway::quota::Window { + window: w.window.clone(), + used_percent: w.used_percent, + reset_in_secs: w.reset_in_secs, + status: w.status.clone(), + }) + .collect(), + }, + ); + Ok(Json(usage)) } /// `wham/usage` 的回答。**只取额度相关的几项**:同一份回答里还有邮箱和用户 ID,不往外带 diff --git a/crates/tw-control/tests/chatgpt.rs b/crates/tw-control/tests/chatgpt.rs index f5ca6d4b..ca426c21 100644 --- a/crates/tw-control/tests/chatgpt.rs +++ b/crates/tw-control/tests/chatgpt.rs @@ -37,6 +37,12 @@ struct OpenAi { backend: Mutex>, /// 用卡接口收到的请求体 consumed: Mutex>, + /// 这个账号不能用设备码登录:换码回 404 + device_closed: Mutex, + /// 问到第几次才算批准。0 就是第一次问就批 + device_approve_after: Mutex, + /// 设备码的两个接口收到的请求体 + device_asks: Mutex>, } fn jwt(claims: Value) -> String { @@ -108,12 +114,56 @@ async fn token( .into_response() } +/// 换一个一次性码。**没开放这条路的账号回 404** +async fn device_code( + State(o): State>, + axum::Json(v): axum::Json, +) -> axum::response::Response { + o.device_asks.lock().unwrap().push(v); + if *o.device_closed.lock().unwrap() { + return ( + StatusCode::NOT_FOUND, + axum::Json(json!({"detail": "Not Found"})), + ) + .into_response(); + } + axum::Json(json!({"device_auth_id": "dev-1", "user_code": "ABCD-1234", "interval": 1})) + .into_response() +} + +/// 批准了没有。**没批准是 403**,批准了才给授权码和服务端生成的 verifier +async fn device_token( + State(o): State>, + axum::Json(v): axum::Json, +) -> axum::response::Response { + let asked = { + let mut asks = o.device_asks.lock().unwrap(); + asks.push(v); + asks.iter().filter(|a| a.get("user_code").is_some()).count() as u32 + }; + if asked <= *o.device_approve_after.lock().unwrap() { + return ( + StatusCode::FORBIDDEN, + axum::Json(json!({"detail": "Forbidden"})), + ) + .into_response(); + } + axum::Json(json!({ + "authorization_code": "code-from-device", + "code_challenge": "challenge-from-server", + "code_verifier": "verifier-from-server", + })) + .into_response() +} + async fn start_openai(o: Arc) -> Endpoints { fn seen(o: &OpenAi, uri: &OriginalUri, headers: HeaderMap) { o.backend.lock().unwrap().push((uri.0.to_string(), headers)); } let app = axum::Router::new() .route("/oauth/token", post(token)) + .route("/api/accounts/deviceauth/usercode", post(device_code)) + .route("/api/accounts/deviceauth/token", post(device_token)) .route( "/oauth/revoke", post(|State(o): State>, axum::Json(v): axum::Json| async move { @@ -651,11 +701,111 @@ async fn a_new_login_replaces_the_one_still_waiting_and_a_login_can_be_cancelled assert_eq!(v["status"], "cancelled"); } +// ---------------------------------------------------------------- 设备码登录 + +#[tokio::test] +async fn a_device_login_waits_for_the_other_device_and_saves_the_account() { + let mut b = bed(|_| String::new()).await; + // 第一次问的时候还没批,要接着等 + *b.openai.device_approve_after.lock().unwrap() = 1; + let (st, v) = b + .call("POST", "/chatgpt/login", json!({"mode": "device"})) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + + // 给用户的是码和一个地址,这台机器上不开浏览器 + let id = v["id"].as_str().unwrap().to_string(); + assert_eq!(v["user_code"], "ABCD-1234"); + assert_eq!( + v["verification_url"], + json!(format!("{}/codex/device", b.endpoints.issuer)) + ); + assert!(v["authorize_url"].is_null(), "{v}"); + let (_, v) = b + .call("GET", &format!("/chatgpt/login/{id}"), Value::Null) + .await; + assert_eq!(v["status"], "pending"); + + assert_eq!( + b.login_finished().await, + (id.clone(), "done".into(), Some("chatgpt".into())) + ); + + // 换码时如实说明自己是谁 + let asked = b.openai.device_asks.lock().unwrap().clone(); + assert_eq!(asked[0]["client_id"], CLIENT_ID); + // 之后每次都带着这一次的设备码去问 + assert!(asked.len() >= 3, "问了几次:{}", asked.len()); + for ask in &asked[1..] { + assert_eq!(ask["device_auth_id"], "dev-1"); + assert_eq!(ask["user_code"], "ABCD-1234"); + } + + // 换 token 用服务端给的 verifier 和设备码那条路的回调地址 + let form = b.openai.token_forms.lock().unwrap()[0].clone(); + assert_eq!(form["grant_type"], "authorization_code"); + assert_eq!(form["code"], "code-from-device"); + assert_eq!(form["code_verifier"], "verifier-from-server"); + assert_eq!( + form["redirect_uri"], + format!("{}/deviceauth/callback", b.endpoints.issuer) + ); + + // 之后和浏览器登录完全一样:凭据进配置,模型清单马上问 + let p = b.provider("chatgpt").expect("登录之后配置里应当有这个上游"); + assert_eq!(p.effective_protocol(), Some(tw_config::Protocol::Chatgpt)); + assert_eq!(p.oauth.as_ref().unwrap().refresh, "rt-login"); + assert_eq!( + p.headers.get("ChatGPT-Account-Id").unwrap().value.raw(), + "acct-1" + ); + let (_, v) = b + .call("GET", &format!("/chatgpt/login/{id}"), Value::Null) + .await; + assert_eq!(v["plan"], "plus"); + eventually("登录后获取模型清单", || { + b.openai + .backend + .lock() + .unwrap() + .iter() + .any(|(path, _)| path.starts_with("/backend-api/codex/models?client_version=")) + }) + .await; +} + +#[tokio::test] +async fn an_account_without_device_login_is_told_to_use_the_browser() { + let b = bed(|_| String::new()).await; + *b.openai.device_closed.lock().unwrap() = true; + let (st, v) = b + .call("POST", "/chatgpt/login", json!({"mode": "device"})) + .await; + assert_eq!(st, StatusCode::CONFLICT); + assert!( + v.to_string().contains("这台电脑"), + "要告诉用户改用浏览器登录:{v}" + ); + assert!(b.provider("chatgpt").is_none()); +} + +#[tokio::test] +async fn a_login_mode_that_is_not_understood_is_refused() { + let b = bed(|_| String::new()).await; + let (st, _) = b + .call("POST", "/chatgpt/login", json!({"mode": "carrier-pigeon"})) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST); +} + // ---------------------------------------------------------------- 用量与重置卡 #[tokio::test] async fn usage_shows_the_limits_without_personal_details() { let b = bed(|e| logged_in("chatgpt", e, "rt-cfg")).await; + // 还没有请求经过,额度就还不知道 + let (_, v) = b.call("GET", "/quota", Value::Null).await; + assert_eq!(v, json!([])); let (st, v) = b .call("GET", "/providers/chatgpt/chatgpt/usage", Value::Null) .await; @@ -673,6 +823,11 @@ async fn usage_shows_the_limits_without_personal_details() { "{text}" ); + // 问来的额度就是这个上游的额度:冷启动之后界面不用等第一次请求 + let (_, q) = b.call("GET", "/quota", Value::Null).await; + assert_eq!(q[0]["provider"], "chatgpt"); + assert_eq!(q[0]["windows"], v["windows"]); + // 如实说明是谁,带着配置里的 access token 和账户 ID;不是对话,不带会话 ID let seen = b.openai.backend.lock().unwrap(); let (path, h) = seen.last().unwrap(); diff --git a/crates/tw-gateway/src/chatgpt.rs b/crates/tw-gateway/src/chatgpt.rs index a0133c2c..cf675c97 100644 --- a/crates/tw-gateway/src/chatgpt.rs +++ b/crates/tw-gateway/src/chatgpt.rs @@ -274,6 +274,32 @@ pub fn authorize_url(issuer: &str, redirect_uri: &str, pkce: &Pkce, state: &str) url.to_string() } +/// 设备码:在这台机器上换一个一次性码。**不是所有账号都开放**,没开放时这个接口回 404 +pub fn device_code_url(issuer: &str) -> String { + format!( + "{}/api/accounts/deviceauth/usercode", + issuer.trim_end_matches('/') + ) +} + +/// 设备码:问一次「批准了没有」 +pub fn device_token_url(issuer: &str) -> String { + format!( + "{}/api/accounts/deviceauth/token", + issuer.trim_end_matches('/') + ) +} + +/// 设备码:让用户在另一台设备上打开、输码的那一页 +pub fn device_page_url(issuer: &str) -> String { + format!("{}/codex/device", issuer.trim_end_matches('/')) +} + +/// 设备码换令牌时要报的回调地址。**这一步没有浏览器跳转**,但它必须和授权时的一致 +pub fn device_redirect_uri(issuer: &str) -> String { + format!("{}/deviceauth/callback", issuer.trim_end_matches('/')) +} + /// 登录换回来的令牌。refresh token、access token 和过期时间写进配置,id_token 只用来读账户信息 pub struct Tokens { pub id_token: String, diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 1bdde1c9..08f80865 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -640,7 +640,12 @@ impl AppState { /// **429 的那一跳也要读**:额度用完时上游回的正是 429,只读成功那一跳的话, /// 「用完了」这件事永远看不到。 pub(crate) fn note_quota(&self, id: u64, provider: &str, headers: &reqwest::header::HeaderMap) { - let quota = crate::quota::from_headers_reqwest(headers); + self.record_quota(id, provider, crate::quota::from_headers_reqwest(headers)); + } + + /// 记下一份额度。**账号接口问来的也走这里**:额度只在内存里,冷启动之后要等第一次 + /// 请求才有,而界面一打开就该看得见 + pub fn record_quota(&self, id: u64, provider: &str, quota: crate::quota::Quota) { if quota.is_empty() { return; } From b1ef58941997b0e1b68d713aa102a27d826036f9 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 18 Sep 2026 23:26:02 +0800 Subject: [PATCH 2/2] fix: say it in writing, not in speech Co-Authored-By: Claude Opus 5 --- crates/tw-control/src/chatgpt.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs index 98860b89..a47dbc94 100644 --- a/crates/tw-control/src/chatgpt.rs +++ b/crates/tw-control/src/chatgpt.rs @@ -181,7 +181,7 @@ impl Want { Some(other) => { return Err(fail( StatusCode::BAD_REQUEST, - format!("登录方式「{other}」不认识"), + format!("不支持的登录方式「{other}」"), )); } };