aKode fase 2b-2: rimosso login ChatGPT e tutti i sottosistemi solo-ChatGPT

- Login: resta solo chiave API (+ header, Bedrock). Rimossi OAuth/browser,
  device code, refresh/revoke su auth.openai.com, PAT, agent/workload identity,
  runtime agent instance, backend-client e openapi-models, workspace routing.
- Rimossi: generazione immagini (ext + skill imagegen), history notes, plugin
  remoti (catalogo, sync, share), cyber access program, daybreak, cloud config
  e requirements (config_server ora fail-closed), attestation, frozen cloud
  skills, EMA MCP auth, Codex Apps/connettori, ricerca ospitata, header/zstd/
  routing/cookie del backend Codex, fallback OPENAI_API_KEY del realtime.
- Messaggi d'errore senza link a chatgpt.com.
- Chiavi di config legacy accettate e ignorate; feature rimosse = Stage::Removed.
- Test: cancellati solo quelli del codice rimosso; test di sicurezza
  (sandbox estensioni, permessi, redazione, auth storage, requirements)
  adattati. Restano solo fallimenti d'ambiente (code-mode-host/V8, ~/.agents).
- Istruzioni di sistema invariate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-10 16:20:15 +01:00
parent 82347a58ed
commit 6089fbde91
1573 changed files with 10289 additions and 177679 deletions

View File

