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};
use serde_json::json;
mod auth_file;
mod callback;
mod interactive;
pub(crate) use auth_file::import_stamp;
use auth_file::{AuthFileError, FileToken, read_auth_file_at};
#[cfg(test)]
use interactive::*;
pub use interactive::{CALLBACK_PATH, CALLBACK_PORT, CallbackPort, Prompt, login_with};
#[cfg(test)]
use sha2::{Digest, Sha256};
#[cfg(test)]
use std::{collections::BTreeMap, ffi::OsStr};
#[cfg(test)]
use tokio::sync::oneshot;
mod timestamp;
use callback::Callback;
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 AUTH_FILE_VARIABLE: &str = "ARTIFACTIZE_CODEX_AUTH_FILE";
pub const ORIGINATOR: &str = "artifactize";
#[cfg(test)]
const CLAIM: &str = "https://api.openai.com/auth";
pub(crate) const CREDENTIALS: &str = "codex.json";
const LOCK: &str = "codex";
const REFRESH_MARGIN: Duration = Duration::from_secs(300);
const AUTH_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
const REVOCATION_TIMEOUT: Duration = Duration::from_secs(10);
const LOGIN_REQUIRED: &str =
"Codex is not signed in; run `artifactize login codex` or set ARTIFACTIZE_CODEX_AUTH_FILE.";
#[derive(Deserialize, Serialize)]
struct Credentials {
access_token: String,
refresh_token: String,
account_id: crate::names::CodexAccountId,
#[serde(with = "timestamp::seconds")]
expires_at: Timestamp,
#[serde(with = "timestamp::seconds")]
saved_at: Timestamp,
}
impl Credentials {
fn values(&self) -> [&str; 2] {
[&self.access_token, &self.refresh_token]
}
fn publish(&self, storage: &Storage) -> Result<(), String> {
crate::secret::history::publish(storage, self.values())
}
}
fn read_stored(storage: &Storage) -> Result<Option<Credentials>, String> {
storage.read(CREDENTIALS)
}
#[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> {
Ok(
crate::llm::variable_endpoint(AUTH_URL_VARIABLE)?.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> {
crate::platform::var(AUTH_FILE_VARIABLE)
.filter(|value| !value.is_empty())
.map(crate::platform::env_path)
}
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>,
#[serde(
default,
deserialize_with = "timestamp::optional_duration::deserialize"
)]
expires_in: Option<Duration>,
}
fn credentials(tokens: TokenResponse, saved_at: Timestamp) -> Result<Credentials, String> {
let invalid = || "Invalid Codex token response; nothing was saved.".to_owned();
let access_token = tokens.access_token.filter(|token| !token.is_empty());
let refresh_token = tokens.refresh_token.filter(|token| !token.is_empty());
let (Some(access_token), Some(refresh_token), Some(expires_in)) = (
access_token,
refresh_token,
tokens.expires_in.filter(|duration| !duration.is_zero()),
) else {
return Err(invalid());
};
let account_id = claims(&access_token)
.and_then(JwtClaims::account_id)
.ok_or("The Codex access token names no ChatGPT account; nothing was saved.")?;
Ok(Credentials {
access_token,
refresh_token,
account_id,
expires_at: saved_at.checked_add(expires_in).ok_or_else(invalid)?,
saved_at,
})
}
#[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"
)
}
enum Exchange {
Authorization,
Refresh,
}
enum ExchangeError {
TerminalRefresh,
Unavailable(TokenError),
}
impl From<TokenError> for ExchangeError {
fn from(error: TokenError) -> Self {
Self::Unavailable(error)
}
}
impl ExchangeError {
fn diagnostic(self) -> TokenError {
match self {
Self::TerminalRefresh => {
"The Codex refresh token is no longer valid; run `artifactize login codex`.".into()
}
Self::Unavailable(error) => error,
}
}
}
fn rejected(exchange: Exchange, status: reqwest::StatusCode, code: Option<&str>) -> ExchangeError {
let number = status.as_u16();
let message = match exchange {
Exchange::Refresh if code.is_some_and(terminal) => return ExchangeError::TerminalRefresh,
Exchange::Refresh => {
format!("Codex token refresh failed (HTTP {number}); the stored sign-in was kept.")
}
Exchange::Authorization if code == Some("invalid_grant") => {
"The Codex authorization code was rejected; run `artifactize login codex` again.".into()
}
Exchange::Authorization => format!("Codex sign-in failed (HTTP {number})."),
};
ExchangeError::Unavailable(TokenError {
transient: status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error(),
message,
})
}
async fn token_request(
root: &Url,
form: &[(&str, &str)],
exchange: Exchange,
) -> Result<TokenResponse, ExchangeError> {
let response = client()
.map_err(TokenError::from)?
.post(endpoint(root, "token").map_err(TokenError::from)?)
.form(form)
.send()
.await
.map_err(|_| TokenError {
transient: true,
message:
"Codex token request failed; check your connection. The stored 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(exchange, status, body.code()));
}
response
.json()
.await
.map_err(|_| TokenError::from("Invalid Codex token response; nothing was saved.").into())
}
pub(crate) async fn access_token(location: Result<&Location, &str>) -> Result<Token, TokenError> {
if let Some(path) = auth_file() {
return Ok(read_auth_file_at(&path, now()?)?.token);
}
stored_token(&Storage::new(location?)?, &auth_root()?).await
}
async fn stored_token(storage: &Storage, root: &Url) -> Result<Token, TokenError> {
stored_token_at(storage, root, now).await
}
async fn stored_token_at(
storage: &Storage,
root: &Url,
clock: impl Fn() -> Result<Timestamp, String>,
) -> Result<Token, TokenError> {
let _lock = storage.lock(LOCK).await?;
let stored = read_stored(storage)?.ok_or(LOGIN_REQUIRED)?;
if stored.expires_at > clock()?.saturating_add(REFRESH_MARGIN) {
return Ok(Token {
access_token: stored.access_token,
refresh_token: Some(stored.refresh_token),
account_id: stored.account_id,
});
}
stored.publish(storage)?;
let tokens = token_request(
root,
&[
("grant_type", "refresh_token"),
("refresh_token", &stored.refresh_token),
("client_id", CLIENT_ID),
],
Exchange::Refresh,
)
.await;
let tokens = match tokens {
Ok(tokens) => tokens,
Err(error) => {
if matches!(error, ExchangeError::TerminalRefresh) {
storage.remove(CREDENTIALS)?;
}
let mut failure = error.diagnostic();
failure.message = crate::secret::Inventory::new(stored.values().map(str::to_owned))
.scrub(&failure.message);
return Err(failure);
}
};
let refreshed = credentials(tokens, clock()?)?;
if refreshed.account_id != stored.account_id {
return Err(
"The refreshed Codex token is for another ChatGPT account; run `artifactize login codex`."
.into(),
);
}
refreshed.publish(storage)?;
storage.save(CREDENTIALS, &refreshed)?;
Ok(Token {
access_token: refreshed.access_token,
refresh_token: Some(refreshed.refresh_token),
account_id: refreshed.account_id,
})
}
#[derive(Debug)]
pub enum FileExpiry {
Usable { expires_at: Option<Timestamp> },
Expired,
}
#[derive(Debug)]
pub enum StoredExpiry {
Usable { expires_at: Timestamp },
Expired { expires_at: Timestamp },
}
pub enum Status {
Absent,
Refused { reason: String },
File { path: PathBuf, expiry: FileExpiry },
Stored { expiry: StoredExpiry },
}
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::Refused { reason } => formatter
.debug_struct("Refused")
.field("reason", reason)
.finish(),
Self::File { path, expiry } => formatter
.debug_struct("File")
.field("path", &crate::platform::path_text(path))
.field("expiry", expiry)
.finish(),
Self::Stored { expiry } => formatter
.debug_struct("Stored")
.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, refused) = match self {
Self::Absent => ("none", None, None, false, None),
Self::Refused { reason } => ("none", None, None, false, Some(reason)),
Self::File {
path,
expiry: FileExpiry::Usable { expires_at },
} => ("file", Some(path), *expires_at, false, None),
Self::File {
path,
expiry: FileExpiry::Expired,
} => ("file", Some(path), None, true, None),
Self::Stored {
expiry: StoredExpiry::Usable { expires_at },
} => ("stored", None, Some(*expires_at), false, None),
Self::Stored {
expiry: StoredExpiry::Expired { expires_at },
} => ("stored", None, Some(*expires_at), true, None),
};
let mut wire = serializer.serialize_struct(
"Status",
3 + usize::from(file.is_some()) + usize::from(refused.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)?;
if let Some(reason) = refused {
wire.serialize_field("refused", reason)?;
}
wire.end()
}
}
pub fn status(location: Result<&Location, &str>) -> Result<Status, String> {
let mut managed = crate::secret::Inventory::read(location.ok(), location.ok());
let status = read_status(location);
managed.merge(crate::secret::Inventory::read(location.ok(), location.ok()));
status
.map_err(|error| managed.scrub(&error))
.and_then(|status| public_status(status, &managed))
}
fn public_status(mut status: Status, managed: &crate::secret::Inventory) -> Result<Status, String> {
let expires_at = match &mut status {
Status::Absent => None,
Status::Refused { reason } => {
*reason = managed.scrub(reason);
None
}
Status::File { path, expiry } => {
let display = crate::platform::path_text(path);
if managed.contains(&display) {
*path = PathBuf::new();
}
if let FileExpiry::Usable { expires_at } = expiry {
*expires_at =
expires_at.filter(|time| !managed.contains(&time.seconds().to_string()));
}
None
}
Status::Stored { expiry } => match expiry {
StoredExpiry::Usable { expires_at } | StoredExpiry::Expired { expires_at } => {
Some(*expires_at)
}
},
};
if expires_at.is_some_and(|time| managed.contains(&time.seconds().to_string())) {
return Err(managed.scrub("Cannot show Codex sign-in expiry safely."));
}
Ok(status)
}
fn read_status(location: Result<&Location, &str>) -> Result<Status, String> {
let now = now()?;
if let Some(path) = auth_file() {
let expiry = match read_auth_file_at(&path, now) {
Ok(FileToken { expires_at, .. }) => FileExpiry::Usable { expires_at },
Err(AuthFileError::Expired(_)) => FileExpiry::Expired,
Err(error) => return Err(error.into()),
};
return Ok(Status::File { path, expiry });
}
let location = location?;
if let Some(reason) = location.refusal(CREDENTIALS)? {
return Ok(Status::Refused { reason });
}
let stored = read_stored(&Storage::inspect(location)?)?;
Ok(match stored {
None => Status::Absent,
Some(stored) => Status::Stored {
expiry: if stored.expires_at <= now {
StoredExpiry::Expired {
expires_at: stored.expires_at,
}
} else {
StoredExpiry::Usable {
expires_at: stored.expires_at,
}
},
},
})
}
pub async fn logout(location: Result<&Location, &str>) -> Result<bool, String> {
sign_out(
&Storage::new(location.map_err(str::to_owned)?)?,
&auth_root()?,
)
.await
}
async fn sign_out(storage: &Storage, root: &Url) -> Result<bool, String> {
let _lock = storage.lock(LOCK).await?;
let Some(stored) = read_stored(storage)? else {
return Ok(true);
};
stored.publish(storage)?;
let revoked = revoke(root, &stored.refresh_token).await;
storage.remove(CREDENTIALS)?;
Ok(revoked)
}
async fn revoke(root: &Url, refresh_token: &str) -> bool {
let Ok(client) = client() else {
return false;
};
let Ok(url) = endpoint(root, "revoke") else {
return false;
};
client
.post(url)
.timeout(REVOCATION_TIMEOUT)
.json(
&json!({"token":refresh_token,"token_type_hint":"refresh_token","client_id":CLIENT_ID}),
)
.send()
.await
.is_ok_and(|response| response.status().is_success())
}
#[cfg(test)]
mod tests;
pub(crate) fn secret_values(location: Option<&Location>) -> Result<Vec<String>, String> {
#[derive(Deserialize)]
struct StoredTokens {
#[serde(default)]
access_token: crate::json::Optional<String>,
#[serde(default)]
refresh_token: crate::json::Optional<String>,
}
let saved = location
.filter(|location| !location.is_refused())
.map(|location| Storage::inspect(location)?.read::<StoredTokens>(CREDENTIALS))
.transpose()?
.flatten();
let mut known = saved
.into_iter()
.flat_map(|tokens| [tokens.access_token.0, tokens.refresh_token.0])
.flatten()
.collect::<Vec<_>>();
if let Some(path) = auth_file() {
known.extend(auth_file::secret_values(&path)?);
}
Ok(known)
}