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 = crate::file_name_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 crate::other_account_file(&path, &tokens.email, &[("account_id", &tokens.account_id)]) {
872 return Err(oauth_error(409, crate::OTHER_ACCOUNT_FILE));
873 }
874 if let Ok(raw) = std::fs::read(&path)
875 && let Ok(existing) = serde_json::from_slice::<Map<String, Value>>(&raw)
876 {
877 merge_existing(&mut record, existing);
878 }
879 let text = encode_go_json(&Value::Object(record));
880 publish(auth_dir, &path, text.as_bytes()).map_err(|_| oauth_error(500, "cannot publish codex credential"))?;
883 Ok(path)
884}
885
886pub(crate) fn publish(dir: &Path, path: &Path, bytes: &[u8]) -> std::io::Result<()> {
887 use std::io::Write;
888 let mut builder = std::fs::DirBuilder::new();
889 builder.recursive(true);
890 #[cfg(unix)]
891 {
892 use std::os::unix::fs::DirBuilderExt;
893 builder.mode(0o700);
894 }
895 builder.create(dir)?;
896 let mut nonce = [0u8; 8];
897 getrandom::fill(&mut nonce).map_err(std::io::Error::other)?;
898 let temp = dir.join(format!(
899 ".codex-{}.tmp",
900 nonce.iter().map(|b| format!("{b:02x}")).collect::<String>()
901 ));
902 let result = (|| {
903 let mut options = std::fs::OpenOptions::new();
904 options.write(true).create_new(true);
905 #[cfg(unix)]
906 {
907 use std::os::unix::fs::OpenOptionsExt;
908 options.mode(0o600);
909 }
910 let mut file = options.open(&temp)?;
911 file.write_all(bytes)?;
912 file.sync_all()?;
913 std::fs::rename(&temp, path)?;
914 #[cfg(unix)]
916 std::fs::File::open(dir)?.sync_all()?;
917 Ok(())
918 })();
919 if result.is_err() {
920 let _ = std::fs::remove_file(&temp);
921 }
922 result
923}
924
925fn random_state() -> Result<String, ExecError> {
927 let mut bytes = [0u8; 16];
928 getrandom::fill(&mut bytes).map_err(|_| oauth_error(500, "secure random source unavailable"))?;
929 Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
930}
931
932pub fn authorize_url(state: &str, challenge: &str, port: u16) -> String {
934 let redirect = redirect_uri(port);
935 let mut url = Url::parse(AUTH_URL).expect("constant URL");
936 url.query_pairs_mut().extend_pairs([
937 ("client_id", CLIENT_ID),
938 ("code_challenge", challenge),
939 ("code_challenge_method", "S256"),
940 ("codex_cli_simplified_flow", "true"),
941 ("id_token_add_organizations", "true"),
942 ("prompt", "login"),
943 ("redirect_uri", &redirect),
944 ("response_type", "code"),
945 ("scope", "openid email profile offline_access"),
946 ("state", state),
947 ]);
948 url.into()
949}
950
951pub struct LoginOptions {
952 pub callback_port: u16,
953 pub no_browser: bool,
954}
955
956impl Default for LoginOptions {
957 fn default() -> Self {
958 Self {
959 callback_port: DEFAULT_CALLBACK_PORT,
960 no_browser: false,
961 }
962 }
963}
964
965fn open_browser(url: &str) {
966 #[cfg(target_os = "linux")]
967 let _ = std::process::Command::new("xdg-open")
968 .arg(url)
969 .stdout(std::process::Stdio::null())
970 .stderr(std::process::Stdio::null())
971 .spawn();
972 #[cfg(target_os = "macos")]
973 let _ = std::process::Command::new("open").arg(url).spawn();
974 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
975 let _ = url;
976}
977
978pub async fn login(auth_dir: &Path, options: &LoginOptions) -> Result<PathBuf, ExecError> {
980 let port = options.callback_port;
981 let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
982 .await
983 .map_err(|_| oauth_error(500, &format!("port {port} is already in use")))?;
984 let (verifier, challenge) = crate::oauth::pkce()?;
985 let state = random_state()?;
986 let url = authorize_url(&state, &challenge, port);
987 if !options.no_browser {
988 println!("Opening browser for Codex authentication");
989 open_browser(&url);
990 }
991 println!("Visit the following URL to continue authentication:\n{url}");
992 println!("Waiting for Codex authentication callback...");
993 let manual = async {
994 tokio::time::sleep(Duration::from_secs(15)).await;
996 match prompt_line(
997 "Paste the Codex callback URL (or press Enter to keep waiting): ",
998 || {
999 let mut line = String::new();
1000 std::io::stdin().read_line(&mut line).map(|_| line)
1001 },
1002 )
1003 .await
1004 {
1005 Ok(line) if line.trim().is_empty() => std::future::pending().await,
1006 Ok(line) => parse_manual_callback(&line),
1007 Err(_) => Err(oauth_error(400, "failed to read callback URL")),
1008 }
1009 };
1010 let callback = tokio::select! {
1011 result = tokio::time::timeout(Duration::from_secs(300), callback(&listener)) => {
1012 result.map_err(|_| oauth_error(408, "timeout waiting for OAuth callback"))?
1013 }
1014 result = manual => result,
1015 }?;
1016 if let Some(error) = callback.error {
1017 return Err(oauth_error(400, &format!("codex oauth error: {error}")));
1018 }
1019 if callback.state != state {
1020 return Err(oauth_error(400, "state mismatch"));
1021 }
1022 let client = plain_client()?;
1023 let tokens = CodexOAuth::new(client)
1024 .exchange(&callback.code, &redirect_uri(port), &verifier)
1025 .await?;
1026 let dir = auth_dir.to_owned();
1027 tokio::task::spawn_blocking(move || write_login(&dir, &tokens))
1028 .await
1029 .map_err(|_| oauth_error(500, "credential publication failed"))?
1030}
1031
1032async fn prompt_line(
1036 prompt: &'static str,
1037 read: impl FnOnce() -> std::io::Result<String> + Send + 'static,
1038) -> std::io::Result<String> {
1039 let (tx, rx) = tokio::sync::oneshot::channel();
1040 std::thread::spawn(move || {
1041 use std::io::Write;
1042 print!("{prompt}");
1043 let _ = std::io::stdout().flush();
1044 let _ = tx.send(read());
1045 });
1046 rx.await
1047 .unwrap_or_else(|_| Err(std::io::Error::other("prompt thread ended")))
1048}
1049
1050pub async fn device_login(auth_dir: &Path, options: &LoginOptions) -> Result<PathBuf, ExecError> {
1052 let oauth = CodexOAuth::new(plain_client()?);
1053 let code = oauth.device_code().await?;
1054 println!("Starting Codex device authentication...");
1055 println!("Codex device URL: {DEVICE_VERIFICATION_URL}");
1056 println!("Codex device code: {}", code.user_code);
1057 if !options.no_browser {
1058 open_browser(DEVICE_VERIFICATION_URL);
1059 }
1060 let tokens = oauth.device_poll(&code, Duration::from_secs(15 * 60)).await?;
1061 let dir = auth_dir.to_owned();
1062 tokio::task::spawn_blocking(move || write_login(&dir, &tokens))
1063 .await
1064 .map_err(|_| oauth_error(500, "credential publication failed"))?
1065}
1066
1067pub(crate) fn plain_client() -> Result<wreq::Client, ExecError> {
1068 wreq::Client::builder()
1069 .redirect(wreq::redirect::Policy::none())
1070 .build()
1071 .map_err(|_| oauth_error(500, "cannot create OAuth transport"))
1072}
1073
1074#[derive(Debug, PartialEq, Eq)]
1075pub(crate) struct Callback {
1076 pub code: String,
1077 pub state: String,
1078 pub error: Option<String>,
1079 pub client_id: String,
1081}
1082
1083fn parse_manual_callback(input: &str) -> Result<Callback, ExecError> {
1085 let trimmed = input.trim();
1086 let candidate = if trimmed.contains("://") {
1087 trimmed.to_owned()
1088 } else if trimmed.starts_with('?') {
1089 format!("http://localhost{trimmed}")
1090 } else if trimmed.contains(['/', '?', '#', ':']) {
1091 format!("http://{trimmed}")
1092 } else if trimmed.contains('=') {
1093 format!("http://localhost/?{trimmed}")
1094 } else {
1095 return Err(oauth_error(400, "invalid callback URL"));
1096 };
1097 let url = Url::parse(&candidate).map_err(|_| oauth_error(400, "invalid callback URL"))?;
1098 fn first<'a>(
1099 mut pairs: impl Iterator<Item = (std::borrow::Cow<'a, str>, std::borrow::Cow<'a, str>)>,
1100 k: &str,
1101 ) -> String {
1102 pairs
1103 .find(|(key, _)| key == k)
1104 .map(|(_, v)| v.trim().to_owned())
1105 .unwrap_or_default()
1106 }
1107 let query = |k: &str| first(url.query_pairs(), k);
1108 let fragment = |k: &str| {
1109 url.fragment()
1110 .map(|f| first(url::form_urlencoded::parse(f.as_bytes()), k))
1111 .unwrap_or_default()
1112 };
1113 let pick = |k: &str| Some(query(k)).filter(|s| !s.is_empty()).unwrap_or_else(|| fragment(k));
1114 let (mut code, mut state, mut error) = (pick("code"), pick("state"), pick("error"));
1115 let description = pick("error_description");
1116 if !code.is_empty()
1117 && state.is_empty()
1118 && let Some((c, s)) = code.clone().split_once('#')
1119 {
1120 code = c.to_owned();
1121 state = s.to_owned();
1122 }
1123 if error.is_empty() && !description.is_empty() {
1124 error = description;
1125 }
1126 if code.is_empty() && error.is_empty() {
1127 return Err(oauth_error(400, "callback URL missing code"));
1128 }
1129 Ok(Callback {
1130 code,
1131 state,
1132 error: (!error.is_empty()).then_some(error),
1133 client_id: String::new(),
1134 })
1135}
1136
1137const 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>";
1138
1139pub(crate) async fn callback(listener: &tokio::net::TcpListener) -> Result<Callback, ExecError> {
1144 loop {
1145 let (mut socket, _) = listener
1146 .accept()
1147 .await
1148 .map_err(|_| oauth_error(500, "callback listener failed"))?;
1149 let handled = tokio::time::timeout(Duration::from_secs(10), async {
1150 let mut head = Vec::new();
1151 let mut byte = [0u8];
1152 while head.len() < 8192 && !head.ends_with(b"\r\n\r\n") {
1153 if socket.read(&mut byte).await? == 0 {
1154 break;
1155 }
1156 head.push(byte[0]);
1157 }
1158 let (response, result) = route_callback(&head);
1159 socket.write_all(response.as_bytes()).await?;
1160 Ok::<_, std::io::Error>(result)
1161 })
1162 .await;
1163 if let Ok(Ok(Some(result))) = handled {
1164 return Ok(result);
1165 }
1166 }
1167}
1168
1169fn http_response(status: &str, content_type: &str, extra: &str, body: &str) -> String {
1170 format!(
1171 "HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\n{extra}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
1172 body.len()
1173 )
1174}
1175
1176fn route_callback(head: &[u8]) -> (String, Option<Callback>) {
1177 let text = String::from_utf8_lossy(head);
1178 let mut line = text.lines().next().unwrap_or_default().split_whitespace();
1179 let (method, target) = (line.next().unwrap_or_default(), line.next().unwrap_or_default());
1180 let Ok(url) = Url::parse(&format!("http://localhost{target}")) else {
1181 return (http_response("400 Bad Request", "text/plain", "", "bad request"), None);
1182 };
1183 match url.path() {
1184 "/success" => (
1185 http_response("200 OK", "text/html; charset=utf-8", "", SUCCESS_HTML),
1186 None,
1187 ),
1188 "/auth/callback" if method != "GET" => (
1189 http_response(
1190 "405 Method Not Allowed",
1191 "text/plain; charset=utf-8",
1192 "",
1193 "Method not allowed\n",
1194 ),
1195 None,
1196 ),
1197 "/auth/callback" => {
1198 let get = |k: &str| {
1199 url.query_pairs()
1200 .find(|(key, _)| key == k)
1201 .map(|(_, v)| v.into_owned())
1202 .unwrap_or_default()
1203 };
1204 let bad = |message: &str, error: &str| {
1205 (
1206 http_response(
1207 "400 Bad Request",
1208 "text/plain; charset=utf-8",
1209 "",
1210 &format!("{message}\n"),
1211 ),
1212 Some(Callback {
1213 code: String::new(),
1214 state: String::new(),
1215 error: Some(error.to_owned()),
1216 client_id: String::new(),
1217 }),
1218 )
1219 };
1220 let error = get("error");
1221 if !error.is_empty() {
1222 return bad(&format!("OAuth error: {error}"), &error);
1223 }
1224 if get("code").is_empty() {
1225 return bad("No authorization code received", "no_code");
1226 }
1227 if get("state").is_empty() {
1228 return bad("No state parameter received", "no_state");
1229 }
1230 (
1231 http_response("302 Found", "text/html; charset=utf-8", "Location: /success\r\n", ""),
1232 Some(Callback {
1233 code: get("code"),
1234 state: get("state"),
1235 error: None,
1236 client_id: get("client_id").trim().to_owned(),
1237 }),
1238 )
1239 }
1240 _ => (
1241 http_response("404 Not Found", "text/plain; charset=utf-8", "", "404 page not found\n"),
1242 None,
1243 ),
1244 }
1245}
1246
1247#[cfg(test)]
1248#[path = "codex_oauth_tests.rs"]
1249mod tests;