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