mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-20 08:01:46 +00:00
fix(api): apply the CLI version gate to Desktop-hosted TUI clients
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -178,7 +178,7 @@ pub(crate) fn client_access_error_response(error: ClientAccessError) -> Response
|
||||
response
|
||||
}
|
||||
|
||||
/// Desktop 优先于内嵌 CLI/Core;未知客户端及未提供应用版本的手机远程客户端返回 `None`
|
||||
/// 识别 Desktop 应用或 CLI/Core;未知客户端及未提供应用版本的手机远程客户端返回 `None`
|
||||
#[must_use]
|
||||
pub fn identify_codex_client(headers: &HeaderMap) -> Option<IdentifiedCodexClient> {
|
||||
const MAXIMUM_HEADER_LENGTH: usize = 4096;
|
||||
@@ -196,25 +196,35 @@ pub fn identify_codex_client(headers: &HeaderMap) -> Option<IdentifiedCodexClien
|
||||
"codex_mcp_server",
|
||||
];
|
||||
|
||||
let originator = bounded_ascii_header(headers, "originator", MAXIMUM_HEADER_LENGTH);
|
||||
let user_agent = bounded_ascii_header(headers, "user-agent", MAXIMUM_HEADER_LENGTH);
|
||||
let is_desktop = originator.is_some_and(|value| value.eq_ignore_ascii_case("Codex Desktop"))
|
||||
let ascii_header = |name: &'static str| headers.get(name).and_then(|value| value.to_str().ok());
|
||||
let raw_user_agent = ascii_header("user-agent");
|
||||
// HeaderValue::to_str 只接受 ASCII,可以按字节截取搜索范围
|
||||
let user_agent = raw_user_agent.map(|ua| &ua[..ua.len().min(MAXIMUM_HEADER_LENGTH)]);
|
||||
let is_desktop = ascii_header("originator")
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case("Codex Desktop"))
|
||||
|| user_agent.is_some_and(|value| contains_ascii_case_insensitive(value, "Codex Desktop"));
|
||||
if is_desktop {
|
||||
let explicit_version = bounded_ascii_header(headers, "version", MAXIMUM_HEADER_LENGTH);
|
||||
let version_header = headers.get("version");
|
||||
let user_agent_version = user_agent.and_then(desktop_version_from_user_agent);
|
||||
// 手机远程初始化会覆盖进程级 UA 后缀,保留的 Desktop/Core 前缀不代表应用版本
|
||||
// 仅缺失版本信息时免于门禁;已提供的版本即使非法,也继续按 Desktop 校验
|
||||
if !headers.contains_key("version")
|
||||
&& user_agent_version.is_none()
|
||||
&& headers
|
||||
.get("user-agent")
|
||||
.is_some_and(|value| value.as_bytes().len() <= MAXIMUM_HEADER_LENGTH)
|
||||
&& user_agent.is_some_and(has_chatgpt_remote_user_agent_suffix)
|
||||
if user_agent_version.is_none()
|
||||
&& let Some(ua) = raw_user_agent.filter(|ua| ua.len() <= MAXIMUM_HEADER_LENGTH)
|
||||
&& let Some(client) = user_agent_client_name(ua)
|
||||
{
|
||||
return None;
|
||||
// 共享 App Server 可保留 Desktop 进程名,TUI 请求的 version 头也可能重复 Core 版本
|
||||
if client.eq_ignore_ascii_case("codex-tui")
|
||||
&& let Some(core) = desktop_core_version(ua)
|
||||
&& version_header.is_none_or(|value| value.as_bytes() == core.as_bytes())
|
||||
{
|
||||
return Some(IdentifiedCodexClient {
|
||||
kind: CodexClientKind::Cli,
|
||||
version: CodexClientVersion::parse(core).ok(),
|
||||
});
|
||||
}
|
||||
if version_header.is_none() && is_chatgpt_remote_client(client) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let version = match explicit_version {
|
||||
let version = match version_header.and_then(|value| value.to_str().ok()) {
|
||||
Some(value) => CodexClientVersion::parse(value).ok(),
|
||||
None => user_agent_version.and_then(|value| CodexClientVersion::parse(value).ok()),
|
||||
};
|
||||
@@ -244,18 +254,6 @@ pub fn identify_codex_client(headers: &HeaderMap) -> Option<IdentifiedCodexClien
|
||||
None
|
||||
}
|
||||
|
||||
fn bounded_ascii_header<'a>(
|
||||
headers: &'a HeaderMap,
|
||||
name: &'static str,
|
||||
maximum_length: usize,
|
||||
) -> Option<&'a str> {
|
||||
let value = headers.get(name)?.to_str().ok()?;
|
||||
if !value.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
Some(&value[..value.len().min(maximum_length)])
|
||||
}
|
||||
|
||||
fn desktop_version_from_user_agent(user_agent: &str) -> Option<&str> {
|
||||
let marker = "Codex Desktop;";
|
||||
let start = find_ascii_case_insensitive(user_agent, marker)? + marker.len();
|
||||
@@ -266,27 +264,29 @@ fn desktop_version_from_user_agent(user_agent: &str) -> Option<&str> {
|
||||
.next()
|
||||
}
|
||||
|
||||
fn has_chatgpt_remote_user_agent_suffix(user_agent: &str) -> bool {
|
||||
let Some((_, suffix)) = user_agent
|
||||
.strip_suffix(')')
|
||||
.and_then(|value| value.rsplit_once(" ("))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Some((name, version)) = suffix.split_once("; ") else {
|
||||
return false;
|
||||
};
|
||||
let Some(platform) = name
|
||||
.strip_prefix("codex_chatgpt_")
|
||||
.and_then(|value| value.strip_suffix("_remote"))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
[platform, version].into_iter().all(|value| {
|
||||
fn desktop_core_version(user_agent: &str) -> Option<&str> {
|
||||
let (product, rest) = user_agent.split_once('/')?;
|
||||
let (version, _) = rest.split_once(' ')?;
|
||||
product
|
||||
.eq_ignore_ascii_case("Codex Desktop")
|
||||
.then_some(version)
|
||||
}
|
||||
|
||||
fn user_agent_client_name(user_agent: &str) -> Option<&str> {
|
||||
let (_, suffix) = user_agent.strip_suffix(')')?.rsplit_once(" (")?;
|
||||
let (name, version) = suffix.split_once("; ")?;
|
||||
let valid_token = |value: &str| {
|
||||
!value.is_empty()
|
||||
&& !value.contains(['(', ')', ';'])
|
||||
&& !value.bytes().any(|byte| byte.is_ascii_whitespace())
|
||||
})
|
||||
};
|
||||
(valid_token(name) && valid_token(version)).then_some(name)
|
||||
}
|
||||
|
||||
fn is_chatgpt_remote_client(name: &str) -> bool {
|
||||
name.strip_prefix("codex_chatgpt_")
|
||||
.and_then(|value| value.strip_suffix("_remote"))
|
||||
.is_some_and(|platform| !platform.is_empty())
|
||||
}
|
||||
|
||||
fn contains_ascii_case_insensitive(haystack: &str, needle: &str) -> bool {
|
||||
|
||||
@@ -228,6 +228,46 @@ fn desktop_headers_should_take_precedence_over_embedded_cli_marker() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desktop_hosted_tui_should_use_core_unless_a_desktop_version_is_supplied() {
|
||||
for (core, version_header, kind, version) in [
|
||||
("0.170.0", None, CodexClientKind::Cli, Some("0.170.0")),
|
||||
(
|
||||
"0.170.0",
|
||||
Some("0.170.0"),
|
||||
CodexClientKind::Cli,
|
||||
Some("0.170.0"),
|
||||
),
|
||||
("invalid", None, CodexClientKind::Cli, None),
|
||||
(
|
||||
"0.170.0",
|
||||
Some("26.1023.51421"),
|
||||
CodexClientKind::Desktop,
|
||||
Some("26.1023.51421"),
|
||||
),
|
||||
("0.170.0", Some("invalid"), CodexClientKind::Desktop, None),
|
||||
] {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("originator", HeaderValue::from_static("Codex Desktop"));
|
||||
headers.insert(
|
||||
"user-agent",
|
||||
HeaderValue::from_str(&format!(
|
||||
"Codex Desktop/{core} (Ubuntu 26.4.0; aarch64) xterm-256color (codex-tui; 0.169.0)"
|
||||
))
|
||||
.unwrap(),
|
||||
);
|
||||
if let Some(value) = version_header {
|
||||
headers.insert("version", HeaderValue::from_static(value));
|
||||
}
|
||||
let client = identify_codex_client(&headers).unwrap();
|
||||
assert_eq!(client.kind(), kind);
|
||||
assert_eq!(
|
||||
client.version().map(ToString::to_string).as_deref(),
|
||||
version
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn official_core_clients_should_use_the_core_version_instead_of_the_app_suffix() {
|
||||
for product in [
|
||||
@@ -322,7 +362,7 @@ fn chatgpt_remote_desktop_without_app_version_should_not_use_a_version_gate() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chatgpt_remote_marker_should_require_a_complete_exact_client_suffix() {
|
||||
fn desktop_should_require_a_complete_exact_client_suffix() {
|
||||
for suffix in [
|
||||
"(codex_chatgpt_android_remote_extra; dev)",
|
||||
"(unofficial_codex_chatgpt_ios_remote; dev)",
|
||||
@@ -340,6 +380,9 @@ fn chatgpt_remote_marker_should_require_a_complete_exact_client_suffix() {
|
||||
"(Codex Desktop; ) (codex_chatgpt_android_remote; dev)",
|
||||
"(Codex Desktop; invalid) (codex_chatgpt_ios_remote; dev)",
|
||||
"(Codex Desktop)",
|
||||
"(codex-tui-custom; 0.169.0)",
|
||||
"(codex-tui; 0.169.0) trailing",
|
||||
"(codex-tui; )",
|
||||
] {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
@@ -395,19 +438,23 @@ fn chatgpt_remote_marker_should_not_override_an_existing_desktop_version_suffix(
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chatgpt_remote_suffix_created_by_header_truncation_should_not_skip_the_gate() {
|
||||
let suffix = " (codex_chatgpt_android_remote; dev)";
|
||||
let mut user_agent = "Codex Desktop/0.154.0-alpha.6.2 ".to_owned();
|
||||
user_agent.push_str(&"x".repeat(4096 - user_agent.len() - suffix.len()));
|
||||
user_agent.push_str(suffix);
|
||||
user_agent.push_str(" (another_client; dev)");
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("user-agent", HeaderValue::from_str(&user_agent).unwrap());
|
||||
fn truncated_client_suffix_should_not_change_the_desktop_gate() {
|
||||
for suffix in [
|
||||
" (codex_chatgpt_android_remote; dev)",
|
||||
" (codex-tui; 0.169.0)",
|
||||
] {
|
||||
let mut user_agent = "Codex Desktop/0.154.0-alpha.6.2 ".to_owned();
|
||||
user_agent.push_str(&"x".repeat(4096 - user_agent.len() - suffix.len()));
|
||||
user_agent.push_str(suffix);
|
||||
user_agent.push_str(" (another_client; dev)");
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("user-agent", HeaderValue::from_str(&user_agent).unwrap());
|
||||
|
||||
let client =
|
||||
identify_codex_client(&headers).expect("incomplete headers still require a version");
|
||||
assert_eq!(client.kind(), CodexClientKind::Desktop);
|
||||
assert!(client.version().is_none());
|
||||
let client =
|
||||
identify_codex_client(&headers).expect("incomplete headers still require a version");
|
||||
assert_eq!(client.kind(), CodexClientKind::Desktop);
|
||||
assert!(client.version().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -2954,20 +2954,21 @@ struct SessionExecution {
|
||||
#[tokio::test]
|
||||
async fn official_core_clients_should_be_version_checked_before_starting_responses() {
|
||||
let admin = crate::admin::AdminTestFixture::new().await.services;
|
||||
for product in [
|
||||
"codex-tui",
|
||||
"codex_exec",
|
||||
"codex_vscode",
|
||||
"codex_sdk_ts",
|
||||
"codex_python_sdk",
|
||||
for (product, client) in [
|
||||
("codex-tui", "codex-tui"),
|
||||
("codex_exec", "codex_exec"),
|
||||
("codex_vscode", "codex_vscode"),
|
||||
("codex_sdk_ts", "codex_sdk_ts"),
|
||||
("codex_python_sdk", "codex_python_sdk"),
|
||||
("Codex Desktop", "codex-tui"),
|
||||
] {
|
||||
for (version, allowed) in [("0.158.0", false), ("0.162.0", true)] {
|
||||
for (version, allowed) in [("0.168.0", false), ("0.170.0", true)] {
|
||||
let trace = Arc::new(Trace::default());
|
||||
let execution = Arc::new(SessionExecution {
|
||||
client: authenticated_client_with_min_versions(
|
||||
"sk_version_test",
|
||||
None,
|
||||
Some("0.162.0"),
|
||||
Some("26.1023.51421"),
|
||||
Some("0.170.0"),
|
||||
),
|
||||
session: Mutex::new(Some(Box::new(FakeSession::streaming(
|
||||
Arc::clone(&trace),
|
||||
@@ -2985,7 +2986,7 @@ async fn official_core_clients_should_be_version_checked_before_starting_respons
|
||||
let request = Request::post("/v1/responses")
|
||||
.header(AUTHORIZATION, "Bearer sk_version_test")
|
||||
.header("user-agent", format!(
|
||||
"{product}/{version} (Mac OS 26.6.2; arm64) Apple_Terminal ({product}; 0.165.0)"
|
||||
"{product}/{version} (Ubuntu 26.4.0; aarch64) xterm-256color ({client}; 0.169.0)"
|
||||
))
|
||||
.body(Body::from(json!({"model": "model-a", "input": "synthetic", "stream": true}).to_string()))
|
||||
.unwrap();
|
||||
@@ -3006,8 +3007,9 @@ async fn official_core_clients_should_be_version_checked_before_starting_respons
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{product}/{version}");
|
||||
let value: Value = serde_json::from_slice(&body).unwrap();
|
||||
assert_eq!(value["error"]["code"], "client_version_too_old");
|
||||
assert_eq!(value["error"]["client"], "codex_cli");
|
||||
assert_eq!(value["error"]["current_version"], version);
|
||||
assert_eq!(value["error"]["min_version"], "0.162.0");
|
||||
assert_eq!(value["error"]["min_version"], "0.170.0");
|
||||
assert!(execution.session.lock().unwrap().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1227,12 +1227,16 @@ fn upgrade_request(authorization: &str) -> Request<Body> {
|
||||
|
||||
#[tokio::test]
|
||||
async fn official_core_version_gate_should_run_before_websocket_upgrade() {
|
||||
let app = api_router(ModelsExecution::with_cli_min("0.162.0")).await;
|
||||
let app = api_router(ModelsExecution::with_cli_min("0.170.0")).await;
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
|
||||
for version in ["0.158.0", "0.162.0"] {
|
||||
for (product, version) in [
|
||||
("codex-tui", "0.158.0"),
|
||||
("Codex Desktop", "0.168.0"),
|
||||
("Codex Desktop", "0.170.0"),
|
||||
] {
|
||||
let mut request = format!("ws://{address}/v1/responses")
|
||||
.into_client_request()
|
||||
.unwrap();
|
||||
@@ -1243,12 +1247,12 @@ async fn official_core_version_gate_should_run_before_websocket_upgrade() {
|
||||
request.headers_mut().insert(
|
||||
"user-agent",
|
||||
HeaderValue::from_str(&format!(
|
||||
"codex-tui/{version} (Mac OS 26.6.2; arm64) Apple_Terminal (codex-tui; 0.165.0)"
|
||||
"{product}/{version} (Ubuntu 26.4.0; aarch64) xterm-256color (codex-tui; 0.169.0)"
|
||||
))
|
||||
.unwrap(),
|
||||
);
|
||||
let result = connect_async(request).await;
|
||||
if version == "0.162.0" {
|
||||
if version == "0.170.0" {
|
||||
let (mut socket, response) = result.expect("current Core upgrades successfully");
|
||||
assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS);
|
||||
socket.close(None).await.unwrap();
|
||||
@@ -1261,8 +1265,9 @@ async fn official_core_version_gate_should_run_before_websocket_upgrade() {
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
let value: Value = serde_json::from_slice(response.body().as_deref().unwrap()).unwrap();
|
||||
assert_eq!(value["error"]["code"], "client_version_too_old");
|
||||
assert_eq!(value["error"]["current_version"], "0.158.0");
|
||||
assert_eq!(value["error"]["min_version"], "0.162.0");
|
||||
assert_eq!(value["error"]["client"], "codex_cli");
|
||||
assert_eq!(value["error"]["current_version"], version);
|
||||
assert_eq!(value["error"]["min_version"], "0.170.0");
|
||||
}
|
||||
}
|
||||
server.abort();
|
||||
|
||||
@@ -55,6 +55,10 @@ Client Key 通过账号分组限定路由范围:未绑定分组时可使用全
|
||||
`codex_python_sdk`、`codex-app-server`、`codex-app-server-sdk` 与 `codex_mcp_server`
|
||||
名称按完整标识匹配且不区分大小写,括号后缀中的应用或 SDK 版本不能替代 Core 版本
|
||||
|
||||
TUI 连接共享 App Server 时,User-Agent 可以是 `Codex Desktop/<Core 版本> … (codex-tui; <TUI 版本>)`。
|
||||
这种请求按 CLI 门槛检查前缀中的 Core 版本,`version` 头可以省略或与 Core 版本相同。
|
||||
若该头提供不同的值,或 UA 另含 Desktop 应用版本后缀,则按 Desktop 规则校验
|
||||
|
||||
Desktop 应用版本优先取 `version` 头,未提供时取 User-Agent 中的 `(Codex Desktop; <版本>)`。
|
||||
ChatGPT 远程控制使用 `(codex_chatgpt_<平台>_remote; <版本>)` 形式的 User-Agent 后缀,已知平台包括
|
||||
`android` 和 `ios`。网关按该命名格式识别非空的平台名,后缀须完整,平台名和版本均不能含空白、括号或分号。
|
||||
|
||||
Reference in New Issue
Block a user