1use cpa_core::gostr::GoStr;
9use std::collections::{BTreeMap, HashMap};
10use std::path::{Path, PathBuf};
11use std::sync::{Arc, Mutex};
12use std::time::{Duration, Instant};
13
14use base64::Engine;
15use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
16use chrono::{DateTime, Local, SecondsFormat, Utc};
17use cpa_core::credential::{Credential, MetadataPatch};
18use cpa_core::exec::{ExecError, FailureScope};
19use futures_util::FutureExt;
20use futures_util::future::{BoxFuture, Shared};
21use serde::Deserialize;
22use serde_json::{Map, Value, json};
23use sha2::{Digest, Sha256};
24use tokio::io::{AsyncReadExt, AsyncWriteExt};
25use url::Url;
26
27pub const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
28pub const AUTH_URL: &str = "https://auth.openai.com/oauth/authorize";
29pub const TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
30pub const DEFAULT_CALLBACK_PORT: u16 = 1455;
31pub const DEVICE_USERCODE_URL: &str = "https://auth.openai.com/api/accounts/deviceauth/usercode";
32pub const DEVICE_TOKEN_URL: &str = "https://auth.openai.com/api/accounts/deviceauth/token";
33pub const DEVICE_VERIFICATION_URL: &str = "https://auth.openai.com/codex/device";
34const DEVICE_REDIRECT_URI: &str = "https://auth.openai.com/deviceauth/callback";
35const DEFAULT_PLAN: &str = "free";
36pub const REFRESH_LEAD: chrono::TimeDelta = chrono::TimeDelta::hours(96);
39
40pub fn redirect_uri(port: u16) -> String {
41 format!("http://localhost:{port}/auth/callback")
42}
43
44#[derive(Debug, Clone, Default, PartialEq, Eq)]
46pub struct Claims {
47 pub email: String,
48 pub account_id: String,
49 pub plan: String,
51}
52
53impl Claims {
54 pub fn plan_type(&self) -> String {
56 match self.plan.trim() {
57 "" => DEFAULT_PLAN.into(),
58 plan => plan.into(),
59 }
60 }
61}
62
63pub fn parse_jwt(token: &str) -> Option<Claims> {
67 #[derive(Deserialize, Default)]
68 #[serde(default)]
69 #[allow(dead_code)]
70 struct Org {
71 id: Option<String>,
72 is_default: Option<bool>,
73 role: Option<String>,
74 title: Option<String>,
75 }
76 #[derive(Deserialize, Default)]
77 #[serde(default)]
78 #[allow(dead_code)]
79 struct AuthInfo {
80 chatgpt_account_id: Option<String>,
81 chatgpt_plan_type: Option<String>,
82 chatgpt_subscription_last_checked: Option<String>,
83 chatgpt_user_id: Option<String>,
84 groups: Option<Vec<Value>>,
85 organizations: Option<Vec<Org>>,
86 user_id: Option<String>,
87 }
88 #[derive(Deserialize, Default)]
89 #[serde(default)]
90 #[allow(dead_code)]
91 struct Raw {
92 at_hash: Option<String>,
93 aud: Option<Vec<String>>,
94 auth_provider: Option<String>,
95 auth_time: Option<i64>,
96 email: Option<String>,
97 email_verified: Option<bool>,
98 exp: Option<i64>,
99 #[serde(rename = "https://api.openai.com/auth")]
100 auth: Option<AuthInfo>,
101 iat: Option<i64>,
102 iss: Option<String>,
103 jti: Option<String>,
104 rat: Option<i64>,
105 sid: Option<String>,
106 sub: Option<String>,
107 }
108 let parts: Vec<&str> = token.split('.').collect();
109 if parts.len() != 3 {
110 return None;
111 }
112 let payload = jwt_engine().decode(parts[1]).ok()?;
113 let raw: Raw = serde_json::from_slice(&payload).ok()?;
114 if let Some(checked) = raw
115 .auth
116 .as_ref()
117 .and_then(|a| a.chatgpt_subscription_last_checked.as_deref())
118 && DateTime::parse_from_rfc3339(checked).is_err()
119 {
120 return None;
121 }
122 let auth = raw.auth.unwrap_or_default();
123 Some(Claims {
124 email: raw.email.unwrap_or_default(),
125 account_id: auth.chatgpt_account_id.unwrap_or_default(),
126 plan: auth.chatgpt_plan_type.unwrap_or_default(),
127 })
128}
129
130fn jwt_engine() -> GeneralPurpose {
131 GeneralPurpose::new(
132 &base64::alphabet::URL_SAFE,
133 GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),
134 )
135}
136
137pub(crate) fn jwt_exp(token: &str) -> Option<DateTime<Utc>> {
139 let parts: Vec<&str> = token.trim().split('.').collect();
140 if parts.len() != 3 {
141 return None;
142 }
143 let payload = jwt_engine().decode(parts[1]).ok()?;
144 let claims: Value = serde_json::from_slice(&payload).ok()?;
145 let exp = match &claims["exp"] {
146 Value::Number(n) => n.as_f64().map(|f| f as i64)?,
147 Value::String(s) => s.trim().parse().ok()?,
148 _ => return None,
149 };
150 if exp <= 0 {
151 return None;
152 }
153 let secs = if exp > 1_000_000_000_000 { exp / 1000 } else { exp };
155 DateTime::from_timestamp(secs, 0)
156}
157
158fn rfc3339(time: DateTime<Local>) -> String {
160 time.to_rfc3339_opts(SecondsFormat::Secs, true)
161}
162
163#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct Tokens {
166 pub id_token: String,
167 pub access_token: String,
168 pub refresh_token: String,
169 pub account_id: String,
170 pub email: String,
171 pub plan_type: String,
172 pub expired: String,
173}
174
175#[derive(Deserialize)]
176struct TokenResponse {
177 #[serde(default)]
178 access_token: Option<String>,
179 #[serde(default)]
180 refresh_token: Option<String>,
181 #[serde(default)]
182 id_token: Option<String>,
183 #[serde(default)]
184 expires_in: Option<i64>,
185}
186
187type RefreshResult<T> = Shared<BoxFuture<'static, Result<T, ExecError>>>;
188const MAX_RETAINED_REFRESHES: usize = 64;
190type Table<T> = Arc<Mutex<HashMap<[u8; 32], (Instant, RefreshResult<T>)>>>;
191
192#[derive(Clone, Default)]
194struct Refreshes {
195 outer: Table<Tokens>,
196 siwc: Table<crate::codex_siwc::Tokens>,
197}
198
199fn single_flight<T: Clone + Send + Sync + 'static>(
204 table: &Table<T>,
205 key: [u8; 32],
206 run: BoxFuture<'static, Result<T, ExecError>>,
207 retain_failures: bool,
208) -> RefreshResult<T> {
209 let mut locked = table.lock().expect("refresh table");
210 locked.retain(|_, (until, _)| *until > Instant::now());
211 if let Some((_, result)) = locked.get(&key) {
212 return result.clone();
213 }
214 while locked.len() >= MAX_RETAINED_REFRESHES {
217 let oldest = locked
218 .iter()
219 .filter(|(_, (_, result))| result.peek().is_some())
220 .min_by_key(|(_, (until, _))| *until)
221 .map(|(k, _)| *k);
222 match oldest {
223 Some(k) => locked.remove(&k),
224 None => break,
225 };
226 }
227 let retained = table.clone();
228 let task = tokio::spawn(async move {
229 let result = run.await;
230 let mut table = retained.lock().expect("refresh table");
231 if result.is_err() && !retain_failures {
232 table.remove(&key);
233 } else if let Some((until, _)) = table.get_mut(&key) {
234 *until = Instant::now() + Duration::from_secs(300);
235 }
236 drop(table);
237 result
238 });
239 let shared = async move { task.await.map_err(|_| oauth_error(500, "codex refresh task failed"))? }
240 .boxed()
241 .shared();
242 locked.insert(key, (Instant::now() + Duration::from_secs(300), shared.clone()));
243 shared
244}
245
246#[derive(Clone)]
248pub struct CodexOAuth {
249 client: wreq::Client,
250 token_url: String,
251 device_usercode_url: String,
252 device_token_url: String,
253 siwc_token_url: String,
254 refreshes: Refreshes,
255 retry_delay: Duration,
256}
257
258impl CodexOAuth {
259 pub fn new(client: wreq::Client) -> Self {
260 Self::with_endpoints(client, TOKEN_URL, DEVICE_USERCODE_URL, DEVICE_TOKEN_URL)
261 }
262
263 pub fn with_endpoints(client: wreq::Client, token: &str, usercode: &str, device_token: &str) -> Self {
265 Self {
266 client,
267 token_url: token.into(),
268 device_usercode_url: usercode.into(),
269 device_token_url: device_token.into(),
270 siwc_token_url: crate::codex_siwc::TOKEN_URL.into(),
271 refreshes: Refreshes::default(),
272 retry_delay: Duration::from_secs(1),
273 }
274 }
275
276 pub fn with_siwc_token_url(mut self, url: &str) -> Self {
278 self.siwc_token_url = url.into();
279 self
280 }
281
282 pub(crate) fn siwc_token_url(&self) -> &str {
283 &self.siwc_token_url
284 }
285
286 pub fn with_retry_delay(mut self, delay: Duration) -> Self {
288 self.retry_delay = delay;
289 self
290 }
291
292 pub fn with_client(&self, client: wreq::Client) -> Self {
295 Self { client, ..self.clone() }
296 }
297
298 pub(crate) async fn post(
302 &self,
303 url: &str,
304 content_type: &str,
305 body: Vec<u8>,
306 ) -> Result<(u16, bytes::Bytes), ExecError> {
307 let failed = || ExecError::local(502, FailureScope::Transport, "codex oauth request failed");
308 let mut headers = crate::proxy::GoHeaders::new();
309 headers.set("Content-Type", content_type);
310 headers.set("Accept", "application/json");
311 let upstream = crate::proxy::send(&self.client, url, headers, body, None)
312 .await
313 .map_err(|_| failed())?;
314 let body = crate::proxy::read_all(upstream.body, crate::proxy::MAX_ERROR_BODY, false)
315 .await
316 .map_err(|_| failed())?;
317 Ok((upstream.status, body))
318 }
319
320 async fn token_request(&self, form: &[(&str, &str)], exchange: bool) -> Result<Tokens, ExecError> {
323 let body = url::form_urlencoded::Serializer::new(String::new())
325 .extend_pairs(form)
326 .finish();
327 let (status, body) = self
328 .post(&self.token_url, "application/x-www-form-urlencoded", body.into_bytes())
329 .await?;
330 if status != 200 && exchange {
331 let message = format!(
332 "token exchange failed with status {status}: {}",
333 String::from_utf8_lossy(&body)
334 );
335 return Err(oauth_error(status, &message));
336 }
337 if status != 200 {
338 return Err(token_error(status, &body));
339 }
340 let parsed: TokenResponse = serde_json::from_slice(&body).map_err(|_| {
343 if exchange {
344 oauth_error(502, "failed to parse token response")
345 } else {
346 oauth_error(502, "failed to parse codex token response")
347 }
348 })?;
349 let id_token = parsed.id_token.unwrap_or_default();
350 let claims = parse_jwt(&id_token).unwrap_or_default();
351 let expires = chrono::TimeDelta::try_seconds(parsed.expires_in.unwrap_or(0)).unwrap_or_default();
352 Ok(Tokens {
353 plan_type: claims.plan_type(),
354 account_id: claims.account_id,
355 email: claims.email,
356 id_token,
357 access_token: parsed.access_token.unwrap_or_default(),
358 refresh_token: parsed.refresh_token.unwrap_or_default(),
359 expired: rfc3339(Local::now() + expires),
360 })
361 }
362
363 pub async fn exchange(&self, code: &str, redirect: &str, verifier: &str) -> Result<Tokens, ExecError> {
365 if redirect.trim().is_empty() {
366 return Err(oauth_error(400, "redirect URI is required for token exchange"));
367 }
368 self.token_request(
369 &[
370 ("client_id", CLIENT_ID),
371 ("code", code),
372 ("code_verifier", verifier),
373 ("grant_type", "authorization_code"),
374 ("redirect_uri", redirect.trim()),
375 ],
376 true,
377 )
378 .await
379 }
380
381 pub async fn refresh(&self, refresh_token: &str) -> Result<Tokens, ExecError> {
384 if refresh_token.is_empty() {
385 return Err(oauth_error(400, "refresh token is required"));
386 }
387 let key: [u8; 32] = Sha256::digest(refresh_token.as_bytes()).into();
388 let oauth = self.clone();
389 let token = refresh_token.to_owned();
390 let run = async move { oauth.refresh_with_retry(&token).await }.boxed();
391 single_flight(&self.refreshes.outer, key, run, true).await
392 }
393
394 pub async fn refresh_siwc(
397 &self,
398 refresh_token: &str,
399 client_id: &str,
400 device_id: &str,
401 ) -> Result<crate::codex_siwc::Tokens, ExecError> {
402 let (refresh_token, client_id) = (refresh_token.trim(), client_id.trim());
403 if refresh_token.is_empty() {
404 return Err(oauth_error(400, "SIWC refresh token is required"));
405 }
406 if client_id.is_empty() {
407 return Err(oauth_error(
408 400,
409 "Stored OpenAI OAuth credential does not contain an issued client ID; reconnect ChatGPT",
410 ));
411 }
412 let key: [u8; 32] = Sha256::digest(format!("{client_id}:{refresh_token}").as_bytes()).into();
413 let oauth = self.clone();
414 let (token, client, device) = (refresh_token.to_owned(), client_id.to_owned(), device_id.to_owned());
415 let run = async move { oauth.refresh_siwc_with_retry(&token, &client, &device).await }.boxed();
416 single_flight(&self.refreshes.siwc, key, run, false).await
417 }
418
419 async fn refresh_siwc_with_retry(
420 &self,
421 refresh_token: &str,
422 client_id: &str,
423 device_id: &str,
424 ) -> Result<crate::codex_siwc::Tokens, ExecError> {
425 let mut last = None;
426 for attempt in 0..3u32 {
427 if attempt > 0 {
428 tokio::time::sleep(self.retry_delay * attempt).await;
429 }
430 let once = tokio::time::timeout(
431 Duration::from_secs(30),
432 self.siwc_token_request(
433 &[
434 ("client_id", client_id),
435 ("grant_type", "refresh_token"),
436 ("refresh_token", refresh_token),
437 ("resource", crate::codex_siwc::RESOURCE),
438 ],
439 client_id,
440 device_id,
441 false,
442 ),
443 )
444 .await
445 .unwrap_or_else(|_| Err(oauth_error(504, "SIWC token refresh timed out")));
446 match once {
447 Ok(tokens) => return Ok(tokens),
448 Err(error) if String::from_utf8_lossy(&error.body).contains("refresh_token_reused") => {
449 return Err(error);
450 }
451 Err(error) => last = Some(error),
452 }
453 }
454 let mut error = last.expect("three attempts ran");
455 error.body = format!(
456 "SIWC token refresh failed after 3 attempts: {}",
457 String::from_utf8_lossy(&error.body)
458 )
459 .into();
460 Err(error)
461 }
462
463 async fn refresh_with_retry(&self, refresh_token: &str) -> Result<Tokens, ExecError> {
464 let mut last = None;
465 for attempt in 0..3u32 {
466 if attempt > 0 {
467 tokio::time::sleep(self.retry_delay * attempt).await;
468 }
469 let once = tokio::time::timeout(
470 Duration::from_secs(30),
471 self.token_request(
472 &[
473 ("client_id", CLIENT_ID),
474 ("grant_type", "refresh_token"),
475 ("refresh_token", refresh_token),
476 ("scope", "openid profile email"),
477 ],
478 false,
479 ),
480 )
481 .await
482 .unwrap_or_else(|_| Err(oauth_error(504, "codex token refresh timed out")));
483 match once {
484 Ok(tokens) => return Ok(tokens),
485 Err(error) if String::from_utf8_lossy(&error.body).contains("refresh_token_reused") => {
486 return Err(error);
487 }
488 Err(error) => last = Some(error),
489 }
490 }
491 let mut error = last.expect("three attempts ran");
492 error.body = format!(
493 "token refresh failed after 3 attempts: {}",
494 String::from_utf8_lossy(&error.body)
495 )
496 .into();
497 Err(error)
498 }
499
500 pub async fn device_code(&self) -> Result<DeviceCode, ExecError> {
502 let body = serde_json::to_vec(&json!({ "client_id": CLIENT_ID })).expect("static JSON");
503 let (status, body) = self.post(&self.device_usercode_url, "application/json", body).await?;
504 if !(200..300).contains(&status) {
505 if status == 404 {
506 return Err(oauth_error(
507 502,
508 &format!("codex device endpoint is unavailable (status {status})"),
509 ));
510 }
511 return Err(oauth_error(
512 502,
513 &format!("codex device code request failed with status {status}"),
514 ));
515 }
516 #[derive(Deserialize)]
517 struct Raw {
518 #[serde(default)]
519 device_auth_id: Option<String>,
520 #[serde(default)]
521 user_code: Option<String>,
522 #[serde(default)]
523 usercode: Option<String>,
524 #[serde(default)]
525 interval: Option<Value>,
526 }
527 let raw: Raw = serde_json::from_slice(&body)
528 .map_err(|_| oauth_error(502, "failed to decode codex device code response"))?;
529 let user_code = raw
530 .user_code
531 .filter(|s| !s.trim().is_empty())
532 .or(raw.usercode)
533 .unwrap_or_default()
534 .trim()
535 .to_owned();
536 let device_auth_id = raw.device_auth_id.unwrap_or_default().trim().to_owned();
537 if user_code.is_empty() || device_auth_id.is_empty() {
538 return Err(oauth_error(502, "codex device flow did not return required fields"));
539 }
540 let seconds = match raw.interval {
541 Some(Value::String(s)) => s.trim().parse::<u64>().ok(),
542 Some(Value::Number(n)) => n.as_u64(),
543 _ => None,
544 }
545 .filter(|s| *s > 0)
546 .unwrap_or(5);
547 Ok(DeviceCode {
548 device_auth_id,
549 user_code,
550 interval: Duration::from_secs(seconds),
551 })
552 }
553
554 pub async fn device_poll(&self, code: &DeviceCode, deadline: Duration) -> Result<Tokens, ExecError> {
556 let started = Instant::now();
557 let body = serde_json::to_vec(&json!({
558 "device_auth_id": code.device_auth_id,
559 "user_code": code.user_code,
560 }))
561 .expect("strings serialize");
562 loop {
563 if started.elapsed() > deadline {
564 return Err(oauth_error(
565 408,
566 "codex device authentication timed out after 15 minutes",
567 ));
568 }
569 let (status, response) = self
570 .post(&self.device_token_url, "application/json", body.clone())
571 .await?;
572 match status {
573 200..=299 => {
574 let value: Value = serde_json::from_slice(&response)
575 .map_err(|_| oauth_error(502, "failed to decode codex device token response"))?;
576 let field = |k: &str| value[k].as_str().unwrap_or_default().trim().to_owned();
577 let (auth_code, verifier) = (field("authorization_code"), field("code_verifier"));
578 if auth_code.is_empty() || verifier.is_empty() || field("code_challenge").is_empty() {
579 return Err(oauth_error(
580 502,
581 "codex device flow token response missing required fields",
582 ));
583 }
584 return self.exchange(&auth_code, DEVICE_REDIRECT_URI, &verifier).await;
585 }
586 403 | 404 => tokio::time::sleep(code.interval).await,
587 _ => {
588 return Err(oauth_error(
589 502,
590 &format!("codex device token polling failed with status {status}"),
591 ));
592 }
593 }
594 }
595 }
596
597 pub async fn refresh_patch(&self, refresh_token: &str) -> Result<MetadataPatch, ExecError> {
599 let tokens = self.refresh(refresh_token).await?;
600 Ok(refresh_patch(&tokens, Local::now()))
601 }
602}
603
604pub struct DeviceCode {
605 pub device_auth_id: String,
606 pub user_code: String,
607 pub interval: Duration,
608}
609
610fn refresh_patch(tokens: &Tokens, now: DateTime<Local>) -> MetadataPatch {
611 let mut patch = MetadataPatch::default();
612 let mut set = |k: &str, v: &str| {
613 patch.set.insert(k.into(), Value::String(v.into()));
614 };
615 set("id_token", &tokens.id_token);
616 set("access_token", &tokens.access_token);
617 if !tokens.refresh_token.is_empty() {
618 set("refresh_token", &tokens.refresh_token);
619 }
620 if !tokens.account_id.is_empty() {
621 set("account_id", &tokens.account_id);
622 }
623 set("email", &tokens.email);
624 set("expired", &tokens.expired);
625 set("type", "codex");
626 set("last_refresh", &rfc3339(now));
627 let plan = match tokens.plan_type.trim() {
628 "" => parse_jwt(&tokens.id_token).unwrap_or_default().plan_type(),
629 plan => plan.to_owned(),
630 };
631 set("plan_type", &plan);
632 patch
633}
634
635fn oauth_error(status: u16, message: &str) -> ExecError {
636 ExecError::local(status, FailureScope::Credential, message)
637}
638
639fn token_error(status: u16, body: &[u8]) -> ExecError {
643 refresh_error(
644 status,
645 &format!("token refresh failed with status {status}: {}", oauth_code(body)),
646 )
647}
648
649pub(crate) fn refresh_error(status: u16, message: &str) -> ExecError {
652 let (status_out, scope) = match status {
653 400..=403 => (401, FailureScope::Credential),
654 _ => (502, FailureScope::Transport),
655 };
656 ExecError::local(status_out, scope, message)
657}
658
659pub(crate) fn oauth_code(body: &[u8]) -> String {
661 serde_json::from_slice::<Value>(body)
662 .ok()
663 .and_then(|v| match &v["error"] {
664 Value::String(s) => Some(s.clone()),
665 Value::Object(o) => o.get("code").and_then(Value::as_str).map(str::to_owned),
666 _ => None,
667 })
668 .filter(|c| c.len() <= 64 && c.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.'))
669 .unwrap_or_default()
670}
671
672pub(crate) fn refresh_token(credential: &Credential) -> &str {
674 credential.str("refresh_token").unwrap_or_default()
675}
676
677pub(crate) fn expiry(credential: &Credential) -> Option<DateTime<Utc>> {
679 if let Some(exp) = credential.str("access_token").and_then(jwt_exp) {
680 return Some(exp);
681 }
682 ["expired", "expire", "expires_at", "expiresAt", "expiry", "expires"]
683 .iter()
684 .find_map(|k| credential.metadata.get(*k).and_then(parse_time))
685}
686
687pub(crate) fn parse_time(value: &Value) -> Option<DateTime<Utc>> {
688 match value {
689 Value::String(s) if s.trim().parse::<i64>().is_ok() => {
690 parse_time(&Value::Number(s.trim().parse::<i64>().ok()?.into()))
691 }
692 Value::String(s) => {
693 let s = s.trim();
694 DateTime::parse_from_rfc3339(s)
695 .ok()
696 .map(|t| t.with_timezone(&Utc))
697 .or_else(|| {
698 ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M"]
699 .iter()
700 .find_map(|f| chrono::NaiveDateTime::parse_from_str(s, f).ok().map(|t| t.and_utc()))
701 })
702 }
703 Value::Number(n) => {
704 let n = n.as_f64()? as i64;
705 let secs = if n > 1_000_000_000_000 { n / 1000 } else { n };
706 (secs > 0).then(|| DateTime::from_timestamp(secs, 0)).flatten()
707 }
708 _ => None,
709 }
710}
711
712pub(crate) fn refresh_due(credential: &Credential, now: DateTime<Utc>) -> bool {
717 if refresh_token(credential).is_empty() {
718 return false;
719 }
720 if let Some(expiry) = expiry(credential) {
721 return expiry - now <= REFRESH_LEAD;
722 }
723 ["last_refresh", "lastRefresh", "last_refreshed_at", "lastRefreshedAt"]
724 .iter()
725 .find_map(|k| credential.metadata.get(*k).and_then(parse_time))
726 .is_none_or(|last| now - last >= REFRESH_LEAD)
727}
728
729pub(crate) fn access_usable(credential: &Credential, now: DateTime<Utc>) -> bool {
731 !credential.str("access_token").unwrap_or_default().is_empty() && expiry(credential).is_none_or(|exp| exp > now)
732}
733
734pub fn credential_file_name(email: &str, plan: &str, account_hash: &str) -> String {
736 let email = email.trim();
737 let plan: Vec<String> = plan
738 .trim()
739 .split(|c: char| !c.is_alphanumeric())
740 .filter(|s| !s.is_empty())
741 .map(GoStr::go_lower)
742 .collect();
743 let plan = plan.join("-");
744 let hash = account_hash.trim();
745 match (hash.is_empty(), plan.is_empty()) {
746 (false, true) => format!("codex-{hash}-{email}.json"),
747 (false, false) => format!("codex-{hash}-{email}-{plan}.json"),
748 (true, true) => format!("codex-{email}.json"),
749 (true, false) => format!("codex-{email}-{plan}.json"),
750 }
751}
752
753pub fn login_record(tokens: &Tokens, last_refresh: &str) -> Result<(String, Map<String, Value>), ExecError> {
756 if tokens.email.is_empty() {
757 return Err(oauth_error(502, "codex token storage missing account information"));
758 }
759 let mut plan = match tokens.plan_type.trim() {
760 "" => DEFAULT_PLAN.to_owned(),
761 plan => plan.to_owned(),
762 };
763 let mut hash = String::new();
764 if let Some(claims) = (!tokens.id_token.is_empty())
765 .then(|| parse_jwt(&tokens.id_token))
766 .flatten()
767 {
768 if !claims.plan.trim().is_empty() {
769 plan = claims.plan.trim().to_owned();
770 }
771 let account = claims.account_id.trim();
772 if !account.is_empty() {
773 hash = Sha256::digest(account.as_bytes())[..4]
774 .iter()
775 .map(|b| format!("{b:02x}"))
776 .collect();
777 }
778 }
779 let name = credential_file_name(&tokens.email, &plan, &hash);
780 let mut record = Map::new();
781 for (k, v) in [
782 ("id_token", &tokens.id_token),
783 ("access_token", &tokens.access_token),
784 ("refresh_token", &tokens.refresh_token),
785 ("account_id", &tokens.account_id),
786 ("last_refresh", &last_refresh.to_owned()),
787 ("email", &tokens.email),
788 ("type", &"codex".to_owned()),
789 ("expired", &tokens.expired),
790 ("plan_type", &plan),
791 ] {
792 record.insert(k.into(), Value::String(v.clone()));
793 }
794 record.insert("disabled".into(), Value::Bool(false));
795 Ok((name, record))
796}
797
798fn merge_existing(record: &mut Map<String, Value>, existing: Map<String, Value>) {
800 const TOKEN_KEYS: &[&str] = &[
801 "access_token",
802 "refresh_token",
803 "id_token",
804 "session_id",
805 "expired",
806 "last_refresh",
807 "expires_in",
808 "timestamp",
809 "token_type",
810 "user_code",
811 "verification_uri",
812 "verification_uri_complete",
813 ];
814 let disabled = existing.get("disabled").and_then(Value::as_bool).unwrap_or(false);
817 for (k, v) in existing {
818 if TOKEN_KEYS.contains(&k.trim().to_ascii_lowercase().as_str()) {
819 continue;
820 }
821 record.entry(k).or_insert(v);
822 }
823 record.insert("disabled".into(), Value::Bool(disabled));
824}
825
826pub fn encode_go_json(value: &Value) -> String {
828 fn write(out: &mut String, value: &Value) {
829 match value {
830 Value::Object(map) => {
831 let sorted: BTreeMap<&String, &Value> = map.iter().collect();
832 out.push('{');
833 for (i, (k, v)) in sorted.into_iter().enumerate() {
834 if i > 0 {
835 out.push(',');
836 }
837 out.push_str(&crate::codex_json::go_quote(k, true));
838 out.push(':');
839 write(out, v);
840 }
841 out.push('}');
842 }
843 Value::Array(items) => {
844 out.push('[');
845 for (i, v) in items.iter().enumerate() {
846 if i > 0 {
847 out.push(',');
848 }
849 write(out, v);
850 }
851 out.push(']');
852 }
853 Value::String(s) => out.push_str(&crate::codex_json::go_quote(s, true)),
854 other => out.push_str(&other.to_string()),
855 }
856 }
857 let mut out = String::new();
858 write(&mut out, value);
859 out.push('\n');
860 out
861}
862
863pub fn write_login(auth_dir: &Path, tokens: &Tokens) -> Result<PathBuf, ExecError> {
866 let (name, mut record) = login_record(tokens, &rfc3339(Local::now()))?;
867 if name.contains(['/', '\\']) {
868 return Err(oauth_error(400, "invalid credential email filename"));
869 }
870 let path = auth_dir.join(&name);
871 if let Ok(raw) = std::fs::read(&path)
872 && let Ok(existing) = serde_json::from_slice::<Map<String, Value>>(&raw)
873 {
874 merge_existing(&mut record, existing);
875 }
876 let text = encode_go_json(&Value::Object(record));
877 publish(auth_dir, &path, text.as_bytes()).map_err(|_| oauth_error(500, "cannot publish codex credential"))?;
880 Ok(path)
881}
882
883pub(crate) fn publish(dir: &Path, path: &Path, bytes: &[u8]) -> std::io::Result<()> {
884 use std::io::Write;
885 let mut builder = std::fs::DirBuilder::new();
886 builder.recursive(true);
887 #[cfg(unix)]
888 {
889 use std::os::unix::fs::DirBuilderExt;
890 builder.mode(0o700);
891 }
892 builder.create(dir)?;
893 let mut nonce = [0u8; 8];
894 getrandom::fill(&mut nonce).map_err(std::io::Error::other)?;
895 let temp = dir.join(format!(
896 ".codex-{}.tmp",
897 nonce.iter().map(|b| format!("{b:02x}")).collect::<String>()
898 ));
899 let result = (|| {
900 let mut options = std::fs::OpenOptions::new();
901 options.write(true).create_new(true);
902 #[cfg(unix)]
903 {
904 use std::os::unix::fs::OpenOptionsExt;
905 options.mode(0o600);
906 }
907 let mut file = options.open(&temp)?;
908 file.write_all(bytes)?;
909 file.sync_all()?;
910 std::fs::rename(&temp, path)?;
911 #[cfg(unix)]
913 std::fs::File::open(dir)?.sync_all()?;
914 Ok(())
915 })();
916 if result.is_err() {
917 let _ = std::fs::remove_file(&temp);
918 }
919 result
920}
921
922fn random_state() -> Result<String, ExecError> {
924 let mut bytes = [0u8; 16];
925 getrandom::fill(&mut bytes).map_err(|_| oauth_error(500, "secure random source unavailable"))?;
926 Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
927}
928
929pub fn authorize_url(state: &str, challenge: &str, port: u16) -> String {
931 let redirect = redirect_uri(port);
932 let mut url = Url::parse(AUTH_URL).expect("constant URL");
933 url.query_pairs_mut().extend_pairs([
934 ("client_id", CLIENT_ID),
935 ("code_challenge", challenge),
936 ("code_challenge_method", "S256"),
937 ("codex_cli_simplified_flow", "true"),
938 ("id_token_add_organizations", "true"),
939 ("prompt", "login"),
940 ("redirect_uri", &redirect),
941 ("response_type", "code"),
942 ("scope", "openid email profile offline_access"),
943 ("state", state),
944 ]);
945 url.into()
946}
947
948pub struct LoginOptions {
949 pub callback_port: u16,
950 pub no_browser: bool,
951}
952
953impl Default for LoginOptions {
954 fn default() -> Self {
955 Self {
956 callback_port: DEFAULT_CALLBACK_PORT,
957 no_browser: false,
958 }
959 }
960}
961
962fn open_browser(url: &str) {
963 #[cfg(target_os = "linux")]
964 let _ = std::process::Command::new("xdg-open")
965 .arg(url)
966 .stdout(std::process::Stdio::null())
967 .stderr(std::process::Stdio::null())
968 .spawn();
969 #[cfg(target_os = "macos")]
970 let _ = std::process::Command::new("open").arg(url).spawn();
971 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
972 let _ = url;
973}
974
975pub async fn login(auth_dir: &Path, options: &LoginOptions) -> Result<PathBuf, ExecError> {
977 let port = options.callback_port;
978 let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
979 .await
980 .map_err(|_| oauth_error(500, &format!("port {port} is already in use")))?;
981 let (verifier, challenge) = crate::oauth::pkce()?;
982 let state = random_state()?;
983 let url = authorize_url(&state, &challenge, port);
984 if !options.no_browser {
985 println!("Opening browser for Codex authentication");
986 open_browser(&url);
987 }
988 println!("Visit the following URL to continue authentication:\n{url}");
989 println!("Waiting for Codex authentication callback...");
990 let manual = async {
991 tokio::time::sleep(Duration::from_secs(15)).await;
993 match prompt_line(
994 "Paste the Codex callback URL (or press Enter to keep waiting): ",
995 || {
996 let mut line = String::new();
997 std::io::stdin().read_line(&mut line).map(|_| line)
998 },
999 )
1000 .await
1001 {
1002 Ok(line) if line.trim().is_empty() => std::future::pending().await,
1003 Ok(line) => parse_manual_callback(&line),
1004 Err(_) => Err(oauth_error(400, "failed to read callback URL")),
1005 }
1006 };
1007 let callback = tokio::select! {
1008 result = tokio::time::timeout(Duration::from_secs(300), callback(&listener)) => {
1009 result.map_err(|_| oauth_error(408, "timeout waiting for OAuth callback"))?
1010 }
1011 result = manual => result,
1012 }?;
1013 if let Some(error) = callback.error {
1014 return Err(oauth_error(400, &format!("codex oauth error: {error}")));
1015 }
1016 if callback.state != state {
1017 return Err(oauth_error(400, "state mismatch"));
1018 }
1019 let client = plain_client()?;
1020 let tokens = CodexOAuth::new(client)
1021 .exchange(&callback.code, &redirect_uri(port), &verifier)
1022 .await?;
1023 let dir = auth_dir.to_owned();
1024 tokio::task::spawn_blocking(move || write_login(&dir, &tokens))
1025 .await
1026 .map_err(|_| oauth_error(500, "credential publication failed"))?
1027}
1028
1029async fn prompt_line(
1033 prompt: &'static str,
1034 read: impl FnOnce() -> std::io::Result<String> + Send + 'static,
1035) -> std::io::Result<String> {
1036 let (tx, rx) = tokio::sync::oneshot::channel();
1037 std::thread::spawn(move || {
1038 use std::io::Write;
1039 print!("{prompt}");
1040 let _ = std::io::stdout().flush();
1041 let _ = tx.send(read());
1042 });
1043 rx.await
1044 .unwrap_or_else(|_| Err(std::io::Error::other("prompt thread ended")))
1045}
1046
1047pub async fn device_login(auth_dir: &Path, options: &LoginOptions) -> Result<PathBuf, ExecError> {
1049 let oauth = CodexOAuth::new(plain_client()?);
1050 let code = oauth.device_code().await?;
1051 println!("Starting Codex device authentication...");
1052 println!("Codex device URL: {DEVICE_VERIFICATION_URL}");
1053 println!("Codex device code: {}", code.user_code);
1054 if !options.no_browser {
1055 open_browser(DEVICE_VERIFICATION_URL);
1056 }
1057 let tokens = oauth.device_poll(&code, Duration::from_secs(15 * 60)).await?;
1058 let dir = auth_dir.to_owned();
1059 tokio::task::spawn_blocking(move || write_login(&dir, &tokens))
1060 .await
1061 .map_err(|_| oauth_error(500, "credential publication failed"))?
1062}
1063
1064pub(crate) fn plain_client() -> Result<wreq::Client, ExecError> {
1065 wreq::Client::builder()
1066 .redirect(wreq::redirect::Policy::none())
1067 .build()
1068 .map_err(|_| oauth_error(500, "cannot create OAuth transport"))
1069}
1070
1071#[derive(Debug, PartialEq, Eq)]
1072pub(crate) struct Callback {
1073 pub code: String,
1074 pub state: String,
1075 pub error: Option<String>,
1076 pub client_id: String,
1078}
1079
1080fn parse_manual_callback(input: &str) -> Result<Callback, ExecError> {
1082 let trimmed = input.trim();
1083 let candidate = if trimmed.contains("://") {
1084 trimmed.to_owned()
1085 } else if trimmed.starts_with('?') {
1086 format!("http://localhost{trimmed}")
1087 } else if trimmed.contains(['/', '?', '#', ':']) {
1088 format!("http://{trimmed}")
1089 } else if trimmed.contains('=') {
1090 format!("http://localhost/?{trimmed}")
1091 } else {
1092 return Err(oauth_error(400, "invalid callback URL"));
1093 };
1094 let url = Url::parse(&candidate).map_err(|_| oauth_error(400, "invalid callback URL"))?;
1095 fn first<'a>(
1096 mut pairs: impl Iterator<Item = (std::borrow::Cow<'a, str>, std::borrow::Cow<'a, str>)>,
1097 k: &str,
1098 ) -> String {
1099 pairs
1100 .find(|(key, _)| key == k)
1101 .map(|(_, v)| v.trim().to_owned())
1102 .unwrap_or_default()
1103 }
1104 let query = |k: &str| first(url.query_pairs(), k);
1105 let fragment = |k: &str| {
1106 url.fragment()
1107 .map(|f| first(url::form_urlencoded::parse(f.as_bytes()), k))
1108 .unwrap_or_default()
1109 };
1110 let pick = |k: &str| Some(query(k)).filter(|s| !s.is_empty()).unwrap_or_else(|| fragment(k));
1111 let (mut code, mut state, mut error) = (pick("code"), pick("state"), pick("error"));
1112 let description = pick("error_description");
1113 if !code.is_empty()
1114 && state.is_empty()
1115 && let Some((c, s)) = code.clone().split_once('#')
1116 {
1117 code = c.to_owned();
1118 state = s.to_owned();
1119 }
1120 if error.is_empty() && !description.is_empty() {
1121 error = description;
1122 }
1123 if code.is_empty() && error.is_empty() {
1124 return Err(oauth_error(400, "callback URL missing code"));
1125 }
1126 Ok(Callback {
1127 code,
1128 state,
1129 error: (!error.is_empty()).then_some(error),
1130 client_id: String::new(),
1131 })
1132}
1133
1134const SUCCESS_HTML: &str = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>Authentication Successful - Codex</title></head><body><h1>Authentication successful</h1><p>You can close this window and return to the terminal.</p></body></html>";
1135
1136pub(crate) async fn callback(listener: &tokio::net::TcpListener) -> Result<Callback, ExecError> {
1141 loop {
1142 let (mut socket, _) = listener
1143 .accept()
1144 .await
1145 .map_err(|_| oauth_error(500, "callback listener failed"))?;
1146 let handled = tokio::time::timeout(Duration::from_secs(10), async {
1147 let mut head = Vec::new();
1148 let mut byte = [0u8];
1149 while head.len() < 8192 && !head.ends_with(b"\r\n\r\n") {
1150 if socket.read(&mut byte).await? == 0 {
1151 break;
1152 }
1153 head.push(byte[0]);
1154 }
1155 let (response, result) = route_callback(&head);
1156 socket.write_all(response.as_bytes()).await?;
1157 Ok::<_, std::io::Error>(result)
1158 })
1159 .await;
1160 if let Ok(Ok(Some(result))) = handled {
1161 return Ok(result);
1162 }
1163 }
1164}
1165
1166fn http_response(status: &str, content_type: &str, extra: &str, body: &str) -> String {
1167 format!(
1168 "HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\n{extra}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
1169 body.len()
1170 )
1171}
1172
1173fn route_callback(head: &[u8]) -> (String, Option<Callback>) {
1174 let text = String::from_utf8_lossy(head);
1175 let mut line = text.lines().next().unwrap_or_default().split_whitespace();
1176 let (method, target) = (line.next().unwrap_or_default(), line.next().unwrap_or_default());
1177 let Ok(url) = Url::parse(&format!("http://localhost{target}")) else {
1178 return (http_response("400 Bad Request", "text/plain", "", "bad request"), None);
1179 };
1180 match url.path() {
1181 "/success" => (
1182 http_response("200 OK", "text/html; charset=utf-8", "", SUCCESS_HTML),
1183 None,
1184 ),
1185 "/auth/callback" if method != "GET" => (
1186 http_response(
1187 "405 Method Not Allowed",
1188 "text/plain; charset=utf-8",
1189 "",
1190 "Method not allowed\n",
1191 ),
1192 None,
1193 ),
1194 "/auth/callback" => {
1195 let get = |k: &str| {
1196 url.query_pairs()
1197 .find(|(key, _)| key == k)
1198 .map(|(_, v)| v.into_owned())
1199 .unwrap_or_default()
1200 };
1201 let bad = |message: &str, error: &str| {
1202 (
1203 http_response(
1204 "400 Bad Request",
1205 "text/plain; charset=utf-8",
1206 "",
1207 &format!("{message}\n"),
1208 ),
1209 Some(Callback {
1210 code: String::new(),
1211 state: String::new(),
1212 error: Some(error.to_owned()),
1213 client_id: String::new(),
1214 }),
1215 )
1216 };
1217 let error = get("error");
1218 if !error.is_empty() {
1219 return bad(&format!("OAuth error: {error}"), &error);
1220 }
1221 if get("code").is_empty() {
1222 return bad("No authorization code received", "no_code");
1223 }
1224 if get("state").is_empty() {
1225 return bad("No state parameter received", "no_state");
1226 }
1227 (
1228 http_response("302 Found", "text/html; charset=utf-8", "Location: /success\r\n", ""),
1229 Some(Callback {
1230 code: get("code"),
1231 state: get("state"),
1232 error: None,
1233 client_id: get("client_id").trim().to_owned(),
1234 }),
1235 )
1236 }
1237 _ => (
1238 http_response("404 Not Found", "text/plain; charset=utf-8", "", "404 page not found\n"),
1239 None,
1240 ),
1241 }
1242}
1243
1244#[cfg(test)]
1245#[path = "codex_oauth_tests.rs"]
1246mod tests;