//! Subscription OAuth (Claude Pro/Max, ChatGPT Plus/Pro). No API keys. //! //! Credentials live in `~/.hx/auth.json` (0600). Existing Claude Code / Codex CLI logins are imported. use crate::{Error, Result}; use base64::Engine; use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; use serde::{Deserialize, Serialize}; use serde_json::Value; use sha2::{Digest, Sha256}; use std::collections::BTreeMap; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::sync::Mutex; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Kind { Claude, Codex, /// OpenAI-compatible endpoint from config; no OAuth. Custom, } impl std::str::FromStr for Kind { type Err = String; fn from_str(s: &str) -> std::result::Result { match s { "claude" | "anthropic" => Ok(Kind::Claude), "codex" | "openai" | "chatgpt" => Ok(Kind::Codex), "custom" | "openai-compat" | "local" => Ok(Kind::Custom), _ => Err(format!("unknown provider {s:?} (claude|codex|custom)")), } } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Credential { pub access: String, pub refresh: String, /// unix ms pub expires: u64, #[serde(default, skip_serializing_if = "Option::is_none")] pub account_id: Option, } struct Oauth { client_id: &'static str, authorize: &'static str, token: &'static str, redirect: &'static str, port: u16, path: &'static str, scope: &'static str, } const CLAUDE: Oauth = Oauth { client_id: "9d1c250a-e61b-44d9-88ed-5944d1962f5e", authorize: "https://claude.ai/oauth/authorize", token: "https://platform.claude.com/v1/oauth/token", redirect: "http://localhost:53692/callback", port: 53692, path: "/callback", scope: "org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload", }; const CODEX: Oauth = Oauth { client_id: "app_EMoamEEZ73f0CkXaXp7hrann", authorize: "https://auth.openai.com/oauth/authorize", token: "https://auth.openai.com/oauth/token", redirect: "http://localhost:1455/auth/callback", port: 1455, path: "/auth/callback", scope: "openid profile email offline_access", }; fn cfg(k: Kind) -> &'static Oauth { match k { Kind::Claude => &CLAUDE, Kind::Codex => &CODEX, Kind::Custom => unreachable!("custom provider has no OAuth"), } } pub fn now_ms() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_millis() as u64) .unwrap_or(0) } fn home() -> PathBuf { std::env::var_os("HOME") .map(PathBuf::from) .unwrap_or_default() } pub fn store_path() -> PathBuf { std::env::var_os("HX_HOME") .map(PathBuf::from) .unwrap_or_else(|| home().join(".hx")) .join("auth.json") } type Store = BTreeMap; fn load_store() -> Store { load_at(&store_path()) } fn load_at(p: &std::path::Path) -> Store { std::fs::read(p) .ok() .and_then(|b| serde_json::from_slice(&b).ok()) .unwrap_or_default() } fn save(k: Kind, c: &Credential) -> Result<()> { save_at(&store_path(), k, Some(c)) } fn save_at(p: &std::path::Path, k: Kind, c: Option<&Credential>) -> Result<()> { let mut s = load_at(p); match c { Some(c) => s.insert(k, c.clone()), None => s.remove(&k), }; let io = |e: std::io::Error| Error::Http(format!("{}: {e}", p.display())); std::fs::create_dir_all(p.parent().unwrap_or(p)).map_err(io)?; let tmp = p.with_extension("tmp"); std::fs::write(&tmp, serde_json::to_vec_pretty(&s).unwrap_or_default()).map_err(io)?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600)).map_err(io)?; } std::fs::rename(&tmp, p).map_err(io) } /// Pull an existing login from Claude Code / Codex CLI. fn import(k: Kind) -> Option { match k { Kind::Custom => None, Kind::Claude => { let v: Value = serde_json::from_slice( &std::fs::read(home().join(".claude/.credentials.json")).ok()?, ) .ok()?; let o = &v["claudeAiOauth"]; Some(Credential { access: o["accessToken"].as_str()?.into(), refresh: o["refreshToken"].as_str()?.into(), expires: o["expiresAt"].as_u64().unwrap_or(0), account_id: None, }) } Kind::Codex => { let codex = std::env::var_os("CODEX_HOME") .map(PathBuf::from) .unwrap_or_else(|| home().join(".codex")); let v: Value = serde_json::from_slice(&std::fs::read(codex.join("auth.json")).ok()?).ok()?; let t = &v["tokens"]; let access = t["access_token"].as_str()?; Some(Credential { access: access.into(), refresh: t["refresh_token"].as_str()?.into(), // unknown: force refresh on first use if the JWT says expired expires: jwt_claims(access) .and_then(|c| c["exp"].as_u64()) .map(|s| s * 1000) .unwrap_or(0), account_id: t["account_id"] .as_str() .map(Into::into) .or_else(|| account_id(access)), }) } } } pub fn jwt_claims(tok: &str) -> Option { let p = tok.split('.').nth(1)?; let b = URL_SAFE_NO_PAD .decode(p.trim_end_matches('=')) .or_else(|_| STANDARD.decode(p)) .ok()?; serde_json::from_slice(&b).ok() } pub fn account_id(tok: &str) -> Option { jwt_claims(tok)?["https://api.openai.com/auth"]["chatgpt_account_id"] .as_str() .map(Into::into) } pub fn pkce() -> (String, String) { let mut b = [0u8; 32]; getrandom::fill(&mut b).expect("os rng"); let verifier = URL_SAFE_NO_PAD.encode(b); let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); (verifier, challenge) } #[derive(Deserialize)] struct TokenResp { access_token: String, refresh_token: Option, expires_in: u64, } async fn token_req(k: Kind, form: &[(&str, &str)]) -> Result { let c = cfg(k); let rb = reqwest::Client::new().post(c.token); // Anthropic wants JSON, OpenAI wants form encoding. let rb = match k { Kind::Claude => rb.json(&form.iter().cloned().collect::>()), Kind::Codex | Kind::Custom => rb.form(form), }; let r = rb.send().await.map_err(|e| Error::Http(e.to_string()))?; let status = r.status().as_u16(); let body = r.text().await.map_err(|e| Error::Http(e.to_string()))?; if !(200..300).contains(&status) { return Err(Error::Api { status, body }); } let t: TokenResp = serde_json::from_str(&body).map_err(|e| Error::Decode(e.to_string()))?; let refresh = t .refresh_token .or_else(|| { form.iter() .find(|(k, _)| *k == "refresh_token") .map(|(_, v)| v.to_string()) }) .ok_or_else(|| Error::Decode("no refresh_token".into()))?; Ok(Credential { account_id: account_id(&t.access_token), access: t.access_token, refresh, // refresh 5 min early expires: now_ms() + t.expires_in.saturating_mul(1000).saturating_sub(300_000), }) } pub async fn refresh(k: Kind, cred: &Credential) -> Result { let mut c = token_req( k, &[ ("grant_type", "refresh_token"), ("client_id", cfg(k).client_id), ("refresh_token", &cred.refresh), ], ) .await?; if c.account_id.is_none() { c.account_id = cred.account_id.clone(); } Ok(c) } /// Percent-decode `%XX` (UTF-8, invalid escapes kept as-is); `+` stays `+` (codes may contain it). pub fn urldec(s: &str) -> String { let b = s.as_bytes(); let mut out = Vec::with_capacity(b.len()); let mut i = 0; while i < b.len() { let hex = |c: u8| (c as char).to_digit(16); match ( b[i], b.get(i + 1).and_then(|&c| hex(c)), b.get(i + 2).and_then(|&c| hex(c)), ) { (b'%', Some(h), Some(l)) => { out.push((h * 16 + l) as u8); i += 3; } (c, ..) => { out.push(c); i += 1; } } } String::from_utf8_lossy(&out).into_owned() } /// Accepts a full redirect URL, `code#state`, a query string, or a bare code. pub fn parse_code(input: &str) -> (Option, Option) { let v = input.trim(); let q = v.split_once('?').map(|(_, q)| q).unwrap_or(v); if q.contains("code=") { let get = |key: &str| { q.split(['&', '#']) .find_map(|kv| kv.strip_prefix(&format!("{key}="))) .map(urldec) }; return (get("code"), get("state")); } match v.split_once('#') { Some((c, s)) => (Some(c.into()), Some(s.into())), None if v.is_empty() => (None, None), None => (Some(v.into()), None), } } /// Wait for the browser redirect on localhost, or for the user to paste the redirect URL on stdin. async fn await_code(c: &Oauth) -> Result { let listener = tokio::net::TcpListener::bind(("127.0.0.1", c.port)) .await .ok(); await_redirect(listener, c.path).await } /// Like the login wait, on a caller-bound listener (`None` = paste only). Returns the redirect request target. pub async fn await_redirect( listener: Option, path: &str, ) -> Result { // Detached std thread: tokio's stdin would block runtime shutdown until a line arrives. let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); std::thread::spawn(move || { for l in std::io::stdin().lines() { if tx.send(l).is_err() { break; } } }); let mut stdin_open = true; loop { tokio::select! { acc = async { listener.as_ref().unwrap().accept().await }, if listener.is_some() => { let Ok((mut s, _)) = acc else { continue }; let mut buf = vec![0u8; 8192]; let n = s.read(&mut buf).await.unwrap_or(0); let req = String::from_utf8_lossy(&buf[..n]); let target = req.split_whitespace().nth(1).unwrap_or(""); if !target.starts_with(path) { let _ = s.write_all(b"HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\n\r\n").await; continue; } let _ = s.write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\nconnection: close\r\n\r\nhx: login complete, you can close this tab.").await; return Ok(target.to_string()); } line = rx.recv(), if stdin_open => match line { Some(Ok(l)) if !l.trim().is_empty() => return Ok(l), Some(Ok(_)) => continue, // stdin closed (non-interactive): keep waiting for the browser redirect if we can _ if listener.is_some() => stdin_open = false, _ => return Err(Error::Http("login cancelled".into())), } } } } /// Percent-encode everything except RFC 3986 unreserved characters. pub fn urlenc(s: &str) -> String { s.bytes() .map(|b| match b { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { (b as char).to_string() } _ => format!("%{b:02X}"), }) .collect() } pub fn authorize_url(k: Kind, challenge: &str, state: &str) -> String { let c = cfg(k); let mut p = vec![ ("response_type", "code"), ("client_id", c.client_id), ("redirect_uri", c.redirect), ("scope", c.scope), ("code_challenge", challenge), ("code_challenge_method", "S256"), ("state", state), ]; match k { Kind::Claude => p.insert(0, ("code", "true")), Kind::Codex | Kind::Custom => p.extend([ ("id_token_add_organizations", "true"), ("codex_cli_simplified_flow", "true"), ("originator", "hx"), ]), } let qs: Vec = p .iter() .map(|(k, v)| format!("{k}={}", urlenc(v))) .collect(); format!("{}?{}", c.authorize, qs.join("&")) } /// Interactive browser login. Prints the URL to stderr. pub async fn login(k: Kind) -> Result { if k == Kind::Custom { let key = read_secret("API key for [openai_compat]: ")?; let cred = Credential { access: key, refresh: String::new(), expires: u64::MAX, account_id: None, }; save(k, &cred)?; return Ok(cred); } let c = cfg(k); let (verifier, challenge) = pkce(); // Claude uses the verifier as state (matches Claude Code); Codex uses a random state. let state = match k { Kind::Claude => verifier.clone(), Kind::Codex | Kind::Custom => pkce().0, }; eprintln!( "Open this URL to log in:\n\n{}\n\nWaiting for redirect on {} (or paste the final redirect URL / code here):", authorize_url(k, &challenge, &state), c.redirect ); let (code, got_state) = parse_code(&await_code(c).await?); if got_state.as_deref().is_some_and(|s| s != state) { return Err(Error::Http("OAuth state mismatch".into())); } let code = code.ok_or_else(|| Error::Http("missing authorization code".into()))?; let mut form = vec![ ("grant_type", "authorization_code"), ("client_id", c.client_id), ("code", code.as_str()), ("redirect_uri", c.redirect), ("code_verifier", verifier.as_str()), ]; if k == Kind::Claude { form.push(("state", state.as_str())); } let cred = token_req(k, &form).await?; if k == Kind::Codex && cred.account_id.is_none() { return Err(Error::Decode("no chatgpt_account_id in token".into())); } save(k, &cred)?; Ok(cred) } /// One line from stdin, echo off when stdin is a terminal. fn read_secret(prompt: &str) -> Result { use std::io::{BufRead, IsTerminal, Write}; let tty = std::io::stdin().is_terminal(); let stty = |arg| { let _ = std::process::Command::new("stty").arg(arg).status(); }; eprint!("{prompt}"); let _ = std::io::stderr().flush(); if tty { stty("-echo"); } let mut s = String::new(); let r = std::io::stdin().lock().read_line(&mut s); if tty { stty("echo"); eprintln!(); } r.map_err(|e| Error::Http(e.to_string()))?; let s = s.trim().to_string(); if s.is_empty() { return Err(Error::Http("empty key".into())); } Ok(s) } /// API key saved by `hx login custom`. pub fn stored_key() -> Option { load_store().remove(&Kind::Custom).map(|c| c.access) } pub fn logout(k: Kind) -> Result<()> { save_at(&store_path(), k, None) } /// Holds one credential, refreshing it when near expiry. pub struct Auth { kind: Kind, cred: Mutex, } impl Auth { /// From `~/.hx/auth.json`, else imported from Claude Code / Codex CLI. pub fn load(kind: Kind) -> Result { let cred = load_store() .remove(&kind) .or_else(|| import(kind)) .ok_or_else(|| { Error::Http(format!( "not logged in to {kind:?}; run `hx login {}`", format!("{kind:?}").to_lowercase() )) })?; Ok(Self::new(kind, cred)) } pub fn new(kind: Kind, cred: Credential) -> Self { Self { kind, cred: Mutex::new(cred), } } /// Fresh access token (+ account id for Codex). pub async fn token(&self) -> Result<(String, Option)> { let mut c = self.cred.lock().await; if c.expires <= now_ms() + 60_000 { *c = refresh(self.kind, &c).await?; save(self.kind, &c)?; } Ok((c.access.clone(), c.account_id.clone())) } } #[cfg(test)] mod tests { use super::*; #[test] fn pkce_shape() { let (v, c) = pkce(); assert_eq!(v.len(), 43); assert_eq!(c.len(), 43); assert_ne!(v, pkce().0); } #[test] fn parse_inputs() { assert_eq!( parse_code("http://localhost:1455/auth/callback?code=abc&state=xyz"), (Some("abc".into()), Some("xyz".into())) ); assert_eq!( parse_code("/callback?code=a&state=b"), (Some("a".into()), Some("b".into())) ); assert_eq!( parse_code("abc#xyz"), (Some("abc".into()), Some("xyz".into())) ); assert_eq!(parse_code(" abc "), (Some("abc".into()), None)); assert_eq!(parse_code(""), (None, None)); } #[test] fn code_is_fully_decoded() { assert_eq!( parse_code("/callback?code=a%3Ab%2Fc%2Bd+e%25&state=s%3D"), (Some("a:b/c+d+e%".into()), Some("s=".into())) ); assert_eq!(urldec("100%"), "100%"); } #[test] fn jwt_account() { let p = URL_SAFE_NO_PAD .encode(br#"{"https://api.openai.com/auth":{"chatgpt_account_id":"acc_1"},"exp":10}"#); let t = format!("h.{p}.s"); assert_eq!(account_id(&t).as_deref(), Some("acc_1")); assert_eq!(jwt_claims(&t).unwrap()["exp"], 10); assert_eq!(account_id("nope"), None); } #[test] fn url_has_params() { let u = authorize_url(Kind::Codex, "CH", "ST"); assert!(u.starts_with("https://auth.openai.com/oauth/authorize?")); assert!(u.contains("code_challenge=CH") && u.contains("state=ST")); assert!(u.contains("redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback")); let u = authorize_url(Kind::Claude, "CH", "ST"); assert!(u.contains("code=true") && u.contains("user%3Ainference")); } #[test] fn store_roundtrip() { let p = std::env::temp_dir().join(format!("hx-auth-{}/auth.json", now_ms())); let c = Credential { access: "a".into(), refresh: "r".into(), expires: 1, account_id: None, }; save_at(&p, Kind::Claude, Some(&c)).unwrap(); assert_eq!(load_at(&p).get(&Kind::Claude), Some(&c)); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; assert_eq!( std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600 ); } save_at(&p, Kind::Claude, None).unwrap(); assert!(load_at(&p).is_empty()); } }