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