@@ -1,491 +0,0 @@
//! ChatGPT cookies shared by HTTP and WebSocket transports. Only infrastructure cookies may be
//! stored globally; configured cookies remain scoped to their factory.
use std::sync::Arc;
use std::sync::LazyLock;
use http::HeaderMap;
use http::HeaderValue;
use http::Uri;
use http::header::SET_COOKIE;
use reqwest::cookie::CookieStore;
use reqwest::cookie::Jar;
use crate::HttpClientFactory;
use crate::chatgpt_hosts::is_allowed_chatgpt_host;
// WARNING: this HTTP cookie store is process-global and may be shared across auth contexts.
// It must only ever contain Cloudflare infrastructure cookies and the `__oailb`
// routing cookie. Never extend this store to persist ChatGPT account, session,
// auth, or other user-specific cookie data.
static SHARED_CHATGPT_CLOUDFLARE_COOKIE_STORE: LazyLock<Arc<ChatGptCloudflareCookieStore>> =
LazyLock::new(|| Arc::new(ChatGptCloudflareCookieStore::default()));
#[derive(Debug, Default)]
struct ChatGptCloudflareCookieStore {
jar: Jar,
}
pub(crate) struct ChatGptCookieStore {
cloudflare: Arc<ChatGptCloudflareCookieStore>,
cookies: Vec<HeaderValue>,
}
impl ChatGptCookieStore {
pub(crate) fn new(cookies: Vec<HeaderValue>) -> Self {
Self {
cloudflare: Arc::clone(&SHARED_CHATGPT_CLOUDFLARE_COOKIE_STORE),
cookies,
}
}
pub(crate) fn configured_cookies(&self) -> &[HeaderValue] {
&self.cookies
}
}
impl CookieStore for ChatGptCloudflareCookieStore {
fn set_cookies(
&self,
cookie_headers: &mut dyn Iterator<Item = &HeaderValue>,
url: &reqwest::Url,
) {
if !is_chatgpt_cookie_url(url) {
return;
}
let mut cloudflare_cookie_headers =
cookie_headers.filter(|header| is_allowed_cloudflare_set_cookie_header(header));
self.jar.set_cookies(&mut cloudflare_cookie_headers, url);
}
fn cookies(&self, url: &reqwest::Url) -> Option<HeaderValue> {
if is_chatgpt_cookie_url(url) {
self.jar.cookies(url).and_then(only_cloudflare_cookies)
} else {
None
}
}
}
impl CookieStore for ChatGptCookieStore {
fn set_cookies(
&self,
cookie_headers: &mut dyn Iterator<Item = &HeaderValue>,
url: &reqwest::Url,
) {
self.cloudflare.set_cookies(cookie_headers, url);
}
fn cookies(&self, url: &reqwest::Url) -> Option<HeaderValue> {
if !is_chatgpt_cookie_url(url) {
return self.cloudflare.cookies(url);
}
let cloudflare = self.cloudflare.cookies(url);
let mut sensitive = cloudflare.as_ref().is_some_and(HeaderValue::is_sensitive);
let mut cookies = cloudflare
.map(|cloudflare| cloudflare.as_bytes().to_vec())
.unwrap_or_default();
for cookie in &self.cookies {
sensitive |= cookie.is_sensitive();
if !cookies.is_empty() {
cookies.extend_from_slice(b"; ");
}
cookies.extend_from_slice(cookie.as_bytes());
}
if cookies.is_empty() {
None
} else {
let mut header = HeaderValue::from_bytes(&cookies).ok()?;
header.set_sensitive(sensitive);
Some(header)
}
}
}
impl HttpClientFactory {
/// Returns cookies for a ChatGPT HTTPS or WSS request, using the same store as HTTP clients.
/// Explicit request Cookie headers should take precedence over this value.
pub fn chatgpt_cookie_header(&self, uri: &Uri) -> Option<HeaderValue> {
let url = chatgpt_cookie_url(uri)?;
let mut cookies = match self.chatgpt_cookie_store() {
Some(store) => store.cookies(&url),
None => SHARED_CHATGPT_CLOUDFLARE_COOKIE_STORE.cookies(&url),
}?;
cookies.set_sensitive(true);
Some(cookies)
}
/// Retains only allowlisted infrastructure cookies from a ChatGPT HTTPS or WSS response.
/// Account and session cookies are never added to the shared store.
pub fn store_chatgpt_response_cookies(&self, uri: &Uri, headers: &HeaderMap) {
if let Some(url) = chatgpt_cookie_url(uri) {
SHARED_CHATGPT_CLOUDFLARE_COOKIE_STORE
.set_cookies(&mut headers.get_all(SET_COOKIE).iter(), &url);
}
}
}
pub(crate) fn chatgpt_cookie_url(uri: &Uri) -> Option<reqwest::Url> {
let mut url = reqwest::Url::parse(&uri.to_string()).ok()?;
// A secure WebSocket handshake has the same cookie scope as HTTPS.
if url.scheme() == "wss" {
url.set_scheme("https").ok()?;
}
is_chatgpt_cookie_url(&url).then_some(url)
}
/// Adds the process-local ChatGPT infrastructure cookie jar used by Codex HTTP clients.
///
/// WARNING: this jar is global within the process. It is only acceptable because it hardcodes a
/// small allowlist of Cloudflare cookie names plus `__oailb` for routing, and refuses all other
/// ChatGPT cookies. Do not store ChatGPT account, session, auth, or other user-specific cookies
/// here. If a future caller needs those cookies, the store must be scoped to the auth/session
/// owner instead of shared globally.
pub fn with_chatgpt_cloudflare_cookie_store(
builder: reqwest::ClientBuilder,
) -> reqwest::ClientBuilder {
builder.cookie_provider(Arc::clone(&SHARED_CHATGPT_CLOUDFLARE_COOKIE_STORE))
}
fn is_chatgpt_cookie_url(url: &reqwest::Url) -> bool {
match url.scheme() {
"https" => {}
_ => return false,
}
let Some(host) = url.host_str() else {
return false;
};
is_allowed_chatgpt_host(host)
}
fn is_allowed_cloudflare_set_cookie_header(header: &HeaderValue) -> bool {
header
.to_str()
.ok()
.and_then(set_cookie_name)
.is_some_and(is_allowed_cloudflare_cookie_name)
}
fn set_cookie_name(header: &str) -> Option<&str> {
let (name, _) = header.split_once('=')?;
let name = name.trim();
(!name.is_empty()).then_some(name)
}
fn only_cloudflare_cookies(header: HeaderValue) -> Option<HeaderValue> {
let header = header.to_str().ok()?;
let cookies = header
.split(';')
.filter_map(|cookie| {
let cookie = cookie.trim();
let name = cookie.split_once('=')?.0.trim();
is_allowed_cloudflare_cookie_name(name).then_some(cookie)
})
.collect::<Vec<_>>()
.join("; ");
if cookies.is_empty() {
None
} else {
HeaderValue::from_str(&cookies).ok()
}
}
fn is_allowed_cloudflare_cookie_name(name: &str) -> bool {
// `__oailb` is an OpenAI infrastructure routing cookie, not an authentication cookie.
// Keep this allowlist aligned with Cloudflare's documented service cookies:
// https://developers.cloudflare.com/fundamentals/reference/policies-compliances/cloudflare-cookies/
matches!(
name,
"__cf_bm"
| "__cflb"
| "__cfruid"
| "__cfseq"
| "__cfwaitingroom"
| "__oailb"
| "_cfuvid"
| "cf_clearance"
| "cf_ob_info"
| "cf_use_ob"
) || name.starts_with("cf_chl_")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
use reqwest::cookie::CookieStore;
#[test]
fn http_and_websocket_cookies_share_the_factory_store() {
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_chatgpt_cookies([HeaderValue::from_static("configured=owner")]);
let store = factory.chatgpt_cookie_store().unwrap();
let https = reqwest::Url::parse("https://http-websocket-cookies.chatgpt.com/api").unwrap();
let wss: Uri = "wss://http-websocket-cookies.chatgpt.com/api"
.parse()
.unwrap();
let cookie = HeaderValue::from_static("__oailb=from-http; Path=/; Secure");
store.set_cookies(&mut std::iter::once(&cookie), &https);
let header = factory.chatgpt_cookie_header(&wss).unwrap();
assert_eq!(header, "__oailb=from-http; configured=owner");
assert!(header.is_sensitive());
let mut response_headers = HeaderMap::new();
response_headers.insert(
SET_COOKIE,
HeaderValue::from_static("__oailb=from-wss; Path=/; Secure"),
);
factory.store_chatgpt_response_cookies(&wss, &response_headers);
assert_eq!(
store.cookies(&https),
Some(HeaderValue::from_static(
"__oailb=from-wss; configured=owner"
))
);
assert_eq!(
factory.chatgpt_cookie_header(
&"ws://http-websocket-cookies.chatgpt.com/api"
.parse()
.unwrap()
),
None
);
assert_eq!(
factory.chatgpt_cookie_header(&"wss://api.openai.com/api".parse().unwrap()),
None
);
}
#[test]
fn additional_cookies_use_current_path_scoped_cloudflare_cookies() {
let cloudflare = Arc::new(ChatGptCloudflareCookieStore::default());
let mut sensitive_cookie = HeaderValue::from_static("additional=true");
sensitive_cookie.set_sensitive(true);
let store = ChatGptCookieStore {
cloudflare: Arc::clone(&cloudflare),
cookies: vec![
sensitive_cookie,
HeaderValue::from_static("another=enabled"),
],
};
let first_url = reqwest::Url::parse("https://cookies.chatgpt.com/a").unwrap();
let second_url = reqwest::Url::parse("https://cookies.chatgpt.com/b").unwrap();
let affinity = HeaderValue::from_static("__cflb=current; Path=/a; Secure");
cloudflare.set_cookies(&mut std::iter::once(&affinity), &first_url);
assert_eq!(
store.cookies(&first_url),
Some(HeaderValue::from_static(
"__cflb=current; additional=true; another=enabled"
))
);
assert!(store.cookies(&first_url).unwrap().is_sensitive());
assert_eq!(
store.cookies(&second_url),
Some(HeaderValue::from_static("additional=true; another=enabled"))
);
let expired = HeaderValue::from_static("__cflb=; Max-Age=0; Path=/a; Secure");
store.set_cookies(&mut std::iter::once(&expired), &first_url);
assert_eq!(
store.cookies(&first_url),
Some(HeaderValue::from_static("additional=true; another=enabled"))
);
}
#[test]
fn additional_cookies_are_restricted_to_https_chatgpt_hosts() {
let store = ChatGptCookieStore {
cloudflare: Arc::new(ChatGptCloudflareCookieStore::default()),
cookies: vec![HeaderValue::from_static("additional=true")],
};
for url in ["http://chatgpt.com/a", "https://api.openai.com/a"] {
let url = reqwest::Url::parse(url).unwrap();
assert_eq!(store.cookies(&url), None);
}
let url = reqwest::Url::parse("https://chatgpt.com/a").unwrap();
assert_eq!(
store.cookies(&url),
Some(HeaderValue::from_static("additional=true"))
);
assert!(!store.cookies(&url).unwrap().is_sensitive());
}
#[test]
fn stores_and_returns_cloudflare_cookies_for_chatgpt_hosts() {
let store = ChatGptCloudflareCookieStore::default();
let url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap();
let load_balancer = HeaderValue::from_static("__cflb=west; Path=/; Secure; HttpOnly");
let cfuvid = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly");
let clearance =
HeaderValue::from_static("cf_clearance=clearance; Path=/; Secure; HttpOnly");
store.set_cookies(&mut [&load_balancer, &cfuvid, &clearance].into_iter(), &url);
let mut cookies = store
.cookies(&url)
.and_then(|value| value.to_str().ok().map(str::to_string))
.map(|header| {
header
.split("; ")
.map(str::to_string)
.collect::<Vec<String>>()
})
.unwrap_or_default();
cookies.sort();
assert_eq!(
cookies,
vec![
"__cflb=west".to_string(),
"_cfuvid=visitor".to_string(),
"cf_clearance=clearance".to_string()
]
);
}
#[test]
fn oailb_cookies_are_replayed_with_scope_and_expiration() {
let store = ChatGptCloudflareCookieStore::default();
let url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap();
let cookie = HeaderValue::from_static(
"__oailb=route; Path=/backend-api; Max-Age=3600; Secure; HttpOnly; SameSite=Lax",
);
store.set_cookies(&mut std::iter::once(&cookie), &url);
let followup_url = reqwest::Url::parse("https://chatgpt.com/backend-api/ps/mcp").unwrap();
assert_eq!(
store.cookies(&followup_url),
Some(HeaderValue::from_static("__oailb=route"))
);
for outside_scope in [
"https://chatgpt.com/",
"https://other.chatgpt.com/backend-api/ps/mcp",
"https://api.openai.com/backend-api/ps/mcp",
"http://chatgpt.com/backend-api/ps/mcp",
] {
let outside_scope = reqwest::Url::parse(outside_scope).unwrap();
assert_eq!(store.cookies(&outside_scope), None);
}
let expired = HeaderValue::from_static(
"__oailb=; Path=/backend-api; Max-Age=0; Secure; HttpOnly; SameSite=Lax",
);
store.set_cookies(&mut std::iter::once(&expired), &url);
assert_eq!(store.cookies(&followup_url), None);
}
#[test]
fn ignores_non_chatgpt_cookies() {
let store = ChatGptCloudflareCookieStore::default();
let url = reqwest::Url::parse("https://api.openai.com/v1/responses").unwrap();
let set_cookie = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly");
store.set_cookies(&mut std::iter::once(&set_cookie), &url);
assert_eq!(store.cookies(&url), None);
}
#[test]
fn ignores_non_cloudflare_cookies_for_chatgpt_hosts() {
let store = ChatGptCloudflareCookieStore::default();
let url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap();
let set_cookie = HeaderValue::from_static(
"__Secure-next-auth.session-token=secret; Path=/; Secure; HttpOnly",
);
store.set_cookies(&mut std::iter::once(&set_cookie), &url);
assert_eq!(store.cookies(&url), None);
}
#[test]
fn ignores_mixed_non_cloudflare_cookies_for_chatgpt_hosts() {
let store = ChatGptCloudflareCookieStore::default();
let url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap();
let cfuvid = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly");
let account_cookie =
HeaderValue::from_static("chatgpt_session=secret; Path=/; Secure; HttpOnly");
store.set_cookies(&mut [&cfuvid, &account_cookie].into_iter(), &url);
assert_eq!(
store
.cookies(&url)
.and_then(|value| value.to_str().ok().map(str::to_string)),
Some("_cfuvid=visitor".to_string())
);
}
#[test]
fn does_not_return_chatgpt_cloudflare_cookies_for_other_hosts() {
let store = ChatGptCloudflareCookieStore::default();
let chatgpt_url =
reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap();
let api_url = reqwest::Url::parse("https://api.openai.com/v1/responses").unwrap();
let set_cookie = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly");
store.set_cookies(&mut std::iter::once(&set_cookie), &chatgpt_url);
assert_eq!(store.cookies(&api_url), None);
}
#[test]
fn rejects_plain_http_chatgpt_cookie_urls() {
let store = ChatGptCloudflareCookieStore::default();
let http_url = reqwest::Url::parse("http://chatgpt.com/backend-api/codex/responses")
.expect("URL should parse");
let https_url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses")
.expect("URL should parse");
let set_cookie = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly");
store.set_cookies(&mut std::iter::once(&set_cookie), &http_url);
assert_eq!(store.cookies(&http_url), None);
assert_eq!(store.cookies(&https_url), None);
}
#[test]
fn only_allows_https_urls() {
let url = reqwest::Url::parse("http://chatgpt.com/backend-api/codex/responses").unwrap();
assert!(!is_chatgpt_cookie_url(&url));
let url = reqwest::Url::parse("wss://chatgpt.com/backend-api/codex/responses").unwrap();
assert!(!is_chatgpt_cookie_url(&url));
}
#[test]
fn allows_only_known_cloudflare_cookie_names() {
for name in [
"__cf_bm",
"__cflb",
"__cfruid",
"__cfseq",
"__cfwaitingroom",
"_cfuvid",
"cf_clearance",
"cf_ob_info",
"cf_use_ob",
"cf_chl_rc_i",
] {
assert!(is_allowed_cloudflare_cookie_name(name));
}
for name in [
"__Secure-next-auth.session-token",
"chatgpt_session",
"oai-auth-token",
"not_cf_clearance",
] {
assert!(!is_allowed_cloudflare_cookie_name(name));
}
}
}

