use std::{
path::{Path, PathBuf},
time::Duration,
};
use base64::{
Engine,
engine::general_purpose::{URL_SAFE, URL_SAFE_NO_PAD},
};
use reqwest::Url;
use serde::{Deserialize, Serialize};
mod auth_file;
pub(crate) use auth_file::import_stamp;
use auth_file::{FileToken, read_auth_file_at};
mod timestamp;
pub use timestamp::Timestamp;
use super::storage::{Location, MAX_CREDENTIAL_BYTES, Storage};
pub const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
const AUTH_ROOT: &str = "https://auth.openai.com";
pub const AUTH_URL_VARIABLE: &str = "ARTIFACTIZE_CODEX_AUTH_URL";
pub const CODEX_HOME_VARIABLE: &str = "CODEX_HOME";
pub const ORIGINATOR: &str = "artifactize";
#[cfg(test)]
const CLAIM: &str = "https://api.openai.com/auth";
const LOCK: &str = "codex";
const REFRESH_MARGIN: Duration = Duration::from_secs(300);
const AUTH_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) const LOGIN_REQUIRED: &str = "Codex is not signed in; run `codex login`.";
const LOGIN_EXPIRED: &str = "The Codex CLI's sign-in has expired; run `codex login` again.";
#[derive(Debug)]
pub struct TokenError {
pub transient: bool,
pub message: String,
}
impl From<String> for TokenError {
fn from(message: String) -> Self {
Self {
transient: false,
message,
}
}
}
impl From<&str> for TokenError {
fn from(message: &str) -> Self {
message.to_owned().into()
}
}
pub(crate) struct Token {
pub access_token: String,
pub account_id: crate::names::CodexAccountId,
pub refresh_token: Option<String>,
}
pub(crate) fn now() -> Result<Timestamp, String> {
Timestamp::now()
}
pub fn auth_root() -> Result<Url, String> {
auth_root_in(&crate::platform::Env::process())
}
pub(crate) fn auth_root_in(env: &crate::platform::Env) -> Result<Url, String> {
Ok(
crate::llm::variable_endpoint_in(AUTH_URL_VARIABLE, |name| env.var(name))?.map_or_else(
|| Url::parse(AUTH_ROOT).expect("built-in Codex auth URL"),
crate::llm::TestEndpoint::into_url,
),
)
}
fn endpoint(root: &Url, route: &str) -> Result<Url, String> {
let mut url = root.clone();
url.path_segments_mut()
.map_err(|_| "Invalid Codex sign-in URL.")?
.pop_if_empty()
.push("oauth")
.push(route);
Ok(url)
}
pub fn auth_file() -> Option<PathBuf> {
auth_file_in(&crate::platform::Env::process())
}
pub(crate) fn auth_file_in(env: &crate::platform::Env) -> Option<PathBuf> {
env.codex_home().map(|home| home.join("auth.json"))
}
fn client() -> Result<reqwest::Client, String> {
reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.retry(reqwest::retry::never())
.timeout(AUTH_HTTP_TIMEOUT)
.build()
.map_err(|_| "Cannot initialize the Codex sign-in HTTP client.".into())
}
fn claims(token: &str) -> Option<JwtClaims> {
let mut parts = token.split('.');
let (_, payload, _, None) = (parts.next()?, parts.next()?, parts.next()?, parts.next()) else {
return None;
};
let bytes = URL_SAFE_NO_PAD
.decode(payload)
.or_else(|_| URL_SAFE.decode(payload))
.ok()?;
serde_json::from_slice(&bytes).ok()
}
impl JwtClaims {
fn account_id(self) -> Option<crate::names::CodexAccountId> {
self.auth.0?.0.chatgpt_account_id.0
}
}
#[derive(Default, Deserialize)]
struct JwtClaims {
#[serde(default)]
exp: crate::json::Optional<Timestamp>,
#[serde(default, rename = "https://api.openai.com/auth")]
auth: crate::json::Optional<crate::json::Object<AccountClaim>>,
}
#[derive(Default, Deserialize)]
struct AccountClaim {
#[serde(default)]
chatgpt_account_id: crate::json::Optional<crate::names::CodexAccountId>,
}
#[derive(Deserialize)]
struct TokenResponse {
access_token: Option<String>,
refresh_token: Option<String>,
id_token: Option<String>,
}
struct Refreshed {
access_token: String,
refresh_token: Option<String>,
id_token: Option<String>,
}
#[derive(Default, Deserialize)]
struct OAuthError {
error: Option<OAuthErrorField>,
code: Option<OAuthCode>,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum OAuthErrorField {
Text(String),
Object { code: Option<OAuthCode> },
Other(serde::de::IgnoredAny),
}
#[derive(Deserialize)]
#[serde(untagged)]
enum OAuthCode {
Text(String),
Other(serde::de::IgnoredAny),
}
impl OAuthCode {
fn text(&self) -> Option<&str> {
match self {
Self::Text(code) => Some(code),
Self::Other(_) => None,
}
}
}
impl OAuthError {
fn code(&self) -> Option<&str> {
let error = match &self.error {
Some(OAuthErrorField::Text(code)) => Some(code.as_str()),
Some(OAuthErrorField::Object { code }) => code.as_ref().and_then(OAuthCode::text),
_ => None,
};
error.or_else(|| self.code.as_ref().and_then(OAuthCode::text))
}
}
fn terminal(code: &str) -> bool {
matches!(
code,
"invalid_grant"
| "refresh_token_expired"
| "refresh_token_reused"
| "refresh_token_invalidated"
)
}
fn rejected(status: reqwest::StatusCode, code: Option<&str>) -> TokenError {
if code.is_some_and(terminal) {
return LOGIN_EXPIRED.into();
}
TokenError {
transient: status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error(),
message: format!(
"Codex token refresh failed (HTTP {}); the Codex CLI's sign-in was kept.",
status.as_u16()
),
}
}
async fn refresh(root: &Url, refresh_token: &str) -> Result<Refreshed, TokenError> {
let response = client()?
.post(endpoint(root, "token")?)
.form(&[
("grant_type", "refresh_token"),
("refresh_token", refresh_token),
("client_id", CLIENT_ID),
])
.send()
.await
.map_err(|_| TokenError {
transient: true,
message: "Codex token refresh failed; check your connection. The Codex CLI's sign-in was kept."
.into(),
})?;
let status = response.status();
if !status.is_success() {
let body: OAuthError = response.json().await.unwrap_or_default();
return Err(rejected(status, body.code()));
}
let invalid = || TokenError::from("Invalid Codex token response; nothing was saved.");
let tokens: TokenResponse = response.json().await.map_err(|_| invalid())?;
let nonempty = |token: Option<String>| token.filter(|token| !token.is_empty());
Ok(Refreshed {
access_token: nonempty(tokens.access_token).ok_or_else(invalid)?,
refresh_token: nonempty(tokens.refresh_token),
id_token: nonempty(tokens.id_token),
})
}
pub(crate) async fn access_token(location: Result<&Location, &str>) -> Result<Token, TokenError> {
access_token_in(location, &crate::platform::Env::process()).await
}
pub(crate) async fn access_token_in(
location: Result<&Location, &str>,
env: &crate::platform::Env,
) -> Result<Token, TokenError> {
let path = auth_file_in(env).ok_or(LOGIN_REQUIRED)?;
current_token_at(&Storage::new(location?)?, &path, &auth_root_in(env)?, now).await
}
fn usable(file: &FileToken, now: Timestamp) -> bool {
file.expires_at
.is_none_or(|expires_at| expires_at > now.saturating_add(REFRESH_MARGIN))
}
async fn current_token_at(
storage: &Storage,
path: &Path,
root: &Url,
clock: impl Fn() -> Result<Timestamp, String>,
) -> Result<Token, TokenError> {
let read = || read_auth_file_at(path)?.ok_or_else(|| TokenError::from(LOGIN_REQUIRED));
let file = read()?;
if usable(&file, clock()?) {
return Ok(file.token);
}
let _lock = storage.lock(LOCK).await?;
let file = read()?;
if usable(&file, clock()?) {
return Ok(file.token);
}
let old = file.token;
let refresh_token = old.refresh_token.clone().ok_or(LOGIN_EXPIRED)?;
let previous = [
Some(old.access_token.as_str()),
Some(&refresh_token),
file.id_token.as_deref(),
];
crate::secret::history::publish(storage, previous.into_iter().flatten())?;
let refreshed = refresh(root, &refresh_token).await.map_err(|mut error| {
error.message =
crate::secret::Inventory::new(previous.into_iter().flatten().map(str::to_owned))
.scrub(&error.message);
error
})?;
let account_id = claims(&refreshed.access_token)
.and_then(JwtClaims::account_id)
.unwrap_or_else(|| old.account_id.clone());
if account_id != old.account_id {
return Err(
"The refreshed Codex token is for another ChatGPT account; run `codex login` again."
.into(),
);
}
let refresh_token = refreshed.refresh_token.clone().unwrap_or(refresh_token);
let next = [
Some(refreshed.access_token.as_str()),
Some(&refresh_token),
refreshed.id_token.as_deref(),
];
crate::secret::history::publish(storage, next.into_iter().flatten())?;
auth_file::write_back(path, &refreshed, &refresh_token)?;
Ok(Token {
access_token: refreshed.access_token,
refresh_token: Some(refresh_token),
account_id,
})
}
#[derive(Debug)]
pub enum FileExpiry {
Usable { expires_at: Option<Timestamp> },
Expired,
}
pub enum Status {
Absent,
File { path: PathBuf, expiry: FileExpiry },
}
impl std::fmt::Debug for Status {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Absent => formatter.write_str("Absent"),
Self::File { path, expiry } => formatter
.debug_struct("File")
.field("path", &crate::platform::path_text(path))
.field("expiry", expiry)
.finish(),
}
}
}
impl Serialize for Status {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let (source, file, expires_at, expired) = match self {
Self::Absent => ("none", None, None, false),
Self::File {
path,
expiry: FileExpiry::Usable { expires_at },
} => ("file", Some(path), *expires_at, false),
Self::File {
path,
expiry: FileExpiry::Expired,
} => ("file", Some(path), None, true),
};
let mut wire = serializer.serialize_struct("Status", 3 + usize::from(file.is_some()))?;
wire.serialize_field("source", source)?;
if let Some(file) = file {
wire.serialize_field("authFile", &crate::platform::path_text(file))?;
}
wire.serialize_field("expiresAt", &expires_at)?;
wire.serialize_field("expired", &expired)?;
wire.end()
}
}
pub fn status() -> Result<Status, String> {
let managed = crate::secret::Inventory::new(secret_values()?);
read_status()
.map_err(|error| managed.scrub(&error))
.map(|status| public_status(status, &managed))
}
fn public_status(mut status: Status, managed: &crate::secret::Inventory) -> Status {
if let Status::File { path, expiry } = &mut status {
if managed.contains(&crate::platform::path_text(path)) {
*path = PathBuf::new();
}
if let FileExpiry::Usable { expires_at } = expiry {
*expires_at = expires_at.filter(|time| !managed.contains(&time.seconds().to_string()));
}
}
status
}
fn read_status() -> Result<Status, String> {
match auth_file() {
Some(path) => read_status_at(path, now()?),
None => Ok(Status::Absent),
}
}
fn read_status_at(path: PathBuf, now: Timestamp) -> Result<Status, String> {
let Some(file) = read_auth_file_at(&path)? else {
return Ok(Status::Absent);
};
let expired = file.expires_at.is_some_and(|expires_at| expires_at <= now)
&& file.token.refresh_token.is_none();
Ok(Status::File {
path,
expiry: if expired {
FileExpiry::Expired
} else {
FileExpiry::Usable {
expires_at: file.expires_at,
}
},
})
}
#[cfg(test)]
mod tests;
pub(crate) fn secret_values() -> Result<Vec<String>, String> {
secret_values_in(&crate::platform::Env::process())
}
pub(crate) fn secret_values_in(env: &crate::platform::Env) -> Result<Vec<String>, String> {
match auth_file_in(env) {
Some(path) => Ok(auth_file::secret_values(&path)?),
None => Ok(Vec::new()),
}
}