1use crate::http_client::{self, HttpClientExt};
13use crate::wasm_compat::{WasmCompatSend, WasmCompatSync};
14use std::sync::Arc;
15
16#[derive(Debug, Clone)]
18pub struct DeviceCodePrompt {
19 pub verification_uri: String,
21 pub user_code: String,
23}
24
25#[cfg(not(target_family = "wasm"))]
28pub(crate) type DeviceCodeCallback = dyn Fn(DeviceCodePrompt) + Send + Sync;
29#[cfg(target_family = "wasm")]
30pub(crate) type DeviceCodeCallback = dyn Fn(DeviceCodePrompt);
31
32#[derive(Clone, Default)]
34pub struct DeviceCodeHandler(pub(crate) Option<Arc<DeviceCodeCallback>>);
35
36impl DeviceCodeHandler {
37 pub fn new<F>(handler: F) -> Self
39 where
40 F: Fn(DeviceCodePrompt) + WasmCompatSend + WasmCompatSync + 'static,
41 {
42 Self(Some(Arc::new(handler)))
43 }
44}
45
46impl DeviceCodeHandler {
47 #[cfg(not(target_family = "wasm"))]
50 pub(crate) fn show(&self, prompt: DeviceCodePrompt, fallback_message: &str) {
51 match &self.0 {
52 Some(callback) => callback(prompt),
53 None => println!("{fallback_message}"),
54 }
55 }
56}
57
58impl std::fmt::Debug for DeviceCodeHandler {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 if self.0.is_some() {
61 f.write_str("DeviceCodeHandler(<callback>)")
62 } else {
63 f.write_str("DeviceCodeHandler(None)")
64 }
65 }
66}
67
68#[derive(Debug, thiserror::Error)]
69pub enum AuthError {
70 #[error("{0}")]
71 Message(String),
72 #[error(transparent)]
73 Io(#[from] std::io::Error),
74 #[error(transparent)]
75 Json(#[from] serde_json::Error),
76 #[error(transparent)]
81 Http(#[from] http_client::Error),
82 #[error("{message}")]
85 Reply {
86 message: String,
88 #[source]
90 source: http_client::Error,
91 },
92 #[error("token store failed: {0}")]
94 Store(#[source] crate::error::BoxError),
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct AuthContext {
100 pub api_key: crate::wire::Secret,
103 pub account_id: Option<String>,
106 pub api_base: Option<String>,
109}
110
111#[derive(Clone)]
116#[cfg_attr(target_family = "wasm", allow(dead_code))]
117pub(crate) struct Shell<S> {
118 pub(crate) source: S,
119 pub(crate) store: Arc<dyn TokenStore>,
120 pub(crate) device_code_handler: DeviceCodeHandler,
121 pub(crate) allow_device_flow: bool,
122 pub(crate) refresh_lock: Arc<futures::lock::Mutex<()>>,
124 pub(crate) remembered: Remembered,
125}
126
127impl<S> Shell<S> {
128 pub(crate) fn new(
129 source: S,
130 store: impl TokenStore + 'static,
131 device_code_handler: DeviceCodeHandler,
132 allow_device_flow: bool,
133 ) -> Self {
134 Self {
135 source,
136 store: Arc::new(store),
137 device_code_handler,
138 allow_device_flow,
139 refresh_lock: Arc::default(),
140 remembered: Remembered::default(),
141 }
142 }
143}
144
145impl<S> Shell<S> {
146 #[cfg_attr(target_family = "wasm", allow(dead_code))]
151 pub(crate) async fn hold(&self, key: &str) -> Result<Held<'_>, AuthError> {
152 let refresh = self.refresh_lock.lock().await;
153 let store = self.store.lock(key).await.map_err(AuthError::Store)?;
154 Ok(Held {
155 _refresh: refresh,
156 _store: store,
157 })
158 }
159}
160
161#[cfg_attr(target_family = "wasm", allow(dead_code))]
163pub(crate) struct Held<'a> {
164 _store: StoreLock,
165 _refresh: futures::lock::MutexGuard<'a, ()>,
166}
167
168impl<'a> Held<'a> {
169 #[cfg_attr(target_family = "wasm", allow(dead_code))]
173 pub(crate) async fn store_free_during<S, T>(
174 self,
175 shell: &Shell<S>,
176 key: &str,
177 wait: impl Future<Output = T>,
178 ) -> Result<(T, Held<'a>), AuthError> {
179 let Held { _store, _refresh } = self;
180 drop(_store);
181 let out = wait.await;
182 let store = shell.store.lock(key).await.map_err(AuthError::Store)?;
183 Ok((
184 out,
185 Held {
186 _store: store,
187 _refresh,
188 },
189 ))
190 }
191}
192
193impl<S: std::fmt::Debug> std::fmt::Debug for Shell<S> {
194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195 f.debug_struct("Authenticator")
196 .field("source", &self.source)
197 .field("device_code_handler", &self.device_code_handler)
198 .field("allow_device_flow", &self.allow_device_flow)
199 .finish_non_exhaustive()
200 }
201}
202
203#[derive(Clone, Default)]
206pub(crate) struct Remembered(Arc<std::sync::Mutex<Option<(AuthContext, i64)>>>);
207
208impl Remembered {
209 pub(crate) fn live(&self, skew_seconds: i64) -> Option<AuthContext> {
211 let held = self.0.lock().ok()?;
212 let (context, expires_at) = held.as_ref()?;
213 (!token_expired(Some(*expires_at), skew_seconds)).then(|| context.clone())
214 }
215
216 pub(crate) fn keep(&self, context: &AuthContext, expires_at: Option<i64>) {
219 if let Ok(mut held) = self.0.lock() {
220 *held = expires_at.map(|expires_at| (context.clone(), expires_at));
221 }
222 }
223
224 pub(crate) fn forget(&self) {
226 if let Ok(mut held) = self.0.lock() {
227 *held = None;
228 }
229 }
230}
231
232pub(crate) fn request(method: http::Method, url: &str) -> http::request::Builder {
234 http::Request::builder().method(method).uri(url)
235}
236
237#[cfg(not(target_family = "wasm"))]
239pub(crate) fn form(
240 builder: http::request::Builder,
241 pairs: &[(&str, &str)],
242) -> http::Result<http::Request<bytes::Bytes>> {
243 let body = url::form_urlencoded::Serializer::new(String::new())
244 .extend_pairs(pairs)
245 .finish();
246 builder
247 .header(
248 http::header::CONTENT_TYPE,
249 "application/x-www-form-urlencoded",
250 )
251 .body(body.into())
252}
253
254pub(crate) async fn send_json<H, T>(
258 http: &H,
259 req: http::Result<http::Request<bytes::Bytes>>,
260) -> Result<T, AuthError>
261where
262 H: HttpClientExt,
263 T: serde::de::DeserializeOwned,
264{
265 let bytes = send_bytes(http, req).await?;
266 Ok(serde_json::from_slice(&bytes)?)
267}
268
269pub(crate) async fn send_bytes<H>(
273 http: &H,
274 req: http::Result<http::Request<bytes::Bytes>>,
275) -> Result<bytes::Bytes, AuthError>
276where
277 H: HttpClientExt,
278{
279 let req = req.map_err(http_client::Error::Protocol)?;
280 let (parts, body) = http.send(req).await?.into_parts();
281 let body = body.await?;
282 if !parts.status.is_success() {
283 return Err(http_client::Error::InvalidStatusCodeWithDetails {
284 status: parts.status,
285 body: String::from_utf8_lossy(&body).into_owned(),
286 headers: parts.headers,
287 }
288 .into());
289 }
290 Ok(body)
291}
292
293pub(crate) fn token_expired(expires_at: Option<i64>, skew_seconds: i64) -> bool {
296 let now = (crate::now_ms() / 1000) as i64;
297 expires_at.is_none_or(|exp| now >= exp - skew_seconds)
298}
299
300#[cfg(not(target_family = "wasm"))]
301pub mod loopback;
302mod store;
303
304#[cfg(not(target_family = "wasm"))]
305pub use store::{FileStoreError, FileTokenStore};
306pub use store::{MemoryTokenStore, StoreLock, TokenStore};
307pub(crate) use store::{load_record, save_record};