View File

@@ -1,39 +0,0 @@
/// Returns whether `host` is one of the ChatGPT hosts Codex is allowed to treat
/// as first-party ChatGPT HTTP traffic.
pub fn is_allowed_chatgpt_host(host: &str) -> bool {
const EXACT_HOSTS: &[&str] = &["chatgpt.com", "chat.openai.com", "chatgpt-staging.com"];
const SUBDOMAIN_SUFFIXES: &[&str] = &[".chatgpt.com", ".chatgpt-staging.com"];
EXACT_HOSTS.contains(&host)
|| SUBDOMAIN_SUFFIXES
.iter()
.any(|suffix| host.ends_with(suffix))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn recognizes_chatgpt_hosts_without_suffix_tricks() {
for host in [
"chatgpt.com",
"foo.chatgpt.com",
"staging.chatgpt.com",
"chat.openai.com",
"chatgpt-staging.com",
"api.chatgpt-staging.com",
] {
assert!(is_allowed_chatgpt_host(host));
}
for host in [
"evilchatgpt.com",
"chatgpt.com.evil.example",
"api.openai.com",
"foo.chat.openai.com",
] {
assert!(!is_allowed_chatgpt_host(host));
}
}
}

View File

@@ -1,115 +0,0 @@
//! Connection-owned ChatGPT routing pins. Keep only the handshake's routing cookies,
//! with their original expiry, and never forward them outside the original endpoint.
use std::sync::Arc;
use http::HeaderMap;
use http::HeaderValue;
use http::Uri;
use http::header::SET_COOKIE;
use reqwest::cookie::CookieStore;
use reqwest::cookie::Jar;
use url::Url;
use crate::chatgpt_cloudflare_cookies::chatgpt_cookie_url;
const ROUTING_COOKIE_NAMES: [&str; 2] = ["__oailb", "__cflb"];
/// A routing pin returned by one connection, independent of the process-wide cookie jar.
/// This is a best-effort hint: the edge still validates the cookie and may fail over.
/// Equality identifies the captured connection, independently of cookie expiry, so a live
/// colocated reviewer socket need not be disconnected when its handshake cookie expires.
#[derive(Clone)]
pub struct ChatGptRoutingAffinity {
url: Url,
jar: Arc<Jar>,
}
impl std::fmt::Debug for ChatGptRoutingAffinity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ChatGptRoutingAffinity")
.finish_non_exhaustive()
}
}
impl PartialEq for ChatGptRoutingAffinity {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.jar, &other.jar)
}
}
impl Eq for ChatGptRoutingAffinity {}
impl ChatGptRoutingAffinity {
/// Captures valid `__oailb` and Cloudflare's native `__cflb` response cookies.
/// Ambiguous or oversized cookies reject the pin; request cookies alone cannot establish
/// where failover landed. Cookie scope and expiry remain owned by the private jar.
pub fn from_response(uri: &Uri, headers: &HeaderMap) -> Option<Self> {
let url = chatgpt_cookie_url(uri)?;
let mut cookies = Vec::with_capacity(2);
for name in ROUTING_COOKIE_NAMES {
let mut matches = headers.get_all(SET_COOKIE).iter().filter(|header| {
header
.to_str()
.ok()
.and_then(|value| value.split_once('='))
.is_some_and(|(cookie_name, _)| cookie_name.trim() == name)
});
if let Some(cookie) = matches.next() {
if cookie.as_bytes().len() > 8192 || matches.next().is_some() {
return None;
}
cookies.push(cookie);
}
}
let jar = Jar::default();
jar.set_cookies(&mut cookies.into_iter(), &url);
jar.cookies(&url)?;
Some(Self {
url,
jar: Arc::new(jar),
})
}
/// Returns the still-valid pin only for the same secure ChatGPT origin and endpoint path.
/// The private jar retains Max-Age/Expires and is never refreshed by unrelated traffic.
pub fn cookie_header(&self, uri: &Uri) -> Option<HeaderValue> {
let url = chatgpt_cookie_url(uri)?;
if url.origin() != self.url.origin() || url.path() != self.url.path() {
return None;
}
let mut cookie = self.jar.cookies(&url)?;
cookie.set_sensitive(true);
Some(cookie)
}
/// Replaces routing cookies with the scoped pin while preserving unrelated cookies.
/// Returns `None` when the pin is no longer valid for this endpoint.
pub fn merge_cookie_header(
&self,
uri: &Uri,
existing: Option<&HeaderValue>,
) -> Option<HeaderValue> {
let pin = self.cookie_header(uri)?;
let mut parts = existing
.and_then(|value| value.to_str().ok())
.into_iter()
.flat_map(|value| value.split(';'))
.map(str::trim)
.filter(|part| {
!part.is_empty()
&& !part
.split_once('=')
.is_some_and(|(name, _)| ROUTING_COOKIE_NAMES.contains(&name.trim()))
})
.collect::<Vec<_>>();
parts.push(pin.to_str().ok()?);
let mut cookies = HeaderValue::from_str(&parts.join("; ")).ok()?;
cookies.set_sensitive(true);
Some(cookies)
}
}
#[cfg(test)]
#[path = "chatgpt_routing_affinity_tests.rs"]
mod tests;

