pub mod chatgpt;
pub mod claude;
mod loopback;
mod pkce;
mod store;
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use crate::catalog::ApiStyle;
use crate::{ClientBuilder, Error, OAuthTokenProvider};
pub use loopback::Catcher;
pub use pkce::Pkce;
pub use store::{now, Credentials, Store, Tokens};
const REFRESH_INTERVAL: i64 = 30;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Subscription {
ChatGpt,
Claude,
}
impl Subscription {
pub const ALL: [Subscription; 2] = [Subscription::ChatGpt, Subscription::Claude];
pub fn parse(provider: &str) -> Option<Self> {
match provider.trim().to_ascii_lowercase().as_str() {
"chatgpt" | "codex" => Some(Self::ChatGpt),
"claude" => Some(Self::Claude),
_ => None,
}
}
pub fn id(self) -> &'static str {
match self {
Self::ChatGpt => "chatgpt",
Self::Claude => "claude",
}
}
pub fn name(self) -> &'static str {
match self {
Self::ChatGpt => "ChatGPT subscription",
Self::Claude => "Claude subscription",
}
}
pub fn metered_provider(self) -> &'static str {
match self {
Self::ChatGpt => "openai",
Self::Claude => "anthropic",
}
}
pub fn default_model(self) -> &'static str {
crate::catalog::provider(self.metered_provider())
.map(|spec| spec.default_model)
.unwrap_or_default()
}
pub fn system_prefix(self) -> Option<&'static str> {
match self {
Self::ChatGpt => None,
Self::Claude => Some(claude::SYSTEM_PREFIX),
}
}
pub fn accepts_output_limit(self) -> bool {
self != Self::ChatGpt
}
pub fn port(self) -> u16 {
match self {
Self::ChatGpt => chatgpt::REDIRECT_PORT,
Self::Claude => claude::REDIRECT_PORT,
}
}
pub fn signed_in(self, store: &Store) -> bool {
store.load().tokens(self.id()).is_some()
}
pub fn login(self, app: impl Into<String>) -> Login {
Login {
subscription: self,
app: app.into(),
timeout: Duration::from_secs(300),
}
}
pub fn logout(self, store: &Store) -> crate::Result<()> {
store.put_tokens(self.id(), None)
}
pub fn session(self, store: &Store, tokens: Tokens) -> Arc<Session> {
session(self, store, tokens)
}
pub fn client(self, session: Arc<Session>, model: impl Into<String>) -> ClientBuilder {
match self {
Self::ChatGpt => {
ClientBuilder::custom(self.id(), ApiStyle::Responses, chatgpt::API_URL, model)
.accepts_output_limit(false)
.header("chatgpt-account-id", session.account_id())
.header("openai-beta", "responses=experimental")
.header("originator", chatgpt::ORIGINATOR)
.header("session_id", session_id())
.oauth(session)
}
Self::Claude => {
ClientBuilder::custom(self.id(), ApiStyle::Anthropic, claude::API_URL, model)
.header("anthropic-beta", claude::BETA_HEADER)
.oauth(session)
}
}
}
fn authorize_url(self, pkce: &Pkce) -> String {
match self {
Self::ChatGpt => chatgpt::authorize_url(&pkce.challenge, &pkce.state),
Self::Claude => claude::authorize_url(&pkce.challenge, &pkce.verifier),
}
}
fn expected_state(self, pkce: &Pkce) -> &str {
match self {
Self::ChatGpt => &pkce.state,
Self::Claude => &pkce.verifier,
}
}
fn exchange(self, code: &str, verifier: &str) -> crate::Result<Tokens> {
match self {
Self::ChatGpt => chatgpt::exchange(code, verifier),
Self::Claude => claude::exchange(code, verifier),
}
}
fn refresh(self, current: &Tokens) -> crate::Result<Tokens> {
match self {
Self::ChatGpt => chatgpt::refresh(current),
Self::Claude => claude::refresh(current),
}
}
}
pub struct Login {
subscription: Subscription,
app: String,
timeout: Duration,
}
impl Login {
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn run(
&self,
store: &Store,
announce: &dyn Fn(&str),
cancel: &AtomicBool,
) -> crate::Result<Tokens> {
let subscription = self.subscription;
let pkce = Pkce::generate()?;
let catcher = Catcher::bind(subscription.port(), &self.app)?;
let url = subscription.authorize_url(&pkce);
announce(&url);
open_browser(&url);
let params = catcher.wait(self.timeout, cancel)?;
if let Some(error) = params.get("error") {
let detail = params
.get("error_description")
.map(|detail| format!(" ({detail})"))
.unwrap_or_default();
return Err(Error::Auth(format!(
"authorization denied: {error}{detail}"
)));
}
if params.get("state").map(String::as_str) != Some(subscription.expected_state(&pkce)) {
return Err(Error::Auth(
"state mismatch on the OAuth redirect; aborting".into(),
));
}
let code = params
.get("code")
.ok_or_else(|| Error::Auth("no authorization code in the redirect".into()))?;
let tokens = subscription
.exchange(code, &pkce.verifier)
.map_err(rate_limit_hint)?;
store.put_tokens(subscription.id(), Some(tokens.clone()))?;
Ok(tokens)
}
}
fn rate_limit_hint(error: Error) -> Error {
let text = error.to_string();
if text.contains("429") || text.contains("rate_limit") {
Error::RateLimited {
message: "the sign-in endpoint is rate limiting. Wait a minute or two and try again; \
repeated sign-in attempts make it last longer."
.into(),
retry_after: Some(Duration::from_secs(60)),
}
} else {
error
}
}
pub fn open_browser(url: &str) {
#[cfg(windows)]
let spawned = std::process::Command::new("rundll32.exe")
.args(["url.dll,FileProtocolHandler", url])
.spawn();
#[cfg(target_os = "macos")]
let spawned = std::process::Command::new("open").arg(url).spawn();
#[cfg(all(unix, not(target_os = "macos")))]
let spawned = std::process::Command::new("xdg-open").arg(url).spawn();
let _ = spawned;
}
pub fn session_id() -> String {
let mut bytes = [0u8; 16];
if getrandom::getrandom(&mut bytes).is_err() {
bytes.copy_from_slice(&(now() as u128).to_le_bytes());
}
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32]
)
}
fn post(url: &str, content_type: &str, body: &str) -> crate::Result<String> {
let agent = ureq::AgentBuilder::new()
.timeout_connect(Duration::from_secs(20))
.timeout_read(Duration::from_secs(60))
.build();
match agent
.post(url)
.set("content-type", content_type)
.set("accept", "application/json")
.send_string(body)
{
Ok(response) => response
.into_string()
.map_err(|error| Error::Decode(format!("reading token response: {error}"))),
Err(ureq::Error::Status(status, response)) => {
let detail = response.into_string().unwrap_or_default();
Err(Error::Auth(format!(
"token endpoint returned HTTP {status}: {}",
detail.trim()
)))
}
Err(error) => Err(Error::Network(format!("token request failed: {error}"))),
}
}
fn post_form(url: &str, body: &str) -> crate::Result<String> {
post(url, "application/x-www-form-urlencoded", body)
}
fn post_json(url: &str, body: &str) -> crate::Result<String> {
post(url, "application/json", body)
}
pub struct Session {
subscription: Subscription,
store: Store,
tokens: Mutex<Tokens>,
last_refresh: Mutex<i64>,
}
pub fn session(subscription: Subscription, store: &Store, tokens: Tokens) -> Arc<Session> {
static SESSIONS: OnceLock<Mutex<HashMap<String, Arc<Session>>>> = OnceLock::new();
let sessions = SESSIONS.get_or_init(|| Mutex::new(HashMap::new()));
let mut sessions = match sessions.lock() {
Ok(sessions) => sessions,
Err(poisoned) => poisoned.into_inner(),
};
let key = format!("{}@{}", subscription.id(), store.path().display());
match sessions.get(&key) {
Some(existing) => {
existing.adopt(tokens);
Arc::clone(existing)
}
None => {
let session = Arc::new(Session::new(subscription, store.clone(), tokens));
sessions.insert(key, Arc::clone(&session));
session
}
}
}
impl Session {
pub fn new(subscription: Subscription, store: Store, tokens: Tokens) -> Self {
Self {
subscription,
store,
tokens: Mutex::new(tokens),
last_refresh: Mutex::new(0),
}
}
pub fn subscription(&self) -> Subscription {
self.subscription
}
pub fn account_id(&self) -> String {
self.tokens
.lock()
.map(|tokens| tokens.account_id.clone())
.unwrap_or_default()
}
fn adopt(&self, tokens: Tokens) {
if let Ok(mut held) = self.tokens.lock() {
if tokens.expires_at > held.expires_at {
*held = tokens;
}
}
}
fn renew(&self) -> crate::Result<String> {
let mut last = self
.last_refresh
.lock()
.map_err(|_| Error::Auth("token store poisoned".into()))?;
let since = now() - *last;
if since < REFRESH_INTERVAL {
return Err(Error::RateLimited {
message: format!("refreshed {since}s ago; waiting before asking again"),
retry_after: Some(Duration::from_secs((REFRESH_INTERVAL - since) as u64)),
});
}
*last = now();
drop(last);
let current = self
.tokens
.lock()
.map_err(|_| Error::Auth("token store poisoned".into()))?
.clone();
let fresh = self
.subscription
.refresh(¤t)
.map_err(rate_limit_hint)?;
self.store
.put_tokens(self.subscription.id(), Some(fresh.clone()))?;
let access = fresh.access_token.clone();
*self
.tokens
.lock()
.map_err(|_| Error::Auth("token store poisoned".into()))? = fresh;
Ok(access)
}
}
impl OAuthTokenProvider for Session {
fn access_token(&self) -> std::result::Result<String, String> {
let current = self
.tokens
.lock()
.map_err(|_| "token store poisoned".to_string())?
.clone();
if current.expired() {
if let Ok(access) = self.renew() {
return Ok(access);
}
}
Ok(current.access_token)
}
fn refresh_access_token(&self) -> std::result::Result<String, String> {
self.renew().map_err(|error| {
format!(
"{} sign-in expired and could not be refreshed ({error}). Sign in to {} again.",
self.subscription.name(),
self.subscription.id()
)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn subscription_ids_and_aliases_resolve() {
assert_eq!(Subscription::parse("chatgpt"), Some(Subscription::ChatGpt));
assert_eq!(Subscription::parse("Codex"), Some(Subscription::ChatGpt));
assert_eq!(Subscription::parse("claude"), Some(Subscription::Claude));
assert_eq!(Subscription::parse("openai"), None);
assert_eq!(Subscription::parse("anthropic"), None);
}
#[test]
fn each_subscription_names_the_metered_provider_behind_it() {
assert_eq!(Subscription::ChatGpt.metered_provider(), "openai");
assert_eq!(Subscription::Claude.metered_provider(), "anthropic");
assert!(!Subscription::Claude.default_model().is_empty());
}
#[test]
fn each_flow_checks_the_state_value_it_actually_sends() {
let pkce = Pkce::generate().unwrap();
assert_eq!(Subscription::ChatGpt.expected_state(&pkce), pkce.state);
assert_eq!(Subscription::Claude.expected_state(&pkce), pkce.verifier);
assert!(Subscription::Claude
.authorize_url(&pkce)
.contains(&pkce::encode(&pkce.verifier)));
}
#[test]
fn the_two_routes_use_different_loopback_ports() {
assert_ne!(Subscription::ChatGpt.port(), Subscription::Claude.port());
}
#[test]
fn only_the_claude_route_carries_a_required_system_prefix() {
assert!(Subscription::ChatGpt.system_prefix().is_none());
assert!(Subscription::Claude.system_prefix().is_some());
assert!(!Subscription::ChatGpt.accepts_output_limit());
assert!(Subscription::Claude.accepts_output_limit());
}
#[test]
fn session_ids_look_like_version_four_uuids() {
let id = session_id();
let fields: Vec<&str> = id.split('-').collect();
assert_eq!(
fields.iter().map(|field| field.len()).collect::<Vec<_>>(),
vec![8, 4, 4, 4, 12]
);
assert!(fields[2].starts_with('4'));
assert!(id.chars().all(|ch| ch.is_ascii_hexdigit() || ch == '-'));
assert_ne!(session_id(), id);
}
#[test]
fn a_session_hands_over_the_token_it_holds() {
let session = Session::new(
Subscription::Claude,
Store::at(std::env::temp_dir().join("modelbridge-unused.json")),
Tokens {
access_token: "at".into(),
..Tokens::default()
},
);
assert_eq!(session.access_token().unwrap(), "at");
}
#[test]
fn a_second_refresh_within_the_interval_is_refused_rather_than_sent() {
let session = Session::new(
Subscription::Claude,
Store::at(std::env::temp_dir().join("modelbridge-unused.json")),
Tokens {
access_token: "at".into(),
refresh_token: "rt".into(),
..Tokens::default()
},
);
*session.last_refresh.lock().unwrap() = now();
assert!(matches!(session.renew(), Err(Error::RateLimited { .. })));
}
#[test]
fn a_subscription_client_carries_its_required_headers() {
let store = Store::at(std::env::temp_dir().join("modelbridge-unused.json"));
let session = Arc::new(Session::new(
Subscription::Claude,
store,
Tokens {
access_token: "at".into(),
..Tokens::default()
},
));
let client = Subscription::Claude
.client(session, "claude-sonnet-5")
.build()
.unwrap();
assert_eq!(client.provider(), "claude");
assert_eq!(client.model(), "claude-sonnet-5");
}
#[test]
fn the_chatgpt_route_sends_no_output_limit_even_when_a_request_names_one() {
fn client_for(subscription: Subscription, model: &str) -> crate::Client {
let session = Arc::new(Session::new(
subscription,
Store::at(std::env::temp_dir().join("modelbridge-unused.json")),
Tokens {
access_token: "at".into(),
..Tokens::default()
},
));
subscription.client(session, model).build().unwrap()
}
let request = crate::Request::new("Be brief")
.user("hello")
.max_output_tokens(420);
let body = client_for(Subscription::ChatGpt, "gpt-5.6-luna").request_body(&request);
assert!(
body["max_output_tokens"].is_null(),
"the Codex backend would reject this body: {body}"
);
let body = client_for(Subscription::Claude, "claude-sonnet-5").request_body(&request);
assert_eq!(body["max_tokens"], 420, "every other route stays capped");
}
}