| 1 | use std::time::Duration; |
| 2 | |
| 3 | use serde_json::{Value, json}; |
| 4 | |
| 5 | use crate::app::App; |
| 6 | use crate::error::{Error, Result}; |
| 7 | use crate::events::{TabControl, TabEvents}; |
| 8 | use crate::request::Outcome; |
| 9 | use crate::scope::Scope; |
| 10 | use crate::session::{FETCH_SCRIPT, NOT_GRANTED_PREFIX, Session}; |
| 11 | |
| 12 | const LOADING_DOCUMENT_DENIAL: &str = "Access is denied for this document"; |
| 13 | const LOADING_DOCUMENT_WAIT: Duration = Duration::from_secs(1); |
| 14 | const TOKEN_MARKER: &str = "if (!token) return {noToken: true, refreshError, page};"; |
| 15 | const ACQUIRE_CALL: &str = "const {token, refreshError} = await acquire(resource, scope);"; |
| 16 | |
| 17 | /// A JS function expression: `(factory)({marginMs, forceRefresh})` resolves to `acquire(resource, scope)`, which answers `{token, refreshError}`. |
| 18 | pub fn token_acquirer_script() -> String { |
| 19 | let call_at = FETCH_SCRIPT |
| 20 | .find(ACQUIRE_CALL) |
| 21 | .expect("fetch.js contains the acquire call"); |
| 22 | format!("{}return acquire;}})", &FETCH_SCRIPT[..call_at]) |
| 23 | } |
| 24 | |
| 25 | impl Session { |
| 26 | /// Opens a dedicated CDP connection to the app tab. Events of the tab arrive on the stream. |
| 27 | pub async fn subscribe(&self, app: App) -> Result<(TabControl, TabEvents)> { |
| 28 | let (control, events) = self |
| 29 | .transport |
| 30 | .open(app, true) |
| 31 | .await? |
| 32 | .ok_or(Error::NoAppTab)?; |
| 33 | Ok((control, events.expect("opened with events"))) |
| 34 | } |
| 35 | |
| 36 | /// Runs `body` inside the app tab after the token lookup of the fetch script. |
| 37 | /// `body` is an async function body that sees `token` and `args`; the token never leaves the page. |
| 38 | pub async fn run_with_token( |
| 39 | &self, |
| 40 | app: App, |
| 41 | scope: &Scope, |
| 42 | body: &str, |
| 43 | args: &Value, |
| 44 | force_refresh: bool, |
| 45 | ) -> Result<Value> { |
| 46 | let marker_at = FETCH_SCRIPT |
| 47 | .find(TOKEN_MARKER) |
| 48 | .expect("fetch.js contains the token marker"); |
| 49 | let payload = json!({ |
| 50 | "requests": [], |
| 51 | "resource": scope.resource, |
| 52 | "scope": scope.name, |
| 53 | "nestedApp": scope.nested_app_json(), |
| 54 | "marginMs": self.config.refresh_margin.as_millis() as u64, |
| 55 | "concurrency": 1, |
| 56 | "maxBytes": 1, |
| 57 | "forceRefresh": force_refresh, |
| 58 | }); |
| 59 | let script = format!( |
| 60 | "{head}{TOKEN_MARKER}\nconst args = {args};\n{body}\n}})", |
| 61 | head = &FETCH_SCRIPT[..marker_at] |
| 62 | ); |
| 63 | let expression = format!("({script})({payload})"); |
| 64 | // Right after launch the app tab can still hold a document without storage access; it settles within a second. |
| 65 | let outcome = match self.evaluate_in(app, &expression).await { |
| 66 | Err(Error::Cdp(text)) if text.contains(LOADING_DOCUMENT_DENIAL) => { |
| 67 | tokio::time::sleep(LOADING_DOCUMENT_WAIT).await; |
| 68 | self.evaluate_in(app, &expression).await |
| 69 | } |
| 70 | outcome => outcome, |
| 71 | }? |
| 72 | .ok_or(Error::NoAppTab)?; |
| 73 | if outcome.get("noToken").and_then(Value::as_bool) == Some(true) { |
| 74 | let outcome: Outcome = serde_json::from_value(outcome) |
| 75 | .map_err(|error| Error::Cdp(format!("unexpected page answer: {error}")))?; |
| 76 | let reason = outcome.refresh_error.unwrap_or_default(); |
| 77 | if reason.starts_with(NOT_GRANTED_PREFIX) { |
| 78 | return Err(Error::LoginRequired(format!( |
| 79 | "{app} app is not granted {scope}" |
| 80 | ))); |
| 81 | } |
| 82 | let mut detail = if reason.is_empty() { |
| 83 | String::new() |
| 84 | } else { |
| 85 | format!(" (token refresh failed in {app}: {reason})") |
| 86 | }; |
| 87 | if let Some(page) = outcome.page { |
| 88 | detail.push_str(&format!(" [{app}: {page}]")); |
| 89 | } |
| 90 | return Err(Error::NoFreshToken { |
| 91 | scope: scope.to_string(), |
| 92 | detail, |
| 93 | }); |
| 94 | } |
| 95 | Ok(outcome) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | #[cfg(test)] |
| 100 | mod tests { |
| 101 | use super::*; |
| 102 | |
| 103 | #[test] |
| 104 | fn acquirer_script_returns_the_acquire_function_before_any_request_runs() { |
| 105 | let script = token_acquirer_script(); |
| 106 | assert!(script.starts_with("(async ({")); |
| 107 | assert!(script.ends_with("return acquire;})")); |
| 108 | assert!(!script.contains("const run = ")); |
| 109 | } |
| 110 | } |