View File

@@ -1,100 +0,0 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn affinity_retains_only_the_response_pin_with_its_cookie_scope_and_expiry() {
let uri: Uri = "wss://affinity.chatgpt.com/backend-api/codex/responses"
.parse()
.unwrap();
let mut headers = HeaderMap::new();
headers.append(
SET_COOKIE,
HeaderValue::from_static("__oailb=parent; Path=/backend-api; Max-Age=3600; Secure"),
);
headers.append(
SET_COOKIE,
HeaderValue::from_static("__cflb=parent-native; Path=/backend-api; Max-Age=3600; Secure"),
);
headers.append(
SET_COOKIE,
HeaderValue::from_static("chatgpt_session=secret; Path=/; Secure"),
);
let affinity = ChatGptRoutingAffinity::from_response(&uri, &headers).unwrap();
let pin = affinity.cookie_header(&uri).unwrap();
let mut cookies = pin.to_str().unwrap().split("; ").collect::<Vec<_>>();
cookies.sort_unstable();
assert_eq!(cookies, ["__cflb=parent-native", "__oailb=parent"]);
assert!(pin.is_sensitive());
let existing = HeaderValue::from_static(
"__oailb=old; cf_clearance=keep; __cflb=old-native; configured=keep",
);
let merged = affinity.merge_cookie_header(&uri, Some(&existing)).unwrap();
let mut cookies = merged.to_str().unwrap().split("; ").collect::<Vec<_>>();
cookies.sort_unstable();
assert_eq!(
cookies,
[
"__cflb=parent-native",
"__oailb=parent",
"cf_clearance=keep",
"configured=keep",
]
);
assert!(merged.is_sensitive());
assert_eq!(
affinity.merge_cookie_header(&uri, /*existing*/ None),
Some(pin.clone())
);
assert_eq!(format!("{affinity:?}"), "ChatGptRoutingAffinity { .. }");
for outside_scope in [
"ws://affinity.chatgpt.com/backend-api/codex/responses",
"wss://other.chatgpt.com/backend-api/codex/responses",
"wss://affinity.chatgpt.com:444/backend-api/codex/responses",
"wss://affinity.chatgpt.com/backend-api/codex/other",
"wss://api.openai.com/backend-api/codex/responses",
] {
assert_eq!(
affinity.cookie_header(&outside_scope.parse().unwrap()),
None
);
assert_eq!(
affinity.merge_cookie_header(&outside_scope.parse().unwrap(), Some(&existing)),
None
);
}
for name in ["__oailb", "__cflb"] {
headers.insert(
SET_COOKIE,
HeaderValue::from_str(&format!("{name}=only; Path=/; Secure")).unwrap(),
);
assert_eq!(
ChatGptRoutingAffinity::from_response(&uri, &headers)
.unwrap()
.cookie_header(&uri),
Some(HeaderValue::from_str(&format!("{name}=only")).unwrap())
);
for invalid in [
"__oailb=deleted; Path=/; Max-Age=0; Secure",
"__oailb=expired; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure",
"__oailb=wrong-path; Path=/elsewhere; Secure",
"__oailb=wrong-domain; Domain=other.chatgpt.com; Path=/; Secure",
"chatgpt_session=secret; Path=/; Secure",
] {
headers.insert(
SET_COOKIE,
HeaderValue::from_str(&invalid.replace("__oailb", name)).unwrap(),
);
assert!(ChatGptRoutingAffinity::from_response(&uri, &headers).is_none());
}
headers.insert(
SET_COOKIE,
HeaderValue::from_str(&format!("{name}=one; Path=/; Secure")).unwrap(),
);
headers.append(
SET_COOKIE,
HeaderValue::from_str(&format!("{name}=two; Path=/; Secure")).unwrap(),
);
assert!(ChatGptRoutingAffinity::from_response(&uri, &headers).is_none());
}
assert_eq!(affinity.cookie_header(&uri), Some(pin));
}

