diff --git a/Cargo.lock b/Cargo.lock index abd1bb6d..0a65b590 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2634,6 +2634,7 @@ dependencies = [ "tw-secret", "tw-types", "uuid", + "zstd", ] [[package]] @@ -3348,3 +3349,31 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.0+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/Cargo.toml b/Cargo.toml index 1a00cff7..e9e0d6ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -133,6 +133,9 @@ blake3 = "1" sha2 = "0.11" uuid = { version = "1", features = ["v4", "serde"] } rand = "0.10" +# 发给 Codex 后端的请求体用 zstd 压缩(Codex 直连它时就这么发)。只要流式编码, +# 不开旧格式和字典训练 +zstd = { version = "0.13", default-features = false } clap = { version = "4", features = ["derive"] } # 控制面契约导出成 TypeScript(tw-api 的 `ts` feature)。**不开任何 serde 以外的 diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index 8ae34a51..8984ec0b 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -11,6 +11,7 @@ config.control_key_invalid config.control_key_missing config.credential.bad_header_name config.credential.bad_header_value +config.credential.chatgpt_client_identity config.credential.chatgpt_without_login config.credential.claude_subscription config.credential.duplicate_header diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index fb39ab11..26417cdf 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -614,7 +614,13 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// 不给就是不需要认证 —— `SecretChange` 和 `ProxyAuthInput` 这两个「保持原样」都删了。 /// 只有 OAuth 还能「保持原样」,见 [`OAuthChange::Keep`]。照 24 写的界面会去 /// `key.display` 里找密钥,保存时不给地址会被拒。 -pub const CONTROL_API_VERSION: u32 = 25; +/// +/// **26 起上游多一个「转发客户端身份」**:[`ProviderView::forward_client_identity`] 和 +/// [`ProviderInput::forward_client_identity`]。发给上游的请求头同版改成白名单:默认只有 +/// 网关填的(含 ThinkWatch 的 User-Agent)、上游配置里写的和各协议要的那几个,客户端 +/// 自己的 User-Agent 和身份头只在这一项打开时才发。照 25 写的界面保存时不给这个字段, +/// 会把它关掉。 +pub const CONTROL_API_VERSION: u32 = 26; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -1601,6 +1607,8 @@ pub struct ProviderView { pub protocol: Option, /// 协议是配置里写明的,还是按地址推断的 pub protocol_explicit: bool, + /// 把客户端自己的身份(User-Agent、身份请求头、请求体里的身份字段)如实发给这家 + pub forward_client_identity: bool, /// `direct` / `system` / 代理名 pub proxy: String, /// `fail` / `direct` @@ -2392,6 +2400,9 @@ pub struct ProviderInput { /// 不给就按地址推断 #[serde(default, skip_serializing_if = "Option::is_none")] pub protocol: Option, + /// 把客户端自己的身份如实发给这家。不给就是不发;ChatGPT 账号不能打开 + #[serde(default)] + pub forward_client_identity: bool, /// `direct` / `system` / 代理名 #[serde(default = "direct")] pub proxy: String, diff --git a/crates/tw-config/src/credential.rs b/crates/tw-config/src/credential.rs index 50f1376c..3f2a9c7e 100644 --- a/crates/tw-config/src/credential.rs +++ b/crates/tw-config/src/credential.rs @@ -280,6 +280,8 @@ pub enum CredentialError { #[error("{}", self.msg())] ChatgptWithoutLogin, #[error("{}", self.msg())] + ChatgptClientIdentity, + #[error("{}", self.msg())] IdentityHeader(String), #[error("{}", self.msg())] TooManyHeaders, @@ -332,6 +334,11 @@ impl CredentialError { "config.credential.chatgpt_without_login" => "a ChatGPT account upstream takes only the credential obtained by signing in" ), + ChatgptClientIdentity => msg!( + "config.credential.chatgpt_client_identity" => + "a ChatGPT account upstream always names ThinkWatch as the sender; it cannot \ + forward the client's identity" + ), IdentityHeader(h) => msg!( "config.credential.identity_header", header = h => "the `{header}` header says where a request came from; the gateway sends it \ @@ -474,6 +481,10 @@ impl Provider { if chatgpt && crate::chatgpt::is_backend(&self.base_url) && self.oauth.is_none() { return Err(CredentialError::ChatgptWithoutLogin); } + // 接 ChatGPT 账号的前提是如实说明请求来自 ThinkWatch:转发客户端的身份就是冒充它 + if chatgpt && self.forward_client_identity { + return Err(CredentialError::ChatgptClientIdentity); + } if self.headers.len() > MAX_HEADERS { return Err(CredentialError::TooManyHeaders); } @@ -814,6 +825,13 @@ mod tests { "{name}" ); } + // 转发客户端的身份也是冒充 + let mut forwarding = login.clone(); + forwarding.forward_client_identity = true; + assert_eq!( + forwarding.check_credential(), + Err(CredentialError::ChatgptClientIdentity) + ); } #[test] diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 40dcb756..69bb8697 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -158,6 +158,7 @@ impl Default for Provider { headers: Headers::default(), oauth: None, protocol: None, + forward_client_identity: false, proxy: default_proxy(), on_proxy_fail: OnProxyFail::default(), models: Vec::new(), @@ -714,6 +715,15 @@ pub struct Provider { /// 不写就从 base_url 猜(最小配置)。 #[serde(default, skip_serializing_if = "Option::is_none")] pub protocol: Option, + /// 把客户端自己的身份如实发给这家:它的 User-Agent 和 `x-app`、`originator` 这类 + /// 身份头,以及请求体里的身份字段(Claude Code 的 `metadata.user_id` 等)。 + /// + /// **默认不发**:请求由 ThinkWatch 发出,上游看到的是 ThinkWatch 的 User-Agent, + /// 客户端是谁、跑在什么系统上不外传。只给按客户端放行的上游打开:Kimi For Coding + /// 只接编程工具的 User-Agent,百炼 Coding Plan 拒绝通用的 User-Agent,有的中转站 + /// 只放官方客户端。发的都是客户端的原值,不伪造。ChatGPT 账号不能打开,见 [`chatgpt`] + #[serde(default, skip_serializing_if = "is_default")] + pub forward_client_identity: bool, /// 代理名,或内置的 `direct` / `system`。 /// /// **默认 `direct` 而不是 `system`**:显式优于隐式。默认跟随系统的 diff --git a/crates/tw-config/src/validate.rs b/crates/tw-config/src/validate.rs index e1da1cbf..72f987f0 100644 --- a/crates/tw-config/src/validate.rs +++ b/crates/tw-config/src/validate.rs @@ -959,6 +959,7 @@ mod msg_codes { ClaudeSubscription, GoogleSubscription, ChatgptWithoutLogin, + ChatgptClientIdentity, IdentityHeader("h".into()), TooManyHeaders, BadHeaderName("h".into()), diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index 04c34683..8c5877bd 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -459,6 +459,15 @@ pub fn sections() -> Vec
{ "上游的接口格式。不写:官方地址按 `base_url` 识别,其余按 `anthropic` 处理。", ), ), + row( + "forward_client_identity", + Kind::Bool, + Def::Is("false"), + t( + "Also send the client's own identity: its `User-Agent`, identity headers such as `x-app` and `originator`, and identity fields in the request body such as `metadata.user_id`. Values are the client's, never made up. Off: requests carry ThinkWatch's `User-Agent` and no client identity. For upstreams that admit only certain clients (Kimi For Coding, Bailian Coding Plan, relays restricted to official clients). Not available for `chatgpt`.", + "同时发送客户端自己的身份:它的 `User-Agent`、`x-app` 和 `originator` 等身份请求头,以及请求体中的身份字段(如 `metadata.user_id`)。发送的都是客户端的原值,不做伪造。关闭时请求使用 ThinkWatch 的 `User-Agent`,不带客户端身份。用于只接受特定客户端的上游(Kimi For Coding、百炼 Coding Plan、只允许官方客户端的中转站)。`chatgpt` 不可用。", + ), + ), row( "proxy", Kind::Str, diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 9714661a..5df1fd29 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -440,6 +440,7 @@ fn provider_view( }), protocol: p.effective_protocol().map(Into::into), protocol_explicit: p.protocol.is_some(), + forward_client_identity: p.forward_client_identity, proxy: p.proxy.clone(), on_proxy_fail: p.on_proxy_fail.into(), models: p.models.clone(), diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index d1c801eb..c0fb82be 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -384,6 +384,7 @@ fn to_provider( headers: tw_config::Headers::new(headers), oauth, protocol: input.protocol.map(Into::into), + forward_client_identity: input.forward_client_identity, models: input .models .iter() diff --git a/crates/tw-gateway/Cargo.toml b/crates/tw-gateway/Cargo.toml index 6d84aee2..a374c3b3 100644 --- a/crates/tw-gateway/Cargo.toml +++ b/crates/tw-gateway/Cargo.toml @@ -46,6 +46,7 @@ tw-dialect = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true } tracing = { workspace = true } +zstd = { workspace = true } [dev-dependencies] # 集成测试里要当 WS 客户端 —— 那一侧需要 connect diff --git a/crates/tw-gateway/src/chatgpt.rs b/crates/tw-gateway/src/chatgpt.rs index 753e7b69..7460f3da 100644 --- a/crates/tw-gateway/src/chatgpt.rs +++ b/crates/tw-gateway/src/chatgpt.rs @@ -5,8 +5,8 @@ //! 发给 Codex 后端的 `originator` 和 User-Agent 是 ThinkWatch 自己的,系统提示词是客户端 //! 自己的,不冒充 Codex,也不做指纹。唯一借用的是 OAuth 客户端 ID(见 //! [`tw_config::chatgpt::CLIENT_ID`])。2026-09-18 用 Plus 账号实测过,后端照常服务。 -//! 客户端带来的官方身份(ChatGPT 应用出具的证明、Codex 的安装 ID)也不转发,见 -//! [`tw_config::chatgpt::IDENTITY_HEADERS`]。 +//! 客户端的请求头只转协议要的那三个(见 [`crate::egress`]),ChatGPT 应用出具的证明、 +//! Codex 的安装 ID 这些官方客户端的身份都不发。 //! //! # 和 OpenAI Responses 不一样的地方 //! @@ -55,8 +55,34 @@ const RESIDENCY_HEADER: &str = "x-openai-internal-codex-residency"; // ---------------------------------------------------------------- 请求 /// `client_metadata` 里说明客户端是谁的两项。Codex 把安装 ID 和夹着它的 turn 元数据 -/// 在请求体里又放了一份,和同名的请求头一样不发(见 [`tw_config::chatgpt::IDENTITY_HEADERS`]) -const IDENTITY_METADATA: [&str; 2] = ["x-codex-installation-id", "x-codex-turn-metadata"]; +/// 在请求体里又放了一份,和同名的请求头一样不发(见 [`crate::egress`]) +pub(crate) const IDENTITY_METADATA: [&str; 2] = + ["x-codex-installation-id", "x-codex-turn-metadata"]; + +/// 去掉 `client_metadata` 里说明客户端是谁的几项([`IDENTITY_METADATA`])。去掉了什么 +/// 返回 true +pub(crate) fn remove_identity_metadata(obj: &mut serde_json::Map) -> bool { + let Some(meta) = obj + .get_mut("client_metadata") + .and_then(Value::as_object_mut) + else { + return false; + }; + let mut removed = false; + for key in IDENTITY_METADATA { + removed |= meta.remove(key).is_some(); + } + removed +} + +/// 压缩发给 Codex 后端的请求体,配 `Content-Encoding: zstd` 发。 +/// +/// Codex 直连这个后端时就这么发(openai/codex 的 `http-client`:zstd 3 级),说明后端 +/// 收压缩的请求体。Codex 的请求带着整段对话,长会话到 MB 级,JSON 压下来通常只剩一两成, +/// 经代理上传时省得最明显。这是标准的传输编码,和请求来自谁无关。压缩失败就原样发 +pub fn compress(body: &[u8]) -> Option { + zstd::stream::encode_all(body, 3).ok().map(Bytes::from) +} /// 客户端本来就说 Responses、这一跳直通时,把请求体改成 Codex 后端接受的样子。 /// @@ -81,14 +107,7 @@ pub fn shape_passthrough(body: &Bytes) -> (Bytes, Vec) { } obj.insert("stream".into(), Value::Bool(true)); obj.insert("store".into(), Value::Bool(false)); - if let Some(meta) = obj - .get_mut("client_metadata") - .and_then(Value::as_object_mut) - { - for key in IDENTITY_METADATA { - meta.remove(key); - } - } + remove_identity_metadata(obj); match serde_json::to_vec(&v) { Ok(b) => (Bytes::from(b), dropped), Err(_) => (body.clone(), Vec::new()), @@ -155,12 +174,6 @@ pub fn identity_headers( out } -/// 客户端带来的这个请求头要不要发给 Codex 后端。说明来源的头由网关自己填,`accept` 也是 -pub fn keeps_client_header(name: &str) -> bool { - let lower = name.to_ascii_lowercase(); - lower != "accept" && !tw_config::chatgpt::IDENTITY_HEADERS.contains(&lower.as_str()) -} - // ---------------------------------------------------------------- 账户 /// 令牌里和账户有关的几项。 @@ -532,17 +545,6 @@ mod tests { .any(|(n, v)| n == "session-id" && !v.is_empty()) ); assert!(!plain.iter().any(|(n, _)| n == RESIDENCY_HEADER)); - - // 客户端报的来源不转发:请求经过的是 ThinkWatch - assert!(!keeps_client_header("Originator")); - assert!(!keeps_client_header("user-agent")); - assert!(!keeps_client_header("accept")); - assert!(keeps_client_header("x-codex-turn-state")); - // 官方客户端才有的身份也不转发:证明是 ChatGPT 应用出具的,安装 ID 是 Codex 的 - assert!(!keeps_client_header("X-OAI-Attestation")); - assert!(!keeps_client_header("x-codex-installation-id")); - assert!(!keeps_client_header("x-codex-turn-metadata")); - assert!(keeps_client_header("x-codex-window-id")); } #[test] diff --git a/crates/tw-gateway/src/egress.rs b/crates/tw-gateway/src/egress.rs new file mode 100644 index 00000000..95dac383 --- /dev/null +++ b/crates/tw-gateway/src/egress.rs @@ -0,0 +1,436 @@ +//! 发给上游的请求头:每种上游发什么。 +//! +//! **白名单。**发出去的请求头只有三个来源: +//! +//! - 网关自己填的:User-Agent(ThinkWatch 的)、请求体经过转换时的 `content-type` +//! ([`gateway_headers`]);ChatGPT 账号另有它的身份头([`crate::chatgpt::identity_headers`]) +//! - 上游配置里写的:凭据和用户加的头(`tw_config::Provider::outbound_headers`) +//! - 从客户端请求里按名取的:这种上游的协议要用的那几个([`takes_from_client`]) +//! +//! 名单外的客户端请求头一个都不发。客户端是谁(`User-Agent`、`x-app`、`x-stainless-*`)、 +//! 它的会话和安装 ID、浏览器带的 `Cookie` 和 `Origin`,都不是上游该知道的。黑名单只挡得住 +//! 列出来的那些,客户端哪天多带一个头就原样漏给上游:ChatGPT 应用出具的证明 +//! (`x-oai-attestation`)就是这样经网关漏给 OpenAI 的,令牌 20 秒后被吊销。 +//! +//! 请求体同理。格式转换时由转换器按目标格式重新写,本来就只有请求的内容;同格式直通时 +//! 原样发,只去掉客户端自动填的身份字段([`strip_body_identity`])。 +//! +//! 有的上游按客户端放行:Kimi For Coding 只接编程工具的 User-Agent,百炼 Coding Plan +//! 拒绝通用的 User-Agent,有的中转站只放官方客户端。这样的上游打开 +//! `forward_client_identity`,客户端自己的身份原样发过去([`CLIENT_IDENTITY`])。发的 +//! 都是客户端的原值,不伪造;ChatGPT 账号不能打开。 + +use bytes::Bytes; +use http::HeaderMap; +use serde_json::Value; +use tw_config::Protocol; +use tw_dialect::ir::Dialect; + +/// 这一跳发给谁、怎么发。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Hop { + /// 这家说的格式。配置没写、地址也认不出时,按客户端的格式算(这时请求原样直通) + pub protocol: Option, + /// 请求体经过了格式转换:描述请求体的头由网关填 + pub translated: bool, + /// 客户端的身份原样发给这家:它打开了 `forward_client_identity`,而且不是 ChatGPT 账号 + pub client_identity: bool, + /// DeepSeek Harness 的请求发给 DeepSeek 官方:它自己的头照发(见 [`tw_dialect::harness`]) + pub harness_to_deepseek: bool, + /// DeepSeek Harness 的请求发给别家:`anthropic-beta` 不取客户端的原值,用去掉工具增删 + /// 那一项的版本(由发送处另外填) + pub harness_elsewhere: bool, +} + +impl Hop { + /// 上游说什么格式:配置写明或按地址认出的;都没有就是客户端的格式 + pub fn protocol_for(provider: Option, client: Option) -> Option { + provider.or(match client? { + Dialect::Anthropic => Some(Protocol::Anthropic), + Dialect::Chat => Some(Protocol::OpenaiChat), + Dialect::Responses => Some(Protocol::OpenaiResponses), + Dialect::Gemini => Some(Protocol::Gemini), + // Bedrock 不是一种上游协议:认不出的上游收到 Bedrock 格式也只能原样直通 + Dialect::Bedrock => None, + }) + } +} + +/// Codex 后端要从客户端取的头。 +/// +/// 照 openai/codex 发给 `/responses` 的头定,只留协议要的: +/// +/// - `x-codex-turn-state`:同一轮里后端发的粘性路由令牌,这一轮后面的请求都要原样带回去 +/// - `x-openai-internal-codex-responses-lite`:gpt-6 这类模型的请求体是精简格式,后端靠它认 +/// - `x-codex-beta-features`:客户端打开的测试功能,后端按它决定回什么 +/// +/// 会话 ID 不在这里:它由 [`crate::chatgpt::identity_headers`] 从客户端的值取过来再填。 +/// 窗口、线程、子代理这些 Codex 自己的上下文头不发,OpenCode 这类如实说明身份的客户端 +/// 也不发它们 +const CODEX_BACKEND: &[&str] = &[ + "x-codex-turn-state", + "x-openai-internal-codex-responses-lite", + "x-codex-beta-features", +]; + +/// OpenAI 接口(Chat、Responses)要从客户端取的头:重试不重复扣费的幂等键,和客户端给 +/// 请求起的追踪 ID。`OpenAI-Organization`、`OpenAI-Project` 属于这家的密钥,写在上游配置里, +/// 不取客户端的 —— 客户端报的是它自己那边的组织,和这家的密钥对不上时是一个 401 +const OPENAI: &[&str] = &["idempotency-key", "x-client-request-id"]; + +/// Anthropic 的这个协议头只对浏览器有意义(跨域放行),服务器之间转发没有用 +const BROWSER_ACCESS: &str = "anthropic-dangerous-direct-browser-access"; + +/// 打开 `forward_client_identity` 时,另外原样发的客户端身份头(User-Agent 由 +/// [`gateway_headers`] 发)。按上游实际核对的那些定:Kimi For Coding、百炼 Coding Plan +/// 看 User-Agent;只放官方客户端的中转站还看 Claude Code 的 `x-app`,以及 Codex 的 +/// `originator`、`version`、会话 ID 和 `x-codex-*` +pub const CLIENT_IDENTITY: &[&str] = + &["x-app", "originator", "version", "session_id", "session-id"]; + +/// [`CLIENT_IDENTITY`] 之外,按前缀认的那一族 +const CLIENT_IDENTITY_PREFIX: &str = "x-codex-"; + +/// 客户端请求里的这个头发不发给这家。 +pub fn takes_from_client(hop: &Hop, name: &str) -> bool { + let n = name.to_ascii_lowercase(); + if hop.client_identity + && (CLIENT_IDENTITY.contains(&n.as_str()) || n.starts_with(CLIENT_IDENTITY_PREFIX)) + { + return true; + } + if hop.harness_to_deepseek && tw_dialect::harness::own_header(&n) { + return true; + } + if hop.protocol == Some(Protocol::Chatgpt) { + return CODEX_BACKEND.contains(&n.as_str()); + } + // 请求体原样发时,说明它是什么的两个头照客户端的;转换过的由网关填 + if n == "content-type" || n == "accept" { + return !hop.translated; + } + match hop.protocol { + // `anthropic-*` 按前缀放行:Claude Code 的网关协议要求这一族原样转发,不按值挑 + Some(Protocol::Anthropic) => { + n.starts_with("anthropic-") + && n != BROWSER_ACCESS + && !(hop.harness_elsewhere && n == "anthropic-beta") + } + Some(Protocol::OpenaiChat | Protocol::OpenaiResponses) => OPENAI.contains(&n.as_str()), + Some(Protocol::Gemini | Protocol::Chatgpt) | None => false, + } +} + +/// 网关自己填的头(ChatGPT 账号的身份头另见 [`crate::chatgpt::identity_headers`]): +/// +/// - User-Agent:ThinkWatch 的;这家打开了 `forward_client_identity` 时用客户端自己的 +/// - `content-type`:请求体经过转换时一定是 JSON;原样发时照客户端的,客户端没写才填 +pub fn gateway_headers(hop: &Hop, client: &HeaderMap) -> Vec<(String, String)> { + let mut out = Vec::new(); + if hop.protocol != Some(Protocol::Chatgpt) { + let theirs = client + .get(http::header::USER_AGENT) + .and_then(|v| v.to_str().ok()) + .filter(|_| hop.client_identity); + let ua = theirs.map_or_else(crate::user_agent, str::to_string); + out.push(("user-agent".to_string(), ua)); + } + let chatgpt = hop.protocol == Some(Protocol::Chatgpt); + if hop.translated || chatgpt || !client.contains_key(http::header::CONTENT_TYPE) { + out.push(("content-type".to_string(), "application/json".to_string())); + } + out +} + +/// 同格式直通时,请求体里客户端自动填的身份字段。 +/// +/// - Anthropic:`metadata.user_id`。Claude Code 在里面写设备 ID、账号 UUID 和会话 ID +/// - Responses:`client_metadata` 里 Codex 的安装 ID 和夹着它的 turn 元数据 +/// ([`crate::chatgpt::IDENTITY_METADATA`]);会话、线程这些照发 +/// +/// 返回去掉之后的请求体;没有可去的是 `None`,请求体一个字节都不动。这不是为了兼容去掉 +/// 请求的内容,所以不算丢弃的字段 +pub fn strip_body_identity(dialect: Dialect, body: &Bytes) -> Option { + // 大多数请求没有这些字段:先便宜地看一眼,免得每个请求都解析、重写一遍请求体 + let text = std::str::from_utf8(body).ok()?; + let marks: &[&str] = match dialect { + Dialect::Anthropic => &["\"user_id\""], + Dialect::Responses => &crate::chatgpt::IDENTITY_METADATA, + _ => return None, + }; + if !marks.iter().any(|m| text.contains(m)) { + return None; + } + let mut v: Value = serde_json::from_str(text).ok()?; + let obj = v.as_object_mut()?; + let removed = match dialect { + Dialect::Anthropic => { + let meta = obj.get_mut("metadata").and_then(Value::as_object_mut); + let removed = meta.is_some_and(|m| m.remove("user_id").is_some()); + // 只剩一个空对象的话整个去掉:`metadata` 本来就可以不写 + if obj + .get("metadata") + .and_then(Value::as_object) + .is_some_and(serde_json::Map::is_empty) + { + obj.remove("metadata"); + } + removed + } + _ => crate::chatgpt::remove_identity_metadata(obj), + }; + if !removed { + return None; + } + serde_json::to_vec(&v).ok().map(Bytes::from) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hop(protocol: Protocol) -> Hop { + Hop { + protocol: Some(protocol), + translated: false, + client_identity: false, + harness_to_deepseek: false, + harness_elsewhere: false, + } + } + + /// Claude Code 实际会带的头 + const CLAUDE_CODE: &[&str] = &[ + "user-agent", + "x-app", + "x-stainless-lang", + "x-stainless-os", + "x-stainless-runtime-version", + "x-stainless-timeout", + "x-claude-code-session-id", + "anthropic-dangerous-direct-browser-access", + ]; + + /// 浏览器和身份类的头,任何上游都不该从客户端那里拿到 + const NEVER: &[&str] = &[ + "cookie", + "origin", + "referer", + "proxy-authorization", + "authorization", + "x-api-key", + "x-goog-api-key", + "host", + "x-oai-attestation", + "x-gemini-api-privileged-user-id", + "x-goog-api-client", + "x-thinkwatch-client", + ]; + + #[test] + fn an_anthropic_upstream_gets_the_anthropic_headers_and_nothing_about_the_client() { + let h = hop(Protocol::Anthropic); + assert!(takes_from_client(&h, "anthropic-version")); + assert!(takes_from_client(&h, "Anthropic-Beta")); + assert!(takes_from_client(&h, "content-type")); + for n in CLAUDE_CODE.iter().chain(NEVER) { + assert!(!takes_from_client(&h, n), "{n}"); + } + } + + #[test] + fn an_openai_upstream_gets_only_the_idempotency_key_and_the_request_id() { + for p in [Protocol::OpenaiChat, Protocol::OpenaiResponses] { + let h = hop(p); + assert!(takes_from_client(&h, "Idempotency-Key")); + assert!(takes_from_client(&h, "x-client-request-id")); + // 组织和项目属于这家的密钥,写在上游配置里 + assert!(!takes_from_client(&h, "openai-organization")); + assert!(!takes_from_client(&h, "openai-project")); + assert!(!takes_from_client(&h, "anthropic-beta")); + for n in CLAUDE_CODE.iter().chain(NEVER) { + assert!(!takes_from_client(&h, n), "{n}"); + } + } + } + + #[test] + fn a_gemini_upstream_gets_nothing_from_the_client_but_the_body_type() { + let h = hop(Protocol::Gemini); + assert!(takes_from_client(&h, "content-type")); + for n in [ + "x-goog-user-project", + "x-server-timeout", + "x-goog-api-client", + ] { + assert!(!takes_from_client(&h, n), "{n}"); + } + } + + #[test] + fn the_codex_backend_gets_its_protocol_headers_and_not_the_official_app() { + let h = hop(Protocol::Chatgpt); + for n in CODEX_BACKEND { + assert!(takes_from_client(&h, n), "{n}"); + } + for n in [ + "originator", + "version", + "session_id", + "x-codex-installation-id", + "x-codex-turn-metadata", + "x-codex-window-id", + // 描述请求体的头也由网关填:Codex 后端只认确切的 `application/json` + "content-type", + "accept", + ] + .iter() + .chain(CLAUDE_CODE) + .chain(NEVER) + { + assert!(!takes_from_client(&h, n), "{n}"); + } + } + + #[test] + fn a_translated_body_is_described_by_the_gateway() { + let h = Hop { + translated: true, + ..hop(Protocol::OpenaiChat) + }; + assert!(!takes_from_client(&h, "content-type")); + assert!(!takes_from_client(&h, "accept")); + let set = gateway_headers(&h, &HeaderMap::new()); + assert!(set.contains(&("content-type".into(), "application/json".into()))); + } + + #[test] + fn the_client_identity_goes_only_where_it_was_asked_for() { + let mut client = HeaderMap::new(); + client.insert( + "user-agent", + "claude-cli/2.1.1 (external, cli)".parse().unwrap(), + ); + client.insert("content-type", "application/json".parse().unwrap()); + + let plain = hop(Protocol::Anthropic); + let ua = |set: Vec<(String, String)>| { + set.into_iter() + .find(|(k, _)| k == "user-agent") + .map(|(_, v)| v) + .unwrap() + }; + assert!(ua(gateway_headers(&plain, &client)).starts_with("thinkwatch/")); + assert!(!takes_from_client(&plain, "x-app")); + + let forwarding = Hop { + client_identity: true, + ..plain + }; + assert_eq!( + ua(gateway_headers(&forwarding, &client)), + "claude-cli/2.1.1 (external, cli)" + ); + for n in [ + "x-app", + "originator", + "version", + "session_id", + "x-codex-window-id", + ] { + assert!(takes_from_client(&forwarding, n), "{n}"); + } + // 身份是客户端的,不是浏览器的,也不是凭据 + for n in NEVER.iter().filter(|n| !n.starts_with("x-codex-")) { + assert!(!takes_from_client(&forwarding, n), "{n}"); + } + // 客户端没报 User-Agent 就还是 ThinkWatch 的 + assert!(ua(gateway_headers(&forwarding, &HeaderMap::new())).starts_with("thinkwatch/")); + } + + #[test] + fn deepseek_harness_headers_go_only_to_deepseek() { + let to_deepseek = Hop { + harness_to_deepseek: true, + ..hop(Protocol::Anthropic) + }; + assert!(takes_from_client( + &to_deepseek, + "x-deepseek-harness-session" + )); + let elsewhere = Hop { + harness_elsewhere: true, + ..hop(Protocol::Anthropic) + }; + assert!(!takes_from_client(&elsewhere, "x-deepseek-harness-session")); + // 发给别家的 `anthropic-beta` 由发送处去掉工具增删那一项后另填 + assert!(!takes_from_client(&elsewhere, "anthropic-beta")); + assert!(takes_from_client(&elsewhere, "anthropic-version")); + } + + #[test] + fn an_unknown_upstream_is_treated_as_the_client_format() { + assert_eq!( + Hop::protocol_for(None, Some(Dialect::Anthropic)), + Some(Protocol::Anthropic) + ); + assert_eq!( + Hop::protocol_for(Some(Protocol::Gemini), Some(Dialect::Anthropic)), + Some(Protocol::Gemini) + ); + assert_eq!(Hop::protocol_for(None, Some(Dialect::Bedrock)), None); + } + + #[test] + fn claude_code_user_id_is_not_sent() { + let body = Bytes::from( + serde_json::json!({ + "model": "claude-sonnet-5", + "metadata": {"user_id": "user_abc_account_123_session_456"}, + "messages": [{"role": "user", "content": "hi"}] + }) + .to_string(), + ); + let out = strip_body_identity(Dialect::Anthropic, &body).unwrap(); + let v: Value = serde_json::from_slice(&out).unwrap(); + assert!(v.get("metadata").is_none(), "{v}"); + assert_eq!(v["messages"][0]["content"], "hi"); + + // 别的 metadata 字段留着 + let body = Bytes::from(r#"{"metadata":{"user_id":"u","note":"x"},"messages":[]}"#); + let v: Value = + serde_json::from_slice(&strip_body_identity(Dialect::Anthropic, &body).unwrap()) + .unwrap(); + assert_eq!(v["metadata"], serde_json::json!({"note": "x"})); + + // 没有身份字段:一个字节都不动 + let plain = Bytes::from(r#"{"messages":[{"role":"user","content":"hi"}]}"#); + assert_eq!(strip_body_identity(Dialect::Anthropic, &plain), None); + // 消息里提到 user_id 不算 + let mention = Bytes::from(r#"{"messages":[{"role":"user","content":"\"user_id\""}]}"#); + assert_eq!(strip_body_identity(Dialect::Anthropic, &mention), None); + } + + #[test] + fn codex_installation_id_is_not_sent_but_the_session_is() { + let body = Bytes::from( + serde_json::json!({ + "model": "gpt-5.5", + "client_metadata": { + "x-codex-installation-id": "inst-1", + "x-codex-turn-metadata": "{}", + "session_id": "conv-1" + } + }) + .to_string(), + ); + let v: Value = + serde_json::from_slice(&strip_body_identity(Dialect::Responses, &body).unwrap()) + .unwrap(); + assert_eq!( + v["client_metadata"], + serde_json::json!({"session_id": "conv-1"}) + ); + assert_eq!(strip_body_identity(Dialect::Chat, &body), None); + } +} diff --git a/crates/tw-gateway/src/forward.rs b/crates/tw-gateway/src/forward.rs index 63fa8227..35fe7f23 100644 --- a/crates/tw-gateway/src/forward.rs +++ b/crates/tw-gateway/src/forward.rs @@ -12,28 +12,6 @@ pub use tw_dialect::url::upstream_url; use crate::error::GatewayError; use tw_types::msg; -/// 这些头是「我们和客户端之间」的,不该转给上游。 -/// -/// `x-stainless-timeout` 那条不显然:客户端 SDK 自带的超时头传到上游, -/// 会让上游按客户端的超时提前断流,表现为莫名其妙的截断。 -pub const STRIP: &[&str] = &[ - "host", - "authorization", - "x-api-key", - "x-goog-api-key", - "content-length", - "connection", - "accept-encoding", - "x-stainless-timeout", -]; - -pub fn should_strip(name: &HeaderName) -> bool { - let n = name.as_str(); - // `x-thinkwatch-*` 是客户端写给网关的(接管 Codex 时写进去的 - // `X-ThinkWatch-Client`),上游不该看见 - STRIP.contains(&n) || n.starts_with("x-thinkwatch-") -} - /// 把这家上游的请求头放上去。**凭据就在里面**(见 `tw_config::credential`)。 /// /// **WS 升级那条路也走同一份** `Provider::outbound_headers`:各写一份的话, @@ -57,33 +35,6 @@ pub fn overridden(headers: &[(String, String)], name: &str) -> bool { headers.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) } -/// 把客户端的请求头搬到上游请求上,剔掉不该走的那些。 -pub fn forward_headers( - builder: reqwest::RequestBuilder, - incoming: &HeaderMap, -) -> reqwest::RequestBuilder { - forward_headers_filtered(builder, incoming, |_| true) -} - -/// 同上,但再过一道调用方给的筛子。 -/// -/// 方言互转要用它(M6+):翻译到另一边之后,方言专属的头全是 -/// 噪音,而有些 OpenAI 兼容实现会因为不认识的头直接 400。 -pub fn forward_headers_filtered( - builder: reqwest::RequestBuilder, - incoming: &HeaderMap, - keep: impl Fn(&str) -> bool, -) -> reqwest::RequestBuilder { - let mut b = builder; - for (name, value) in incoming.iter() { - if should_strip(name) || !keep(name.as_str()) { - continue; - } - b = b.header(name.clone(), value.clone()); - } - b -} - /// 上游响应里也有不该原样回给客户端的头。 pub fn response_headers(upstream: &reqwest::header::HeaderMap) -> HeaderMap { let mut out = HeaderMap::new(); @@ -266,13 +217,6 @@ pub fn check_body_size(body: &Bytes, max: usize) -> Result<(), GatewayError> { mod tests { use super::*; - #[test] - fn headers_meant_for_the_gateway_never_reach_the_upstream() { - assert!(should_strip(&HeaderName::from_static( - "x-thinkwatch-client" - ))); - } - #[test] fn a_configured_header_replaces_the_one_the_client_sent() { let configured = vec![("Anthropic-Version".to_string(), "2023-06-01".to_string())]; @@ -280,30 +224,6 @@ mod tests { assert!(!overridden(&configured, "anthropic-beta")); } - #[test] - fn our_own_auth_headers_never_reach_the_upstream() { - // 客户端带的是**我们的**网关密钥。原样转出去等于把它送给中转站。 - for h in ["authorization", "x-api-key", "x-goog-api-key"] { - assert!(should_strip(&HeaderName::from_static(h)), "{h} 应该被剔掉"); - } - } - - #[test] - fn client_sdk_timeout_headers_are_stripped() { - // 传给上游会让它按客户端的超时提前断流,表现为莫名其妙的截断。 - assert!(should_strip(&HeaderName::from_static( - "x-stainless-timeout" - ))); - } - - #[test] - fn dialect_headers_are_kept() { - // anthropic-version / anthropic-beta 是上游要认的,剔掉就废了。 - for h in ["anthropic-version", "anthropic-beta", "content-type"] { - assert!(!should_strip(&HeaderName::from_static(h)), "{h} 不该被剔掉"); - } - } - #[test] fn response_drops_length_and_framing_headers() { let mut up = reqwest::header::HeaderMap::new(); diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 4457cd9a..628e30b1 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -11,6 +11,7 @@ pub mod bodies; pub mod chatgpt; pub mod client_api; pub mod clientprobe; +pub mod egress; pub mod ending; pub mod error; pub mod fixture; diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index 58bc7975..08985995 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -36,9 +36,8 @@ struct Outbound { target: Option, /// ChatGPT 账号(Codex 后端):只收流式、不认输出上限、身份头由网关填 chatgpt: bool, - /// DeepSeek Harness 的请求发给 DeepSeek 官方以外的上游:它自己的请求头不转发 - /// (见 [`tw_dialect::harness`]) - harness_elsewhere: bool, + /// 这一跳发哪些请求头(见 [`crate::egress`]) + hop: crate::egress::Hop, /// 回程要用的转换会话:转换过的,或者直通到 Codex 后端、客户端却要整包时 /// 收齐流要用的 session: Option, @@ -392,8 +391,13 @@ fn prepare( let (shaped, more) = crate::chatgpt::shape_passthrough(&out); dropped.extend(more); shaped - } else { + } else if provider.forward_client_identity { out + } else { + // 客户端自动填的身份字段不发(见 `egress` 模块)。**不算丢弃的字段** + client_dialect + .and_then(|d| crate::egress::strip_body_identity(d, &out)) + .unwrap_or(out) }; if let Some(d) = client_dialect.filter(|_| !dropped.is_empty()) { let same = crate::wire::dialect(d); @@ -495,13 +499,20 @@ fn prepare( path = "/responses".to_string(); query = None; } + let hop = crate::egress::Hop { + protocol: crate::egress::Hop::protocol_for(provider.effective_protocol(), client_dialect), + translated: target.is_some(), + client_identity: provider.forward_client_identity && !chatgpt, + harness_to_deepseek: harness && to_deepseek, + harness_elsewhere: harness && !to_deepseek, + }; Ok(Outbound { body, path, query, target, chatgpt, - harness_elsewhere: harness && !to_deepseek, + hop, session, }) } @@ -518,16 +529,13 @@ async fn send( ) -> Result { let url = forward::upstream_url(&provider.base_url, &out.path, out.query.as_deref()); let method = reqwest::Method::from_bytes(b"POST").expect("POST is a valid method"); - let client_dialect = req.api.map(|a| a.dialect()); - let (target, chatgpt, headers) = (out.target, out.chatgpt, &req.headers); + let (target, chatgpt, hop, headers) = (out.target, out.chatgpt, out.hop, &req.headers); let required = target .map(crate::translate::required_headers) .unwrap_or_default(); - // DeepSeek Harness 发给别家:它自己的头不转发;直通时 `anthropic-beta` 去掉对话中途 - // 增删工具那一项(那些块已经去掉了),剩下的照发 - let harness = out.harness_elsewhere; - // 分几行发的也要都看:下面一律不转发原来的,只转发这一份 - let beta = (harness && target.is_none()) + // DeepSeek Harness 发给别家:直通时 `anthropic-beta` 去掉对话中途增删工具那一项(那些块 + // 已经去掉了),剩下的照发。分几行发的也要都看:客户端原来的不发,只发这一份 + let beta = (hop.harness_elsewhere && target.is_none()) .then(|| { headers .get_all("anthropic-beta") @@ -537,32 +545,44 @@ async fn send( .join(",") }) .and_then(|v| tw_dialect::harness::anthropic_beta(&v)); + // Anthropic 格式原样直通、客户端没写 `anthropic-version`:Anthropic 要这个头,补上默认的 + let version = (hop.protocol == Some(tw_config::Protocol::Anthropic) + && target.is_none() + && !headers.contains_key("anthropic-version")) + .then_some(("anthropic-version", tw_dialect::official::ANTHROPIC_VERSION)); + let gateway = crate::egress::gateway_headers(&hop, headers); + // Codex 后端收 zstd 压缩的请求体(见 `chatgpt::compress`) + let (body, encoding) = match chatgpt.then(|| crate::chatgpt::compress(&body)).flatten() { + Some(z) => (z, Some("zstd")), + None => (body, None), + }; let build = |upstream_headers: &[(String, String)]| { let mut req = http.request(method.clone(), &url); - req = forward::forward_headers_filtered(req, headers, |n| { - let own = match (target, client_dialect) { - (Some(_), Some(c)) => !crate::translate::keeps_header(c, n), - _ => false, - }; - // 请求来自谁由网关如实填写:客户端报的来源(比如 Codex CLI 的 originator) - // 不转发,请求经过的是 ThinkWatch - let identity = chatgpt && !crate::chatgpt::keeps_client_header(n); - let dsh = harness - && (tw_dialect::harness::own_header(n) || n.eq_ignore_ascii_case("anthropic-beta")); - !own && !identity - && !dsh + // 从客户端取的:只有这种上游的协议要的那几个(白名单,见 `egress` 模块) + for (name, value) in headers { + let n = name.as_str(); + if crate::egress::takes_from_client(&hop, n) && !required.iter().any(|(k, _)| k.eq_ignore_ascii_case(n)) && !forward::overridden(upstream_headers, n) - }); + { + req = req.header(name.clone(), value.clone()); + } + } if let Some(b) = &beta && !forward::overridden(upstream_headers, "anthropic-beta") { req = req.header("anthropic-beta", b.as_str()); } // 目标格式必需的头(Anthropic 的 anthropic-version)。上游配置里写了同名头时以配置为准 - for (k, v) in required { + for (k, v) in required.iter().copied().chain(version) { if !forward::overridden(upstream_headers, k) { - req = req.header(*k, *v); + req = req.header(k, v); + } + } + // 网关自己填的:User-Agent,和转换过的请求体的类型。上游配置里写了同名头时以配置为准 + for (k, v) in &gateway { + if !forward::overridden(upstream_headers, k) { + req = req.header(k.as_str(), v.as_str()); } } req = forward::apply_headers(req, upstream_headers); @@ -572,6 +592,9 @@ async fn send( &crate::chatgpt::identity_headers(headers, upstream_headers), ); } + if let Some(e) = encoding { + req = req.header(http::header::CONTENT_ENCODING, e); + } req }; let sent_at = std::time::Instant::now(); diff --git a/crates/tw-gateway/src/translate.rs b/crates/tw-gateway/src/translate.rs index af4f7af8..8832c710 100644 --- a/crates/tw-gateway/src/translate.rs +++ b/crates/tw-gateway/src/translate.rs @@ -40,33 +40,6 @@ pub fn plan( (target != api.dialect()).then_some(target) } -/// 转换时,客户端发来的这个请求头还发不发给上游。 -pub fn keeps_header(client: Dialect, name: &str) -> bool { - let name = name.to_ascii_lowercase(); - let own: &[&str] = match client { - Dialect::Anthropic => &[ - "anthropic-version", - "anthropic-beta", - "anthropic-dangerous-direct-browser-access", - ], - // Codex 带的 originator / session_id / version 说的是它和 OpenAI 之间的事 - Dialect::Chat | Dialect::Responses => &[ - "openai-beta", - "openai-organization", - "openai-project", - "chatgpt-account-id", - "originator", - "session_id", - "conversation_id", - "version", - ], - // SigV4 签的是这一次请求的内容,转发给别的上游只会是一个签错的头 - Dialect::Bedrock => &["x-amzn-bedrock-accept", "x-amzn-bedrock-save"], - Dialect::Gemini => &["x-goog-api-client", "x-goog-user-project"], - }; - !own.contains(&name.as_str()) -} - /// 转成这种格式时必须带的请求头(上游配置里写了同名头时以配置为准)。 pub fn required_headers(target: Dialect) -> &'static [(&'static str, &'static str)] { match target { @@ -159,11 +132,7 @@ mod tests { } #[test] - fn a_clients_own_headers_stay_behind_and_anthropic_gets_its_version() { - assert!(!keeps_header(Dialect::Anthropic, "Anthropic-Beta")); - assert!(keeps_header(Dialect::Anthropic, "user-agent")); - assert!(!keeps_header(Dialect::Responses, "originator")); - assert!(!keeps_header(Dialect::Gemini, "x-goog-api-client")); + fn anthropic_gets_its_version_when_a_request_is_translated_to_it() { assert_eq!( required_headers(Dialect::Anthropic), [("anthropic-version", "2023-06-01")] diff --git a/crates/tw-gateway/tests/chatgpt.rs b/crates/tw-gateway/tests/chatgpt.rs index d5ccf6b7..ed12ddb7 100644 --- a/crates/tw-gateway/tests/chatgpt.rs +++ b/crates/tw-gateway/tests/chatgpt.rs @@ -3,7 +3,9 @@ //! 假的 token 端点和假的 Codex 后端,按 2026-09-18 实测到的样子回:流式响应**不带 //! Content-Type**、额度在 `x-codex-*` 头里、token 端点收 JSON。验的是网关把这些接缝接对了: //! -//! - 身份是 ThinkWatch 自己的,客户端报的来源不转发 +//! - 身份是 ThinkWatch 自己的:客户端的请求头只转 Codex 协议要的那几个,官方客户端的身份 +//! 和 Claude Code 这类客户端自己的头都不发 +//! - 请求体用 zstd 压缩(Codex 直连时就这么发) //! - 请求改成 Codex 后端接受的样子(只收流式、不认输出上限、路径是 `/responses`) //! - 没有 Content-Type 的流照样按流处理;客户端要整包时由网关收齐 //! - 401 换一次 token 重发;并发请求只刷新一次;refresh token 作废只报一次 @@ -120,7 +122,7 @@ async fn start_backend(b: Arc) -> String { State(b): State>, OriginalUri(uri): OriginalUri, headers: HeaderMap, - body: String, + body: axum::body::Bytes, ) -> axum::response::Response { b.calls.fetch_add(1, Ordering::SeqCst); let auth = headers @@ -128,7 +130,14 @@ async fn start_backend(b: Arc) -> String { .and_then(|v| v.to_str().ok()) .unwrap_or("") .to_string(); - let parsed = serde_json::from_str(&body).unwrap_or(Value::Null); + // 网关发来的请求体是 zstd 压缩的,和 Codex 直连时一样 + let zstd = headers.get("content-encoding").is_some_and(|v| v == "zstd"); + let body = if zstd { + zstd::stream::decode_all(&body[..]).expect("a zstd body") + } else { + body.to_vec() + }; + let parsed = serde_json::from_slice(&body).unwrap_or(Value::Null); b.seen .lock() .unwrap() @@ -318,6 +327,10 @@ async fn a_codex_cli_request_reaches_the_backend_as_thinkwatch() { ("x-codex-installation-id", "inst-1"), ("x-codex-turn-metadata", "{\"installation_id\":\"inst-1\"}"), ("x-codex-window-id", "w-1"), + ("x-codex-turn-state", "ts-1"), + ("x-openai-internal-codex-responses-lite", "true"), + // 客户端以后新加的头 + ("x-codex-something-new", "1"), ], codex_request(true), ) @@ -357,10 +370,18 @@ async fn a_codex_cli_request_reaches_the_backend_as_thinkwatch() { "x-oai-attestation", "x-codex-installation-id", "x-codex-turn-metadata", + "x-codex-window-id", + "x-codex-something-new", ] { - assert_eq!(h(k), None, "官方客户端的身份不转发:{k}"); + assert_eq!(h(k), None, "只转 Codex 协议要的头:{k}"); } - assert_eq!(h("x-codex-window-id").as_deref(), Some("w-1")); + assert_eq!(h("x-codex-turn-state").as_deref(), Some("ts-1")); + assert_eq!( + h("x-openai-internal-codex-responses-lite").as_deref(), + Some("true") + ); + assert_eq!(h("content-encoding").as_deref(), Some("zstd")); + assert_eq!(h("content-type").as_deref(), Some("application/json")); assert_eq!(h("chatgpt-account-id").as_deref(), Some("acc-123")); assert_eq!(h("authorization").as_deref(), Some("Bearer at-1")); assert_eq!(h("accept").as_deref(), Some("text/event-stream")); @@ -406,6 +427,64 @@ async fn a_codex_cli_request_reaches_the_backend_as_thinkwatch() { assert_eq!(windows[0].used_percent, 21.0); } +#[tokio::test] +async fn claude_code_reaches_the_codex_backend_without_its_own_headers() { + let tokens = Arc::new(TokenServer::default()); + let token_url = start_token_server(tokens.clone()).await; + let backend = Arc::new(Backend::default()); + let base = start_backend(backend.clone()).await; + let (gw, _, _rx) = start_gateway(chatgpt_provider(&base, &token_url)).await; + + let (status, _, body) = post_json( + gw, + "/v1/messages", + &[ + ("x-api-key", "tw-k"), + ("user-agent", "claude-cli/2.1.1 (external, cli)"), + ("x-app", "cli"), + ("anthropic-version", "2023-06-01"), + ("anthropic-beta", "claude-code-20250219"), + ("x-stainless-lang", "js"), + ("x-stainless-os", "MacOS"), + ("x-stainless-runtime-version", "v22.18.0"), + ("x-claude-code-session-id", "sess-1"), + ("cookie", "a=b"), + ("origin", "http://localhost:3000"), + ], + json!({ + "model": "gpt-5.5", + "max_tokens": 64, + "stream": true, + "metadata": {"user_id": "user_abc_account_123_session_456"}, + "messages": [{"role": "user", "content": "hi"}] + }), + ) + .await; + assert_eq!(status, 200, "{body}"); + + let seen = backend.seen.lock().unwrap().clone(); + let (_, headers, sent) = &seen[0]; + let mut names: Vec<&str> = headers.keys().map(|k| k.as_str()).collect(); + names.sort_unstable(); + // 发出去的只有网关填的、上游配置里的;Claude Code 的头一个都没有 + assert_eq!( + names, + [ + "accept", + "authorization", + "chatgpt-account-id", + "content-encoding", + "content-length", + "content-type", + "host", + "originator", + "session-id", + "user-agent", + ] + ); + assert!(sent.get("metadata").is_none(), "{sent}"); +} + #[tokio::test] async fn a_client_that_wants_a_whole_answer_gets_one_from_the_stream_only_backend() { let tokens = Arc::new(TokenServer::default()); diff --git a/crates/tw-gateway/tests/harness.rs b/crates/tw-gateway/tests/harness.rs index c29bf815..e7117305 100644 --- a/crates/tw-gateway/tests/harness.rs +++ b/crates/tw-gateway/tests/harness.rs @@ -306,12 +306,19 @@ async fn messages_to_another_anthropic_upstream_are_cleaned_in_place() { let s = generation(&log); assert_eq!(s.uri, "/v1/messages"); assert_clean(&s); - // 别的 beta 照发,User-Agent 照发 + // 别的 beta 照发。User-Agent 是 ThinkWatch 的:客户端是谁不外传(见 `egress`) assert_eq!( s.headers.get("anthropic-beta").unwrap(), "files-api-2025-04-14" ); - assert_eq!(s.headers.get("user-agent").unwrap(), UA); + assert!( + s.headers + .get("user-agent") + .unwrap() + .to_str() + .unwrap() + .starts_with("thinkwatch/") + ); let v: Value = serde_json::from_slice(&s.body).unwrap(); assert_eq!( v["system"], diff --git a/crates/tw-gateway/tests/headers_and_paths.rs b/crates/tw-gateway/tests/headers_and_paths.rs index ded9f9df..764876bd 100644 --- a/crates/tw-gateway/tests/headers_and_paths.rs +++ b/crates/tw-gateway/tests/headers_and_paths.rs @@ -7,6 +7,8 @@ //! - Gemini 的 `POST /v1beta/models/{model}:generateContent` 被只认 GET 的路由拒成 405 //! - 查询串里的 `key=`(网关密钥)被原样拼到上游地址上 //! - 只能填一把密钥,要求自定义鉴权头的中转站接不进来 +//! - 客户端的请求头几乎原样转给上游:Claude Code 的 `x-app`、`x-stainless-*`、会话 ID, +//! 浏览器的 Cookie,全都到了上游手里。现在每种上游只收它的协议要的(见 `egress`) use std::net::SocketAddr; use std::sync::{Arc, Mutex}; @@ -22,6 +24,7 @@ struct Seen { method: Option, uri: String, headers: HeaderMap, + body: Vec, } async fn start_upstream() -> (SocketAddr, Arc>) { @@ -31,11 +34,13 @@ async fn start_upstream() -> (SocketAddr, Arc>) { |State(s): State>>, method: Method, OriginalUri(uri): OriginalUri, - headers: HeaderMap| async move { + headers: HeaderMap, + body: axum::body::Bytes| async move { let mut g = s.lock().unwrap(); g.method = Some(method); g.uri = uri.to_string(); g.headers = headers; + g.body = body.to_vec(); axum::response::Response::builder() .header("content-type", "application/json") .body(axum::body::Body::from(r#"{"ok":true}"#)) @@ -351,3 +356,241 @@ async fn the_public_data_client_still_follows_a_redirect() { assert_eq!(r.status(), 200); assert_eq!(seen.lock().unwrap().uri, "/moved"); } + +// ───────────────────────────────────────────── 每种上游收到的请求头 + +/// Claude Code 实际会带的请求头,外加浏览器类客户端会带的 +const CLAUDE_CODE: &[(&str, &str)] = &[ + ("x-api-key", "tw-testkey"), + ("user-agent", "claude-cli/2.1.1 (external, cli)"), + ("x-app", "cli"), + ("anthropic-version", "2023-06-01"), + ( + "anthropic-beta", + "claude-code-20250219,interleaved-thinking-2025-05-14", + ), + ("anthropic-dangerous-direct-browser-access", "true"), + ("x-stainless-lang", "js"), + ("x-stainless-os", "MacOS"), + ("x-stainless-runtime-version", "v22.18.0"), + ("x-stainless-timeout", "600"), + ("x-claude-code-session-id", "sess-1"), + ("accept", "application/json"), + ("content-type", "application/json"), + ("cookie", "a=b"), + ("origin", "http://localhost:3000"), +]; + +const CLAUDE_CODE_BODY: &str = r#"{"model":"claude-sonnet-4-5","max_tokens":16,"metadata":{"user_id":"user_abc_account_123_session_456"},"messages":[{"role":"user","content":"hi"}]}"#; + +async fn post(gw: SocketAddr, path: &str, headers: &[(&str, &str)], body: &str) -> u16 { + let mut r = reqwest::Client::new().post(format!("http://{gw}{path}")); + for (k, v) in headers { + r = r.header(*k, *v); + } + let resp = r.body(body.to_string()).send().await.unwrap(); + let status = resp.status().as_u16(); + let text = resp.text().await.unwrap(); + assert_eq!(status, 200, "{text}"); + status +} + +fn names(h: &HeaderMap) -> Vec { + let mut v: Vec = h.keys().map(|k| k.to_string()).collect(); + v.sort(); + v +} + +#[tokio::test] +async fn an_anthropic_upstream_gets_the_request_and_nothing_about_the_client() { + let (up, seen) = start_upstream().await; + let gw = start_gateway(anthropic(up)).await; + post(gw, "/v1/messages", CLAUDE_CODE, CLAUDE_CODE_BODY).await; + + let g = seen.lock().unwrap(); + assert_eq!( + names(&g.headers), + [ + "accept", + "anthropic-beta", + "anthropic-version", + "content-length", + "content-type", + "host", + "user-agent", + "x-api-key", + ] + ); + assert!( + g.headers + .get("user-agent") + .unwrap() + .to_str() + .unwrap() + .starts_with("thinkwatch/") + ); + assert_eq!(g.headers.get("x-api-key").unwrap(), "sk-upstream"); + assert_eq!( + g.headers.get("anthropic-beta").unwrap(), + "claude-code-20250219,interleaved-thinking-2025-05-14" + ); + // 请求体原样,只少了 Claude Code 自动填的身份 + let v: serde_json::Value = serde_json::from_slice(&g.body).unwrap(); + assert!(v.get("metadata").is_none(), "{v}"); + assert_eq!(v["messages"][0]["content"], "hi"); +} + +#[tokio::test] +async fn an_upstream_that_asks_for_it_gets_the_clients_own_identity() { + let (up, seen) = start_upstream().await; + let mut p = anthropic(up); + p.forward_client_identity = true; + let gw = start_gateway(p).await; + post(gw, "/v1/messages", CLAUDE_CODE, CLAUDE_CODE_BODY).await; + + let g = seen.lock().unwrap(); + assert_eq!( + g.headers.get("user-agent").unwrap(), + "claude-cli/2.1.1 (external, cli)" + ); + assert_eq!(g.headers.get("x-app").unwrap(), "cli"); + let v: serde_json::Value = serde_json::from_slice(&g.body).unwrap(); + assert_eq!( + v["metadata"]["user_id"], "user_abc_account_123_session_456", + "{v}" + ); + // 转发的是客户端的身份,不是它的 SDK 细节、浏览器状态和凭据 + for n in [ + "x-stainless-lang", + "x-stainless-timeout", + "x-claude-code-session-id", + "cookie", + "origin", + "anthropic-dangerous-direct-browser-access", + "authorization", + ] { + assert!(g.headers.get(n).is_none(), "{n}"); + } + assert_eq!(g.headers.get("x-api-key").unwrap(), "sk-upstream"); +} + +#[tokio::test] +async fn an_anthropic_upstream_gets_a_version_even_when_the_client_sent_none() { + let (up, seen) = start_upstream().await; + let gw = start_gateway(anthropic(up)).await; + post( + gw, + "/v1/messages", + &[ + ("x-api-key", "tw-testkey"), + ("content-type", "application/json"), + ], + BODY, + ) + .await; + let g = seen.lock().unwrap(); + let versions: Vec<_> = g.headers.get_all("anthropic-version").iter().collect(); + assert_eq!(versions, ["2023-06-01"]); +} + +#[tokio::test] +async fn an_openai_upstream_takes_the_organization_from_its_own_configuration() { + let (up, seen) = start_upstream().await; + let p = Provider { + name: "openai".into(), + base_url: format!("http://{up}/v1"), + key: Some("sk-upstream".into()), + protocol: Some(Protocol::OpenaiChat), + models: vec!["gpt-5.5".into()], + headers: Headers::new(vec![Header { + name: "OpenAI-Organization".into(), + value: Secret::new("org-upstream"), + }]), + ..Default::default() + }; + let gw = start_gateway(p).await; + post( + gw, + "/v1/chat/completions", + &[ + ("authorization", "Bearer tw-testkey"), + ("content-type", "application/json"), + ("user-agent", "OpenAI/Python 1.99.0"), + ("x-stainless-lang", "python"), + ("openai-organization", "org-client"), + ("openai-project", "proj-client"), + ("idempotency-key", "idem-1"), + ("x-client-request-id", "req-1"), + ], + r#"{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}]}"#, + ) + .await; + let g = seen.lock().unwrap(); + assert_eq!( + names(&g.headers), + [ + "accept", + "authorization", + "content-length", + "content-type", + "host", + "idempotency-key", + "openai-organization", + "user-agent", + "x-client-request-id", + ] + ); + // 客户端没写 accept:这是 HTTP 库自己的默认值,不是客户端的 + assert_eq!(g.headers.get("accept").unwrap(), "*/*"); + assert_eq!( + g.headers.get("authorization").unwrap(), + "Bearer sk-upstream" + ); + let orgs: Vec<_> = g.headers.get_all("openai-organization").iter().collect(); + assert_eq!(orgs, ["org-upstream"], "组织属于这家的密钥,不取客户端的"); +} + +#[tokio::test] +async fn a_gemini_upstream_gets_nothing_from_the_client_but_the_body_type() { + let (up, seen) = start_upstream().await; + let p = Provider { + name: "gemini".into(), + base_url: format!("http://{up}"), + key: Some("g-upstream".into()), + protocol: Some(Protocol::Gemini), + models: vec!["gemini-3-pro-preview".into()], + ..Default::default() + }; + let gw = start_gateway(p).await; + post( + gw, + "/v1beta/models/gemini-3-pro-preview:generateContent", + &[ + ("x-goog-api-key", "tw-testkey"), + ("content-type", "application/json"), + ("user-agent", "GeminiCLI/0.40.0 (darwin; arm64)"), + ( + "x-goog-api-client", + "google-genai-sdk/1.30.0 gl-node/v22.18.0", + ), + ("x-gemini-api-privileged-user-id", "install-1"), + ("x-server-timeout", "600"), + ], + r#"{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}"#, + ) + .await; + let g = seen.lock().unwrap(); + assert_eq!( + names(&g.headers), + [ + "accept", + "content-length", + "content-type", + "host", + "user-agent", + "x-goog-api-key", + ] + ); + assert_eq!(g.headers.get("accept").unwrap(), "*/*"); + assert_eq!(g.headers.get("x-goog-api-key").unwrap(), "g-upstream"); +} diff --git a/docs/config.md b/docs/config.md index aa8cf718..ffa84583 100644 --- a/docs/config.md +++ b/docs/config.md @@ -314,6 +314,7 @@ Upstreams: the APIs requests are forwarded to. | `headers` | map of header name → value | `{}` | Additional request headers, in the order written; values may use `${VAR}`, and `{{access_token}}` where `oauth` is set. At most 32. Headers HTTP or the gateway manages (`host`, `content-length`, `connection`, …) cannot be set. | | `oauth` | object, [`providers[].oauth`](#cfg-providers-oauth) | — | OAuth credential: an access token obtained from a refresh token. Instead of `key`. | | `protocol` | `anthropic` \| `openai-chat` \| `openai-responses` \| `gemini` \| `chatgpt` | — | API format of the upstream. Unset: recognized from `base_url` for the official endpoints, otherwise treated as `anthropic`. | +| `forward_client_identity` | bool | `false` | Also send the client's own identity: its `User-Agent`, identity headers such as `x-app` and `originator`, and identity fields in the request body such as `metadata.user_id`. Values are the client's, never made up. Off: requests carry ThinkWatch's `User-Agent` and no client identity. For upstreams that admit only certain clients (Kimi For Coding, Bailian Coding Plan, relays restricted to official clients). Not available for `chatgpt`. | | `proxy` | string | `direct` | `direct`; `system`, the proxy in the core process's `HTTPS_PROXY`, `HTTP_PROXY` or `ALL_PROXY` environment variables; or the name of an entry in `proxies`. | | `on_proxy_fail` | `fail` \| `direct` | `fail` | When the proxy cannot be reached: `fail` the request, or go `direct`. | | `models` | list of strings | `[]` | Models to assume when the upstream does not answer `/v1/models`. | @@ -350,6 +351,15 @@ providers: billing: free ``` +A request carries the request itself and the headers its upstream needs, +and nothing else from the client: the credential and the headers written in +`headers`; ThinkWatch's own `User-Agent`; and, from the client's request, only +the headers the upstream's protocol uses (`anthropic-*` for Anthropic, +`Idempotency-Key` and `X-Client-Request-Id` for OpenAI, none for Gemini). +Identity fields that clients fill in themselves, such as Claude Code's +`metadata.user_id`, are removed from the body. For an upstream that admits only +certain clients, turn on `forward_client_identity`. + A ChatGPT account upstream (`protocol: chatgpt`) takes only the credential the desktop app obtains by signing in; it cannot be written by hand. Claude and Google subscription sign-ins are not supported; use an API key. diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index e2a37f93..ce0898bb 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -238,6 +238,7 @@ clients: | `headers` | 请求头名 → 值的映射 | `{}` | 额外的请求头,按书写顺序发送;值可以用 `${VAR}`,配置了 `oauth` 时可以用 `{{access_token}}`。最多 32 个。HTTP 或网关管理的请求头(`host`、`content-length`、`connection` 等)不能设置。 | | `oauth` | 对象,见 [`providers[].oauth`](#cfg-providers-oauth) | — | OAuth 凭据:用 refresh token 换取 access token。与 `key` 二选一。 | | `protocol` | `anthropic` \| `openai-chat` \| `openai-responses` \| `gemini` \| `chatgpt` | — | 上游的接口格式。不写:官方地址按 `base_url` 识别,其余按 `anthropic` 处理。 | +| `forward_client_identity` | 布尔 | `false` | 同时发送客户端自己的身份:它的 `User-Agent`、`x-app` 和 `originator` 等身份请求头,以及请求体中的身份字段(如 `metadata.user_id`)。发送的都是客户端的原值,不做伪造。关闭时请求使用 ThinkWatch 的 `User-Agent`,不带客户端身份。用于只接受特定客户端的上游(Kimi For Coding、百炼 Coding Plan、只允许官方客户端的中转站)。`chatgpt` 不可用。 | | `proxy` | 字符串 | `direct` | `direct`;`system`,即 core 进程环境变量 `HTTPS_PROXY`、`HTTP_PROXY`、`ALL_PROXY` 中的代理;或 `proxies` 中某一项的名字。 | | `on_proxy_fail` | `fail` \| `direct` | `fail` | 代理不可用时:请求失败(`fail`),或改为直连(`direct`)。 | | `models` | 字符串列表 | `[]` | 上游不支持 `/v1/models` 时,按这份清单认定它提供的模型。 | @@ -270,6 +271,8 @@ providers: billing: free ``` +每个请求只带请求本身和上游需要的请求头,客户端的其他信息一律不发:凭据和 `headers` 中写的请求头、ThinkWatch 自己的 `User-Agent`,以及客户端请求中该上游协议使用的请求头(Anthropic 为 `anthropic-*`,OpenAI 为 `Idempotency-Key` 和 `X-Client-Request-Id`,Gemini 没有)。客户端自动填写的身份字段(如 Claude Code 的 `metadata.user_id`)从请求体中去掉。只接受特定客户端的上游,打开 `forward_client_identity`。 + ChatGPT 账号上游(`protocol: chatgpt`)只接受桌面应用登录得到的凭据,不能手写。不支持 Claude 和 Google 的订阅登录,请使用 API 密钥。 #### `providers[].oauth`