use super::*;
use std::io::Read;
pub(super) const FILE_MARGIN: Duration = Duration::from_secs(60);
#[derive(Default)]
struct AuthFile {
tokens: crate::json::Optional<crate::json::Object<AuthFileTokens>>,
}
#[derive(Default)]
struct AuthFileTokens {
access_token: crate::json::Optional<String>,
refresh_token: crate::json::Optional<String>,
account_id: crate::json::Optional<String>,
}
impl<'de> Deserialize<'de> for AuthFile {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct AuthVisitor;
impl<'de> serde::de::Visitor<'de> for AuthVisitor {
type Value = AuthFile;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("an auth-file object")
}
fn visit_map<M: serde::de::MapAccess<'de>>(
self,
mut map: M,
) -> Result<Self::Value, M::Error> {
let mut auth = AuthFile::default();
while let Some(field) = map.next_key::<String>()? {
if field == "tokens" {
auth.tokens = map.next_value()?;
} else {
map.next_value::<crate::json::Ignored>()?;
}
}
Ok(auth)
}
}
deserializer.deserialize_map(AuthVisitor)
}
}
impl<'de> Deserialize<'de> for AuthFileTokens {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct TokensVisitor;
impl<'de> serde::de::Visitor<'de> for TokensVisitor {
type Value = AuthFileTokens;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("an auth-file token object")
}
fn visit_map<M: serde::de::MapAccess<'de>>(
self,
mut map: M,
) -> Result<Self::Value, M::Error> {
let mut tokens = AuthFileTokens::default();
while let Some(field) = map.next_key::<String>()? {
match field.as_str() {
"access_token" => tokens.access_token = map.next_value()?,
"refresh_token" => tokens.refresh_token = map.next_value()?,
"account_id" => tokens.account_id = map.next_value()?,
_ => {
map.next_value::<crate::json::Ignored>()?;
}
}
}
Ok(tokens)
}
}
deserializer.deserialize_map(TokensVisitor)
}
}
#[derive(Debug)]
pub(super) enum AuthFileError {
Expired(String),
Unreadable(String),
}
impl std::fmt::Display for AuthFileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Expired(message) | Self::Unreadable(message) => write!(f, "{message}"),
}
}
}
impl From<AuthFileError> for String {
fn from(error: AuthFileError) -> Self {
error.to_string()
}
}
impl From<AuthFileError> for TokenError {
fn from(error: AuthFileError) -> Self {
error.to_string().into()
}
}
pub(super) struct FileToken {
pub(super) token: Token,
pub(super) expires_at: Option<Timestamp>,
}
#[derive(PartialEq, Eq)]
pub(crate) struct ImportStamp {
path: PathBuf,
file: artifactize_foundation::platform::private::FileIdentity,
parent_modified: std::time::SystemTime,
modified: std::time::SystemTime,
content: sha2::digest::Output<sha2::Sha256>,
}
pub(crate) fn import_stamp() -> std::io::Result<Option<ImportStamp>> {
use sha2::{Digest, Sha256};
let Some(path) = auth_file() else {
return Ok(None);
};
let absolute = crate::platform::absolute(&path)?;
let parent = absolute.parent().ok_or(std::io::ErrorKind::InvalidInput)?;
let file = crate::platform::open_regular(&absolute)?;
let identity = artifactize_foundation::platform::private::file_identity(&file)?;
let modified = file.metadata()?.modified()?;
let parent_modified = parent.metadata()?.modified()?;
let mut data = Vec::new();
file.take(MAX_CREDENTIAL_BYTES as u64 + 1)
.read_to_end(&mut data)?;
if data.len() > MAX_CREDENTIAL_BYTES {
return Err(std::io::ErrorKind::InvalidData.into());
}
Ok(Some(ImportStamp {
path: absolute,
file: identity,
parent_modified,
modified,
content: Sha256::digest(data),
}))
}
fn read_file(
path: &Path,
unreadable: impl Fn(&str) -> AuthFileError,
) -> Result<Option<AuthFileTokens>, AuthFileError> {
let file =
crate::platform::open_regular(path).map_err(|error| unreadable(&error.to_string()))?;
if !file.metadata().is_ok_and(|metadata| metadata.is_file()) {
return Err(unreadable("it is not a regular file"));
}
let mut data = Vec::new();
file.take(MAX_CREDENTIAL_BYTES as u64 + 1)
.read_to_end(&mut data)
.map_err(|error| unreadable(&error.to_string()))?;
if data.len() > MAX_CREDENTIAL_BYTES {
return Err(unreadable("it is larger than 1 MiB"));
}
let auth: crate::json::Optional<crate::json::Object<AuthFile>> =
serde_json::from_slice(&data).map_err(|_| unreadable("it is not a Codex auth file"))?;
Ok(auth
.0
.and_then(|crate::json::Object(auth)| auth.tokens.0)
.map(|crate::json::Object(tokens)| tokens))
}
pub(super) fn secret_values(path: &Path) -> Result<Vec<String>, AuthFileError> {
let tokens = read_file(path, |reason| AuthFileError::Unreadable(reason.to_owned()))?;
Ok(tokens
.into_iter()
.flat_map(|tokens| [tokens.access_token.0, tokens.refresh_token.0])
.flatten()
.collect())
}
pub(super) fn read_auth_file_at(path: &Path, now: Timestamp) -> Result<FileToken, AuthFileError> {
let name = crate::platform::path_text(path);
let unreadable = |reason: &str| {
AuthFileError::Unreadable(format!(
"{AUTH_FILE_VARIABLE}: cannot read {name}: {reason}."
))
};
let tokens = read_file(path, unreadable)?;
let access_token = tokens
.as_ref()
.and_then(|tokens| tokens.access_token.0.as_deref())
.filter(|token| !token.is_empty())
.ok_or_else(|| unreadable("it holds no ChatGPT sign-in tokens"))?;
let claims = claims(access_token).unwrap_or_default();
let expires_at = claims.exp.0;
if expires_at.is_some_and(|exp| exp <= now.saturating_add(FILE_MARGIN)) {
return Err(AuthFileError::Expired(format!(
"The Codex access token in {name} has expired; sign in with Codex again (for example `codex login`). artifactize never refreshes that file."
)));
}
let account_id = tokens
.as_ref()
.and_then(|tokens| tokens.account_id.0.as_deref())
.filter(|id| !id.is_empty())
.and_then(|id| id.parse().ok())
.or_else(|| claims.account_id())
.ok_or_else(|| unreadable("its token names no ChatGPT account"))?;
Ok(FileToken {
token: Token {
access_token: access_token.to_owned(),
refresh_token: tokens.and_then(|tokens| tokens.refresh_token.0),
account_id,
},
expires_at,
})
}