BlueGit

ict rusty-teams

Files

rusty-teams / crates / session / src / page_script.rs

page_script.rs

page_script.rs 4.2 KiB Download Raw
1use std::time::Duration;
2
3use serde_json::{Value, json};
4
5use crate::app::App;
6use crate::error::{Error, Result};
7use crate::events::{TabControl, TabEvents};
8use crate::request::Outcome;
9use crate::scope::Scope;
10use crate::session::{FETCH_SCRIPT, NOT_GRANTED_PREFIX, Session};
11
12const LOADING_DOCUMENT_DENIAL: &str = "Access is denied for this document";
13const LOADING_DOCUMENT_WAIT: Duration = Duration::from_secs(1);
14const TOKEN_MARKER: &str = "if (!token) return {noToken: true, refreshError, page};";
15const 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}`.
18pub 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
25impl 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 "tenant": self.tenant(),
59 });
60 let script = format!(
61 "{head}{TOKEN_MARKER}\nconst args = {args};\n{body}\n}})",
62 head = &FETCH_SCRIPT[..marker_at]
63 );
64 let expression = format!("({script})({payload})");
65 // Right after launch the app tab can still hold a document without storage access; it settles within a second.
66 let outcome = match self.evaluate_in(app, &expression).await {
67 Err(Error::Cdp(text)) if text.contains(LOADING_DOCUMENT_DENIAL) => {
68 tokio::time::sleep(LOADING_DOCUMENT_WAIT).await;
69 self.evaluate_in(app, &expression).await
70 }
71 outcome => outcome,
72 }?
73 .ok_or(Error::NoAppTab)?;
74 if outcome.get("noToken").and_then(Value::as_bool) == Some(true) {
75 let outcome: Outcome = serde_json::from_value(outcome)
76 .map_err(|error| Error::Cdp(format!("unexpected page answer: {error}")))?;
77 let reason = outcome.refresh_error.unwrap_or_default();
78 if reason.starts_with(NOT_GRANTED_PREFIX) {
79 return Err(Error::LoginRequired(format!(
80 "{app} app is not granted {scope}"
81 )));
82 }
83 let mut detail = if reason.is_empty() {
84 String::new()
85 } else {
86 format!(" (token refresh failed in {app}: {reason})")
87 };
88 if let Some(page) = outcome.page {
89 detail.push_str(&format!(" [{app}: {page}]"));
90 }
91 return Err(Error::NoFreshToken {
92 scope: scope.to_string(),
93 detail,
94 });
95 }
96 Ok(outcome)
97 }
98}
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103
104 #[test]
105 fn acquirer_script_returns_the_acquire_function_before_any_request_runs() {
106 let script = token_acquirer_script();
107 assert!(script.starts_with("(async ({"));
108 assert!(script.ends_with("return acquire;})"));
109 assert!(!script.contains("const run = "));
110 }
111}