feat(session): send requests from Rust, the page only hands out tokens
- access tokens cached in memory until 2 min before expiry, never stored or logged - websocket exchanges, body tokens and cookie-bound app origin calls stay in the page - Teams /api/ and /registrar/ run natively (bearer only, checked live) - TEAMS_PAGE_FETCH=1 restores the page path; tests keep the page path by default - native_http_probe compares page and native status codes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -138,7 +138,8 @@ It signs you in through a real Teams web page and lets that page make the API ca
138
138
1. A hidden browser page loads Teams web with its own profile. On Windows this is WebView2, so single sign-on with the Windows account usually just works.
139
139
2. If Teams asks for a login, the login window shows itself. After that the page stays parked in the background.
140
140
3. Every API call is sent to that page over CDP. A small script (`crates/session/assets/fetch.js`) picks the matching token from the page's MSAL cache, refreshes it when needed, and runs the `fetch`.
141
4. Only the response goes back to Rust. The one exception is the Trouter socket: Rust opens it itself and asks the page for the chat service token to sign in, held in memory only, never stored or logged. That lets the page park even during a call.
141
4. The page only hands out access tokens. Rust sends the requests itself and keeps each token in memory until shortly before it expires, never stored or logged. Websocket exchanges and calls that need the app's cookies still run inside the page. `TEAMS_PAGE_FETCH=1` sends everything through the page again.
142
5. The Trouter socket is opened from Rust too, so the page can park even during a call.
142
143
143
144
</details>
144
145
@@ -138,7 +138,8 @@ It signs you in through a real Teams web page and lets that page make the API ca138
1. A hidden browser page loads Teams web with its own profile. On Windows this is WebView2, so single sign-on with the Windows account usually just works.138
1. A hidden browser page loads Teams web with its own profile. On Windows this is WebView2, so single sign-on with the Windows account usually just works.139
2. If Teams asks for a login, the login window shows itself. After that the page stays parked in the background.139
2. If Teams asks for a login, the login window shows itself. After that the page stays parked in the background.140
3. Every API call is sent to that page over CDP. A small script (`crates/session/assets/fetch.js`) picks the matching token from the page's MSAL cache, refreshes it when needed, and runs the `fetch`.140
3. Every API call is sent to that page over CDP. A small script (`crates/session/assets/fetch.js`) picks the matching token from the page's MSAL cache, refreshes it when needed, and runs the `fetch`.141
4. Only the response goes back to Rust. The one exception is the Trouter socket: Rust opens it itself and asks the page for the chat service token to sign in, held in memory only, never stored or logged. That lets the page park even during a call.141
4. The page only hands out access tokens. Rust sends the requests itself and keeps each token in memory until shortly before it expires, never stored or logged. Websocket exchanges and calls that need the app's cookies still run inside the page. `TEAMS_PAGE_FETCH=1` sends everything through the page again.142
5. The Trouter socket is opened from Rust too, so the page can park even during a call.142
143
143
</details>144
</details>144
145
@@ -162,7 +162,7 @@ async fn supervise(
162
162
) {
163
163
let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));
164
164
let session = loop {
165
match Session::with_transport(transport.clone(), SessionConfig::default()).await {
165
match Session::with_transport(transport.clone(), SessionConfig::for_app()).await {
166
166
Ok(session) => break session,
167
167
Err(error) => {
168
168
let _ = events.send(BackendEvent::Connection(classify_session_error(&error)));
@@ -162,7 +162,7 @@ async fn supervise(162
) {162
) {163
let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));163
let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));164
let session = loop {164
let session = loop {165
match Session::with_transport(transport.clone(), SessionConfig::default()).await {165
match Session::with_transport(transport.clone(), SessionConfig::for_app()).await {166
Ok(session) => break session,166
Ok(session) => break session,167
Err(error) => {167
Err(error) => {168
let _ = events.send(BackendEvent::Connection(classify_session_error(&error)));168
let _ = events.send(BackendEvent::Connection(classify_session_error(&error)));@@ -322,8 +322,8 @@ async fn start_engine(
322
322
CallEngine,
323
323
tokio::sync::mpsc::UnboundedReceiver<EngineEvent>,
324
324
)> {
325
let session = Session::with_transport(transport.clone(), SessionConfig::default()).await?;
326
let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;
325
let session = Session::with_transport(transport.clone(), SessionConfig::for_app()).await?;
326
let poll_session = Session::with_transport(transport, SessionConfig::for_app()).await?;
327
327
let config = EngineConfig {
328
328
ringable,
329
329
dump_dir: crate::diagnostics::directory().map(|directory| directory.join(CALL_DUMPS_DIR)),
@@ -322,8 +322,8 @@ async fn start_engine(322
CallEngine,322
CallEngine,323
tokio::sync::mpsc::UnboundedReceiver<EngineEvent>,323
tokio::sync::mpsc::UnboundedReceiver<EngineEvent>,324
)> {324
)> {325
let session = Session::with_transport(transport.clone(), SessionConfig::default()).await?;325
let session = Session::with_transport(transport.clone(), SessionConfig::for_app()).await?;326
let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;326
let poll_session = Session::with_transport(transport, SessionConfig::for_app()).await?;327
let config = EngineConfig {327
let config = EngineConfig {328
ringable,328
ringable,329
dump_dir: crate::diagnostics::directory().map(|directory| directory.join(CALL_DUMPS_DIR)),329
dump_dir: crate::diagnostics::directory().map(|directory| directory.join(CALL_DUMPS_DIR)),@@ -6,7 +6,9 @@ license.workspace = true
6
6
publish.workspace = true
7
7
8
8
[dependencies]
9
base64.workspace = true
9
10
futures-util.workspace = true
11
reqwest = { version = "0.13", default-features = false, features = ["rustls"] }
10
12
serde.workspace = true
11
13
serde_json.workspace = true
12
14
thiserror.workspace = true
@@ -6,7 +6,9 @@ license.workspace = true6
publish.workspace = true6
publish.workspace = true7
7
8
[dependencies]8
[dependencies]9
base64.workspace = true9
futures-util.workspace = true10
futures-util.workspace = true11
reqwest = { version = "0.13", default-features = false, features = ["rustls"] }10
serde.workspace = true12
serde.workspace = true11
serde_json.workspace = true13
serde_json.workspace = true12
thiserror.workspace = true14
thiserror.workspace = true@@ -0,0 +1,38 @@
1
//! Read-only: the same GETs once through the page and once from Rust with the page's token (no cookies). Prints status codes only.
2
use serde_json::json;
3
use session::{App, DEFAULT_ENDPOINT, GRAPH, IC3, Request, SPACES, Scope, Session, SessionConfig};
4
5
#[tokio::main]
6
async fn main() {
7
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
8
let page = Session::connect(&endpoint).await.expect("browser");
9
let native = Session::connect_with(&endpoint, SessionConfig { native_http: true, ..SessionConfig::default() }).await.expect("browser");
10
let client = reqwest::Client::new();
11
let checks = [
12
("graph me", "https://graph.microsoft.com/v1.0/me?$select=id", Scope::new(GRAPH, "User.Read")),
13
("chatsvc conversations", "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations?view=msnp24Equivalent&pageSize=1", Scope::new(IC3, "Teams.AccessAsUser.All")),
14
("mt calendar", "https://teams.cloud.microsoft/api/mt/emea/v2.1/me/calendars/calendarView?startDate=2026-11-10T00:00:00Z&endDate=2026-11-11T00:00:00Z", Scope::new(SPACES, "user_impersonation")),
15
];
16
for (label, url, scope) in checks {
17
let page_status = page.send(Request::get(url), &scope).await.map(|response| response.status).unwrap_or_else(|error| match error {
18
session::Error::Api { status, .. } => status,
19
_ => 0,
20
});
21
let session_status = native.send(Request::get(url), &scope).await.map(|response| response.status).unwrap_or_else(|error| match error {
22
session::Error::Api { status, .. } => status,
23
_ => 0,
24
});
25
let raw_status = match page.run_with_token(App::Teams, &scope, "return token;", &json!({}), false).await {
26
Ok(serde_json::Value::String(token)) => client
27
.get(url)
28
.bearer_auth(token)
29
.header("Origin", "https://teams.cloud.microsoft")
30
.send()
31
.await
32
.map(|response| response.status().as_u16())
33
.unwrap_or(0),
34
_ => 0,
35
};
36
println!("{label}: page {page_status}, session native {session_status}, rust without cookies {raw_status}");
37
}
38
}
@@ -0,0 +1,38 @@1
//! Read-only: the same GETs once through the page and once from Rust with the page's token (no cookies). Prints status codes only.2
use serde_json::json;3
use session::{App, DEFAULT_ENDPOINT, GRAPH, IC3, Request, SPACES, Scope, Session, SessionConfig};4
5
#[tokio::main]6
async fn main() {7
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());8
let page = Session::connect(&endpoint).await.expect("browser");9
let native = Session::connect_with(&endpoint, SessionConfig { native_http: true, ..SessionConfig::default() }).await.expect("browser");10
let client = reqwest::Client::new();11
let checks = [12
("graph me", "https://graph.microsoft.com/v1.0/me?$select=id", Scope::new(GRAPH, "User.Read")),13
("chatsvc conversations", "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations?view=msnp24Equivalent&pageSize=1", Scope::new(IC3, "Teams.AccessAsUser.All")),14
("mt calendar", "https://teams.cloud.microsoft/api/mt/emea/v2.1/me/calendars/calendarView?startDate=2026-11-10T00:00:00Z&endDate=2026-11-11T00:00:00Z", Scope::new(SPACES, "user_impersonation")),15
];16
for (label, url, scope) in checks {17
let page_status = page.send(Request::get(url), &scope).await.map(|response| response.status).unwrap_or_else(|error| match error {18
session::Error::Api { status, .. } => status,19
_ => 0,20
});21
let session_status = native.send(Request::get(url), &scope).await.map(|response| response.status).unwrap_or_else(|error| match error {22
session::Error::Api { status, .. } => status,23
_ => 0,24
});25
let raw_status = match page.run_with_token(App::Teams, &scope, "return token;", &json!({}), false).await {26
Ok(serde_json::Value::String(token)) => client27
.get(url)28
.bearer_auth(token)29
.header("Origin", "https://teams.cloud.microsoft")30
.send()31
.await32
.map(|response| response.status().as_u16())33
.unwrap_or(0),34
_ => 0,35
};36
println!("{label}: page {page_status}, session native {session_status}, rust without cookies {raw_status}");37
}38
}@@ -2,6 +2,7 @@ mod app;
2
2
mod error;
3
3
mod events;
4
4
mod http;
5
mod native;
5
6
mod page_script;
6
7
mod request;
7
8
mod scope;
@@ -2,6 +2,7 @@ mod app;2
mod error;2
mod error;3
mod events;3
mod events;4
mod http;4
mod http;5
mod native;5
mod page_script;6
mod page_script;6
mod request;7
mod request;7
mod scope;8
mod scope;@@ -0,0 +1,225 @@
1
use std::collections::HashMap;
2
use std::sync::Mutex;
3
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
4
5
use base64::Engine as _;
6
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
7
use futures_util::future::join_all;
8
use serde_json::{Value, json};
9
10
use crate::app::App;
11
use crate::request::{ApiResponse, Method, Request};
12
use crate::scope::Scope;
13
use crate::session::Session;
14
15
const TOKEN_BODY: &str = "return token;";
16
const CONCURRENCY: usize = 6;
17
18
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
19
struct TokenKey {
20
resource: String,
21
name: String,
22
nested_client: Option<&'static str>,
23
}
24
25
impl TokenKey {
26
fn of(scope: &Scope) -> Self {
27
TokenKey {
28
resource: scope.resource.to_string(),
29
name: scope.name.to_string(),
30
nested_client: scope.nested_app.map(|app| app.client_id),
31
}
32
}
33
}
34
35
struct HeldToken {
36
app: App,
37
token: String,
38
usable_until: Instant,
39
}
40
41
/// Sends requests from Rust; the app tab is asked only for an access token, which stays in memory until shortly before it expires.
42
pub(crate) struct NativeHttp {
43
client: reqwest::Client,
44
tokens: Mutex<HashMap<TokenKey, HeldToken>>,
45
max_bytes: u64,
46
}
47
48
impl NativeHttp {
49
pub(crate) fn new(timeout: Duration, max_bytes: u64) -> Option<Self> {
50
let client = reqwest::Client::builder().timeout(timeout).build().ok()?;
51
Some(NativeHttp { client, tokens: Mutex::new(HashMap::new()), max_bytes })
52
}
53
54
pub(crate) fn forget(&self, scope: &Scope) {
55
self.tokens.lock().expect("token lock").remove(&TokenKey::of(scope));
56
}
57
58
fn held(&self, scope: &Scope) -> Option<(App, String)> {
59
let tokens = self.tokens.lock().expect("token lock");
60
let held = tokens.get(&TokenKey::of(scope))?;
61
(Instant::now() < held.usable_until).then(|| (held.app, held.token.clone()))
62
}
63
64
/// `None` hands the batch to the page path, which waits for sign-in, reloads and explains failures.
65
pub(crate) async fn run(&self, session: &Session, requests: &[&Request], scope: &Scope, force_refresh: bool) -> Option<Vec<ApiResponse>> {
66
if !requests.iter().all(|request| eligible(request)) {
67
return None;
68
}
69
let credential = if requests.iter().all(|request| request.anonymous) {
70
None
71
} else {
72
Some(self.token(session, scope, force_refresh).await?)
73
};
74
let mut answers = Vec::with_capacity(requests.len());
75
for chunk in requests.chunks(CONCURRENCY) {
76
let mut pending = Vec::with_capacity(chunk.len());
77
for request in chunk {
78
pending.push(self.execute(request, credential.as_ref()));
79
}
80
answers.extend(join_all(pending).await);
81
}
82
if answers.iter().any(|answer| answer.status == 401) {
83
self.forget(scope);
84
}
85
Some(answers)
86
}
87
88
async fn token(&self, session: &Session, scope: &Scope, force_refresh: bool) -> Option<(App, String)> {
89
if !force_refresh && let Some(held) = self.held(scope) {
90
return Some(held);
91
}
92
for app in scope.tab_order() {
93
let Ok(Value::String(token)) = session.run_with_token(app, scope, TOKEN_BODY, &json!({}), force_refresh).await else {
94
continue;
95
};
96
let usable_until = usable_until(&token, session.config.refresh_margin)?;
97
self.tokens
98
.lock()
99
.expect("token lock")
100
.insert(TokenKey::of(scope), HeldToken { app, token: token.clone(), usable_until });
101
return Some((app, token));
102
}
103
None
104
}
105
106
async fn execute(&self, request: &Request, credential: Option<&(App, String)>) -> ApiResponse {
107
match self.exchange(request, credential).await {
108
Ok(response) => response,
109
Err(error) => ApiResponse { status: 0, body: Value::String(error.without_url().to_string()), retry_after: None },
110
}
111
}
112
113
async fn exchange(&self, request: &Request, credential: Option<&(App, String)>) -> reqwest::Result<ApiResponse> {
114
let mut builder = self.client.request(method(request.method), &request.url);
115
let mut has_content_type = false;
116
for (name, value) in &request.headers {
117
has_content_type |= name.eq_ignore_ascii_case("content-type");
118
builder = builder.header(name, value);
119
}
120
if let Some((app, token)) = credential.filter(|_| !request.anonymous) {
121
builder = builder.bearer_auth(token).header("Origin", app.origins()[0]);
122
}
123
if let Some(encoded) = &request.body_base64 {
124
builder = builder.body(STANDARD.decode(encoded).unwrap_or_default());
125
} else if let Some(body) = &request.body {
126
if !has_content_type {
127
builder = builder.header("Content-Type", "application/json");
128
}
129
builder = builder.body(body.to_string());
130
}
131
let response = builder.send().await?;
132
let status = response.status().as_u16();
133
let retry_after = response.headers().get("Retry-After").and_then(|value| value.to_str().ok()).map(str::to_owned);
134
if request.binary && response.status().is_success() {
135
let content_type = response.headers().get("Content-Type").and_then(|value| value.to_str().ok()).map(str::to_owned);
136
let bytes = response.bytes().await?;
137
if bytes.len() as u64 > self.max_bytes {
138
let body = format!("download is {} bytes, over the {} limit", bytes.len(), self.max_bytes);
139
return Ok(ApiResponse { status: 413, body: Value::String(body), retry_after: None });
140
}
141
let body = json!({"base64": STANDARD.encode(&bytes), "contentType": content_type});
142
return Ok(ApiResponse { status, body, retry_after });
143
}
144
let text = response.text().await?;
145
let body = if text.is_empty() { Value::Null } else { serde_json::from_str(&text).unwrap_or(Value::String(text)) };
146
Ok(ApiResponse { status, body, retry_after })
147
}
148
}
149
150
const TEAMS_BEARER_PATHS: [&str; 2] = ["/api/", "/registrar/"];
151
152
/// Page-only: websocket exchanges, tokens spliced into bodies, and app-origin calls that may rely on its cookies.
153
fn eligible(request: &Request) -> bool {
154
request.signalr.is_none()
155
&& request.augloop.is_none()
156
&& request.body_tokens.is_empty()
157
&& request.url.starts_with("https://")
158
&& !needs_page_cookies(&request.url)
159
}
160
161
fn needs_page_cookies(url: &str) -> bool {
162
App::ALL.iter().any(|&app| {
163
app.origins().iter().any(|origin| {
164
same_origin(url, origin)
165
&& !(app == App::Teams && TEAMS_BEARER_PATHS.iter().any(|path| url[origin.len()..].starts_with(path)))
166
})
167
})
168
}
169
170
fn same_origin(url: &str, origin: &str) -> bool {
171
url.strip_prefix(origin).is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))
172
}
173
174
fn method(method: Method) -> reqwest::Method {
175
match method {
176
Method::Get => reqwest::Method::GET,
177
Method::Post => reqwest::Method::POST,
178
Method::Put => reqwest::Method::PUT,
179
Method::Patch => reqwest::Method::PATCH,
180
Method::Delete => reqwest::Method::DELETE,
181
}
182
}
183
184
fn expires_at(token: &str) -> Option<u64> {
185
let payload = token.split('.').nth(1)?;
186
let claims: Value = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?).ok()?;
187
claims.get("exp")?.as_u64()
188
}
189
190
fn usable_until(token: &str, margin: Duration) -> Option<Instant> {
191
let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
192
let left = expires_at(token)?.checked_sub(now)?.checked_sub(margin.as_secs())?;
193
Some(Instant::now() + Duration::from_secs(left))
194
}
195
196
#[cfg(test)]
197
mod tests {
198
use super::*;
199
200
fn token_expiring_at(exp: u64) -> String {
201
format!("e30.{}.sig", URL_SAFE_NO_PAD.encode(format!("{{\"exp\":{exp}}}")))
202
}
203
204
#[test]
205
fn a_token_is_used_until_the_margin_before_it_expires() {
206
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
207
let until = usable_until(&token_expiring_at(now + 3600), Duration::from_secs(120)).unwrap();
208
let left = until.saturating_duration_since(Instant::now()).as_secs();
209
assert!((3470..=3480).contains(&left), "{left}");
210
assert!(usable_until(&token_expiring_at(now + 60), Duration::from_secs(120)).is_none());
211
assert!(usable_until("not-a-jwt", Duration::from_secs(120)).is_none());
212
}
213
214
#[test]
215
fn only_plain_cross_origin_requests_leave_the_page() {
216
assert!(eligible(&Request::get("https://graph.microsoft.com/v1.0/me")));
217
assert!(eligible(&Request::anonymous_binary_get("https://media.giphy.com/x.gif", Vec::new())));
218
assert!(eligible(&Request::get("https://teams.cloud.microsoft/api/mt/emea/beta/users")));
219
assert!(!eligible(&Request::get("https://teams.cloud.microsoft/v2/")));
220
assert!(!eligible(&Request::get("https://outlook.office.com/api/v2.0/me/messages")));
221
assert!(!eligible(&Request::get("http://graph.microsoft.com/v1.0/me")));
222
let spliced = Request::with_body(Method::Post, "https://x.example/", json!({"t": "@@t@@"})).with_body_token("https://r", "s", "@@t@@");
223
assert!(!eligible(&spliced));
224
}
225
}
@@ -0,0 +1,225 @@1
use std::collections::HashMap;2
use std::sync::Mutex;3
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};4
5
use base64::Engine as _;6
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};7
use futures_util::future::join_all;8
use serde_json::{Value, json};9
10
use crate::app::App;11
use crate::request::{ApiResponse, Method, Request};12
use crate::scope::Scope;13
use crate::session::Session;14
15
const TOKEN_BODY: &str = "return token;";16
const CONCURRENCY: usize = 6;17
18
#[derive(Debug, Clone, PartialEq, Eq, Hash)]19
struct TokenKey {20
resource: String,21
name: String,22
nested_client: Option<&'static str>,23
}24
25
impl TokenKey {26
fn of(scope: &Scope) -> Self {27
TokenKey {28
resource: scope.resource.to_string(),29
name: scope.name.to_string(),30
nested_client: scope.nested_app.map(|app| app.client_id),31
}32
}33
}34
35
struct HeldToken {36
app: App,37
token: String,38
usable_until: Instant,39
}40
41
/// Sends requests from Rust; the app tab is asked only for an access token, which stays in memory until shortly before it expires.42
pub(crate) struct NativeHttp {43
client: reqwest::Client,44
tokens: Mutex<HashMap<TokenKey, HeldToken>>,45
max_bytes: u64,46
}47
48
impl NativeHttp {49
pub(crate) fn new(timeout: Duration, max_bytes: u64) -> Option<Self> {50
let client = reqwest::Client::builder().timeout(timeout).build().ok()?;51
Some(NativeHttp { client, tokens: Mutex::new(HashMap::new()), max_bytes })52
}53
54
pub(crate) fn forget(&self, scope: &Scope) {55
self.tokens.lock().expect("token lock").remove(&TokenKey::of(scope));56
}57
58
fn held(&self, scope: &Scope) -> Option<(App, String)> {59
let tokens = self.tokens.lock().expect("token lock");60
let held = tokens.get(&TokenKey::of(scope))?;61
(Instant::now() < held.usable_until).then(|| (held.app, held.token.clone()))62
}63
64
/// `None` hands the batch to the page path, which waits for sign-in, reloads and explains failures.65
pub(crate) async fn run(&self, session: &Session, requests: &[&Request], scope: &Scope, force_refresh: bool) -> Option<Vec<ApiResponse>> {66
if !requests.iter().all(|request| eligible(request)) {67
return None;68
}69
let credential = if requests.iter().all(|request| request.anonymous) {70
None71
} else {72
Some(self.token(session, scope, force_refresh).await?)73
};74
let mut answers = Vec::with_capacity(requests.len());75
for chunk in requests.chunks(CONCURRENCY) {76
let mut pending = Vec::with_capacity(chunk.len());77
for request in chunk {78
pending.push(self.execute(request, credential.as_ref()));79
}80
answers.extend(join_all(pending).await);81
}82
if answers.iter().any(|answer| answer.status == 401) {83
self.forget(scope);84
}85
Some(answers)86
}87
88
async fn token(&self, session: &Session, scope: &Scope, force_refresh: bool) -> Option<(App, String)> {89
if !force_refresh && let Some(held) = self.held(scope) {90
return Some(held);91
}92
for app in scope.tab_order() {93
let Ok(Value::String(token)) = session.run_with_token(app, scope, TOKEN_BODY, &json!({}), force_refresh).await else {94
continue;95
};96
let usable_until = usable_until(&token, session.config.refresh_margin)?;97
self.tokens98
.lock()99
.expect("token lock")100
.insert(TokenKey::of(scope), HeldToken { app, token: token.clone(), usable_until });101
return Some((app, token));102
}103
None104
}105
106
async fn execute(&self, request: &Request, credential: Option<&(App, String)>) -> ApiResponse {107
match self.exchange(request, credential).await {108
Ok(response) => response,109
Err(error) => ApiResponse { status: 0, body: Value::String(error.without_url().to_string()), retry_after: None },110
}111
}112
113
async fn exchange(&self, request: &Request, credential: Option<&(App, String)>) -> reqwest::Result<ApiResponse> {114
let mut builder = self.client.request(method(request.method), &request.url);115
let mut has_content_type = false;116
for (name, value) in &request.headers {117
has_content_type |= name.eq_ignore_ascii_case("content-type");118
builder = builder.header(name, value);119
}120
if let Some((app, token)) = credential.filter(|_| !request.anonymous) {121
builder = builder.bearer_auth(token).header("Origin", app.origins()[0]);122
}123
if let Some(encoded) = &request.body_base64 {124
builder = builder.body(STANDARD.decode(encoded).unwrap_or_default());125
} else if let Some(body) = &request.body {126
if !has_content_type {127
builder = builder.header("Content-Type", "application/json");128
}129
builder = builder.body(body.to_string());130
}131
let response = builder.send().await?;132
let status = response.status().as_u16();133
let retry_after = response.headers().get("Retry-After").and_then(|value| value.to_str().ok()).map(str::to_owned);134
if request.binary && response.status().is_success() {135
let content_type = response.headers().get("Content-Type").and_then(|value| value.to_str().ok()).map(str::to_owned);136
let bytes = response.bytes().await?;137
if bytes.len() as u64 > self.max_bytes {138
let body = format!("download is {} bytes, over the {} limit", bytes.len(), self.max_bytes);139
return Ok(ApiResponse { status: 413, body: Value::String(body), retry_after: None });140
}141
let body = json!({"base64": STANDARD.encode(&bytes), "contentType": content_type});142
return Ok(ApiResponse { status, body, retry_after });143
}144
let text = response.text().await?;145
let body = if text.is_empty() { Value::Null } else { serde_json::from_str(&text).unwrap_or(Value::String(text)) };146
Ok(ApiResponse { status, body, retry_after })147
}148
}149
150
const TEAMS_BEARER_PATHS: [&str; 2] = ["/api/", "/registrar/"];151
152
/// Page-only: websocket exchanges, tokens spliced into bodies, and app-origin calls that may rely on its cookies.153
fn eligible(request: &Request) -> bool {154
request.signalr.is_none()155
&& request.augloop.is_none()156
&& request.body_tokens.is_empty()157
&& request.url.starts_with("https://")158
&& !needs_page_cookies(&request.url)159
}160
161
fn needs_page_cookies(url: &str) -> bool {162
App::ALL.iter().any(|&app| {163
app.origins().iter().any(|origin| {164
same_origin(url, origin)165
&& !(app == App::Teams && TEAMS_BEARER_PATHS.iter().any(|path| url[origin.len()..].starts_with(path)))166
})167
})168
}169
170
fn same_origin(url: &str, origin: &str) -> bool {171
url.strip_prefix(origin).is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))172
}173
174
fn method(method: Method) -> reqwest::Method {175
match method {176
Method::Get => reqwest::Method::GET,177
Method::Post => reqwest::Method::POST,178
Method::Put => reqwest::Method::PUT,179
Method::Patch => reqwest::Method::PATCH,180
Method::Delete => reqwest::Method::DELETE,181
}182
}183
184
fn expires_at(token: &str) -> Option<u64> {185
let payload = token.split('.').nth(1)?;186
let claims: Value = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?).ok()?;187
claims.get("exp")?.as_u64()188
}189
190
fn usable_until(token: &str, margin: Duration) -> Option<Instant> {191
let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();192
let left = expires_at(token)?.checked_sub(now)?.checked_sub(margin.as_secs())?;193
Some(Instant::now() + Duration::from_secs(left))194
}195
196
#[cfg(test)]197
mod tests {198
use super::*;199
200
fn token_expiring_at(exp: u64) -> String {201
format!("e30.{}.sig", URL_SAFE_NO_PAD.encode(format!("{{\"exp\":{exp}}}")))202
}203
204
#[test]205
fn a_token_is_used_until_the_margin_before_it_expires() {206
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();207
let until = usable_until(&token_expiring_at(now + 3600), Duration::from_secs(120)).unwrap();208
let left = until.saturating_duration_since(Instant::now()).as_secs();209
assert!((3470..=3480).contains(&left), "{left}");210
assert!(usable_until(&token_expiring_at(now + 60), Duration::from_secs(120)).is_none());211
assert!(usable_until("not-a-jwt", Duration::from_secs(120)).is_none());212
}213
214
#[test]215
fn only_plain_cross_origin_requests_leave_the_page() {216
assert!(eligible(&Request::get("https://graph.microsoft.com/v1.0/me")));217
assert!(eligible(&Request::anonymous_binary_get("https://media.giphy.com/x.gif", Vec::new())));218
assert!(eligible(&Request::get("https://teams.cloud.microsoft/api/mt/emea/beta/users")));219
assert!(!eligible(&Request::get("https://teams.cloud.microsoft/v2/")));220
assert!(!eligible(&Request::get("https://outlook.office.com/api/v2.0/me/messages")));221
assert!(!eligible(&Request::get("http://graph.microsoft.com/v1.0/me")));222
let spliced = Request::with_body(Method::Post, "https://x.example/", json!({"t": "@@t@@"})).with_body_token("https://r", "s", "@@t@@");223
assert!(!eligible(&spliced));224
}225
}@@ -10,6 +10,7 @@ use tokio::time::{Instant, sleep};
10
10
use crate::app::App;
11
11
use crate::error::{Error, Result};
12
12
use crate::events::TabControl;
13
use crate::native::NativeHttp;
13
14
use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult};
14
15
use crate::scope::Scope;
15
16
use crate::transport::{CdpTransport, Transport};
@@ -30,6 +31,7 @@ pub struct SessionConfig {
30
31
pub max_retry_wait: Duration,
31
32
pub default_retry_wait: Duration,
32
33
pub unauthorized_reload_wait: Duration,
34
pub native_http: bool,
33
35
}
34
36
35
37
impl Default for SessionConfig {
@@ -43,6 +45,17 @@ impl Default for SessionConfig {
43
45
max_retry_wait: Duration::from_secs(30),
44
46
default_retry_wait: Duration::from_secs(2),
45
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()
46
59
}
47
60
}
48
61
}
@@ -60,6 +73,7 @@ pub struct Session {
60
73
pub(crate) config: SessionConfig,
61
74
tabs: Arc<HashMap<App, Mutex<Option<TabControl>>>>,
62
75
force_refresh: Arc<AtomicBool>,
76
native: Option<Arc<NativeHttp>>,
63
77
}
64
78
65
79
impl Session {
@@ -73,7 +87,13 @@ impl Session {
73
87
74
88
pub async fn with_transport(transport: Arc<dyn Transport>, config: SessionConfig) -> Result<Self> {
75
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);
76
95
Ok(Session {
96
native,
77
97
transport,
78
98
config,
79
99
tabs: Arc::new(App::ALL.into_iter().map(|app| (app, Mutex::new(None))).collect()),
@@ -153,6 +173,11 @@ impl Session {
153
173
}
154
174
155
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
}
156
181
let mut search = TokenSearch::default();
157
182
if let Some(results) = self.run_in_any_tab(requests, scope, &mut search).await? {
158
183
return Ok(results);
@@ -10,6 +10,7 @@ use tokio::time::{Instant, sleep};10
use crate::app::App;10
use crate::app::App;11
use crate::error::{Error, Result};11
use crate::error::{Error, Result};12
use crate::events::TabControl;12
use crate::events::TabControl;13
use crate::native::NativeHttp;13
use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult};14
use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult};14
use crate::scope::Scope;15
use crate::scope::Scope;15
use crate::transport::{CdpTransport, Transport};16
use crate::transport::{CdpTransport, Transport};@@ -30,6 +31,7 @@ pub struct SessionConfig {30
pub max_retry_wait: Duration,31
pub max_retry_wait: Duration,31
pub default_retry_wait: Duration,32
pub default_retry_wait: Duration,32
pub unauthorized_reload_wait: Duration,33
pub unauthorized_reload_wait: Duration,34
pub native_http: bool,33
}35
}34
36
35
impl Default for SessionConfig {37
impl Default for SessionConfig {@@ -43,6 +45,17 @@ impl Default for SessionConfig {43
max_retry_wait: Duration::from_secs(30),45
max_retry_wait: Duration::from_secs(30),44
default_retry_wait: Duration::from_secs(2),46
default_retry_wait: Duration::from_secs(2),45
unauthorized_reload_wait: Duration::from_secs(5),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()46
}59
}47
}60
}48
}61
}@@ -60,6 +73,7 @@ pub struct Session {60
pub(crate) config: SessionConfig,73
pub(crate) config: SessionConfig,61
tabs: Arc<HashMap<App, Mutex<Option<TabControl>>>>,74
tabs: Arc<HashMap<App, Mutex<Option<TabControl>>>>,62
force_refresh: Arc<AtomicBool>,75
force_refresh: Arc<AtomicBool>,76
native: Option<Arc<NativeHttp>>,63
}77
}64
78
65
impl Session {79
impl Session {@@ -73,7 +87,13 @@ impl Session {73
87
74
pub async fn with_transport(transport: Arc<dyn Transport>, config: SessionConfig) -> Result<Self> {88
pub async fn with_transport(transport: Arc<dyn Transport>, config: SessionConfig) -> Result<Self> {75
transport.check().await?;89
transport.check().await?;90
let native = config91
.native_http92
.then(|| NativeHttp::new(config.evaluate_timeout, MAX_DOWNLOAD_BYTES))93
.flatten()94
.map(Arc::new);76
Ok(Session {95
Ok(Session {96
native,77
transport,97
transport,78
config,98
config,79
tabs: Arc::new(App::ALL.into_iter().map(|app| (app, Mutex::new(None))).collect()),99
tabs: Arc::new(App::ALL.into_iter().map(|app| (app, Mutex::new(None))).collect()),@@ -153,6 +173,11 @@ impl Session {153
}173
}154
174
155
async fn run_with_fresh_token(&self, requests: &[&Request], scope: &Scope) -> Result<Vec<ApiResponse>> {175
async fn run_with_fresh_token(&self, requests: &[&Request], scope: &Scope) -> Result<Vec<ApiResponse>> {176
if let Some(native) = &self.native177
&& let Some(results) = native.run(self, requests, scope, self.force_refresh.load(Ordering::SeqCst)).await178
{179
return Ok(results);180
}156
let mut search = TokenSearch::default();181
let mut search = TokenSearch::default();157
if let Some(results) = self.run_in_any_tab(requests, scope, &mut search).await? {182
if let Some(results) = self.run_in_any_tab(requests, scope, &mut search).await? {158
return Ok(results);183
return Ok(results);