| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | use std::sync::Arc; |
| 3 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 4 | use std::time::Duration; |
| 5 | |
| 6 | use serde_json::{Value, json}; |
| 7 | use tokio::sync::Mutex; |
| 8 | use tokio::time::{Instant, sleep}; |
| 9 | |
| 10 | use crate::app::App; |
| 11 | use crate::error::{Error, Result}; |
| 12 | use crate::events::TabControl; |
| 13 | use crate::native::NativeHttp; |
| 14 | use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult}; |
| 15 | use crate::scope::Scope; |
| 16 | use crate::transport::{CdpTransport, Transport}; |
| 17 | |
| 18 | pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:9222"; |
| 19 | pub(crate) const FETCH_SCRIPT: &str = include_str!("../assets/fetch.js"); |
| 20 | pub(crate) const NOT_GRANTED_PREFIX: &str = "the app is not granted"; |
| 21 | const MAX_DOWNLOAD_BYTES: u64 = 60 * 1024 * 1024; |
| 22 | const DEFAULT_CONCURRENCY: usize = 6; |
| 23 | |
| 24 | #[derive(Debug, Clone)] |
| 25 | pub struct SessionConfig { |
| 26 | pub refresh_margin: Duration, |
| 27 | pub token_wait: Duration, |
| 28 | pub token_poll: Duration, |
| 29 | pub evaluate_timeout: Duration, |
| 30 | pub max_throttle_retries: usize, |
| 31 | pub max_retry_wait: Duration, |
| 32 | pub default_retry_wait: Duration, |
| 33 | pub unauthorized_reload_wait: Duration, |
| 34 | pub native_http: bool, |
| 35 | } |
| 36 | |
| 37 | impl Default for SessionConfig { |
| 38 | fn default() -> Self { |
| 39 | SessionConfig { |
| 40 | refresh_margin: Duration::from_secs(120), |
| 41 | token_wait: Duration::from_secs(60), |
| 42 | token_poll: Duration::from_secs(3), |
| 43 | evaluate_timeout: Duration::from_secs(60), |
| 44 | max_throttle_retries: 3, |
| 45 | max_retry_wait: Duration::from_secs(30), |
| 46 | default_retry_wait: Duration::from_secs(2), |
| 47 | unauthorized_reload_wait: Duration::from_secs(5), |
| 48 | native_http: false, |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | impl SessionConfig { |
| 54 | /// The app's settings: requests go out from Rust unless TEAMS_PAGE_FETCH is set. |
| 55 | pub fn for_app() -> Self { |
| 56 | SessionConfig { |
| 57 | native_http: std::env::var_os("TEAMS_PAGE_FETCH").is_none(), |
| 58 | ..SessionConfig::default() |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | #[derive(Default)] |
| 64 | struct TokenSearch { |
| 65 | refresh_error: Option<String>, |
| 66 | pages: Vec<String>, |
| 67 | ungranted: HashSet<App>, |
| 68 | } |
| 69 | |
| 70 | #[derive(Clone)] |
| 71 | pub struct Session { |
| 72 | pub(crate) transport: Arc<dyn Transport>, |
| 73 | pub(crate) config: SessionConfig, |
| 74 | tabs: Arc<HashMap<App, Mutex<Option<TabControl>>>>, |
| 75 | force_refresh: Arc<AtomicBool>, |
| 76 | native: Option<Arc<NativeHttp>>, |
| 77 | } |
| 78 | |
| 79 | impl Session { |
| 80 | pub async fn connect(endpoint: &str) -> Result<Self> { |
| 81 | Self::connect_with(endpoint, SessionConfig::default()).await |
| 82 | } |
| 83 | |
| 84 | pub async fn connect_with(endpoint: &str, config: SessionConfig) -> Result<Self> { |
| 85 | Self::with_transport(Arc::new(CdpTransport::new(endpoint)), config).await |
| 86 | } |
| 87 | |
| 88 | pub async fn with_transport(transport: Arc<dyn Transport>, config: SessionConfig) -> Result<Self> { |
| 89 | transport.check().await?; |
| 90 | let native = config |
| 91 | .native_http |
| 92 | .then(|| NativeHttp::new(config.evaluate_timeout, MAX_DOWNLOAD_BYTES)) |
| 93 | .flatten() |
| 94 | .map(Arc::new); |
| 95 | Ok(Session { |
| 96 | native, |
| 97 | transport, |
| 98 | config, |
| 99 | tabs: Arc::new(App::ALL.into_iter().map(|app| (app, Mutex::new(None))).collect()), |
| 100 | force_refresh: Arc::new(AtomicBool::new(false)), |
| 101 | }) |
| 102 | } |
| 103 | |
| 104 | pub async fn request(&self, method: Method, url: &str, scope: &Scope, body: Option<Value>) -> Result<ApiResponse> { |
| 105 | let request = Request { |
| 106 | method, |
| 107 | body, |
| 108 | ..Request::get(url) |
| 109 | }; |
| 110 | self.send(request, scope).await |
| 111 | } |
| 112 | |
| 113 | pub async fn send(&self, request: Request, scope: &Scope) -> Result<ApiResponse> { |
| 114 | let url = request.url.clone(); |
| 115 | let response = self.batch(&[request], scope).await?.remove(0); |
| 116 | if response.status >= 400 || response.status == 0 { |
| 117 | return Err(Error::api(response.status, &url, response.body)); |
| 118 | } |
| 119 | Ok(response) |
| 120 | } |
| 121 | |
| 122 | pub async fn batch(&self, requests: &[Request], scope: &Scope) -> Result<Vec<ApiResponse>> { |
| 123 | let mut results: Vec<Option<ApiResponse>> = vec![None; requests.len()]; |
| 124 | let mut pending: Vec<usize> = (0..requests.len()).collect(); |
| 125 | for attempt in 0..=self.config.max_throttle_retries { |
| 126 | let batch: Vec<&Request> = pending.iter().map(|&index| &requests[index]).collect(); |
| 127 | let answers = self.run_with_fresh_token(&batch, scope).await?; |
| 128 | let unauthorized_first_try = attempt == 0 && answers.iter().any(|answer| answer.status == 401); |
| 129 | if unauthorized_first_try { |
| 130 | // A CAE-revoked token stays unexpired in the app cache, so only a refresh-token grant replaces it. |
| 131 | self.force_refresh.store(true, Ordering::SeqCst); |
| 132 | self.reload_all().await; |
| 133 | sleep(self.config.unauthorized_reload_wait).await; |
| 134 | self.drop_all().await; |
| 135 | } |
| 136 | let mut retry = Vec::new(); |
| 137 | for (&index, answer) in pending.iter().zip(answers) { |
| 138 | let throttled = answer.status == 429 || (attempt == 0 && answer.status == 401); |
| 139 | results[index] = Some(answer); |
| 140 | if throttled { |
| 141 | retry.push(index); |
| 142 | } |
| 143 | } |
| 144 | if !unauthorized_first_try { |
| 145 | self.force_refresh.store(false, Ordering::SeqCst); |
| 146 | } |
| 147 | if retry.is_empty() || attempt == self.config.max_throttle_retries { |
| 148 | break; |
| 149 | } |
| 150 | let wait = retry |
| 151 | .iter() |
| 152 | .filter_map(|&index| results[index].as_ref()) |
| 153 | .map(|answer| retry_wait(answer.retry_after.as_deref(), self.config.default_retry_wait)) |
| 154 | .max() |
| 155 | .unwrap_or_default(); |
| 156 | sleep(wait.min(self.config.max_retry_wait)).await; |
| 157 | pending = retry; |
| 158 | } |
| 159 | Ok(results.into_iter().flatten().collect()) |
| 160 | } |
| 161 | |
| 162 | /// Keeps the app tab where it is until the guard drops, e.g. for the length of a call. |
| 163 | pub fn hold_tab(&self, app: App) -> TabHold { |
| 164 | self.transport.hold(app, true); |
| 165 | TabHold { |
| 166 | transport: self.transport.clone(), |
| 167 | app, |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | pub async fn close(&self) { |
| 172 | self.drop_all().await; |
| 173 | } |
| 174 | |
| 175 | async fn run_with_fresh_token(&self, requests: &[&Request], scope: &Scope) -> Result<Vec<ApiResponse>> { |
| 176 | if let Some(native) = &self.native |
| 177 | && let Some(results) = native.run(self, requests, scope, self.force_refresh.load(Ordering::SeqCst)).await |
| 178 | { |
| 179 | return Ok(results); |
| 180 | } |
| 181 | let mut search = TokenSearch::default(); |
| 182 | if let Some(results) = self.run_in_any_tab(requests, scope, &mut search).await? { |
| 183 | return Ok(results); |
| 184 | } |
| 185 | if search.ungranted.len() == App::ALL.len() { |
| 186 | return Err(Error::LoginRequired(format!( |
| 187 | "neither the Teams nor the Outlook web app is granted {scope}" |
| 188 | ))); |
| 189 | } |
| 190 | self.reload_all().await; |
| 191 | let deadline = Instant::now() + self.config.token_wait; |
| 192 | while Instant::now() < deadline { |
| 193 | sleep(self.config.token_poll).await; |
| 194 | self.drop_all().await; |
| 195 | if let Some(results) = self.run_in_any_tab(requests, scope, &mut search).await? { |
| 196 | return Ok(results); |
| 197 | } |
| 198 | } |
| 199 | let diagnosis = self.transport.diagnose().await?; |
| 200 | if diagnosis.login_pending { |
| 201 | return Err(Error::LoginRequired("sign in in the browser window".into())); |
| 202 | } |
| 203 | if !diagnosis.app_tab_open { |
| 204 | return Err(Error::NoAppTab); |
| 205 | } |
| 206 | let mut detail = search |
| 207 | .refresh_error |
| 208 | .map(|reason| format!(" (token refresh failed in {reason})")) |
| 209 | .unwrap_or_default(); |
| 210 | if !search.pages.is_empty() { |
| 211 | detail.push_str(&format!(" [{}]", search.pages.join("; "))); |
| 212 | } |
| 213 | Err(Error::NoFreshToken { |
| 214 | scope: scope.to_string(), |
| 215 | detail, |
| 216 | }) |
| 217 | } |
| 218 | |
| 219 | async fn run_in_any_tab( |
| 220 | &self, |
| 221 | requests: &[&Request], |
| 222 | scope: &Scope, |
| 223 | search: &mut TokenSearch, |
| 224 | ) -> Result<Option<Vec<ApiResponse>>> { |
| 225 | let payload = self.payload(requests, scope); |
| 226 | let expression = format!("({FETCH_SCRIPT})({payload})"); |
| 227 | let has_write = requests.iter().any(|request| request.method != Method::Get); |
| 228 | for app in tab_order(requests, scope) { |
| 229 | let outcome = match self.evaluate_in(app, &expression).await { |
| 230 | Ok(Some(value)) => value, |
| 231 | Ok(None) => continue, |
| 232 | Err(error) => { |
| 233 | self.drop_connection(app).await; |
| 234 | if has_write { |
| 235 | return Err(Error::WriteInterrupted(error.to_string())); |
| 236 | } |
| 237 | continue; |
| 238 | } |
| 239 | }; |
| 240 | let outcome: Outcome = |
| 241 | serde_json::from_value(outcome).map_err(|error| Error::Cdp(format!("unexpected page answer: {error}")))?; |
| 242 | if let Some(results) = outcome.results { |
| 243 | return Ok(Some(results.into_iter().map(WireResult::into).collect())); |
| 244 | } |
| 245 | if let Some(page) = &outcome.page { |
| 246 | let line = format!("{app}: {page}"); |
| 247 | search.pages.retain(|seen| !seen.starts_with(&format!("{app}:"))); |
| 248 | search.pages.push(line); |
| 249 | } |
| 250 | if let Some(reason) = outcome.refresh_error { |
| 251 | if reason.starts_with(NOT_GRANTED_PREFIX) { |
| 252 | search.ungranted.insert(app); |
| 253 | } |
| 254 | search.refresh_error.get_or_insert_with(|| format!("{app}: {reason}")); |
| 255 | } |
| 256 | } |
| 257 | Ok(None) |
| 258 | } |
| 259 | |
| 260 | fn payload(&self, requests: &[&Request], scope: &Scope) -> String { |
| 261 | let wire: Vec<WireRequest> = requests.iter().map(|&request| request.into()).collect(); |
| 262 | json!({ |
| 263 | "requests": wire, |
| 264 | "resource": scope.resource, |
| 265 | "scope": scope.name, |
| 266 | "nestedApp": scope.nested_app_json(), |
| 267 | "marginMs": self.config.refresh_margin.as_millis() as u64, |
| 268 | "concurrency": DEFAULT_CONCURRENCY, |
| 269 | "maxBytes": MAX_DOWNLOAD_BYTES, |
| 270 | "forceRefresh": self.force_refresh.load(Ordering::SeqCst), |
| 271 | }) |
| 272 | .to_string() |
| 273 | } |
| 274 | |
| 275 | pub(crate) async fn evaluate_in(&self, app: App, expression: &str) -> Result<Option<Value>> { |
| 276 | let mut slot = self.tabs[&app].lock().await; |
| 277 | if slot.is_none() { |
| 278 | let Some((control, _)) = self.transport.open(app, false).await? else { |
| 279 | return Ok(None); |
| 280 | }; |
| 281 | *slot = Some(control); |
| 282 | } |
| 283 | let control = slot.as_ref().expect("connection set above"); |
| 284 | let outcome = control.evaluate_within(expression, self.config.evaluate_timeout).await; |
| 285 | if outcome.is_err() { |
| 286 | *slot = None; |
| 287 | } |
| 288 | outcome.map(Some) |
| 289 | } |
| 290 | |
| 291 | async fn drop_connection(&self, app: App) { |
| 292 | *self.tabs[&app].lock().await = None; |
| 293 | } |
| 294 | |
| 295 | async fn drop_all(&self) { |
| 296 | for app in App::ALL { |
| 297 | self.drop_connection(app).await; |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | async fn reload_all(&self) { |
| 302 | for app in App::ALL { |
| 303 | let _ = self.transport.wake(app).await; |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | pub struct TabHold { |
| 309 | transport: Arc<dyn Transport>, |
| 310 | app: App, |
| 311 | } |
| 312 | |
| 313 | impl Drop for TabHold { |
| 314 | fn drop(&mut self) { |
| 315 | self.transport.hold(self.app, false); |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration { |
| 320 | header |
| 321 | .and_then(|value| value.trim().parse::<f64>().ok()) |
| 322 | .filter(|seconds| seconds.is_finite() && *seconds >= 0.0) |
| 323 | .map(Duration::from_secs_f64) |
| 324 | .unwrap_or(default) |
| 325 | } |
| 326 | |
| 327 | /// Requests without a token go to the Teams tab first: the Outlook mail page's CSP blocks cross-origin fetches. |
| 328 | fn tab_order(requests: &[&Request], scope: &Scope) -> [App; 2] { |
| 329 | if requests.iter().all(|request| request.anonymous) { |
| 330 | [App::Teams, App::Outlook] |
| 331 | } else { |
| 332 | scope.tab_order() |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | #[cfg(test)] |
| 337 | mod tests { |
| 338 | use std::sync::Mutex as StdMutex; |
| 339 | |
| 340 | use super::*; |
| 341 | use crate::transport::{BoxFuture, Diagnosis, OpenedTab}; |
| 342 | |
| 343 | #[derive(Default)] |
| 344 | struct HoldRecorder { |
| 345 | holds: StdMutex<Vec<(App, bool)>>, |
| 346 | } |
| 347 | |
| 348 | impl Transport for HoldRecorder { |
| 349 | fn check(&self) -> BoxFuture<'_, Result<()>> { |
| 350 | Box::pin(async { Ok(()) }) |
| 351 | } |
| 352 | |
| 353 | fn open(&self, _app: App, _with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>> { |
| 354 | Box::pin(async { Ok(None) }) |
| 355 | } |
| 356 | |
| 357 | fn wake(&self, _app: App) -> BoxFuture<'_, Result<()>> { |
| 358 | Box::pin(async { Ok(()) }) |
| 359 | } |
| 360 | |
| 361 | fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> { |
| 362 | Box::pin(async { Ok(Diagnosis::default()) }) |
| 363 | } |
| 364 | |
| 365 | fn hold(&self, app: App, held: bool) { |
| 366 | self.holds.lock().unwrap().push((app, held)); |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | #[tokio::test] |
| 371 | async fn tab_hold_releases_the_tab_when_dropped() { |
| 372 | let recorder = Arc::new(HoldRecorder::default()); |
| 373 | let session = Session::with_transport(recorder.clone(), SessionConfig::default()).await.unwrap(); |
| 374 | let hold = session.hold_tab(App::Teams); |
| 375 | assert_eq!(*recorder.holds.lock().unwrap(), vec![(App::Teams, true)]); |
| 376 | drop(hold); |
| 377 | assert_eq!(*recorder.holds.lock().unwrap(), vec![(App::Teams, true), (App::Teams, false)]); |
| 378 | } |
| 379 | |
| 380 | #[test] |
| 381 | fn retry_after_seconds_parse() { |
| 382 | let default = Duration::from_secs(2); |
| 383 | assert_eq!(retry_wait(Some("7"), default), Duration::from_secs(7)); |
| 384 | assert_eq!(retry_wait(Some(" 1.5 "), default), Duration::from_millis(1500)); |
| 385 | } |
| 386 | |
| 387 | #[test] |
| 388 | fn retry_after_falls_back() { |
| 389 | let default = Duration::from_secs(2); |
| 390 | assert_eq!(retry_wait(None, default), default); |
| 391 | assert_eq!(retry_wait(Some("Wed, 21 Oct 2026 07:28:00 GMT"), default), default); |
| 392 | assert_eq!(retry_wait(Some("-3"), default), default); |
| 393 | } |
| 394 | |
| 395 | #[test] |
| 396 | fn anonymous_requests_try_the_teams_tab_first() { |
| 397 | let chat_scope = Scope::graph("Chat.Read"); |
| 398 | let image = Request::anonymous_binary_get("https://media.giphy.com/media/x/giphy.gif", Vec::new()); |
| 399 | let chats = Request::get("https://graph.microsoft.com/v1.0/me/chats"); |
| 400 | assert_eq!(tab_order(&[&image], &chat_scope), [App::Teams, App::Outlook]); |
| 401 | assert_eq!(tab_order(&[&chats], &chat_scope), [App::Outlook, App::Teams]); |
| 402 | } |
| 403 | } |