1use super::{Authenticator, BrowserSignInPrompt, STORE_KEY, SignInMethod, SignInPrompt, SignedOut};
4use crate::http_client::HttpClientExt;
5use crate::json_utils::Lenient;
6use crate::providers::auth::loopback::LoopbackError;
7use crate::providers::auth::{
8 AuthContext, AuthError, DeviceCodePrompt, form, load_record, request, save_record, send_bytes,
9 send_json, token_expired,
10};
11use crate::wasm_compat::{WasmCompatSend, WasmCompatSync};
12use base64::Engine;
13use base64::prelude::BASE64_URL_SAFE_NO_PAD;
14use bytes::Bytes;
15use http::Method;
16use serde::{Deserialize, Serialize};
17
18mod browser;
19
20pub use browser::browser_command;
21
22const CHATGPT_AUTH_BASE: &str = "https://auth.openai.com";
23const CHATGPT_DEVICE_CODE_URL: &str = "https://auth.openai.com/api/accounts/deviceauth/usercode";
24const CHATGPT_DEVICE_TOKEN_URL: &str = "https://auth.openai.com/api/accounts/deviceauth/token";
25const CHATGPT_OAUTH_TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
26const CHATGPT_OAUTH_REVOKE_URL: &str = "https://auth.openai.com/api/accounts/oauth/revoke";
30const CHATGPT_DEVICE_VERIFY_URL: &str = "https://auth.openai.com/codex/device";
31const CHATGPT_CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
32const TOKEN_EXPIRY_SKEW_SECONDS: i64 = 60;
33const DEVICE_CODE_TIMEOUT_SECONDS: i64 = 15 * 60;
34const BROWSER_SIGN_IN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15 * 60);
35const DEVICE_CODE_POLL_SLEEP_SECONDS: u64 = 5;
36
37#[derive(Debug, Clone, Deserialize, Serialize, Default)]
38struct AuthRecord {
39 access_token: Option<String>,
40 refresh_token: Option<String>,
41 id_token: Option<String>,
42 expires_at: Option<i64>,
43 account_id: Option<String>,
44}
45
46#[derive(Debug, Deserialize)]
47struct DeviceCodeResponse {
48 device_auth_id: String,
49 #[serde(alias = "usercode")]
50 user_code: String,
51 interval: Option<serde_json::Value>,
53}
54
55#[derive(Debug, Deserialize)]
56struct DeviceTokenResponse {
57 authorization_code: String,
58 code_verifier: String,
59}
60
61#[derive(Debug, Deserialize)]
62struct OAuthTokenResponse {
63 access_token: String,
64 refresh_token: Option<String>,
65 id_token: Option<String>,
66}
67
68#[derive(Debug, Deserialize)]
69struct OAuthErrorResponse {
70 error: Option<String>,
71 error_description: Option<String>,
72}
73
74enum RefreshTokensError {
75 Reauthenticate,
76 Auth(AuthError),
77}
78
79#[derive(Clone)]
82pub(super) struct BrowserSignIn {
83 opener: std::sync::Arc<dyn Fn(&str) -> bool + Send + Sync>,
84 app: String,
85}
86
87impl Default for BrowserSignIn {
88 fn default() -> Self {
89 Self {
90 opener: std::sync::Arc::new(browser::open_browser),
91 app: "rig".into(),
92 }
93 }
94}
95
96impl SignInMethod {
97 pub fn detect(device_asked: bool) -> Self {
102 let set = |name: &str| std::env::var_os(name).is_some_and(|value| !value.is_empty());
103 let graphical = !(set("SSH_CONNECTION") || set("SSH_TTY"))
104 && (cfg!(any(target_os = "macos", windows))
105 || set("DISPLAY")
106 || set("WAYLAND_DISPLAY"));
107 if device_asked || !graphical {
108 Self::DeviceCode
109 } else {
110 Self::Browser
111 }
112 }
113}
114
115impl Authenticator {
116 #[must_use]
122 pub fn with_browser_opener(
123 mut self,
124 opener: impl Fn(&str) -> bool + WasmCompatSend + WasmCompatSync + 'static,
125 ) -> Self {
126 self.1.opener = std::sync::Arc::new(opener);
127 self
128 }
129
130 #[must_use]
133 pub fn with_app_name(mut self, app: impl Into<String>) -> Self {
134 self.1.app = app.into();
135 self
136 }
137
138 pub(super) async fn auth_context_oauth<H>(&self, http: &H) -> Result<AuthContext, AuthError>
139 where
140 H: HttpClientExt,
141 {
142 if let Some(context) = self.0.remembered.live(TOKEN_EXPIRY_SKEW_SECONDS) {
143 return Ok(context);
144 }
145 let held = self.0.hold(STORE_KEY).await?;
146 let mut record: AuthRecord = load_record(&*self.0.store, STORE_KEY).await?;
147
148 if let Some(access_token) = record.access_token.clone()
149 && !token_expired(record.expires_at, TOKEN_EXPIRY_SKEW_SECONDS)
150 {
151 let account_id = record
152 .account_id
153 .clone()
154 .or_else(|| extract_account_id(record.id_token.as_deref()))
155 .or_else(|| extract_account_id(Some(&access_token)));
156 if account_id != record.account_id {
157 record.account_id = account_id;
158 save_record(&*self.0.store, STORE_KEY, &record).await?;
159 }
160 return Ok(self.remember(record));
161 }
162
163 if let Some(refresh_token) = record.refresh_token.clone() {
164 match self.refresh_tokens(http, &refresh_token).await {
165 Ok(refreshed) => {
166 save_record(&*self.0.store, STORE_KEY, &refreshed).await?;
167 return Ok(self.remember(refreshed));
168 }
169 Err(RefreshTokensError::Reauthenticate) => {
170 let kept: AuthRecord = load_record(&*self.0.store, STORE_KEY).await?;
173 if kept.refresh_token != record.refresh_token
174 && kept.access_token.is_some()
175 && !token_expired(kept.expires_at, TOKEN_EXPIRY_SKEW_SECONDS)
176 {
177 return Ok(self.remember(kept));
178 }
179 }
180 Err(RefreshTokensError::Auth(err)) => return Err(err),
181 }
182 }
183
184 if !self.0.allow_device_flow {
185 return Err(AuthError::Message(
186 "ChatGPT sign-in required. Reconnect ChatGPT in Settings before using this provider."
187 .into(),
188 ));
189 }
190
191 let (fresh, _held) = held
192 .store_free_during(&self.0, STORE_KEY, self.login_device_flow(http))
193 .await?;
194 self.keep(fresh?).await
195 }
196
197 pub async fn sign_in<H, F>(
202 &self,
203 http: &H,
204 method: SignInMethod,
205 mut prompt: F,
206 ) -> Result<AuthContext, AuthError>
207 where
208 H: HttpClientExt,
209 F: FnMut(SignInPrompt) + WasmCompatSend,
210 {
211 if method == SignInMethod::Browser {
212 let browser = self
213 .sign_in_with_browser(http, |page| prompt(SignInPrompt::Browser(page)))
214 .await;
215 match browser {
216 Err(AuthError::Io(error)) if error.kind() == std::io::ErrorKind::AddrInUse => {
217 prompt(SignInPrompt::BrowserUnavailable(error.to_string()));
218 }
219 other => return other,
220 }
221 }
222 self.sign_in_with_device_code(http).await
223 }
224
225 pub async fn sign_in_with_device_code<H>(&self, http: &H) -> Result<AuthContext, AuthError>
229 where
230 H: HttpClientExt,
231 {
232 let fresh = self.login_device_flow(http).await?;
233 let _held = self.0.hold(STORE_KEY).await?;
234 self.keep(fresh).await
235 }
236
237 pub async fn sign_in_with_browser<H, F>(
252 &self,
253 http: &H,
254 prompt: F,
255 ) -> Result<AuthContext, AuthError>
256 where
257 H: HttpClientExt,
258 F: FnOnce(BrowserSignInPrompt) + WasmCompatSend,
259 {
260 let state = browser::random_token(2);
261 let listener = browser::loopback(&self.1.app)
262 .listen(
263 state.clone(),
264 std::time::Instant::now() + BROWSER_SIGN_IN_TIMEOUT,
265 )
266 .map_err(listen_error)?;
267 let redirect_uri = listener.redirect_uri().to_owned();
268 let pkce = browser::Pkce::generate();
269 let authorize_url =
270 browser::authorize_url(&redirect_uri, &pkce.challenge, &state, &originator());
271 let browser_launched = (self.1.opener)(&authorize_url);
272 prompt(BrowserSignInPrompt {
273 authorize_url,
274 browser_launched,
275 });
276
277 let received = listener.code().await.map_err(listen_error)?;
278 let exchanged =
279 exchange_authorization_code(http, received.code(), &pkce.verifier, &redirect_uri).await;
280 match &exchanged {
281 Ok(_) => received.succeeded(),
282 Err(error) => received.failed(&error.to_string()),
283 }
284 let fresh = exchanged?;
285 let _held = self.0.hold(STORE_KEY).await?;
286 self.keep(fresh).await
287 }
288
289 pub async fn sign_out<H>(&self, http: &H) -> Result<SignedOut, AuthError>
299 where
300 H: HttpClientExt,
301 {
302 let _held = self.0.hold(STORE_KEY).await?;
303 let record: AuthRecord = load_record(&*self.0.store, STORE_KEY).await?;
304 let tokens = [
305 (record.refresh_token.as_deref(), "refresh_token"),
306 (record.access_token.as_deref(), "access_token"),
307 ];
308 let mut revoked = None;
309 for (token, hint) in tokens {
310 let Some(token) = token else { continue };
311 let result = revoke(http, token, hint).await;
312 let result = result.map_err(|error| format!("revoking the {hint} failed: {error}"));
313 revoked = Some(match revoked {
314 Some(Err(earlier)) => Err(earlier),
315 _ => result,
316 });
317 }
318 self.0
319 .store
320 .delete(STORE_KEY)
321 .await
322 .map_err(AuthError::Store)?;
323 self.0.remembered.forget();
324 Ok(match revoked {
325 Some(revoked) => SignedOut::Forgotten { revoked },
326 None => SignedOut::NotSignedIn,
327 })
328 }
329
330 async fn keep(&self, fresh: AuthRecord) -> Result<AuthContext, AuthError> {
332 save_record(&*self.0.store, STORE_KEY, &fresh).await?;
333 Ok(self.remember(fresh))
334 }
335
336 fn remember(&self, record: AuthRecord) -> AuthContext {
338 let context = AuthContext {
339 api_key: record.access_token.unwrap_or_default().into(),
340 account_id: record.account_id,
341 api_base: None,
342 };
343 self.0.remembered.keep(&context, record.expires_at);
344 context
345 }
346
347 async fn login_device_flow<H>(&self, http: &H) -> Result<AuthRecord, AuthError>
348 where
349 H: HttpClientExt,
350 {
351 let device: DeviceCodeResponse = send_json(
352 http,
353 request(Method::POST, CHATGPT_DEVICE_CODE_URL)
354 .header(http::header::CONTENT_TYPE, "application/json")
355 .body(Bytes::from(serde_json::to_vec(
356 &serde_json::json!({ "client_id": CHATGPT_CLIENT_ID }),
357 )?)),
358 )
359 .await?;
360
361 self.0.device_code_handler.show(
362 DeviceCodePrompt {
363 verification_uri: CHATGPT_DEVICE_VERIFY_URL.to_string(),
364 user_code: device.user_code.clone(),
365 },
366 &format!(
367 "Sign in with ChatGPT:\n1) Visit {CHATGPT_DEVICE_VERIFY_URL}\n2) Enter code: {}\nDo not share this device code.",
368 device.user_code
369 ),
370 );
371
372 let interval = device
373 .interval
374 .as_ref()
375 .and_then(Lenient::as_u64_lenient)
376 .unwrap_or(DEVICE_CODE_POLL_SLEEP_SECONDS)
377 .max(1);
378 let start = std::time::Instant::now();
379 let code = loop {
380 if start.elapsed().as_secs() as i64 >= DEVICE_CODE_TIMEOUT_SECONDS {
381 return Err(AuthError::Message(
382 "Timed out waiting for ChatGPT device authorization".into(),
383 ));
384 }
385
386 let poll = send_json::<_, DeviceTokenResponse>(
387 http,
388 request(Method::POST, CHATGPT_DEVICE_TOKEN_URL)
389 .header(http::header::CONTENT_TYPE, "application/json")
390 .body(Bytes::from(serde_json::to_vec(&serde_json::json!({
391 "device_auth_id": device.device_auth_id,
392 "user_code": device.user_code,
393 }))?)),
394 )
395 .await;
396
397 match poll {
398 Ok(token_response) => break token_response,
399 Err(AuthError::Http(err))
402 if matches!(
403 err.non_success_status().map(|status| status.as_u16()),
404 Some(403 | 404)
405 ) =>
406 {
407 crate::wasm_compat::sleep(std::time::Duration::from_secs(interval)).await;
408 continue;
409 }
410 Err(AuthError::Http(err)) if err.non_success_status().is_some() => {
411 let status = err.non_success_status().unwrap_or_default();
412 let text = err.non_success_body().unwrap_or_default();
413 return Err(AuthError::Reply {
414 message: format!("ChatGPT device authorization failed: {status} {text}"),
415 source: err,
416 });
417 }
418 Err(err) => return Err(err),
419 }
420 };
421
422 exchange_authorization_code(
423 http,
424 &code.authorization_code,
425 &code.code_verifier,
426 &format!("{CHATGPT_AUTH_BASE}/deviceauth/callback"),
427 )
428 .await
429 }
430
431 async fn refresh_tokens<H>(
432 &self,
433 http: &H,
434 refresh_token: &str,
435 ) -> Result<AuthRecord, RefreshTokensError>
436 where
437 H: HttpClientExt,
438 {
439 let response = send_json::<_, OAuthTokenResponse>(
440 http,
441 form(
442 request(Method::POST, CHATGPT_OAUTH_TOKEN_URL),
443 &[
444 ("client_id", CHATGPT_CLIENT_ID),
445 ("grant_type", "refresh_token"),
446 ("refresh_token", refresh_token),
447 ("scope", "openid profile email"),
448 ],
449 ),
450 )
451 .await;
452
453 let (status, body, reply) = match response {
454 Ok(tokens) => {
455 return Ok(build_auth_record(tokens, Some(refresh_token.to_owned())));
456 }
457 Err(AuthError::Http(err)) if err.non_success_status().is_some() => (
458 err.non_success_status().unwrap_or_default(),
459 err.non_success_body().unwrap_or_default().to_owned(),
460 err,
461 ),
462 Err(err) => return Err(RefreshTokensError::Auth(err)),
463 };
464 let oauth_error = serde_json::from_str::<OAuthErrorResponse>(&body).ok();
465 if should_reauthenticate_after_refresh(
466 status,
467 oauth_error
468 .as_ref()
469 .and_then(|error| error.error.as_deref()),
470 ) {
471 return Err(RefreshTokensError::Reauthenticate);
472 }
473
474 Err(RefreshTokensError::Auth(AuthError::Reply {
475 message: format_refresh_error(status, oauth_error.as_ref(), &body),
476 source: reply,
477 }))
478 }
479}
480
481fn listen_error(error: LoopbackError) -> AuthError {
484 match error {
485 LoopbackError::Bind(error) | LoopbackError::Io(error) => AuthError::Io(error),
486 other => AuthError::Message(other.to_string()),
487 }
488}
489
490async fn revoke<H>(http: &H, token: &str, hint: &str) -> Result<(), AuthError>
493where
494 H: HttpClientExt,
495{
496 send_bytes(
497 http,
498 form(
499 request(Method::POST, CHATGPT_OAUTH_REVOKE_URL),
500 &[
501 ("token", token),
502 ("token_type_hint", hint),
503 ("client_id", CHATGPT_CLIENT_ID),
504 ],
505 ),
506 )
507 .await
508 .map(drop)
509}
510
511async fn exchange_authorization_code<H>(
513 http: &H,
514 code: &str,
515 code_verifier: &str,
516 redirect_uri: &str,
517) -> Result<AuthRecord, AuthError>
518where
519 H: HttpClientExt,
520{
521 let tokens: OAuthTokenResponse = send_json(
522 http,
523 form(
524 request(Method::POST, CHATGPT_OAUTH_TOKEN_URL),
525 &[
526 ("grant_type", "authorization_code"),
527 ("code", code),
528 ("redirect_uri", redirect_uri),
529 ("client_id", CHATGPT_CLIENT_ID),
530 ("code_verifier", code_verifier),
531 ],
532 ),
533 )
534 .await?;
535
536 Ok(build_auth_record(tokens, None))
537}
538
539fn originator() -> String {
541 let identity = crate::providers::chatgpt::IDENTITY;
542 std::env::var(identity.originator_env)
543 .ok()
544 .filter(|value| !value.is_empty())
545 .unwrap_or_else(|| identity.originator.to_owned())
546}
547
548fn build_auth_record(
549 tokens: OAuthTokenResponse,
550 previous_refresh_token: Option<String>,
551) -> AuthRecord {
552 let access_token = Some(tokens.access_token);
553 let id_token = tokens.id_token;
554 AuthRecord {
555 expires_at: access_token
556 .as_deref()
557 .and_then(extract_expiration_timestamp),
558 account_id: extract_account_id(id_token.as_deref()).or_else(|| {
559 access_token
560 .as_deref()
561 .and_then(|token| extract_account_id(Some(token)))
562 }),
563 access_token,
564 refresh_token: tokens.refresh_token.or(previous_refresh_token),
565 id_token,
566 }
567}
568
569fn extract_expiration_timestamp(token: &str) -> Option<i64> {
570 decode_jwt_claims(token)
571 .get("exp")
572 .and_then(|value| value.as_i64().or_else(|| value.as_u64().map(|v| v as i64)))
573}
574
575fn extract_account_id(token: Option<&str>) -> Option<String> {
576 let claims = decode_jwt_claims(token?);
577 claims
578 .get("https://api.openai.com/auth")
579 .and_then(|value| value.as_object())
580 .and_then(|map| map.get("chatgpt_account_id"))
581 .and_then(|value| value.as_str())
582 .map(ToOwned::to_owned)
583}
584
585fn decode_jwt_claims(token: &str) -> serde_json::Value {
586 let payload = token.split('.').nth(1).unwrap_or_default();
587 let decoded = BASE64_URL_SAFE_NO_PAD.decode(payload.as_bytes());
588 decoded
589 .ok()
590 .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
591 .unwrap_or(serde_json::Value::Null)
592}
593
594fn should_reauthenticate_after_refresh(status: http::StatusCode, error_code: Option<&str>) -> bool {
595 matches!(
596 status,
597 http::StatusCode::BAD_REQUEST | http::StatusCode::UNAUTHORIZED
598 ) && matches!(error_code, Some("invalid_grant"))
599}
600
601fn format_refresh_error(
602 status: http::StatusCode,
603 oauth_error: Option<&OAuthErrorResponse>,
604 body: &str,
605) -> String {
606 let error_code = oauth_error.and_then(|error| error.error.as_deref());
607 let description = oauth_error.and_then(|error| error.error_description.as_deref());
608
609 if let Some(description) = description
610 .map(str::trim)
611 .filter(|description| !description.is_empty())
612 {
613 return format!(
614 "ChatGPT token refresh failed: {status} {} ({description})",
615 error_code.unwrap_or("unknown_error")
616 );
617 }
618
619 if let Some(error_code) = error_code {
620 return format!("ChatGPT token refresh failed: {status} {error_code}");
621 }
622
623 if !body.trim().is_empty() {
624 return format!("ChatGPT token refresh failed: {status} {body}");
625 }
626
627 format!("ChatGPT token refresh failed: {status}")
628}
629
630#[cfg(test)]
631mod tests;