artifactize_provider/auth/
codex.rs1use std::{
13 path::{Path, PathBuf},
14 time::Duration,
15};
16
17use base64::{
18 Engine,
19 engine::general_purpose::{URL_SAFE, URL_SAFE_NO_PAD},
20};
21use reqwest::Url;
22use serde::{Deserialize, Serialize};
23mod auth_file;
24pub(crate) use auth_file::import_stamp;
25use auth_file::{FileToken, read_auth_file_at};
26mod timestamp;
27pub use timestamp::Timestamp;
28
29use super::storage::{Location, MAX_CREDENTIAL_BYTES, Storage};
30
31pub const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
33const AUTH_ROOT: &str = "https://auth.openai.com";
34pub const AUTH_URL_VARIABLE: &str = "ARTIFACTIZE_CODEX_AUTH_URL";
36pub const CODEX_HOME_VARIABLE: &str = "CODEX_HOME";
38pub const ORIGINATOR: &str = "artifactize";
40#[cfg(test)]
41const CLAIM: &str = "https://api.openai.com/auth";
42const LOCK: &str = "codex";
44const REFRESH_MARGIN: Duration = Duration::from_secs(300);
46const AUTH_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
48pub(crate) const LOGIN_REQUIRED: &str = "Codex is not signed in; run `codex login`.";
49const LOGIN_EXPIRED: &str = "The Codex CLI's sign-in has expired; run `codex login` again.";
50
51#[derive(Debug)]
54pub struct TokenError {
55 pub transient: bool,
56 pub message: String,
57}
58
59impl From<String> for TokenError {
60 fn from(message: String) -> Self {
61 Self {
62 transient: false,
63 message,
64 }
65 }
66}
67
68impl From<&str> for TokenError {
69 fn from(message: &str) -> Self {
70 message.to_owned().into()
71 }
72}
73
74pub(crate) struct Token {
76 pub access_token: String,
77 pub account_id: crate::names::CodexAccountId,
78 pub refresh_token: Option<String>,
79}
80
81pub(crate) fn now() -> Result<Timestamp, String> {
82 Timestamp::now()
83}
84
85pub fn auth_root() -> Result<Url, String> {
87 Ok(
88 crate::llm::variable_endpoint(AUTH_URL_VARIABLE)?.map_or_else(
89 || Url::parse(AUTH_ROOT).expect("built-in Codex auth URL"),
90 crate::llm::TestEndpoint::into_url,
91 ),
92 )
93}
94
95fn endpoint(root: &Url, route: &str) -> Result<Url, String> {
96 let mut url = root.clone();
97 url.path_segments_mut()
98 .map_err(|_| "Invalid Codex sign-in URL.")?
99 .pop_if_empty()
100 .push("oauth")
101 .push(route);
102 Ok(url)
103}
104
105pub fn auth_file() -> Option<PathBuf> {
107 crate::platform::codex_home().map(|home| home.join("auth.json"))
108}
109
110fn client() -> Result<reqwest::Client, String> {
111 reqwest::Client::builder()
112 .redirect(reqwest::redirect::Policy::none())
113 .retry(reqwest::retry::never())
114 .timeout(AUTH_HTTP_TIMEOUT)
115 .build()
116 .map_err(|_| "Cannot initialize the Codex sign-in HTTP client.".into())
117}
118
119fn claims(token: &str) -> Option<JwtClaims> {
122 let mut parts = token.split('.');
123 let (_, payload, _, None) = (parts.next()?, parts.next()?, parts.next()?, parts.next()) else {
124 return None;
125 };
126 let bytes = URL_SAFE_NO_PAD
127 .decode(payload)
128 .or_else(|_| URL_SAFE.decode(payload))
129 .ok()?;
130 serde_json::from_slice(&bytes).ok()
131}
132
133impl JwtClaims {
134 fn account_id(self) -> Option<crate::names::CodexAccountId> {
135 self.auth.0?.0.chatgpt_account_id.0
136 }
137}
138
139#[derive(Default, Deserialize)]
140struct JwtClaims {
141 #[serde(default)]
142 exp: crate::json::Optional<Timestamp>,
143 #[serde(default, rename = "https://api.openai.com/auth")]
144 auth: crate::json::Optional<crate::json::Object<AccountClaim>>,
145}
146#[derive(Default, Deserialize)]
147struct AccountClaim {
148 #[serde(default)]
149 chatgpt_account_id: crate::json::Optional<crate::names::CodexAccountId>,
150}
151
152#[derive(Deserialize)]
153struct TokenResponse {
154 access_token: Option<String>,
155 refresh_token: Option<String>,
156 id_token: Option<String>,
157}
158
159struct Refreshed {
162 access_token: String,
163 refresh_token: Option<String>,
164 id_token: Option<String>,
165}
166
167#[derive(Default, Deserialize)]
168struct OAuthError {
169 error: Option<OAuthErrorField>,
170 code: Option<OAuthCode>,
171}
172
173#[derive(Deserialize)]
174#[serde(untagged)]
175enum OAuthErrorField {
176 Text(String),
177 Object { code: Option<OAuthCode> },
178 Other(serde::de::IgnoredAny),
179}
180
181#[derive(Deserialize)]
182#[serde(untagged)]
183enum OAuthCode {
184 Text(String),
185 Other(serde::de::IgnoredAny),
186}
187
188impl OAuthCode {
189 fn text(&self) -> Option<&str> {
190 match self {
191 Self::Text(code) => Some(code),
192 Self::Other(_) => None,
193 }
194 }
195}
196
197impl OAuthError {
198 fn code(&self) -> Option<&str> {
199 let error = match &self.error {
200 Some(OAuthErrorField::Text(code)) => Some(code.as_str()),
201 Some(OAuthErrorField::Object { code }) => code.as_ref().and_then(OAuthCode::text),
202 _ => None,
203 };
204 error.or_else(|| self.code.as_ref().and_then(OAuthCode::text))
205 }
206}
207
208fn terminal(code: &str) -> bool {
210 matches!(
211 code,
212 "invalid_grant"
213 | "refresh_token_expired"
214 | "refresh_token_reused"
215 | "refresh_token_invalidated"
216 )
217}
218
219fn rejected(status: reqwest::StatusCode, code: Option<&str>) -> TokenError {
220 if code.is_some_and(terminal) {
221 return LOGIN_EXPIRED.into();
222 }
223 TokenError {
224 transient: status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error(),
225 message: format!(
226 "Codex token refresh failed (HTTP {}); the Codex CLI's sign-in was kept.",
227 status.as_u16()
228 ),
229 }
230}
231
232async fn refresh(root: &Url, refresh_token: &str) -> Result<Refreshed, TokenError> {
235 let response = client()?
236 .post(endpoint(root, "token")?)
237 .form(&[
238 ("grant_type", "refresh_token"),
239 ("refresh_token", refresh_token),
240 ("client_id", CLIENT_ID),
241 ])
242 .send()
243 .await
244 .map_err(|_| TokenError {
245 transient: true,
246 message: "Codex token refresh failed; check your connection. The Codex CLI's sign-in was kept."
247 .into(),
248 })?;
249 let status = response.status();
250 if !status.is_success() {
251 let body: OAuthError = response.json().await.unwrap_or_default();
252 return Err(rejected(status, body.code()));
253 }
254 let invalid = || TokenError::from("Invalid Codex token response; nothing was saved.");
255 let tokens: TokenResponse = response.json().await.map_err(|_| invalid())?;
256 let nonempty = |token: Option<String>| token.filter(|token| !token.is_empty());
257 Ok(Refreshed {
258 access_token: nonempty(tokens.access_token).ok_or_else(invalid)?,
259 refresh_token: nonempty(tokens.refresh_token),
260 id_token: nonempty(tokens.id_token),
261 })
262}
263
264pub(crate) async fn access_token(location: Result<&Location, &str>) -> Result<Token, TokenError> {
266 let path = auth_file().ok_or(LOGIN_REQUIRED)?;
267 current_token_at(&Storage::new(location?)?, &path, &auth_root()?, now).await
268}
269
270fn usable(file: &FileToken, now: Timestamp) -> bool {
271 file.expires_at
272 .is_none_or(|expires_at| expires_at > now.saturating_add(REFRESH_MARGIN))
273}
274
275async fn current_token_at(
276 storage: &Storage,
277 path: &Path,
278 root: &Url,
279 clock: impl Fn() -> Result<Timestamp, String>,
280) -> Result<Token, TokenError> {
281 let read = || read_auth_file_at(path)?.ok_or_else(|| TokenError::from(LOGIN_REQUIRED));
282 let file = read()?;
283 if usable(&file, clock()?) {
284 return Ok(file.token);
285 }
286 let _lock = storage.lock(LOCK).await?;
288 let file = read()?;
289 if usable(&file, clock()?) {
290 return Ok(file.token);
291 }
292 let old = file.token;
293 let refresh_token = old.refresh_token.clone().ok_or(LOGIN_EXPIRED)?;
294 crate::secret::history::publish(storage, [old.access_token.as_str(), &refresh_token])?;
295 let refreshed = refresh(root, &refresh_token).await.map_err(|mut error| {
296 error.message =
297 crate::secret::Inventory::new([old.access_token.clone(), refresh_token.clone()])
298 .scrub(&error.message);
299 error
300 })?;
301 let account_id = claims(&refreshed.access_token)
302 .and_then(JwtClaims::account_id)
303 .unwrap_or_else(|| old.account_id.clone());
304 if account_id != old.account_id {
305 return Err(
306 "The refreshed Codex token is for another ChatGPT account; run `codex login` again."
307 .into(),
308 );
309 }
310 let refresh_token = refreshed.refresh_token.clone().unwrap_or(refresh_token);
311 crate::secret::history::publish(storage, [refreshed.access_token.as_str(), &refresh_token])?;
312 auth_file::write_back(path, &refreshed, &refresh_token)?;
313 Ok(Token {
314 access_token: refreshed.access_token,
315 refresh_token: Some(refresh_token),
316 account_id,
317 })
318}
319
320#[derive(Debug)]
323pub enum FileExpiry {
324 Usable { expires_at: Option<Timestamp> },
325 Expired,
326}
327
328pub enum Status {
330 Absent,
331 File { path: PathBuf, expiry: FileExpiry },
332}
333
334impl std::fmt::Debug for Status {
335 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
336 match self {
337 Self::Absent => formatter.write_str("Absent"),
338 Self::File { path, expiry } => formatter
339 .debug_struct("File")
340 .field("path", &crate::platform::path_text(path))
341 .field("expiry", expiry)
342 .finish(),
343 }
344 }
345}
346
347impl Serialize for Status {
348 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
349 use serde::ser::SerializeStruct;
350 let (source, file, expires_at, expired) = match self {
351 Self::Absent => ("none", None, None, false),
352 Self::File {
353 path,
354 expiry: FileExpiry::Usable { expires_at },
355 } => ("file", Some(path), *expires_at, false),
356 Self::File {
357 path,
358 expiry: FileExpiry::Expired,
359 } => ("file", Some(path), None, true),
360 };
361 let mut wire = serializer.serialize_struct("Status", 3 + usize::from(file.is_some()))?;
362 wire.serialize_field("source", source)?;
363 if let Some(file) = file {
364 wire.serialize_field("authFile", &crate::platform::path_text(file))?;
365 }
366 wire.serialize_field("expiresAt", &expires_at)?;
367 wire.serialize_field("expired", &expired)?;
368 wire.end()
369 }
370}
371
372pub fn status() -> Result<Status, String> {
374 let managed = crate::secret::Inventory::new(secret_values()?);
375 read_status()
376 .map_err(|error| managed.scrub(&error))
377 .map(|status| public_status(status, &managed))
378}
379
380fn public_status(mut status: Status, managed: &crate::secret::Inventory) -> Status {
381 if let Status::File { path, expiry } = &mut status {
382 if managed.contains(&crate::platform::path_text(path)) {
383 *path = PathBuf::new();
385 }
386 if let FileExpiry::Usable { expires_at } = expiry {
387 *expires_at = expires_at.filter(|time| !managed.contains(&time.seconds().to_string()));
388 }
389 }
390 status
391}
392
393fn read_status() -> Result<Status, String> {
394 match auth_file() {
395 Some(path) => read_status_at(path, now()?),
396 None => Ok(Status::Absent),
397 }
398}
399
400fn read_status_at(path: PathBuf, now: Timestamp) -> Result<Status, String> {
401 let Some(file) = read_auth_file_at(&path)? else {
402 return Ok(Status::Absent);
403 };
404 let expired = file.expires_at.is_some_and(|expires_at| expires_at <= now)
405 && file.token.refresh_token.is_none();
406 Ok(Status::File {
407 path,
408 expiry: if expired {
409 FileExpiry::Expired
410 } else {
411 FileExpiry::Usable {
412 expires_at: file.expires_at,
413 }
414 },
415 })
416}
417
418#[cfg(test)]
419mod tests;
420
421pub(crate) fn secret_values() -> Result<Vec<String>, String> {
423 match auth_file() {
424 Some(path) => Ok(auth_file::secret_values(&path)?),
425 None => Ok(Vec::new()),
426 }
427}