From f88e67bc9f0e4330f4dfd9e38820d8dea935472f Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 18 Sep 2026 01:53:39 +0800 Subject: [PATCH] feat: sign in with a ChatGPT account A ChatGPT subscription becomes an upstream like any other: sign in once in the browser, and the credentials land in config.yaml next to every other provider. Login (control plane) - POST /chatgpt/login starts an OAuth authorization-code + PKCE flow and waits for the browser on 127.0.0.1:1455 (or 1457), the redirect URIs registered for the Codex client. GET/DELETE /chatgpt/login/{id} report or cancel it; LoginFinished is emitted when it settles. - The callback exchanges the code through the chosen proxy and writes the provider: protocol chatgpt, refresh + access token + expiry, the account ID header, subscription billing. Signing in again replaces only the credentials. The page can hand back to the app through an app-scheme return_to; web URLs are refused so it cannot be an open redirect. - A callback with the wrong state is ignored, duplicates exchange the code once, and the callback port is released as soon as the login settles. - Deleting a signed-in provider revokes its refresh token, unless another provider still uses the same one. Usage and rate-limit reset credits - GET /providers/{name}/chatgpt/usage returns plan, windows and the number of reset credits, without the email or user ID in the same response. - GET/POST /providers/{name}/chatgpt/resets lists and consumes reset credits. Consuming requires an idempotency key and only happens on an explicit request; the gateway never spends one on its own. Gateway - Requests identify as ThinkWatch (originator, user agent, session ID); identity headers are not configurable and the client's are not forwarded. - The backend only streams and rejects max_output_tokens: requests are shaped accordingly, and a client that asked for a whole response gets one collected from the stream. The stream has no Content-Type, so success responses are marked as SSE. This also fixes converted streams being sent as application/json to non-streaming clients. - A 401 from an OAuth upstream gets one fresh token and one retry, unless the token was obtained within the last minute. Refreshes are single-flight per provider, since rotated refresh tokens are single-use. - Access tokens and their expiry are persisted to config.yaml on every renewal, so a restart reuses them instead of rotating the refresh token. - CredentialExpired and QuotaExhausted are emitted once per transition. Codex quota windows are named from window-minutes; zero-length windows are skipped. Models come from /models?client_version. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 5 + Cargo.toml | 2 + bin/twcore/src/main.rs | 1 + crates/tw-api/src/lib.rs | 158 +++++ crates/tw-config/src/chatgpt.rs | 64 ++ crates/tw-config/src/credential.rs | 69 +- crates/tw-config/src/lib.rs | 92 ++- crates/tw-control/Cargo.toml | 3 + crates/tw-control/src/chatgpt.rs | 834 ++++++++++++++++++++++ crates/tw-control/src/dryrun.rs | 3 +- crates/tw-control/src/lib.rs | 16 +- crates/tw-control/src/resources.rs | 31 + crates/tw-control/src/rotation.rs | 118 +++- crates/tw-control/tests/adopt.rs | 1 + crates/tw-control/tests/chatgpt.rs | 847 +++++++++++++++++++++++ crates/tw-control/tests/dryrun.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/speed.rs | 1 + crates/tw-gateway/Cargo.toml | 3 + crates/tw-gateway/src/chatgpt.rs | 531 ++++++++++++++ crates/tw-gateway/src/client_api.rs | 3 +- crates/tw-gateway/src/l3.rs | 2 +- crates/tw-gateway/src/lib.rs | 1 + crates/tw-gateway/src/oauth.rs | 388 +++++++++-- crates/tw-gateway/src/probe.rs | 23 +- crates/tw-gateway/src/quota.rs | 71 +- crates/tw-gateway/src/server.rs | 378 ++++++++-- crates/tw-gateway/src/translate.rs | 2 +- crates/tw-gateway/tests/chatgpt.rs | 636 +++++++++++++++++ crates/tw-gateway/tests/oauth.rs | 16 +- crates/tw-store/src/recorder.rs | 3 + 34 files changed, 4094 insertions(+), 213 deletions(-) create mode 100644 crates/tw-config/src/chatgpt.rs create mode 100644 crates/tw-control/src/chatgpt.rs create mode 100644 crates/tw-control/tests/chatgpt.rs create mode 100644 crates/tw-gateway/src/chatgpt.rs create mode 100644 crates/tw-gateway/tests/chatgpt.rs diff --git a/Cargo.lock b/Cargo.lock index 084a9794..6bf6188f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2820,6 +2820,7 @@ name = "tw-control" version = "0.4.0" dependencies = [ "axum", + "base64", "bytes", "chrono", "futures", @@ -2830,6 +2831,7 @@ dependencies = [ "serde", "serde_json", "serde_yaml_ng", + "sha2", "tempfile", "thiserror", "tokio", @@ -2898,12 +2900,14 @@ dependencies = [ "http-body-util", "hyper", "hyper-util", + "rand 0.10.2", "reqwest", "rustls", "rustls-platform-verifier", "serde", "serde_json", "serde_yaml_ng", + "sha2", "tempfile", "thiserror", "tokio", @@ -2921,6 +2925,7 @@ dependencies = [ "tw-scan", "tw-secret", "tw-types", + "uuid", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index d0038dbc..f91a1186 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -115,6 +115,8 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] } chrono = { version = "0.4", features = ["serde"] } arc-swap = "1" blake3 = "1" +# PKCE 的 S256。版本跟着 reqwest 的传递依赖走,不引新的树 +sha2 = "0.11" uuid = { version = "1", features = ["v4", "serde"] } rand = "0.10" diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 63949918..bc0e2a66 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -734,6 +734,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> gateway_addr: if safe { None } else { Some(addr.to_string()) }, store, price_updater: Default::default(), + chatgpt: Default::default(), }; // 盯着客户端配置面。**只报告** —— 这条路径上没有任何 // 一处会改用户的文件。盯不住就只是少了「变更时告警」,页面上 diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 8a33690a..19c8ef57 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -199,6 +199,33 @@ pub enum Event { detail: String, at_ms: u64, }, + /// OAuth 凭据失效了:refresh token 过期、被用过或者被吊销。 + /// + /// **重试没有用,只有重新登录能恢复**,而在那之前这家上游的请求全部失败,所以要 + /// 让人知道。只在失效的那一刻报一次;重新登录之后再失效,会重新报。 + CredentialExpired { + id: u64, + provider: String, + /// 失效的原因,**已打码** + detail: String, + at_ms: u64, + }, + /// 一次账号登录结束了:成功、失败、过期或者取消。 + /// + /// 登录是在浏览器里完成的,**界面等的就是这一条**:收到它就能切回前台、说明结果, + /// 不用一直问。 + LoginFinished { + id: u64, + /// 发起登录时拿到的 ID + login: String, + /// `done` / `failed` / `expired` / `cancelled` + status: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + provider: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + error: Option, + at_ms: u64, + }, /// 这次请求做了方言互转(M6+)。 /// /// **`dropped` 非空时必须让用户看见**:`thinking` 在 OpenAI chat @@ -313,6 +340,20 @@ pub enum Event { windows: Vec, at_ms: u64, }, + /// 一个订阅额度窗口用完了,这家上游在窗口重置之前不再接受请求。 + /// + /// **只在用完的那一刻报一次。**之后同一个窗口里的请求照样被拒,但同一句话说第二遍, + /// 只会让人学会忽略通知。窗口重置、额度恢复之后再用完,会重新报。 + QuotaExhausted { + id: u64, + provider: String, + /// 和 `QuotaWindow.window` 同一个词表 + window: String, + /// 多久之后重置。上游没说就没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + reset_in_secs: Option, + at_ms: u64, + }, /// 配置换了一份新的进去,已经生效。 /// /// **界面靠它知道自己手里那份过期了。**没有它,用户在编辑器里改完 @@ -425,6 +466,7 @@ impl Event { | Event::ConfigReloaded { id, .. } | Event::ConfigRejected { id, .. } | Event::QuotaSeen { id, .. } + | Event::QuotaExhausted { id, .. } | Event::LeakSeen { id, .. } | Event::ScanAlert { id, .. } | Event::RequestPriced { id, .. } @@ -435,6 +477,8 @@ impl Event { | Event::ResponseInspected { id, .. } | Event::Translated { id, .. } | Event::CredentialRotated { id, .. } + | Event::CredentialExpired { id, .. } + | Event::LoginFinished { id, .. } | Event::RequestRouted { id, .. } => *id, } } @@ -640,6 +684,15 @@ pub struct OAuthView { pub endpoint: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub client_id: Option, + /// access token 什么时候过期,RFC 3339。不知道就没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expires_at: Option, + /// 最近一次刷新失败的原因。**已打码**;没失败过、或者已经恢复就没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failure: Option, + /// 凭据已经失效,只有重新登录能恢复 + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub needs_login: bool, } /// 配置里引用了某个上游的一处。 @@ -1591,6 +1644,111 @@ pub struct ProviderQuota { pub windows: Vec, } +// ---------------------------------------------------------------- ChatGPT 账号 + +/// 发起 ChatGPT 登录(`POST /chatgpt/login`)。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct ChatgptLoginStart { + /// 登录后写进配置的上游名。不给就是 `chatgpt`;已经有同名的 ChatGPT 账号上游时, + /// 换掉它的凭据(重新登录),其余设置不动 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + /// 换 token 走哪条路:`direct` / `system` / 代理名。不给是 `direct`。新建上游时也写成它的出站方式 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub proxy: Option, + /// 登录完成后,浏览器页面跳到哪里。**只接受应用自己的协议**(`thinkwatch://…`), + /// 不接受网页地址 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub return_to: Option, +} + +/// 一次进行中的登录。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChatgptLogin { + pub id: String, + /// 在浏览器里打开的授权地址 + pub authorize_url: String, + /// 多少秒内要完成 + pub expires_in_secs: u64, +} + +/// 登录进行到哪一步(`GET /chatgpt/login/{id}`)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChatgptLoginStatus { + pub id: String, + /// `pending` / `done` / `failed` / `expired` / `cancelled` + pub status: String, + /// 写进配置的上游名。`done` 时有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider: Option, + /// 套餐:`plus` / `pro` / `team` …。`done` 时有,令牌里没写就没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plan: Option, + /// `failed` 时的原因 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +/// ChatGPT 账号的用量(`GET /providers/{name}/chatgpt/usage`)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChatgptUsage { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plan: Option, + /// 额度窗口,词表同 [`QuotaWindow`] + pub windows: Vec, + /// 可用的额度重置卡张数。账号没有这一项时没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reset_credits: Option, +} + +/// 一张额度重置卡。 +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct ResetCreditView { + pub id: String, + /// 重置哪种额度,后端的原词 + pub reset_type: String, + /// 后端的原词 + pub status: String, + pub granted_at: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expires_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, +} + +/// 账号上的额度重置卡(`GET /providers/{name}/chatgpt/resets`)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ResetCredits { + pub available_count: i64, + pub credits: Vec, +} + +/// 用一张额度重置卡(`POST /providers/{name}/chatgpt/resets`)。 +/// +/// **卡用掉就回不来**,所以只在用户明确点下去时发,网关自己从不用。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ResetCreditUse { + /// 幂等键。同一次操作重试时用同一个值,后端不会重复扣卡 + pub idempotency_key: String, + /// 用哪一张。不给由后端挑 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub credit_id: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct ResetCreditUsed { + /// - `reset`:额度已重置 + /// - `nothing_to_reset`:额度没用完,不需要重置,没有扣卡 + /// - `no_credit`:没有可用的卡(指定了卡时:那张已经不能用) + /// - `already_redeemed`:这个幂等键已经用过,额度在那一次已经重置 + pub code: String, + /// 重置了几个窗口 + #[serde(default)] + pub windows_reset: i64, +} + /// L3 测速要花多少。 /// /// **这是「你确认要花钱吗」那个对话框的全部内容。**触发前必须显示它, diff --git a/crates/tw-config/src/chatgpt.rs b/crates/tw-config/src/chatgpt.rs new file mode 100644 index 00000000..18a3f377 --- /dev/null +++ b/crates/tw-config/src/chatgpt.rs @@ -0,0 +1,64 @@ +//! ChatGPT 账号:用 OpenAI 登录拿到的凭据,调 ChatGPT 订阅背后的 Codex 后端。 +//! +//! 这里只放配置层要认的东西:地址、token 端点、客户端 ID、哪些请求头由网关填。 +//! 登录、刷新和转发的细节在网关和控制面。 + +/// Codex 后端。请求发到 `{BASE_URL}/responses`,模型清单在 `{BASE_URL}/models` +pub const BASE_URL: &str = "https://chatgpt.com/backend-api/codex"; + +/// OpenAI 的 token 端点:登录换 token、之后的刷新都在这里 +pub const TOKEN_ENDPOINT: &str = "https://auth.openai.com/oauth/token"; + +/// OAuth 客户端 ID。 +/// +/// **这是 Codex 的客户端 ID。**OpenAI 没有开放第三方注册 OAuth 客户端,OpenCode 等 +/// 开源客户端用的也是这一个。除了它,请求里的身份都是 ThinkWatch 自己的(见 +/// [`IDENTITY_HEADERS`])。 +pub const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann"; + +/// 账户 ID 所在的请求头。登录时从 id_token 读出来,写进上游的 `headers` +pub const ACCOUNT_HEADER: &str = "ChatGPT-Account-Id"; + +/// 说明请求来自谁的请求头。 +/// +/// **由网关如实填写,配置里不能写。**能写的话,一行配置就能让 ThinkWatch 冒充 +/// Codex 或别的客户端 —— 而接入 ChatGPT 账号的前提是如实说明自己是谁。 +pub const IDENTITY_HEADERS: &[&str] = &[ + "originator", + "user-agent", + "session-id", + "session_id", + "version", +]; + +/// 这个地址是不是 Codex 后端。 +/// +/// 按 host 和路径比,**不按包含比**:`https://relay.example/chatgpt.com/backend-api/codex` +/// 也「含有」那一段。 +pub fn is_backend(base_url: &str) -> bool { + let rest = base_url.trim().split("://").nth(1).unwrap_or(""); + let path = rest.find('/').map_or("", |i| &rest[i..]); + crate::credential::host_of(base_url) == "chatgpt.com" + && (path.trim_end_matches('/') == "/backend-api/codex" + || path.starts_with("/backend-api/codex/")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_codex_backend_on_chatgpt_com_counts() { + assert!(is_backend(BASE_URL)); + assert!(is_backend("https://chatgpt.com/backend-api/codex/")); + assert!(is_backend("HTTPS://ChatGPT.com/backend-api/codex")); + assert!(!is_backend("https://chatgpt.com/backend-api")); + assert!(!is_backend("https://chatgpt.com/backend-api/codexx")); + assert!(!is_backend( + "https://relay.example/chatgpt.com/backend-api/codex" + )); + assert!(!is_backend( + "https://chatgpt.com.evil.example/backend-api/codex" + )); + } +} diff --git a/crates/tw-config/src/credential.rs b/crates/tw-config/src/credential.rs index e5a12e92..7be58420 100644 --- a/crates/tw-config/src/credential.rs +++ b/crates/tw-config/src/credential.rs @@ -242,7 +242,7 @@ impl<'de> Deserialize<'de> for Headers { pub fn auth_header(protocol: Option) -> (&'static str, &'static str) { match protocol { Some(Protocol::Gemini) => ("x-goog-api-key", ""), - Some(Protocol::OpenaiChat) | Some(Protocol::OpenaiResponses) => { + Some(Protocol::OpenaiChat) | Some(Protocol::OpenaiResponses) | Some(Protocol::Chatgpt) => { ("authorization", "Bearer ") } Some(Protocol::Anthropic) | None => ("x-api-key", ""), @@ -262,6 +262,10 @@ pub enum CredentialError { ClaudeSubscription, #[error("不支持接入 Gemini CLI 的 Google 登录凭据,请改用 Gemini API 密钥")] GoogleSubscription, + #[error("ChatGPT 账号上游只能使用登录获得的凭据")] + ChatgptWithoutLogin, + #[error("请求头「{0}」说明请求的来源,由网关如实发送,不能在配置中设置")] + IdentityHeader(String), #[error("请求头不能超过 {MAX_HEADERS} 个")] TooManyHeaders, #[error( @@ -299,7 +303,7 @@ impl From for CredentialError { } } -fn host_of(url: &str) -> String { +pub(crate) fn host_of(url: &str) -> String { let h = url.trim().to_ascii_lowercase(); h.split("://") .nth(1) @@ -373,6 +377,11 @@ impl Provider { return Err(CredentialError::GoogleSubscription); } } + // **Codex 后端只认登录拿到的凭据**,API 密钥发过去只会是一个 401 + let chatgpt = self.effective_protocol() == Some(Protocol::Chatgpt); + if chatgpt && crate::chatgpt::is_backend(&self.base_url) && self.oauth.is_none() { + return Err(CredentialError::ChatgptWithoutLogin); + } if self.headers.len() > MAX_HEADERS { return Err(CredentialError::TooManyHeaders); } @@ -392,6 +401,9 @@ impl Provider { if RESERVED.contains(&lower.as_str()) { return Err(CredentialError::ReservedHeader(h.name.clone())); } + if chatgpt && crate::chatgpt::IDENTITY_HEADERS.contains(&lower.as_str()) { + return Err(CredentialError::IdentityHeader(h.name.clone())); + } if seen.contains(&lower) { return Err(CredentialError::DuplicateHeader(h.name.clone())); } @@ -491,6 +503,7 @@ mod tests { fn oauth() -> OAuth { OAuth { access: None, + expires_at: None, refresh: "r".into(), endpoint: "https://auth.example.com/token".into(), client_id: None, @@ -651,6 +664,58 @@ mod tests { lookalike.check_credential().unwrap(); } + #[test] + fn a_chatgpt_account_takes_only_a_login_and_its_identity_is_not_configurable() { + let bare = p("name: c\nbase_url: https://chatgpt.com/backend-api/codex\n"); + assert_eq!(bare.effective_protocol(), Some(Protocol::Chatgpt)); + assert_eq!( + bare.check_credential(), + Err(CredentialError::ChatgptWithoutLogin) + ); + let key = p("name: c\nbase_url: https://chatgpt.com/backend-api/codex\nkey: sk-x\n"); + assert_eq!( + key.check_credential(), + Err(CredentialError::ChatgptWithoutLogin) + ); + + let mut login = p( + "name: c\nbase_url: https://chatgpt.com/backend-api/codex\nheaders:\n ChatGPT-Account-Id: acc-1\n", + ); + login.oauth = Some(OAuth { + endpoint: crate::chatgpt::TOKEN_ENDPOINT.into(), + client_id: Some(crate::chatgpt::CLIENT_ID.into()), + ..oauth() + }); + login.check_credential().unwrap(); + assert_eq!( + login.outbound_headers(Some("at"), None).unwrap(), + vec![ + ("authorization".to_string(), "Bearer at".to_string()), + ("ChatGPT-Account-Id".to_string(), "acc-1".to_string()), + ] + ); + + // 一行配置就能冒充 Codex 的话,「如实说明身份」就只是个默认值 + for name in [ + "originator", + "User-Agent", + "session-id", + "session_id", + "version", + ] { + let mut forged = login.clone(); + forged.headers = p(&format!( + "name: c\nbase_url: https://x\nheaders:\n {name}: codex_cli_rs\n" + )) + .headers; + assert_eq!( + forged.check_credential(), + Err(CredentialError::IdentityHeader(name.to_string())), + "{name}" + ); + } + } + #[test] fn a_key_written_as_a_mapping_says_where_oauth_goes() { let e = serde_yaml_ng::from_str::( diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index f665d9f3..ba18fc49 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; pub use tw_types::Limits; +pub mod chatgpt; pub mod credential; pub mod edit; pub mod history; @@ -371,14 +372,23 @@ pub struct Client { /// 但不写回更糟:**换发新的那一刻旧的已经在服务端作废了**,不写回等于 /// 让配置文件从那一秒起就是坏的,只是症状延迟到下一次重启。 /// -/// 写回只动那一个标量(span 补丁),而且不进配置历史 —— 回滚到一次 +/// 写回只动这几个标量(span 补丁),而且不进配置历史 —— 回滚到一次 /// 轮换之前拿到的是一个作废的 token,那不是可以退回去的状态。 +/// +/// # access token 也写在这里 +/// +/// 每次刷新之后,网关把新的 access token 和过期时间一起写回来(2026-09-18 定)。 +/// 重启之后手里那个没过期就直接用:不用先换一次 token,也就不会每次重启都轮换 +/// 一次 refresh token、写一次文件;启动时 token 端点一时连不上,请求也照样能发。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct OAuth { - /// 现成的 access token。**可选** —— 不写就启动后立刻用 refresh 换一个 + /// access token。**可选** —— 不写就在第一次用到时拿 refresh 换一个,换来的写回这里 #[serde(default, skip_serializing_if = "Option::is_none")] pub access: Option, + /// `access` 什么时候过期,RFC 3339(UTC)。不知道的话就一直用到上游回 401 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expires_at: Option, pub refresh: String, /// token 端点 pub endpoint: String, @@ -600,6 +610,9 @@ pub enum Protocol { OpenaiChat, OpenaiResponses, Gemini, + /// ChatGPT 账号:Codex 后端。说的是 OpenAI Responses 格式,但只接受流式、 + /// 不认 `max_output_tokens`、身份头由网关填(见 [`chatgpt`]) + Chatgpt, } impl Protocol { @@ -610,6 +623,7 @@ impl Protocol { Protocol::OpenaiChat => "openai-chat", Protocol::OpenaiResponses => "openai-responses", Protocol::Gemini => "gemini", + Protocol::Chatgpt => "chatgpt", } } } @@ -618,6 +632,9 @@ impl Provider { /// 从 base_url 猜协议。猜不出来返回 None —— **不猜一个默认值**, /// 因为猜错的表现是「请求发出去了但上游 400」,比直接说不知道难查。 pub fn guess_protocol(base_url: &str) -> Option { + if chatgpt::is_backend(base_url) { + return Some(Protocol::Chatgpt); + } let h = base_url.to_ascii_lowercase(); if h.contains("api.anthropic.com") { Some(Protocol::Anthropic) @@ -650,6 +667,7 @@ impl Provider { "api.moonshot.cn", "open.bigmodel.cn", "dashscope.aliyuncs.com", + "chatgpt.com", ]; let h = self.base_url.to_ascii_lowercase(); // **要在 host 上比,不能只看包含。**`https://evil.com/api.anthropic.com/` @@ -701,49 +719,71 @@ impl Provider { } } -/// 把 token 端点换发的新 refresh token 写回 config.yaml 的**那一个标量**。 +/// 刷新之后要写回配置的值。 +#[derive(Debug, Clone, Copy)] +pub struct RenewedTokens<'a> { + pub access: &'a str, + /// RFC 3339(UTC)。服务器没说有效期就是 `None`,那时删掉配置里旧的过期时间 + pub expires_at: Option<&'a str>, + /// 服务器换发了新的 refresh token 才有 + pub refresh: Option<&'a str>, +} + +/// 把刷新换回来的 token 写回 config.yaml:access token、过期时间,以及换发的 +/// refresh token(有的话)。 /// /// # 为什么要写回 /// /// **服务器换发新 refresh token 的那一刻,旧的已经在服务端作废了。** /// 所以「不写回」不是保守选项 —— 它保证了配置文件从那一秒起就是坏的, /// 只是症状延迟到下一次重启(表现是这家上游突然全是 401,而那时没人 -/// 会想到是几天前的一次轮换)。写回才是安全的那一边。 +/// 会想到是几天前的一次轮换)。写回才是安全的那一边。access token 写回的理由 +/// 见 [`OAuth`]。 /// /// # 为什么是 span 补丁而不是 serde 往返 /// /// 往返会把用户的注释、空行、字段顺序全洗掉 —— 而这是**用户没要求的 -/// 一次写入**,它必须只动它该动的那 40 个字符。cc-switch 那 147 个 +/// 一次写入**,它必须只动它该动的那几个字段。cc-switch 那 147 个 /// commit 的白名单教训在这里同样成立:我们要写什么是清楚的, /// 「要保留什么」永远数不完。 /// -/// 找不到那个字段就报错,**不追加**:追加意味着我们猜错了结构,而在 -/// 一个装着明文密钥的文件里猜结构是不能接受的。 -pub fn patch_oauth_refresh( +/// `oauth.refresh` 找不到就报错,**不追加**:那说明我们猜错了结构,而在一个装着 +/// 明文密钥的文件里猜结构是不能接受的。`access` 和 `expires_at` 是可选字段, +/// 没写过就加在 `oauth` 下面。 +pub fn patch_oauth_tokens( text: &str, provider: &str, - new_refresh: &str, + tokens: RenewedTokens<'_>, ) -> Result { // 名字对应第几个 provider —— 从**文本本身**数,不从解析后的结构数。 // 两者理论上一致,但真正要动的是文本里的那个位置。 let idx = provider_index(text, provider).ok_or_else(|| RotateError::NoProvider { provider: provider.to_string(), })?; - let path = tw_yaml::path!["providers", idx, "oauth", "refresh"]; - // 先确认它在那儿。`set` 对不存在的路径行为是另一回事,而这里 - // 「不在那儿」本身就是「别写」的理由 - tw_yaml::find(text, &path).map_err(|source| RotateError::Shape { + let shape = |source| RotateError::Shape { provider: provider.to_string(), source, - })?; - let out = tw_yaml::set(text, &path, &tw_yaml::Scalar::s(new_refresh)).map_err(|source| { - RotateError::Shape { - provider: provider.to_string(), - source, + }; + let refresh_path = tw_yaml::path!["providers", idx, "oauth", "refresh"]; + // 先确认它在那儿:不在那儿本身就是「别写」的理由 + tw_yaml::find(text, &refresh_path).map_err(shape)?; + let mut out = text.to_string(); + if let Some(r) = tokens.refresh { + out = tw_yaml::set(&out, &refresh_path, &tw_yaml::Scalar::s(r)).map_err(shape)?; + } + let access_path = tw_yaml::path!["providers", idx, "oauth", "access"]; + out = tw_yaml::insert(&out, &access_path, &tw_yaml::Scalar::s(tokens.access)).map_err(shape)?; + let expires_path = tw_yaml::path!["providers", idx, "oauth", "expires_at"]; + out = match tokens.expires_at { + Some(at) => tw_yaml::insert(&out, &expires_path, &tw_yaml::Scalar::s(at)).map_err(shape)?, + // 新 token 的有效期不知道:旧的过期时间留着只会让它被当成旧 token 的寿命 + None if tw_yaml::find(&out, &expires_path).is_ok() => { + tw_yaml::remove_key(&out, &expires_path).map_err(shape)? } - })?; + None => out, + }; // **写之前先自己读一遍。**patch 出来的东西必须还是一份能加载的配置, - // 而且那个字段真的变成了新值 —— 否则我们会把一份坏配置留在盘上, + // 而且那几个字段真的变成了新值 —— 否则我们会把一份坏配置留在盘上, // 而用户下一次启动才撞上它(「先校验再写」同一条)。 let re = try_parse(&out).map_err(|r| RotateError::Broke { provider: provider.to_string(), @@ -754,11 +794,15 @@ pub fn patch_oauth_refresh( .iter() .find(|p| p.name == provider) .and_then(|p| p.oauth.as_ref()) - .is_some_and(|o| o.refresh == new_refresh); + .is_some_and(|o| { + o.access.as_deref() == Some(tokens.access) + && o.expires_at.as_deref() == tokens.expires_at + && tokens.refresh.is_none_or(|r| o.refresh == r) + }); if !ok { return Err(RotateError::Broke { provider: provider.to_string(), - why: "写入后读回的 refresh token 不是新值".into(), + why: "写入后读回的 token 不是新值".into(), }); } Ok(out) @@ -908,6 +952,10 @@ providers: Provider::guess_protocol("https://generativelanguage.googleapis.com/v1beta"), Some(Protocol::Gemini) ); + assert_eq!( + Provider::guess_protocol("https://chatgpt.com/backend-api/codex"), + Some(Protocol::Chatgpt) + ); // 中转站猜不出来 —— 返回 None 而不是编一个默认值。 assert_eq!( Provider::guess_protocol("https://relay.example.cn/v1"), diff --git a/crates/tw-control/Cargo.toml b/crates/tw-control/Cargo.toml index f69ebd8b..94ac1189 100644 --- a/crates/tw-control/Cargo.toml +++ b/crates/tw-control/Cargo.toml @@ -39,6 +39,9 @@ tower = { workspace = true } tracing = { workspace = true } [dev-dependencies] +# 测试里的假 OpenAI:拼 id_token、核对 PKCE +base64 = { workspace = true } +sha2 = { workspace = true } tw-yaml = { workspace = true } serde_yaml_ng = { workspace = true } tempfile = "3" diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs new file mode 100644 index 00000000..29a69808 --- /dev/null +++ b/crates/tw-control/src/chatgpt.rs @@ -0,0 +1,834 @@ +//! ChatGPT 账号:浏览器登录、用量、额度重置卡。 +//! +//! # 登录 +//! +//! 在浏览器里完成 OAuth 授权(PKCE)。**回调只能回本机的 1455 或 1457 端口**:那是登记在 +//! Codex 客户端上的回调地址,OpenAI 不开放第三方登记自己的地址。core 在其中一个端口上等 +//! 回调,用授权码换 token,把上游写进 config.yaml —— refresh token、access token、过期时间和 +//! 账户 ID 都在配置里,和别的上游一起管理。桌面版只负责打开浏览器。 +//! +//! **同一时刻只有一次登录**:回调端口只有一个。新的登录开始时,还没完成的那次作废。 +//! +//! # 额度重置卡 +//! +//! 用掉就回不来,**只在用户明确点下去时用**。网关自己从不用,额度用完时只发通知。 + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::Json; +use axum::extract::{Path, Query, State}; +use axum::http::StatusCode; +use axum::response::Html; +use axum::routing::{get, post}; +use serde_json::Value; +use tw_config::Protocol; +use tw_config::history::Origin; +use tw_gateway::chatgpt; + +use crate::{ControlState, Fail, fail}; + +/// 登录要在多久之内完成。和 Codex 一样是 15 分钟 +const LOGIN_TTL: Duration = Duration::from_secs(15 * 60); +/// 不指定名字时,上游叫这个 +const DEFAULT_NAME: &str = "chatgpt"; +/// 调 ChatGPT 后端接口(用量、重置卡)的超时 +const API_TIMEOUT: Duration = Duration::from_secs(15); + +pub fn router() -> axum::Router { + axum::Router::new() + .route("/chatgpt/login", post(start)) + .route("/chatgpt/login/{id}", get(status).delete(cancel)) + .route("/providers/{name}/chatgpt/usage", get(usage)) + .route( + "/providers/{name}/chatgpt/resets", + get(list_resets).post(use_reset), + ) +} + +/// 登录要用的地址。**平时是 OpenAI 的**,测试里换成本机的假服务器 +#[derive(Debug, Clone)] +pub struct Endpoints { + /// 登录页所在 + pub issuer: String, + /// 换 token,也是写进上游配置的 token 端点 + pub token: String, + /// 删除上游时吊销 refresh token + pub revoke: String, + /// 登录得来的上游写成这个接口地址 + pub backend: String, + /// 依次尝试的回调端口。`0` 由系统挑一个空闲的 + pub ports: Vec, +} + +impl Default for Endpoints { + fn default() -> Self { + Self { + issuer: chatgpt::ISSUER.to_string(), + token: chatgpt::TOKEN_ENDPOINT.to_string(), + revoke: chatgpt::REVOKE_ENDPOINT.to_string(), + backend: tw_config::chatgpt::BASE_URL.to_string(), + ports: chatgpt::CALLBACK_PORTS.to_vec(), + } + } +} + +/// 登录的状态。**进程里只有一份**(见模块文档) +#[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::ChatgptLoginStatus) { + 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::ChatgptLoginStatus, + /// 等回调的那个任务。取消、或者新的登录开始时停掉它 + task: tokio::task::JoinHandle<()>, +} + +impl Current { + /// 停掉等回调的任务,**等它真的停下**:端口要让给下一次登录 + async fn stop(self, s: &ControlState) { + self.task.abort(); + let _ = self.task.await; + if self.status.status == "pending" { + announce(s, &self.status.id, "cancelled", None, None); + } + } +} + +/// 一次登录要记住的东西。**PKCE 的 verifier 只在这里**,不出进程 +struct Flow { + s: ControlState, + id: String, + name: String, + proxy: String, + return_to: Option, + redirect_uri: String, + verifier: String, + state: String, + /// 回调处理完之后给浏览器的那一页。**同一时刻只处理一个回调**:浏览器重试会带着 + /// 同一个授权码再来一次,那时直接给上次的结果 + outcome: tokio::sync::Mutex>, + /// 回调处理完了(不论成败) + settled: AtomicBool, + /// 处理完之后停掉回调服务 + done: tokio::sync::Notify, +} + +// ---------------------------------------------------------------- 登录 + +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(_) => { + return Err(fail( + StatusCode::BAD_REQUEST, + "登录完成后的跳转地址只能使用应用自己的协议,不能是网页地址", + )); + } + None => None, + }; + + // 还没完成的上一次登录作废:回调端口要让出来 + let prev = s.chatgpt.current.lock().ok().and_then(|mut g| g.take()); + if let Some(prev) = prev { + prev.stop(&s).await; + } + let (listener, port) = bind_callback(&s.chatgpt.endpoints.ports) + .await + .ok_or_else(|| { + let ports = s + .chatgpt + .endpoints + .ports + .iter() + .map(|p| p.to_string()) + .collect::>() + .join("、"); + fail( + StatusCode::CONFLICT, + format!("登录回调端口 {ports} 均被占用。如果 Codex 正在登录,请先完成或关闭它"), + ) + })?; + + let pkce = chatgpt::Pkce::new(); + let redirect_uri = chatgpt::redirect_uri(port); + let state = chatgpt::new_state(); + let authorize_url = + chatgpt::authorize_url(&s.chatgpt.endpoints.issuer, &redirect_uri, &pkce, &state); + let id = chatgpt::new_state(); + let flow = Arc::new(Flow { + s: s.clone(), + id: id.clone(), + name, + proxy, + return_to, + redirect_uri, + verifier: pkce.verifier, + state, + outcome: tokio::sync::Mutex::new(None), + 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, + 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), + }; + if let Some(prev) = raced { + prev.stop(&s).await; + } + Ok(Json(tw_api::ChatgptLogin { + id, + authorize_url, + expires_in_secs: LOGIN_TTL.as_secs(), + })) +} + +async fn status( + State(s): State, + Path(id): Path, +) -> Result, Fail> { + s.chatgpt + .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, + "没有这次登录,或者它已被新的登录替代", + ) + }) +} + +async fn cancel( + State(s): State, + Path(id): Path, +) -> Result, Fail> { + let mut status = { + let g = s + .chatgpt + .current + .lock() + .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))?; + let c = g.as_ref().filter(|c| c.status.id == id).ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + "没有这次登录,或者它已被新的登录替代", + ) + })?; + if c.status.status != "pending" { + return Ok(Json(c.status.clone())); + } + // 不用等它停下:端口晚一点让出来也没关系,下一次登录会等 + c.task.abort(); + c.status.clone() + }; + status.status = "cancelled".into(); + s.chatgpt.set_status(status.clone()); + announce(&s, &id, "cancelled", None, None); + Ok(Json(status)) +} + +/// 依次试回调端口。**刚取消的上一次登录可能还没把端口让出来**,每个端口多等几次 +async fn bind_callback(ports: &[u16]) -> Option<(tokio::net::TcpListener, u16)> { + for attempt in 0..5 { + for port in ports { + if let Ok(l) = tokio::net::TcpListener::bind(("127.0.0.1", *port)).await + && let Ok(addr) = l.local_addr() + { + return Some((l, addr.port())); + } + } + if attempt < 4 { + tokio::time::sleep(Duration::from_millis(100)).await; + } + } + None +} + +/// 等浏览器回调。处理完或者 15 分钟过去就停 +async fn serve_callback(flow: Arc, listener: tokio::net::TcpListener) { + let app = axum::Router::new() + .route("/auth/callback", get(callback)) + .with_state(flow.clone()); + let stop = flow.clone(); + // **到点也是优雅停止**:正在换 token 的那个回调要让它做完,不然换到手的凭据没写进配置就丢了 + let serve = axum::serve(listener, app).with_graceful_shutdown(async move { + tokio::select! { + _ = stop.done.notified() => {} + _ = tokio::time::sleep(LOGIN_TTL) => {} + } + }); + // 一个一直不发完请求的连接会让优雅停止等下去,再给一分钟就不等了 + let _ = tokio::time::timeout(LOGIN_TTL + Duration::from_secs(60), serve).await; + if !flow.settled.load(Ordering::SeqCst) { + flow.s.chatgpt.set_status(tw_api::ChatgptLoginStatus { + id: flow.id.clone(), + status: "expired".into(), + provider: None, + plan: None, + error: Some("15 分钟内没有完成授权".into()), + }); + announce(&flow.s, &flow.id, "expired", None, None); + } +} + +async fn callback( + State(flow): State>, + Query(q): Query>, +) -> Html { + // **state 对不上就当没来过**:可能是别的网页在试探这个端口,不能让它终止这次登录 + if q.get("state") != Some(&flow.state) { + return Html(page( + "登录链接已失效", + "请回到 ThinkWatch 重新发起登录。", + None, + )); + } + let mut outcome = flow.outcome.lock().await; + if let Some(html) = outcome.as_ref() { + return Html(html.clone()); + } + let result = match (q.get("error"), q.get("code").filter(|c| !c.is_empty())) { + (Some(e), _) => { + let detail = q.get("error_description").unwrap_or(e); + Err(format!( + "授权页返回错误:{}", + 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(), + ) + } + 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 + } + }; + *outcome = Some(html.clone()); + flow.settled.store(true, Ordering::SeqCst); + // 这一页先发出去,服务再停 + flow.done.notify_one(); + Html(html) +} + +/// 用授权码换 token,写进配置。返回上游名和套餐。 +async fn complete(flow: &Flow, code: &str) -> Result<(String, Option), String> { + let s = &flow.s; + 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 account = chatgpt::account(&tokens.id_token); + let oauth = tw_config::OAuth { + access: Some(tokens.access.clone()), + expires_at: tokens.expires_in.map(|secs| { + (chrono::Utc::now() + chrono::Duration::seconds(secs.min(i64::MAX as u64) as i64)) + .to_rfc3339_opts(chrono::SecondsFormat::Secs, true) + }), + refresh: tokens.refresh.clone(), + endpoint: endpoints.token.clone(), + client_id: Some(chatgpt::CLIENT_ID.to_string()), + client_secret: None, + refresh_before: None, + }; + let name = flow.name.clone(); + let proxy = flow.proxy.clone(); + let backend = endpoints.backend.clone(); + let account_id = account.account_id.clone(); + s.cfg + .transform(None, Origin::Ui, |text, cfg| { + let existing = cfg.providers.iter().find(|p| p.name == name); + if let Some(e) = existing + && e.effective_protocol() != Some(Protocol::Chatgpt) + { + return Err(crate::resources::invalid(format!( + "已有名为「{name}」的上游,且不是 ChatGPT 账号上游" + ))); + } + let mut p = existing.cloned().unwrap_or_else(|| tw_config::Provider { + name: name.clone(), + base_url: backend.clone(), + protocol: Some(Protocol::Chatgpt), + proxy: proxy.clone(), + billing: Some(tw_config::Billing::Subscription), + ..Default::default() + }); + // 重新登录:换掉凭据和账户 ID,其余设置(出站方式、模型范围、停用…)不动 + p.key = None; + p.oauth = Some(oauth.clone()); + let mut headers: Vec = p + .headers + .iter() + .filter(|h| !h.name.eq_ignore_ascii_case(chatgpt::ACCOUNT_HEADER)) + .cloned() + .collect(); + if let Some(id) = &account_id { + headers.push(tw_config::Header { + name: chatgpt::ACCOUNT_HEADER.to_string(), + value: tw_config::Secret::new(id.clone()), + }); + } + p.headers = tw_config::Headers::new(headers); + 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!("无法写入配置:{e}"))?; + // 模型清单现在就问一次:不然要等到下一轮定时刷新,新上游的模型才出现 + let gateway = s.gateway.clone(); + let provider = flow.name.clone(); + tokio::spawn(async move { + tw_gateway::models::refresh_one(&gateway, &provider).await; + }); + Ok((flow.name.clone(), account.plan)) +} + +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) +} + +/// 是不是应用自己的协议(`thinkwatch://…`)。**网页地址不行**:跳转地址是调用方给的, +/// 放行网页地址就是一个开放跳转 +fn app_link(v: &str) -> bool { + let Some((scheme, rest)) = v.split_once(':') else { + return false; + }; + let scheme = scheme.to_ascii_lowercase(); + let well_formed = scheme + .chars() + .next() + .is_some_and(|c| c.is_ascii_lowercase()) + && scheme + .chars() + .all(|c| c.is_ascii_alphanumeric() || "+.-".contains(c)); + let web = matches!( + scheme.as_str(), + "http" + | "https" + | "javascript" + | "data" + | "file" + | "blob" + | "about" + | "vbscript" + | "ftp" + | "ws" + | "wss" + ); + well_formed && !web && !rest.is_empty() && v.len() <= 512 && !v.chars().any(|c| c.is_control()) +} + +/// 回调之后浏览器里显示的那一页 +fn page(title: &str, detail: &str, return_to: Option<&str>) -> String { + let (redirect, link) = match return_to { + Some(url) => { + let u = escape(url); + ( + format!(r#""#), + format!(r#"

返回 ThinkWatch

"#), + ) + } + None => (String::new(), String::new()), + }; + format!( + r#"ThinkWatch{redirect}

{}

{}

{link}
"#, + escape(title), + escape(detail) + ) +} + +fn escape(s: &str) -> String { + s.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") +} + +// ---------------------------------------------------------------- 用量与重置卡 + +/// 调这个账号的 ChatGPT 后端接口(`wham/{path}`),读回 JSON。 +/// +/// **和转发一样,401 时换一个 access token 重发一次**:配置里那个可能已经在别处被吊销, +/// 不重发的话要等到下一个对话请求把它换掉,这里才恢复。用卡的请求重发也安全:401 说明 +/// 没有被处理,而且带着同一个幂等键。 +async fn account_call( + s: &ControlState, + name: &str, + method: reqwest::Method, + path: &str, + body: Option<&Value>, +) -> Result { + let cfg = s.config(); + let p = cfg + .providers + .iter() + .find(|p| p.name == name) + .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("上游「{name}」不存在")))?; + if p.effective_protocol() != Some(Protocol::Chatgpt) { + return Err(fail( + StatusCode::BAD_REQUEST, + format!("上游「{name}」不是 ChatGPT 账号上游"), + )); + } + let http = s.gateway.client_for(name); + let url = chatgpt::wham_url(&p.base_url, path); + let no_credential = |e: String| { + fail( + StatusCode::BAD_GATEWAY, + format!("无法获取上游「{name}」的凭据:{e}"), + ) + }; + let headers = s + .gateway + .headers_for(p, &http, None) + .await + .map_err(no_credential)?; + let sent_at = std::time::Instant::now(); + let mut resp = send(&http, method.clone(), &url, &headers, body).await?; + if resp.status() == StatusCode::UNAUTHORIZED + && let Ok(fresh) = s.gateway.headers_after_401(p, &http, None, sent_at).await + && fresh != headers + { + resp = send(&http, method, &url, &fresh, body).await?; + } + let status = resp.status(); + let text = resp.text().await.unwrap_or_default(); + if !status.is_success() { + let body = tw_secret::mask_body(&text) + .chars() + .take(400) + .collect::(); + return Err(fail( + StatusCode::BAD_GATEWAY, + format!("ChatGPT 后端返回 {}:{body}", status.as_u16()), + )); + } + serde_json::from_str(&text) + .map_err(|_| fail(StatusCode::BAD_GATEWAY, "ChatGPT 后端的响应不是 JSON")) +} + +/// 发一次。**这几个接口也如实报身份**;它们不是流式对话,不带会话 ID 和流式的 accept +async fn send( + http: &reqwest::Client, + method: reqwest::Method, + url: &str, + headers: &[(String, String)], + body: Option<&Value>, +) -> Result { + let identity: Vec<(String, String)> = + chatgpt::identity_headers(&axum::http::HeaderMap::new(), headers) + .into_iter() + .filter(|(k, _)| k != "accept" && k != "session-id") + .collect(); + let mut req = http.request(method, url).timeout(API_TIMEOUT); + req = tw_gateway::forward::apply_headers(req, headers); + req = tw_gateway::forward::apply_headers(req, &identity); + if let Some(b) = body { + req = req.json(b); + } + req.send().await.map_err(|e| { + fail( + StatusCode::BAD_GATEWAY, + format!( + "无法连接 ChatGPT 后端:{}", + tw_gateway::forward::map_reqwest_error(e).message + ), + ) + }) +} + +async fn usage( + State(s): State, + Path(name): Path, +) -> Result, Fail> { + let v = account_call(&s, &name, reqwest::Method::GET, "usage", None).await?; + Ok(Json(parse_usage(&v))) +} + +/// `wham/usage` 的回答。**只取额度相关的几项**:同一份回答里还有邮箱和用户 ID,不往外带 +fn parse_usage(v: &Value) -> tw_api::ChatgptUsage { + let window = |w: &Value| { + let secs = w.get("limit_window_seconds")?.as_u64().filter(|s| *s > 0)?; + let used = w.get("used_percent")?.as_f64()?.clamp(0.0, 100.0); + Some(tw_api::QuotaWindow { + window: tw_gateway::quota::codex_window(secs / 60), + used_percent: used, + reset_in_secs: w.get("reset_after_seconds").and_then(|x| x.as_u64()), + status: (used >= 100.0).then(|| "rejected".to_string()), + }) + }; + let limits = &v["rate_limit"]; + tw_api::ChatgptUsage { + plan: v["plan_type"].as_str().map(str::to_string), + windows: [&limits["primary_window"], &limits["secondary_window"]] + .into_iter() + .filter_map(window) + .collect(), + reset_credits: v["rate_limit_reset_credits"]["available_count"].as_i64(), + } +} + +async fn list_resets( + State(s): State, + Path(name): Path, +) -> Result, Fail> { + let v = account_call( + &s, + &name, + reqwest::Method::GET, + "rate-limit-reset-credits", + None, + ) + .await?; + serde_json::from_value(v) + .map(Json) + .map_err(|e| fail(StatusCode::BAD_GATEWAY, format!("无法识别重置卡清单:{e}"))) +} + +async fn use_reset( + State(s): State, + Path(name): Path, + Json(req): Json, +) -> Result, Fail> { + let key = req.idempotency_key.trim(); + if key.is_empty() || key.len() > 128 || key.chars().any(|c| c.is_control()) { + return Err(fail( + StatusCode::BAD_REQUEST, + "幂等键不能为空,且不超过 128 个字符", + )); + } + let mut body = serde_json::json!({ "redeem_request_id": key }); + if let Some(id) = req + .credit_id + .as_deref() + .map(str::trim) + .filter(|id| !id.is_empty()) + { + body["credit_id"] = Value::from(id); + } + let v = account_call( + &s, + &name, + reqwest::Method::POST, + "rate-limit-reset-credits/consume", + Some(&body), + ) + .await?; + let code = v["code"] + .as_str() + .ok_or_else(|| fail(StatusCode::BAD_GATEWAY, "无法识别使用重置卡的结果"))? + .to_ascii_lowercase(); + tracing::info!(provider = %name, %code, "已请求使用额度重置卡"); + Ok(Json(tw_api::ResetCreditUsed { + code, + windows_reset: v["windows_reset"].as_i64().unwrap_or(0), + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_app_links_are_accepted_as_the_return_address() { + assert!(app_link("thinkwatch://login/done")); + assert!(app_link("thinkwatch-lite:chatgpt")); + for bad in [ + "https://evil.example/phish", + "http://localhost:1420/", + "javascript:alert(1)", + "data:text/html,hi", + "file:///etc/passwd", + "thinkwatch:", + "not a url", + "1bad://x", + ] { + assert!(!app_link(bad), "{bad}"); + } + } + + #[test] + fn the_callback_page_escapes_what_it_shows() { + let html = page("标题", "", Some("thinkwatch://a\"b")); + assert!(!html.contains("