View File

@@ -20,12 +20,10 @@ use crate::HttpClient;
use crate::HttpClientFactory;
use crate::HttpClientTlsConfig;
use crate::OutboundProxyRoute;
use crate::chatgpt_cloudflare_cookies::ChatGptCookieStore;
use crate::client::HttpClientBackend;
use crate::client::RequestLogging;
use crate::client::TransportClient;
use crate::custom_ca::build_reqwest_client_with_custom_ca;
use crate::with_chatgpt_cloudflare_cookie_store;
/// Configures an [`HttpClient`] without exposing the underlying HTTP implementation.
///
@@ -40,8 +38,6 @@ pub struct HttpClientBuilder {
follow_redirects: bool,
pub(crate) redirect_observed: Option<Arc<AtomicBool>>,
pub(crate) connect_timeout: Option<Duration>,
chatgpt_cloudflare_cookie_store: bool,
chatgpt_cookie_store: Option<Arc<ChatGptCookieStore>>,
pub(crate) request_logging: RequestLogging,
tls_backend: TlsBackend,
pub(crate) tls: HttpClientTlsConfig,
@@ -157,18 +153,6 @@ impl HttpClientBuilder {
self
}
pub fn with_chatgpt_cloudflare_cookie_store(mut self) -> Self {
self.chatgpt_cloudflare_cookie_store = true;
self
}
/// Uses the factory's configured ChatGPT cookies without changing proxy behavior.
pub fn with_chatgpt_cookies(mut self, http_client_factory: &HttpClientFactory) -> Self {
self.chatgpt_cloudflare_cookie_store = true;
self.chatgpt_cookie_store = http_client_factory.chatgpt_cookie_store();
self
}
/// Suppresses request URL and response-header diagnostics.
pub fn without_request_logging(mut self) -> Self {
self.request_logging = RequestLogging::Disabled;
@@ -181,7 +165,7 @@ impl HttpClientBuilder {
/// resolve a concrete direct or proxy route when the factory is configured with
/// [`crate::OutboundProxyPolicy::RespectSystemProxy`].
pub fn build_respecting_outbound_proxy_policy(
mut self,
self,
http_client_factory: &HttpClientFactory,
request_url: &str,
route_class: ClientRouteClass,
@@ -207,7 +191,6 @@ impl HttpClientBuilder {
)?
.into_client());
}
self.chatgpt_cookie_store = http_client_factory.chatgpt_cookie_store();
let (builder, request_logging, default_headers) = self.into_reqwest_parts();
let inner =
crate::outbound_proxy::build_reqwest_client_for_route(builder, route_class, &route)?;
@@ -220,12 +203,10 @@ impl HttpClientBuilder {
/// Builds a client for a route that was already resolved by a route-aware caller.
pub(crate) fn build_for_resolved_route(
mut self,
http_client_factory: &HttpClientFactory,
self,
route_class: ClientRouteClass,
route: &OutboundProxyRoute,
) -> Result<TransportClient, BuildRouteAwareHttpClientError> {
self.chatgpt_cookie_store = http_client_factory.chatgpt_cookie_store();
let explicit_roots = self.tls.root_certificate.is_some();
let (builder, request_logging, default_headers) = self.into_reqwest_parts();
let inner = if explicit_roots {
@@ -423,12 +404,6 @@ impl HttpClientBuilder {
if let Some(connect_timeout) = self.connect_timeout {
builder = builder.connect_timeout(connect_timeout);
}
if self.chatgpt_cloudflare_cookie_store {
builder = match self.chatgpt_cookie_store {
Some(store) => builder.cookie_provider(store),
None => with_chatgpt_cloudflare_cookie_store(builder),
};
}
builder
}
}
@@ -442,8 +417,6 @@ impl Default for HttpClientBuilder {
follow_redirects: true,
redirect_observed: None,
connect_timeout: None,
chatgpt_cloudflare_cookie_store: false,
chatgpt_cookie_store: None,
request_logging: RequestLogging::Enabled,
tls_backend: TlsBackend::TransportDefault,
tls: HttpClientTlsConfig::default(),

View File

@@ -1,9 +1,6 @@
use url::Host;
use url::Url;
mod chatgpt_cloudflare_cookies;
mod chatgpt_hosts;
mod chatgpt_routing_affinity;
mod client;
mod client_builder;
mod client_tls;
@@ -24,9 +21,6 @@ mod route_aware_redirect;
mod tls_backend_fallback;
mod transport;
pub use crate::chatgpt_cloudflare_cookies::with_chatgpt_cloudflare_cookie_store;
pub use crate::chatgpt_hosts::is_allowed_chatgpt_host;
pub use crate::chatgpt_routing_affinity::ChatGptRoutingAffinity;
pub use crate::client::HttpClient;
pub use crate::client::HttpError;
pub use crate::client_builder::HttpClientBuilder;
@@ -52,6 +46,7 @@ pub use crate::network_policy::NetworkPolicyDenied;
pub use crate::network_policy::NetworkPolicyRevision;
pub use crate::openai_endpoints::OpenAiDestination;
pub use crate::openai_endpoints::classify_openai_api_url;
pub use crate::openai_endpoints::is_allowed_chatgpt_host;
pub use crate::openai_endpoints::is_openai_api_url;
pub use crate::openai_headers::CHATGPT_ACCOUNT_ID_HEADER;
pub use crate::openai_headers::OPENAI_ORGANIZATION_HEADER;

View File

@@ -1,7 +1,5 @@
//! Classify OpenAI API destinations without treating an unsupported origin as another provider.
use crate::is_allowed_chatgpt_host;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OpenAiDestination {
Supported,
@@ -67,6 +65,18 @@ pub fn classify_openai_api_url(destination: &str) -> OpenAiDestination {
}
}
/// Returns whether `host` is one of the ChatGPT hosts Codex is allowed to treat
/// as first-party ChatGPT HTTP traffic.
pub fn is_allowed_chatgpt_host(host: &str) -> bool {
const EXACT_HOSTS: &[&str] = &["chatgpt.com", "chat.openai.com", "chatgpt-staging.com"];
const SUBDOMAIN_SUFFIXES: &[&str] = &[".chatgpt.com", ".chatgpt-staging.com"];
EXACT_HOSTS.contains(&host)
|| SUBDOMAIN_SUFFIXES
.iter()
.any(|suffix| host.ends_with(suffix))
}
pub fn is_openai_api_url(destination: &str) -> bool {
classify_openai_api_url(destination) == OpenAiDestination::Supported
}
@@ -74,6 +84,7 @@ pub fn is_openai_api_url(destination: &str) -> bool {
#[cfg(test)]
mod tests {
use super::OpenAiDestination;
use super::is_allowed_chatgpt_host;
use super::classify_openai_api_url;
use super::is_openai_api_url;
@@ -152,4 +163,27 @@ mod tests {
assert!(!is_openai_api_url(destination), "{destination}");
}
}
#[test]
fn recognizes_chatgpt_hosts_without_suffix_tricks() {
for host in [
"chatgpt.com",
"foo.chatgpt.com",
"staging.chatgpt.com",
"chat.openai.com",
"chatgpt-staging.com",
"api.chatgpt-staging.com",
] {
assert!(is_allowed_chatgpt_host(host));
}
for host in [
"evilchatgpt.com",
"chatgpt.com.evil.example",
"api.openai.com",
"foo.chat.openai.com",
] {
assert!(!is_allowed_chatgpt_host(host));
}
}
}

View File

@@ -8,7 +8,6 @@ use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::io;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::time::Duration;
@@ -16,10 +15,7 @@ use std::time::Instant;
#[cfg(any(target_os = "windows", target_os = "macos"))]
use tokio::sync::Semaphore;
use http::HeaderValue;
use crate::NetworkPolicy;
use crate::chatgpt_cloudflare_cookies::ChatGptCookieStore;
use crate::custom_ca::BuildCustomCaTransportError;
use crate::custom_ca::build_reqwest_client_with_custom_ca;
use sha2::Digest;
@@ -168,7 +164,6 @@ pub struct HttpClientFactory {
outbound_proxy_policy: OutboundProxyPolicy,
system_proxy_fallback: bool,
protect_sensitive_headers: bool,
chatgpt_cookie_store: Option<Arc<ChatGptCookieStore>>,
network_policy: NetworkPolicy,
}
@@ -178,14 +173,6 @@ impl PartialEq for HttpClientFactory {
&& self.system_proxy_fallback == other.system_proxy_fallback
&& self.protect_sensitive_headers == other.protect_sensitive_headers
&& self.network_policy == other.network_policy
&& self
.chatgpt_cookie_store
.as_ref()
.map(|store| store.configured_cookies())
== other
.chatgpt_cookie_store
.as_ref()
.map(|store| store.configured_cookies())
}
}
@@ -209,7 +196,6 @@ impl HttpClientFactory {
outbound_proxy_policy,
system_proxy_fallback: false,
protect_sensitive_headers: false,
chatgpt_cookie_store: None,
network_policy: NetworkPolicy::unmanaged(),
}
}
@@ -236,7 +222,7 @@ impl HttpClientFactory {
&self.network_policy
}
/// Changes the route policy while retaining the configured cookies and network policy.
/// Changes the route policy while retaining the network policy.
pub fn with_outbound_proxy_policy(mut self, policy: OutboundProxyPolicy) -> Self {
self.outbound_proxy_policy = policy;
self
@@ -254,23 +240,6 @@ impl HttpClientFactory {
&& self.outbound_proxy_policy == OutboundProxyPolicy::ReqwestDefault
}
/// Adds process-scoped cookies to requests made by ChatGPT cookie-store clients.
pub fn with_chatgpt_cookies(mut self, cookies: impl IntoIterator<Item = HeaderValue>) -> Self {
let cookies = cookies.into_iter().collect::<Vec<_>>();
self.chatgpt_cookie_store =
(!cookies.is_empty()).then(|| Arc::new(ChatGptCookieStore::new(cookies)));
self
}
/// Returns whether ChatGPT cookie-store clients have additional configured cookies.
pub fn has_chatgpt_cookies(&self) -> bool {
self.chatgpt_cookie_store.is_some()
}
pub(crate) fn chatgpt_cookie_store(&self) -> Option<Arc<ChatGptCookieStore>> {
self.chatgpt_cookie_store.clone()
}
/// Returns the outbound proxy policy used for clients built by this factory.
pub const fn outbound_proxy_policy(&self) -> OutboundProxyPolicy {
self.outbound_proxy_policy

View File

@@ -122,28 +122,6 @@ fn read_http_message(stream: &mut impl Read) -> String {
String::from_utf8_lossy(&buffer).into_owned()
}
#[test]
fn cloned_factories_share_chatgpt_cookie_stores_without_changing_value_equality() {
let factory =
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault).with_chatgpt_cookies([
HeaderValue::from_static("first=true"),
HeaderValue::from_static("second=true"),
]);
let cloned = factory.clone();
assert!(Arc::ptr_eq(
&factory.chatgpt_cookie_store().expect("configured store"),
&cloned.chatgpt_cookie_store().expect("shared store"),
));
assert_eq!(
factory,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault).with_chatgpt_cookies([
HeaderValue::from_static("first=true"),
HeaderValue::from_static("second=true"),
])
);
}
#[test]
fn websocket_route_uses_http_equivalent_for_system_resolution() {
let env = MapEnv {

View File

@@ -308,7 +308,6 @@ impl RouteAwareClientPool {
) -> Result<Self, BuildRouteAwareHttpClientError> {
let mut pool = Self::with_builder(http_client_factory, route_class, client_builder);
let client = pool.client_builder_for_route().build_for_resolved_route(
&pool.http_client_factory,
pool.route_class,
&route,
)?;
@@ -385,77 +384,6 @@ impl RouteAwareClientPool {
self
}
/// Creates a pool that retains the Cloudflare cookies required by ChatGPT endpoints.
pub fn with_chatgpt_cloudflare_cookies(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
) -> Self {
Self::with_chatgpt_cloudflare_cookies_and_default_headers(
http_client_factory,
route_class,
HeaderMap::new(),
)
}
/// Creates a pool with ChatGPT Cloudflare cookies and default headers on every route.
pub fn with_chatgpt_cloudflare_cookies_and_default_headers(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
default_headers: HeaderMap,
) -> Self {
Self::with_builder(
http_client_factory,
route_class,
HttpClientBuilder::new()
.default_headers(default_headers)
.with_chatgpt_cloudflare_cookie_store(),
)
}
/// Creates a no-redirect pool that retains the Cloudflare cookies required by ChatGPT
/// endpoints.
pub fn with_chatgpt_cloudflare_cookies_without_redirects(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
) -> Self {
Self::with_builder(
http_client_factory,
route_class,
HttpClientBuilder::new()
.with_chatgpt_cloudflare_cookie_store()
.without_redirects(),
)
}
/// Creates a no-redirect ChatGPT Cloudflare-cookie pool without request diagnostics.
pub fn with_chatgpt_cloudflare_cookies_without_redirects_or_request_logging(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
) -> Self {
Self::with_builder(
http_client_factory,
route_class,
HttpClientBuilder::new()
.with_chatgpt_cloudflare_cookie_store()
.without_redirects()
.without_request_logging(),
)
}
/// Creates a ChatGPT Cloudflare-cookie pool without URL or response-header diagnostics.
pub fn with_chatgpt_cloudflare_cookies_without_request_logging(
http_client_factory: HttpClientFactory,
route_class: ClientRouteClass,
) -> Self {
Self::with_builder(
http_client_factory,
route_class,
HttpClientBuilder::new()
.with_chatgpt_cloudflare_cookie_store()
.without_request_logging(),
)
}
pub fn get<U>(&self, url: U) -> RequestBuilder
where
U: IntoUrl,
@@ -561,7 +489,6 @@ impl RouteAwareClientPool {
OutboundProxyPolicy::RespectSystemProxy,
CustomCaFallback::LegacyTransportDefault,
) => client_builder.build_for_resolved_route(
&pool.http_client_factory,
pool.route_class,
&build_route,
),
@@ -608,7 +535,7 @@ impl RouteAwareClientPool {
client_builder = client_builder.without_redirects();
}
client_builder
.build_for_resolved_route(&self.http_client_factory, self.route_class, route)
.build_for_resolved_route(self.route_class, route)
.map_err(Into::into)
}
}

View File

@@ -360,7 +360,7 @@ impl RouteAwareClientPool {
builder = builder.with_rustls_tls();
}
builder
.build_for_resolved_route(&self.http_client_factory, self.route_class, route)
.build_for_resolved_route(self.route_class, route)
.map_err(Into::into)
}
}

View File

@@ -414,7 +414,7 @@ async fn legacy_custom_ca_fallback_is_limited_to_reqwest_default() {
"respect-system-proxy" => OutboundProxyPolicy::RespectSystemProxy,
_ => panic!("unexpected test proxy policy: {policy_name}"),
};
let pool = RouteAwareClientPool::with_chatgpt_cloudflare_cookies(
let pool = RouteAwareClientPool::new(
HttpClientFactory::new(outbound_proxy_policy),
ClientRouteClass::Other,
);
@@ -541,7 +541,6 @@ async fn cached_tls_backend_only_changes_its_destination_and_route() {
let fallback_client = HttpClientBuilder::new()
.with_rustls_tls()
.build_for_resolved_route(
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ClientRouteClass::Api,
&OutboundProxyRoute::Direct,
)

View File

@@ -207,7 +207,6 @@ fn direct_rustls_client() -> crate::client::TransportClient {
HttpClientBuilder::new()
.with_rustls_tls()
.build_for_resolved_route(
&crate::HttpClientFactory::new(crate::OutboundProxyPolicy::ReqwestDefault),
crate::ClientRouteClass::Api,
&OutboundProxyRoute::Direct,
)