Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 以外的
Expand Down
1 change: 1 addition & 0 deletions crates/tw-api/msg-codes.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 12 additions & 1 deletion crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))]
Expand Down Expand Up @@ -1601,6 +1607,8 @@ pub struct ProviderView {
pub protocol: Option<Protocol>,
/// 协议是配置里写明的,还是按地址推断的
pub protocol_explicit: bool,
/// 把客户端自己的身份(User-Agent、身份请求头、请求体里的身份字段)如实发给这家
pub forward_client_identity: bool,
/// `direct` / `system` / 代理名
pub proxy: String,
/// `fail` / `direct`
Expand Down Expand Up @@ -2392,6 +2400,9 @@ pub struct ProviderInput {
/// 不给就按地址推断
#[serde(default, skip_serializing_if = "Option::is_none")]
pub protocol: Option<Protocol>,
/// 把客户端自己的身份如实发给这家。不给就是不发;ChatGPT 账号不能打开
#[serde(default)]
pub forward_client_identity: bool,
/// `direct` / `system` / 代理名
#[serde(default = "direct")]
pub proxy: String,
Expand Down
18 changes: 18 additions & 0 deletions crates/tw-config/src/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,8 @@ pub enum CredentialError {
#[error("{}", self.msg())]
ChatgptWithoutLogin,
#[error("{}", self.msg())]
ChatgptClientIdentity,
#[error("{}", self.msg())]
IdentityHeader(String),
#[error("{}", self.msg())]
TooManyHeaders,
Expand Down Expand Up @@ -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 \
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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]
Expand Down
10 changes: 10 additions & 0 deletions crates/tw-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -714,6 +715,15 @@ pub struct Provider {
/// 不写就从 base_url 猜(最小配置)。
#[serde(default, skip_serializing_if = "Option::is_none")]
pub protocol: Option<Protocol>,
/// 把客户端自己的身份如实发给这家:它的 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`**:显式优于隐式。默认跟随系统的
Expand Down
1 change: 1 addition & 0 deletions crates/tw-config/src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,7 @@ mod msg_codes {
ClaudeSubscription,
GoogleSubscription,
ChatgptWithoutLogin,
ChatgptClientIdentity,
IdentityHeader("h".into()),
TooManyHeaders,
BadHeaderName("h".into()),
Expand Down
9 changes: 9 additions & 0 deletions crates/tw-config/tests/manual/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,15 @@ pub fn sections() -> Vec<Section> {
"上游的接口格式。不写:官方地址按 `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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/src/resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
1 change: 1 addition & 0 deletions crates/tw-gateway/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ tw-dialect = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
zstd = { workspace = true }

[dev-dependencies]
# 集成测试里要当 WS 客户端 —— 那一侧需要 connect
Expand Down
60 changes: 31 additions & 29 deletions crates/tw-gateway/src/chatgpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 不一样的地方
//!
Expand Down Expand Up @@ -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<String, Value>) -> 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<Bytes> {
zstd::stream::encode_all(body, 3).ok().map(Bytes::from)
}

/// 客户端本来就说 Responses、这一跳直通时,把请求体改成 Codex 后端接受的样子。
///
Expand All @@ -81,14 +107,7 @@ pub fn shape_passthrough(body: &Bytes) -> (Bytes, Vec<String>) {
}
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()),
Expand Down Expand Up @@ -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())
}

// ---------------------------------------------------------------- 账户

/// 令牌里和账户有关的几项。
Expand Down Expand Up @@ -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]
Expand Down
Loading
Loading