rig_core/providers/chatgpt/auth/mod.rs
1//! ChatGPT access-token configuration and native OAuth authentication.
2//!
3//! ```no_run
4//! use rig_core::providers::auth::{DeviceCodeHandler, FileTokenStore};
5//! use rig_core::providers::chatgpt::auth::{AuthSource, Authenticator};
6//!
7//! let store = FileTokenStore::new("/path/to/credentials");
8//! let auth = Authenticator::new(AuthSource::OAuth, store, DeviceCodeHandler::default(), true);
9//! ```
10
11use crate::http_client::HttpClientExt;
12use crate::providers::auth::{AuthContext, AuthError, DeviceCodeHandler, Shell, TokenStore};
13use std::fmt;
14
15#[cfg(not(target_family = "wasm"))]
16mod native;
17#[cfg(not(target_family = "wasm"))]
18pub use native::browser_command;
19
20/// The key the sign-in is kept under in the store.
21#[cfg(not(target_family = "wasm"))]
22const STORE_KEY: &str = super::PROVIDER_NAME;
23
24/// What a browser sign-in shows the user while it waits.
25#[derive(Debug, Clone)]
26pub struct BrowserSignInPrompt {
27 /// The sign-in page, for the user to open when the browser did not.
28 pub authorize_url: String,
29 /// Whether the desktop's opener started; the page may still not show.
30 pub browser_launched: bool,
31}
32
33/// How a sign-in asks the user to authorize: in the browser, or with a
34/// code entered on another device.
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum SignInMethod {
37 /// A page opened in the browser, returning to a local listener.
38 Browser,
39 /// A code the user enters at a URL, on any device.
40 DeviceCode,
41}
42
43/// What [`Authenticator::sign_in`] asks the user to do, besides entering a
44/// device code, which goes to the authenticator's [`DeviceCodeHandler`].
45#[derive(Debug, Clone)]
46pub enum SignInPrompt {
47 /// Sign in on the page the browser was asked to open.
48 Browser(BrowserSignInPrompt),
49 /// The browser sign-in could not listen for its callback, for this
50 /// reason; a device code follows.
51 BrowserUnavailable(String),
52}
53
54/// What [`Authenticator::sign_out`] did.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum SignedOut {
57 /// No sign-in was kept.
58 NotSignedIn,
59 /// The sign-in was deleted from the store and forgotten. `revoked` says
60 /// whether the provider revoked its tokens too, or why not.
61 Forgotten {
62 /// The revocation, or why it failed.
63 revoked: Result<(), String>,
64 },
65}
66
67/// Where the ChatGPT credential comes from: a given access token, or a stored OAuth sign-in.
68#[derive(Clone)]
69pub enum AuthSource {
70 /// A token the caller already holds.
71 AccessToken {
72 /// The token.
73 access_token: String,
74 /// The ChatGPT account it belongs to, when known.
75 account_id: Option<String>,
76 },
77 /// The OAuth sign-in kept in the token store, refreshed as needed.
78 OAuth,
79}
80
81impl fmt::Debug for AuthSource {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 match self {
84 Self::AccessToken { .. } => f.write_str("AccessToken(<redacted>)"),
85 Self::OAuth => f.write_str("OAuth"),
86 }
87 }
88}
89
90/// Signs in to ChatGPT and keeps the stored credential fresh. Clones share
91/// the store, the refresh lock and the browser opener.
92#[derive(Clone)]
93pub struct Authenticator(
94 Shell<AuthSource>,
95 #[cfg(not(target_family = "wasm"))] native::BrowserSignIn,
96);
97
98impl fmt::Debug for Authenticator {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 self.0.fmt(f)
101 }
102}
103
104impl Authenticator {
105 /// An authenticator over `source`, keeping an OAuth sign-in in `store`
106 /// under [`PROVIDER_NAME`](super::PROVIDER_NAME), `chatgpt`;
107 /// `device_code_handler` shows a device code when the device flow is
108 /// allowed.
109 pub fn new(
110 source: AuthSource,
111 store: impl TokenStore + 'static,
112 device_code_handler: DeviceCodeHandler,
113 allow_device_flow: bool,
114 ) -> Self {
115 Self(
116 Shell::new(source, store, device_code_handler, allow_device_flow),
117 #[cfg(not(target_family = "wasm"))]
118 native::BrowserSignIn::default(),
119 )
120 }
121
122 /// Forget the credential held in memory, so the next request reads the
123 /// store: after the store's record is deleted, as a sign-out does.
124 pub fn forget(&self) {
125 self.0.remembered.forget();
126 }
127
128 /// This authenticator showing device codes with `handler`, still
129 /// sharing its store and refresh lock with the original.
130 #[must_use]
131 pub fn with_device_code_handler(mut self, handler: DeviceCodeHandler) -> Self {
132 self.0.device_code_handler = handler;
133 self
134 }
135
136 /// Resolve the access token and account id, refreshing through `http` as needed.
137 /// Return cache, transport, or authorization errors. OAuth is unsupported
138 /// on WASM; explicit access tokens remain available.
139 #[cfg_attr(target_family = "wasm", allow(unused_variables))]
140 pub async fn auth_context<H>(&self, http: &H) -> Result<AuthContext, AuthError>
141 where
142 H: HttpClientExt,
143 {
144 match &self.0.source {
145 AuthSource::AccessToken {
146 access_token,
147 account_id,
148 } => Ok(AuthContext {
149 api_key: access_token.clone().into(),
150 account_id: account_id.clone(),
151 api_base: None,
152 }),
153 #[cfg(not(target_family = "wasm"))]
154 AuthSource::OAuth => self.auth_context_oauth(http).await,
155 #[cfg(target_family = "wasm")]
156 AuthSource::OAuth => Err(AuthError::Message(
157 "ChatGPT OAuth is not supported on wasm targets".into(),
158 )),
159 }
160 }
161}