BlueGit

ict rusty-teams

feat(chatsvc): native Trouter websocket, page tab may park during calls

- realtime/native.rs speaks Trouter from Rust and emits the same payloads as trouter.js
- token lookup and registrar calls still run in the page, token kept in memory only
- TEAMS_PAGE_TROUTER=1 falls back to the page worker
- calls no longer hold the Teams tab
- native_trouter_probe example prints event kinds only

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-10 · 2 weeks ago

Hash
062a2e2b483c1fbda13953eefebedccc7cbc9d35
Parent
4af5e7ab
7 files changed +754 −25
README.md +2 −2
@@ -26,7 +26,7 @@
26 26 |---|---|
27 27 | 🏢 Works in company tenants | No app registration, no admin consent: it runs on the Teams web app your account is already allowed to use |
28 28 | ⚡ Starts instantly | Renders from a local SQLite cache before the network answers |
29 | 🔒 No tokens stored | Signs in through a real Teams web page; tokens never leave it |
29 | 🔒 No tokens stored | Signs in through a real Teams web page; tokens are never written to disk |
30 30 | 📡 Live, no polling | Realtime socket pushes every change |
31 31 | 🔎 Offline search | Full-text index over your chats, `Ctrl+K` switcher |
32 32
@@ -138,7 +138,7 @@ 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. Tokens never leave the page.
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.
142 142
143 143 </details>
144 144
@@ -26,7 +26,7 @@
26|---|---|
26|---|---|
27| 🏢 Works in company tenants | No app registration, no admin consent: it runs on the Teams web app your account is already allowed to use |
27| 🏢 Works in company tenants | No app registration, no admin consent: it runs on the Teams web app your account is already allowed to use |
28| ⚡ Starts instantly | Renders from a local SQLite cache before the network answers |
28| ⚡ Starts instantly | Renders from a local SQLite cache before the network answers |
29| 🔒 No tokens stored | Signs in through a real Teams web page; tokens never leave it |
29| 🔒 No tokens stored | Signs in through a real Teams web page; tokens are never written to disk |
30| 📡 Live, no polling | Realtime socket pushes every change |
30| 📡 Live, no polling | Realtime socket pushes every change |
31| 🔎 Offline search | Full-text index over your chats, `Ctrl+K` switcher |
31| 🔎 Offline search | Full-text index over your chats, `Ctrl+K` switcher |
32
32
@@ -138,7 +138,7 @@ It signs you in through a real Teams web page and lets that page make the API ca
1381. 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.
1381. 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.
1392. If Teams asks for a login, the login window shows itself. After that the page stays parked in the background.
1392. If Teams asks for a login, the login window shows itself. After that the page stays parked in the background.
1403. 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`.
1403. 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`.
1414. Only the response goes back to Rust. Tokens never leave the page.
1414. 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.
142
142
143</details>
143</details>
144
144
crates/calling/src/call.rs +0 −1
@@ -454,7 +454,6 @@ impl CallEngine {
454 454 }
455 455 }
456 456 };
457 let _trouter_tab_stays = inner.session.hold_tab(session::App::Teams);
458 457 let timeline = Timeline::new(options.trace);
459 458 let stay_awake = crate::awake::StayAwake::new();
460 459 timeline.record("stay awake", if stay_awake.holding() { "system and display kept awake" } else { "not available" });
@@ -454,7 +454,6 @@ impl CallEngine {
454 }
454 }
455 }
455 }
456 };
456 };
457 let _trouter_tab_stays = inner.session.hold_tab(session::App::Teams);
458 let timeline = Timeline::new(options.trace);
457 let timeline = Timeline::new(options.trace);
459 let stay_awake = crate::awake::StayAwake::new();
458 let stay_awake = crate::awake::StayAwake::new();
460 timeline.record("stay awake", if stay_awake.holding() { "system and display kept awake" } else { "not available" });
459 timeline.record("stay awake", if stay_awake.holding() { "system and display kept awake" } else { "not available" });
crates/chatsvc/Cargo.toml +2 −1
@@ -15,8 +15,9 @@ serde_json.workspace = true
15 15 session.workspace = true
16 16 thiserror.workspace = true
17 17 tokio.workspace = true
18 tokio-tungstenite = { workspace = true, features = ["rustls-tls-webpki-roots"] }
18 19 uuid.workspace = true
19 20
20 21 [dev-dependencies]
21 22 tokio = { workspace = true }
22 tokio-tungstenite.workspace = true
23 reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
@@ -15,8 +15,9 @@ serde_json.workspace = true
15session.workspace = true
15session.workspace = true
16thiserror.workspace = true
16thiserror.workspace = true
17tokio.workspace = true
17tokio.workspace = true
18tokio-tungstenite = { workspace = true, features = ["rustls-tls-webpki-roots"] }
18uuid.workspace = true
19uuid.workspace = true
19
20
20[dev-dependencies]
21[dev-dependencies]
21tokio = { workspace = true }
22tokio = { workspace = true }
22tokio-tungstenite.workspace = true
23reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
crates/chatsvc/examples/native_trouter_probe.rs added +30 −0
@@ -0,0 +1,30 @@
1 //! Connects the native Trouter client and prints event kinds (no content) for the given seconds.
2 use std::time::Duration;
3
4 use chatsvc::{Realtime, RealtimeConfig, RealtimeEvent};
5 use session::{DEFAULT_ENDPOINT, Session};
6
7 #[tokio::main]
8 async fn main() {
9 let seconds = std::env::args().nth(1).and_then(|value| value.parse().ok()).unwrap_or(60);
10 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
11 let session = Session::connect(&endpoint).await.expect("browser");
12 let config = RealtimeConfig { native: true, initially_active: true, ..RealtimeConfig::default() };
13 let mut realtime = Realtime::start_with(&session, config).await.expect("realtime start");
14 println!("host {}", realtime.host());
15 let watch = async {
16 while let Some(event) = realtime.recv().await {
17 let label = match &event {
18 RealtimeEvent::Status(status) => format!("status {:?} {}", status.kind, status.detail),
19 RealtimeEvent::Endpoint(_) => "endpoint".to_owned(),
20 RealtimeEvent::Message(message) => format!("message {:?}", message.kind),
21 RealtimeEvent::Presence(entries) => format!("presence x{}", entries.len()),
22 RealtimeEvent::Typing(_) => "typing".to_owned(),
23 };
24 println!("{label}");
25 }
26 };
27 let _ = tokio::time::timeout(Duration::from_secs(seconds), watch).await;
28 realtime.stop().await;
29 println!("stopped");
30 }
@@ -0,0 +1,30 @@
1//! Connects the native Trouter client and prints event kinds (no content) for the given seconds.
2use std::time::Duration;
3
4use chatsvc::{Realtime, RealtimeConfig, RealtimeEvent};
5use session::{DEFAULT_ENDPOINT, Session};
6
7#[tokio::main]
8async fn main() {
9 let seconds = std::env::args().nth(1).and_then(|value| value.parse().ok()).unwrap_or(60);
10 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
11 let session = Session::connect(&endpoint).await.expect("browser");
12 let config = RealtimeConfig { native: true, initially_active: true, ..RealtimeConfig::default() };
13 let mut realtime = Realtime::start_with(&session, config).await.expect("realtime start");
14 println!("host {}", realtime.host());
15 let watch = async {
16 while let Some(event) = realtime.recv().await {
17 let label = match &event {
18 RealtimeEvent::Status(status) => format!("status {:?} {}", status.kind, status.detail),
19 RealtimeEvent::Endpoint(_) => "endpoint".to_owned(),
20 RealtimeEvent::Message(message) => format!("message {:?}", message.kind),
21 RealtimeEvent::Presence(entries) => format!("presence x{}", entries.len()),
22 RealtimeEvent::Typing(_) => "typing".to_owned(),
23 };
24 println!("{label}");
25 }
26 };
27 let _ = tokio::time::timeout(Duration::from_secs(seconds), watch).await;
28 realtime.stop().await;
29 println!("stopped");
30}
crates/chatsvc/src/realtime/mod.rs +40 −21
@@ -1,6 +1,7 @@
1 1 mod callback;
2 2 mod event;
3 3 mod host;
4 mod native;
4 5 mod runner;
5 6
6 7 use std::pin::Pin;
@@ -21,6 +22,7 @@ pub use event::{
21 22 pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
22 23
23 24 use crate::error::Result;
25 use native::NativeTrouter;
24 26 use runner::{Runner, attach};
25 27
26 28 const STOP_TIMEOUT: Duration = Duration::from_secs(15);
@@ -37,6 +39,7 @@ pub struct RealtimeConfig {
37 39 pub forward_callbacks: bool,
38 40 pub ringable: bool,
39 41 pub initially_active: bool,
42 pub native: bool,
40 43 }
41 44
42 45 /// Page globals of one Trouter client; a second client in the same tab needs its own names.
@@ -70,6 +73,7 @@ impl Default for RealtimeConfig {
70 73 forward_callbacks: false,
71 74 ringable: false,
72 75 initially_active: false,
76 native: std::env::var_os("TEAMS_PAGE_TROUTER").is_none(),
73 77 }
74 78 }
75 79 }
@@ -94,32 +98,47 @@ impl Realtime {
94 98 pub async fn start_with(session: &Session, config: RealtimeConfig) -> Result<Realtime> {
95 99 let session = session.clone();
96 100 let host = host::resolve(&session, &config).await;
97 let script = runner::PageScript::new(&config);
98 let attached = attach(&session, &script).await?;
99 101 let (output, events) = mpsc::unbounded_channel();
100 102 let (callback_output, callbacks) = mpsc::unbounded_channel();
101 103 let (reply_sender, replies) = mpsc::unbounded_channel();
102 104 let (activity, activity_receiver) = watch::channel(config.initially_active);
103 105 let resend = Arc::new(Notify::new());
104 106 let (stop, stop_receiver) = oneshot::channel();
105 let mut runner = Runner::new(
106 session,
107 config,
108 script,
109 host.clone(),
110 output,
111 runner::CallbackPipes {
112 output: callback_output,
113 replies,
114 },
115 activity_receiver,
116 resend.clone(),
117 );
118 if let Err(error) = runner.ensure().await {
119 attached.shutdown().await;
120 return Err(error.into());
121 }
122 let task = tokio::spawn(runner.run(attached, stop_receiver));
107 let pipes = runner::CallbackPipes {
108 output: callback_output,
109 replies,
110 };
111 let task = if config.native {
112 let mut trouter = NativeTrouter::new(
113 session,
114 config,
115 host.clone(),
116 output,
117 pipes,
118 activity_receiver,
119 resend.clone(),
120 );
121 trouter.token().await?;
122 tokio::spawn(trouter.run(stop_receiver))
123 } else {
124 let script = runner::PageScript::new(&config);
125 let attached = attach(&session, &script).await?;
126 let mut runner = Runner::new(
127 session,
128 config,
129 script,
130 host.clone(),
131 output,
132 pipes,
133 activity_receiver,
134 resend.clone(),
135 );
136 if let Err(error) = runner.ensure().await {
137 attached.shutdown().await;
138 return Err(error.into());
139 }
140 tokio::spawn(runner.run(attached, stop_receiver))
141 };
123 142 Ok(Realtime {
124 143 host,
125 144 events,
@@ -159,7 +178,7 @@ impl Realtime {
159 178 self.resend.notify_one();
160 179 }
161 180
162 /// Deletes the registration and closes the page-side socket.
181 /// Deletes the registration and closes the socket.
163 182 pub async fn stop(mut self) {
164 183 if let Some(stop) = self.stop.take() {
165 184 let (done, finished) = oneshot::channel();
@@ -1,6 +1,7 @@
1mod callback;
1mod callback;
2mod event;
2mod event;
3mod host;
3mod host;
4mod native;
4mod runner;
5mod runner;
5
6
6use std::pin::Pin;
7use std::pin::Pin;
@@ -21,6 +22,7 @@ pub use event::{
21pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
22pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
22
23
23use crate::error::Result;
24use crate::error::Result;
25use native::NativeTrouter;
24use runner::{Runner, attach};
26use runner::{Runner, attach};
25
27
26const STOP_TIMEOUT: Duration = Duration::from_secs(15);
28const STOP_TIMEOUT: Duration = Duration::from_secs(15);
@@ -37,6 +39,7 @@ pub struct RealtimeConfig {
37 pub forward_callbacks: bool,
39 pub forward_callbacks: bool,
38 pub ringable: bool,
40 pub ringable: bool,
39 pub initially_active: bool,
41 pub initially_active: bool,
42 pub native: bool,
40}
43}
41
44
42/// Page globals of one Trouter client; a second client in the same tab needs its own names.
45/// Page globals of one Trouter client; a second client in the same tab needs its own names.
@@ -70,6 +73,7 @@ impl Default for RealtimeConfig {
70 forward_callbacks: false,
73 forward_callbacks: false,
71 ringable: false,
74 ringable: false,
72 initially_active: false,
75 initially_active: false,
76 native: std::env::var_os("TEAMS_PAGE_TROUTER").is_none(),
73 }
77 }
74 }
78 }
75}
79}
@@ -94,32 +98,47 @@ impl Realtime {
94 pub async fn start_with(session: &Session, config: RealtimeConfig) -> Result<Realtime> {
98 pub async fn start_with(session: &Session, config: RealtimeConfig) -> Result<Realtime> {
95 let session = session.clone();
99 let session = session.clone();
96 let host = host::resolve(&session, &config).await;
100 let host = host::resolve(&session, &config).await;
97 let script = runner::PageScript::new(&config);
98 let attached = attach(&session, &script).await?;
99 let (output, events) = mpsc::unbounded_channel();
101 let (output, events) = mpsc::unbounded_channel();
100 let (callback_output, callbacks) = mpsc::unbounded_channel();
102 let (callback_output, callbacks) = mpsc::unbounded_channel();
101 let (reply_sender, replies) = mpsc::unbounded_channel();
103 let (reply_sender, replies) = mpsc::unbounded_channel();
102 let (activity, activity_receiver) = watch::channel(config.initially_active);
104 let (activity, activity_receiver) = watch::channel(config.initially_active);
103 let resend = Arc::new(Notify::new());
105 let resend = Arc::new(Notify::new());
104 let (stop, stop_receiver) = oneshot::channel();
106 let (stop, stop_receiver) = oneshot::channel();
105 let mut runner = Runner::new(
107 let pipes = runner::CallbackPipes {
106 session,
108 output: callback_output,
107 config,
109 replies,
108 script,
110 };
109 host.clone(),
111 let task = if config.native {
110 output,
112 let mut trouter = NativeTrouter::new(
111 runner::CallbackPipes {
113 session,
112 output: callback_output,
114 config,
113 replies,
115 host.clone(),
114 },
116 output,
115 activity_receiver,
117 pipes,
116 resend.clone(),
118 activity_receiver,
117 );
119 resend.clone(),
118 if let Err(error) = runner.ensure().await {
120 );
119 attached.shutdown().await;
121 trouter.token().await?;
120 return Err(error.into());
122 tokio::spawn(trouter.run(stop_receiver))
121 }
123 } else {
122 let task = tokio::spawn(runner.run(attached, stop_receiver));
124 let script = runner::PageScript::new(&config);
125 let attached = attach(&session, &script).await?;
126 let mut runner = Runner::new(
127 session,
128 config,
129 script,
130 host.clone(),
131 output,
132 pipes,
133 activity_receiver,
134 resend.clone(),
135 );
136 if let Err(error) = runner.ensure().await {
137 attached.shutdown().await;
138 return Err(error.into());
139 }
140 tokio::spawn(runner.run(attached, stop_receiver))
141 };
123 Ok(Realtime {
142 Ok(Realtime {
124 host,
143 host,
125 events,
144 events,
@@ -159,7 +178,7 @@ impl Realtime {
159 self.resend.notify_one();
178 self.resend.notify_one();
160 }
179 }
161
180
162 /// Deletes the registration and closes the page-side socket.
181 /// Deletes the registration and closes the socket.
163 pub async fn stop(mut self) {
182 pub async fn stop(mut self) {
164 if let Some(stop) = self.stop.take() {
183 if let Some(stop) = self.stop.take() {
165 let (done, finished) = oneshot::channel();
184 let (done, finished) = oneshot::channel();
crates/chatsvc/src/realtime/native.rs added +679 −0
@@ -0,0 +1,679 @@
1 use std::collections::HashMap;
2 use std::sync::Arc;
3 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
4
5 use futures_util::{SinkExt, StreamExt};
6 use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
7 use serde_json::{Map, Value, json};
8 use session::{App, Method, Request, Session};
9 use tokio::net::TcpStream;
10 use tokio::sync::{Notify, mpsc, oneshot, watch};
11 use tokio::time::{MissedTickBehavior, interval, sleep, sleep_until, timeout};
12 use tokio_tungstenite::tungstenite::Message;
13 use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, connect_async};
14
15 use super::RealtimeConfig;
16 use super::callback::{CallbackReply, decode_callback};
17 use super::event::{RealtimeEvent, StatusEvent, StatusKind, decode_payload};
18 use super::host::ic3_scope;
19 use super::runner::CallbackPipes;
20
21 const REGISTRAR: &str = "https://teams.cloud.microsoft/registrar/prod/V2/registrations";
22 const UI_VERSION: &str = "1415/26091712213";
23 const CLIENT_VERSION: &str = "2026.36.01.1";
24 const PING_EVERY: Duration = Duration::from_secs(30);
25 const SILENCE_LIMIT: Duration = Duration::from_secs(100);
26 const REREGISTER_AFTER: Duration = Duration::from_secs(40 * 60);
27 const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
28 const MAX_BACKOFF: Duration = Duration::from_secs(30);
29 const ACTIVITY_DEBOUNCE: Duration = Duration::from_secs(1);
30 const ACTIVITY_ACK_TIMEOUT: Duration = Duration::from_secs(10);
31 const CALLBACK_REPLY_TIMEOUT: Duration = Duration::from_secs(5);
32 const STOP_STEP_TIMEOUT: Duration = Duration::from_secs(10);
33 const CALLBACK_PREFIX: &str = "callAgent/";
34 const MAX_PRESENCE_ENTRIES: usize = 1000;
35 const MAX_PRESENCE_FIELD: usize = 128;
36 const MAX_SENDER_NAME: usize = 256;
37 const MAX_RESOURCE_TYPE: usize = 64;
38 const MAX_LOSS_DETAIL: usize = 200;
39 const TOKEN_BODY: &str = "return token;";
40
41 type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;
42
43 /// One Trouter frame: `type:id:endpoint:data`.
44 #[derive(Debug, PartialEq, Eq)]
45 pub(super) struct Frame<'a> {
46 pub kind: char,
47 pub data: &'a str,
48 }
49
50 pub(super) fn parse_frame(text: &str) -> Option<Frame<'_>> {
51 let mut parts = text.splitn(4, ':');
52 let kind = parts.next()?;
53 let (Some(_id), Some(_endpoint)) = (parts.next(), parts.next()) else { return None };
54 let mut chars = kind.chars();
55 let kind = chars.next().filter(|kind| kind.is_ascii_digit() && chars.next().is_none())?;
56 Some(Frame { kind, data: parts.next().unwrap_or("") })
57 }
58
59 pub(super) fn socket_url(host: &str, endpoint_id: &str, correlation: &str, now_ms: u128) -> String {
60 let client_info = json!({"cv": CLIENT_VERSION, "ua": "TeamsCDL", "hr": "", "v": UI_VERSION}).to_string();
61 format!(
62 "wss://{host}/v4/c?tc={}&timeout=40&epid={endpoint_id}&ccid=&cor_id={correlation}&con_num={now_ms}_0",
63 percent_encode(&client_info)
64 )
65 }
66
67 const URI_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'_').remove(b'.').remove(b'!').remove(b'~').remove(b'*').remove(b'\'').remove(b'(').remove(b')');
68
69 fn percent_encode(text: &str) -> String {
70 utf8_percent_encode(text, URI_COMPONENT).to_string()
71 }
72
73 pub(super) fn registration_body(ringable: bool, endpoint_id: &str, surl: &str) -> Value {
74 let (app_id, template_key) = if ringable { ("SkypeSpacesWeb", "SkypeSpacesWeb_2.6") } else { ("TeamsCDLWebWorker", "TeamsCDLWebWorker_2.6") };
75 let mut description = json!({
76 "appId": app_id, "aesKey": "", "languageId": "en-US", "platform": "chrome",
77 "templateKey": template_key, "platformUIVersion": UI_VERSION,
78 });
79 if ringable {
80 description["productContext"] = json!("");
81 }
82 json!({
83 "clientDescription": description,
84 "registrationId": endpoint_id, "nodeId": "",
85 "transports": {"TROUTER": [{"context": "", "path": surl, "ttl": 3600}]},
86 })
87 }
88
89 fn header_value(headers: &Value, name: &str) -> Option<String> {
90 let headers = headers.as_object()?;
91 headers.iter().find(|(key, _)| key.eq_ignore_ascii_case(name)).map(|(_, value)| match value {
92 Value::String(text) => text.clone(),
93 other => other.to_string(),
94 })
95 }
96
97 /// Headers a callback reply echoes back to Trouter.
98 pub(super) fn echoed_headers(headers: &Value) -> Value {
99 let mut echoed = Map::new();
100 for name in ["X-Microsoft-Skype-Chain-ID", "trouter-request"] {
101 if let Some(value) = header_value(headers, name) {
102 echoed.insert(name.to_owned(), Value::String(value));
103 }
104 }
105 if let Some(correlation) = header_value(headers, "MS-CV") {
106 echoed.insert("MS-CV".to_owned(), Value::String(format!("{correlation}.0")));
107 }
108 Value::Object(echoed)
109 }
110
111 fn request_path(url: &str) -> String {
112 let Some(rest) = url.strip_prefix("/v4/f/") else { return url.to_owned() };
113 match rest.split_once('/') {
114 Some((_, path)) => path.to_owned(),
115 None => url.to_owned(),
116 }
117 }
118
119 fn conversation_of(resource: &Value) -> String {
120 let link = ["conversationLink", "to", "id"]
121 .iter()
122 .find_map(|key| resource.get(key).and_then(Value::as_str).filter(|value| !value.is_empty()))
123 .unwrap_or("");
124 let raw = match link.find("conversations/") {
125 Some(start) => {
126 let after = &link[start + "conversations/".len()..];
127 after.split([';', '/', '?']).next().unwrap_or("")
128 }
129 None => link.split(';').next().unwrap_or(""),
130 };
131 percent_decode(raw).unwrap_or_else(|| raw.to_owned())
132 }
133
134 fn percent_decode(text: &str) -> Option<String> {
135 percent_decode_str(text).decode_utf8().ok().map(|decoded| decoded.into_owned())
136 }
137
138 fn classify(resource_type: &str, message_type: &str) -> &'static str {
139 match resource_type {
140 "NewMessage" => {
141 if message_type.starts_with("Control/Typing") || message_type.starts_with("Control/ClearTyping") {
142 "typing"
143 } else if message_type == "ThreadActivity/MemberConsumptionHorizonUpdate" {
144 "read_receipt"
145 } else if message_type == "ThreadActivity/PinnedItemsUpdate" {
146 "pins_changed"
147 } else if message_type.starts_with("ThreadActivity/") {
148 "thread_activity"
149 } else if message_type.starts_with("Control/") {
150 "control"
151 } else {
152 "new_message"
153 }
154 }
155 "MessageUpdate" => "message_update",
156 "ThreadUpdate" => "thread_update",
157 _ => "other",
158 }
159 }
160
161 fn cut(text: &str, limit: usize) -> String {
162 text.chars().take(limit).collect()
163 }
164
165 fn typing_sender(from: &str) -> Option<String> {
166 let lower = from.to_ascii_lowercase();
167 let start = lower.rfind("/contacts/8:orgid:")? + "/contacts/8:orgid:".len();
168 let id = from[start..].trim_end_matches('/');
169 (!id.is_empty() && id.len() <= 64 && id.chars().all(|character| character.is_ascii_hexdigit() || character == '-')).then(|| id.to_owned())
170 }
171
172 /// The same message the page worker forwards for a Trouter notification.
173 pub(super) fn notification_payload(path: &str, body: Option<&Value>, received_at_ms: i64) -> Option<Value> {
174 if path == "unifiedPresenceService" {
175 let entries: Vec<Value> = body
176 .and_then(|body| body.get("presence"))
177 .and_then(Value::as_array)
178 .into_iter()
179 .flatten()
180 .take(MAX_PRESENCE_ENTRIES)
181 .filter_map(|entry| {
182 let text = |pointer: &str| entry.pointer(pointer).and_then(Value::as_str).map(|value| cut(value, MAX_PRESENCE_FIELD));
183 let mri = text("/mri")?;
184 let availability = text("/presence/availability")?;
185 Some(json!({
186 "mri": mri, "availability": availability, "activity": text("/presence/activity"),
187 "outOfOffice": entry.pointer("/presence/calendarData/isOutOfOffice").and_then(Value::as_bool).unwrap_or(false),
188 }))
189 })
190 .collect();
191 return (!entries.is_empty()).then(|| json!({"channel": "presence", "entries": entries}));
192 }
193 let resource = body.and_then(|body| body.get("resource")).filter(|resource| !resource.is_null());
194 let resource_type = body
195 .and_then(|body| body.get("resourceType"))
196 .and_then(Value::as_str)
197 .filter(|value| !value.is_empty())
198 .unwrap_or(if path.is_empty() { "unknown" } else { path });
199 let resource_type = cut(resource_type, MAX_RESOURCE_TYPE);
200 let message_type = resource.and_then(|resource| resource.get("messagetype")).and_then(Value::as_str).unwrap_or("");
201 let event_kind = if path == "messaging" { classify(&resource_type, message_type) } else { "other" };
202 let message_like = matches!(event_kind, "new_message" | "message_update");
203 let mut payload = json!({
204 "channel": "event", "resourceType": resource_type, "eventKind": event_kind, "receivedAt": received_at_ms,
205 "conversationId": resource.map(conversation_of).filter(|id| !id.is_empty()),
206 "messageId": resource.filter(|_| message_like).and_then(|resource| resource.get("id")).map(|id| match id {
207 Value::String(text) => text.clone(),
208 other => other.to_string(),
209 }),
210 });
211 if event_kind == "typing"
212 && let Some(resource) = resource
213 {
214 payload["typing"] = json!(if message_type.starts_with("Control/ClearTyping") { "clear" } else { "start" });
215 payload["senderId"] = json!(resource.get("from").and_then(Value::as_str).and_then(typing_sender));
216 payload["senderName"] = json!(resource.get("imdisplayname").and_then(Value::as_str).map(|name| cut(name, MAX_SENDER_NAME)));
217 }
218 Some(payload)
219 }
220
221 fn now_ms() -> i64 {
222 SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_millis() as i64)
223 }
224
225 fn status_payload(kind: &str, detail: &str) -> String {
226 json!({"channel": "status", "kind": kind, "detail": detail}).to_string()
227 }
228
229 struct PendingReply {
230 headers: Value,
231 deadline: tokio::time::Instant,
232 }
233
234 enum Ended {
235 Stopped(Option<oneshot::Sender<()>>),
236 Lost { was_ready: bool },
237 }
238
239 /// Trouter over a websocket of its own; only the token lookup and the registrar calls run in the app tab, which may stay parked.
240 pub(super) struct NativeTrouter {
241 pub session: Session,
242 pub config: RealtimeConfig,
243 pub host: String,
244 pub output: mpsc::UnboundedSender<RealtimeEvent>,
245 pub callbacks: CallbackPipes,
246 pub activity: watch::Receiver<bool>,
247 pub resend: Arc<Notify>,
248 pub endpoint_id: String,
249 force_refresh: bool,
250 retry: u32,
251 ack_counter: u64,
252 surl: String,
253 registered_at: Option<Instant>,
254 }
255
256 struct Connection {
257 socket: Socket,
258 token: String,
259 ready: bool,
260 last_frame: Instant,
261 sent_activity: Option<bool>,
262 activity_ack_id: u64,
263 activity_due: Option<tokio::time::Instant>,
264 activity_resend_due: Option<tokio::time::Instant>,
265 pending: HashMap<i64, PendingReply>,
266 }
267
268 fn far_future() -> tokio::time::Instant {
269 tokio::time::Instant::now() + Duration::from_secs(365 * 24 * 3600)
270 }
271
272 impl NativeTrouter {
273 pub(super) fn new(
274 session: Session,
275 config: RealtimeConfig,
276 host: String,
277 output: mpsc::UnboundedSender<RealtimeEvent>,
278 callbacks: CallbackPipes,
279 activity: watch::Receiver<bool>,
280 resend: Arc<Notify>,
281 ) -> Self {
282 NativeTrouter {
283 session,
284 config,
285 host,
286 output,
287 callbacks,
288 activity,
289 resend,
290 endpoint_id: uuid::Uuid::new_v4().to_string(),
291 force_refresh: false,
292 retry: 0,
293 ack_counter: 0,
294 surl: String::new(),
295 registered_at: None,
296 }
297 }
298
299 pub(super) async fn token(&mut self) -> session::Result<String> {
300 let value = self.session.run_with_token(App::Teams, &ic3_scope(), TOKEN_BODY, &json!({}), self.force_refresh).await?;
301 self.force_refresh = false;
302 value.as_str().map(str::to_owned).ok_or_else(|| session::Error::Cdp("token lookup gave no text".into()))
303 }
304
305 pub(super) async fn run(mut self, mut stop: oneshot::Receiver<oneshot::Sender<()>>) {
306 loop {
307 let connected = tokio::select! {
308 connected = self.connect() => connected,
309 done = &mut stop => Err(done.ok()),
310 };
311 let ended = match connected {
312 Ok(connection) => self.drive(connection, &mut stop).await,
313 Err(Some(done)) => Ended::Stopped(Some(done)),
314 Err(None) => Ended::Lost { was_ready: false },
315 };
316 match ended {
317 Ended::Stopped(done) => {
318 self.unregister().await;
319 if let Some(done) = done {
320 let _ = done.send(());
321 }
322 return;
323 }
324 Ended::Lost { was_ready } => {
325 if was_ready {
326 self.forward(&status_payload("disconnected", "closed"));
327 }
328 self.retry += 1;
329 let delay = Duration::from_secs(1u64 << self.retry.min(5)).min(MAX_BACKOFF);
330 tokio::select! {
331 _ = sleep(delay) => {}
332 done = &mut stop => {
333 self.unregister().await;
334 if let Ok(done) = done {
335 let _ = done.send(());
336 }
337 return;
338 }
339 _ = self.output.closed() => return,
340 }
341 }
342 }
343 }
344 }
345
346 async fn connect(&mut self) -> Result<Connection, Option<oneshot::Sender<()>>> {
347 let token = match self.token().await {
348 Ok(token) => token,
349 Err(error) => {
350 self.forward(&status_payload("disconnected", &format!("token_failed: {}", short(&error.to_string()))));
351 return Err(None);
352 }
353 };
354 let url = socket_url(&self.host, &self.endpoint_id, &uuid::Uuid::new_v4().to_string(), now_ms() as u128);
355 let Ok(Ok((socket, _))) = timeout(CONNECT_TIMEOUT, connect_async(url.as_str())).await else {
356 self.forward(&status_payload("disconnected", "connect_failed"));
357 return Err(None);
358 };
359 Ok(Connection {
360 socket,
361 token,
362 ready: false,
363 last_frame: Instant::now(),
364 sent_activity: None,
365 activity_ack_id: 0,
366 activity_due: None,
367 activity_resend_due: None,
368 pending: HashMap::new(),
369 })
370 }
371
372 async fn drive(&mut self, mut connection: Connection, stop: &mut oneshot::Receiver<oneshot::Sender<()>>) -> Ended {
373 let mut ping = interval(PING_EVERY);
374 ping.set_missed_tick_behavior(MissedTickBehavior::Delay);
375 ping.tick().await;
376 let connect_deadline = tokio::time::Instant::now() + CONNECT_TIMEOUT;
377 loop {
378 let next_reply = connection.pending.values().map(|pending| pending.deadline).min().unwrap_or_else(far_future);
379 tokio::select! {
380 frame = connection.socket.next() => {
381 let Some(Ok(message)) = frame else { return Ended::Lost { was_ready: connection.ready } };
382 let text = match message {
383 Message::Text(text) => text.to_string(),
384 Message::Close(_) => return Ended::Lost { was_ready: connection.ready },
385 _ => continue,
386 };
387 connection.last_frame = Instant::now();
388 if !self.on_frame(&mut connection, &text).await {
389 let _ = connection.socket.close(None).await;
390 return Ended::Lost { was_ready: connection.ready };
391 }
392 }
393 _ = sleep_until(connect_deadline), if !connection.ready => {
394 let _ = connection.socket.close(None).await;
395 return Ended::Lost { was_ready: false };
396 }
397 _ = ping.tick() => {
398 if connection.last_frame.elapsed() > SILENCE_LIMIT {
399 let _ = connection.socket.close(None).await;
400 return Ended::Lost { was_ready: connection.ready };
401 }
402 self.send_event(&mut connection, "ping", json!([])).await;
403 if connection.ready && self.registered_at.is_some_and(|at| at.elapsed() > REREGISTER_AFTER) {
404 let surl = self.surl.clone();
405 if let Err(detail) = self.register(&surl).await {
406 self.forward(&status_payload("error", &detail));
407 }
408 }
409 }
410 changed = self.activity.changed() => {
411 if changed.is_ok() {
412 let wanted = *self.activity.borrow_and_update();
413 connection.activity_due = (connection.ready && connection.sent_activity != Some(wanted)).then(|| tokio::time::Instant::now() + ACTIVITY_DEBOUNCE);
414 }
415 }
416 _ = sleep_until(connection.activity_due.unwrap_or_else(far_future)), if connection.activity_due.is_some() => {
417 self.transmit_activity(&mut connection, false).await;
418 }
419 _ = sleep_until(connection.activity_resend_due.unwrap_or_else(far_future)), if connection.activity_resend_due.is_some() => {
420 self.transmit_activity(&mut connection, true).await;
421 }
422 _ = self.resend.notified() => self.transmit_activity(&mut connection, false).await,
423 Some(reply) = self.callbacks.replies.recv() => self.answer(&mut connection, reply).await,
424 _ = sleep_until(next_reply), if !connection.pending.is_empty() => {
425 let now = tokio::time::Instant::now();
426 let due: Vec<i64> = connection.pending.iter().filter(|(_, pending)| pending.deadline <= now).map(|(id, _)| *id).collect();
427 for request_id in due {
428 self.answer(&mut connection, CallbackReply { request_id, status: 200, body: String::new() }).await;
429 }
430 }
431 done = &mut *stop => {
432 let _ = connection.socket.close(None).await;
433 return Ended::Stopped(done.ok());
434 }
435 _ = self.output.closed() => {
436 let _ = connection.socket.close(None).await;
437 return Ended::Stopped(None);
438 }
439 }
440 }
441 }
442
443 /// Answers whether the connection should stay open.
444 async fn on_frame(&mut self, connection: &mut Connection, text: &str) -> bool {
445 let Some(frame) = parse_frame(text) else { return true };
446 match frame.kind {
447 '1' => {
448 let authenticate = json!({"name": "user.authenticate", "args": [{"headers": {
449 "X-Ms-Test-User": "False", "Authorization": format!("Bearer {}", connection.token), "X-MS-Migration": "True",
450 }}]});
451 send(connection, format!("5:::{authenticate}")).await;
452 }
453 '2' => send(connection, "2::".to_owned()).await,
454 '5' => {
455 let Ok(event) = serde_json::from_str::<Value>(frame.data) else { return true };
456 match event.get("name").and_then(Value::as_str) {
457 Some("trouter.connected") => {
458 let surl = event.pointer("/args/0/surl").and_then(Value::as_str).unwrap_or_default().to_owned();
459 if let Err(detail) = self.register(&surl).await {
460 self.forward(&status_payload("error", &detail));
461 return false;
462 }
463 connection.ready = true;
464 self.retry = 0;
465 self.transmit_activity(connection, false).await;
466 let endpoint = json!({"channel": "endpoint", "endpointId": self.endpoint_id, "trouterUri": format!("{}/unifiedPresenceService", self.surl)});
467 self.forward(&endpoint.to_string());
468 self.forward(&status_payload("connected", ""));
469 }
470 Some("trouter.message_loss") => {
471 let args = event.get("args").cloned().unwrap_or(Value::Null);
472 let dropped: Vec<String> = args
473 .pointer("/0/droppedIndicators")
474 .and_then(Value::as_array)
475 .into_iter()
476 .flatten()
477 .map(|indicator| indicator.get("tag").map(|tag| tag.as_str().map_or_else(|| tag.to_string(), str::to_owned)).unwrap_or_default())
478 .collect();
479 self.send_event(connection, "trouter.processed_message_loss", args).await;
480 self.forward(&status_payload("message_loss", &cut(&dropped.join(","), MAX_LOSS_DETAIL)));
481 }
482 _ => {}
483 }
484 }
485 '6' => {
486 if frame.data.split('+').next().and_then(|id| id.parse::<u64>().ok()) == Some(connection.activity_ack_id) {
487 connection.activity_resend_due = None;
488 }
489 }
490 '3' => {
491 let Ok(request) = serde_json::from_str::<Value>(frame.data) else { return true };
492 let Some(request_id) = request.get("id").and_then(Value::as_i64) else { return true };
493 let path = request_path(request.get("url").and_then(Value::as_str).unwrap_or(""));
494 let raw_body = match request.get("body") {
495 Some(Value::String(text)) => text.clone(),
496 Some(Value::Null) | None => "null".to_owned(),
497 Some(other) => other.to_string(),
498 };
499 let headers = request.get("headers").cloned().unwrap_or(Value::Null);
500 if self.config.forward_callbacks && path.starts_with(CALLBACK_PREFIX) {
501 connection.pending.insert(request_id, PendingReply { headers: echoed_headers(&headers), deadline: tokio::time::Instant::now() + CALLBACK_REPLY_TIMEOUT });
502 let callback = json!({"channel": "callback", "requestId": request_id, "path": path,
503 "contentEncoding": header_value(&headers, "X-Microsoft-Skype-Content-Encoding"), "body": raw_body});
504 self.forward(&callback.to_string());
505 return true;
506 }
507 send(connection, format!("3:::{}", json!({"id": request_id, "status": 200, "headers": {}, "body": ""}))).await;
508 let body = serde_json::from_str::<Value>(&raw_body).ok();
509 if self.config.forward_callbacks && body.as_ref().is_some_and(|body| body.get("evt").is_some_and(Value::is_number)) {
510 let callback = json!({"channel": "callback", "requestId": request_id, "path": "", "contentEncoding": null, "body": raw_body});
511 self.forward(&callback.to_string());
512 return true;
513 }
514 if let Some(payload) = notification_payload(&path, body.as_ref(), now_ms()) {
515 self.forward(&payload.to_string());
516 }
517 }
518 _ => {}
519 }
520 true
521 }
522
523 async fn answer(&mut self, connection: &mut Connection, reply: CallbackReply) {
524 let Some(pending) = connection.pending.remove(&reply.request_id) else { return };
525 let frame = json!({"id": reply.request_id, "status": reply.status, "headers": pending.headers, "body": reply.body});
526 send(connection, format!("3:::{frame}")).await;
527 }
528
529 async fn send_event(&mut self, connection: &mut Connection, name: &str, args: Value) {
530 self.ack_counter += 1;
531 send(connection, format!("5:{}+::{}", self.ack_counter, json!({"name": name, "args": args}))).await;
532 }
533
534 async fn transmit_activity(&mut self, connection: &mut Connection, resend: bool) {
535 connection.activity_due = None;
536 connection.activity_resend_due = None;
537 if !connection.ready {
538 return;
539 }
540 let active = *self.activity.borrow();
541 let label = if active { "active" } else { "inactive" };
542 self.send_event(connection, "user.activity", json!([{"state": label, "cv": uuid::Uuid::new_v4().to_string()}])).await;
543 connection.sent_activity = Some(active);
544 connection.activity_ack_id = self.ack_counter;
545 if !resend {
546 connection.activity_resend_due = Some(tokio::time::Instant::now() + ACTIVITY_ACK_TIMEOUT);
547 }
548 }
549
550 async fn register(&mut self, surl: &str) -> Result<(), String> {
551 if !surl.is_empty() {
552 self.surl = surl.to_owned();
553 }
554 let mut request = Request::with_body(Method::Post, REGISTRAR, registration_body(self.config.ringable, &self.endpoint_id, &self.surl));
555 request.headers.extend([("X-MS-Migration".to_owned(), "True".to_owned()), ("Accept".to_owned(), "application/json, text/javascript".to_owned())]);
556 match self.session.send(request, &ic3_scope()).await {
557 Ok(_) => {
558 self.registered_at = Some(Instant::now());
559 Ok(())
560 }
561 Err(session::Error::Api { status, .. }) => {
562 if matches!(status, 401 | 403) {
563 self.force_refresh = true;
564 }
565 Err(format!("registrar_http_{status}"))
566 }
567 Err(_) => Err("registrar_failed".to_owned()),
568 }
569 }
570
571 async fn unregister(&self) {
572 if self.registered_at.is_none() {
573 return;
574 }
575 let mut request = Request::get(format!("{REGISTRAR}/{}", self.endpoint_id));
576 request.method = Method::Delete;
577 request.headers.push(("X-MS-Migration".to_owned(), "True".to_owned()));
578 let _ = timeout(STOP_STEP_TIMEOUT, self.session.send(request, &ic3_scope())).await;
579 }
580
581 fn forward(&mut self, payload: &str) {
582 if let Some(callback) = decode_callback(payload) {
583 let _ = self.callbacks.output.send(callback);
584 return;
585 }
586 if let Ok(event) = decode_payload(payload) {
587 if let RealtimeEvent::Status(StatusEvent { kind: StatusKind::Error, detail }) = &event
588 && matches!(detail.as_str(), "registrar_http_401" | "registrar_http_403")
589 {
590 self.force_refresh = true;
591 }
592 let _ = self.output.send(event);
593 }
594 }
595 }
596
597 async fn send(connection: &mut Connection, text: String) {
598 let _ = connection.socket.send(Message::Text(text.into())).await;
599 }
600
601 fn short(text: &str) -> String {
602 text.chars().take(120).collect()
603 }
604
605 #[cfg(test)]
606 mod tests {
607 use super::*;
608
609 #[test]
610 fn frames_split_into_type_and_data() {
611 assert_eq!(parse_frame("1::"), Some(Frame { kind: '1', data: "" }));
612 assert_eq!(parse_frame("5:3+::{\"a\":1}"), Some(Frame { kind: '5', data: "{\"a\":1}" }));
613 assert_eq!(parse_frame("3:::{\"x\":\"a:b\"}"), Some(Frame { kind: '3', data: "{\"x\":\"a:b\"}" }));
614 assert_eq!(parse_frame("garbage"), None);
615 assert_eq!(parse_frame("12::"), None);
616 }
617
618 #[test]
619 fn the_socket_url_carries_the_endpoint_and_encoded_client_info() {
620 let url = socket_url("go-eu.trouter.teams.microsoft.com", "ep-1", "cor-1", 42);
621 assert!(url.starts_with("wss://go-eu.trouter.teams.microsoft.com/v4/c?tc=%7B%22cv%22"), "{url}");
622 assert!(url.ends_with("&timeout=40&epid=ep-1&ccid=&cor_id=cor-1&con_num=42_0"), "{url}");
623 }
624
625 #[test]
626 fn ringable_registration_uses_the_calling_app() {
627 let calling = registration_body(true, "ep", "https://surl/");
628 assert_eq!(calling["clientDescription"]["appId"], "SkypeSpacesWeb");
629 assert_eq!(calling["clientDescription"]["productContext"], "");
630 let worker = registration_body(false, "ep", "https://surl/");
631 assert_eq!(worker["clientDescription"]["templateKey"], "TeamsCDLWebWorker_2.6");
632 assert!(worker["clientDescription"].get("productContext").is_none());
633 assert_eq!(worker["transports"]["TROUTER"][0]["path"], "https://surl/");
634 }
635
636 #[test]
637 fn callback_replies_echo_chain_request_and_correlation() {
638 let echoed = echoed_headers(&json!({"x-microsoft-skype-chain-id": "c", "Trouter-Request": "r", "ms-cv": "abc", "Other": "o"}));
639 assert_eq!(echoed, json!({"X-Microsoft-Skype-Chain-ID": "c", "trouter-request": "r", "MS-CV": "abc.0"}));
640 }
641
642 #[test]
643 fn request_paths_drop_the_forwarding_prefix() {
644 assert_eq!(request_path("/v4/f/abc123/messaging"), "messaging");
645 assert_eq!(request_path("/v4/f/abc/callAgent/x/y"), "callAgent/x/y");
646 assert_eq!(request_path("messaging"), "messaging");
647 }
648
649 #[test]
650 fn a_message_notification_becomes_the_page_event() {
651 let body = json!({"resourceType": "NewMessage", "resource": {"messagetype": "RichText/Html", "id": "177",
652 "conversationLink": "https://emea.ng.msg.teams.microsoft.com/v1/users/ME/conversations/19%3Aabc%40thread.v2"}});
653 let payload = notification_payload("messaging", Some(&body), 5).unwrap();
654 assert_eq!(payload["eventKind"], "new_message");
655 assert_eq!(payload["conversationId"], "19:abc@thread.v2");
656 assert_eq!(payload["messageId"], "177");
657 assert!(matches!(decode_payload(&payload.to_string()), Ok(RealtimeEvent::Message(_))));
658 }
659
660 #[test]
661 fn typing_names_the_sender() {
662 let body = json!({"resourceType": "NewMessage", "resource": {"messagetype": "Control/Typing", "imdisplayname": "Ada",
663 "from": "https://x/v1/users/ME/contacts/8:orgid:0a1b2c3d-0000-0000-0000-000000000000", "conversationLink": "conversations/19:t@thread.v2"}});
664 let payload = notification_payload("messaging", Some(&body), 5).unwrap();
665 assert_eq!(payload["eventKind"], "typing");
666 assert_eq!(payload["typing"], "start");
667 assert_eq!(payload["senderId"], "0a1b2c3d-0000-0000-0000-000000000000");
668 assert_eq!(payload["senderName"], "Ada");
669 assert!(payload["messageId"].is_null());
670 }
671
672 #[test]
673 fn presence_keeps_entries_with_an_availability() {
674 let body = json!({"presence": [{"mri": "8:orgid:a", "presence": {"availability": "Available", "activity": "Available"}}, {"mri": "8:orgid:b"}]});
675 let payload = notification_payload("unifiedPresenceService", Some(&body), 5).unwrap();
676 assert_eq!(payload["entries"].as_array().unwrap().len(), 1);
677 assert!(notification_payload("unifiedPresenceService", Some(&json!({"presence": []})), 5).is_none());
678 }
679 }
@@ -0,0 +1,679 @@
1use std::collections::HashMap;
2use std::sync::Arc;
3use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
4
5use futures_util::{SinkExt, StreamExt};
6use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
7use serde_json::{Map, Value, json};
8use session::{App, Method, Request, Session};
9use tokio::net::TcpStream;
10use tokio::sync::{Notify, mpsc, oneshot, watch};
11use tokio::time::{MissedTickBehavior, interval, sleep, sleep_until, timeout};
12use tokio_tungstenite::tungstenite::Message;
13use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, connect_async};
14
15use super::RealtimeConfig;
16use super::callback::{CallbackReply, decode_callback};
17use super::event::{RealtimeEvent, StatusEvent, StatusKind, decode_payload};
18use super::host::ic3_scope;
19use super::runner::CallbackPipes;
20
21const REGISTRAR: &str = "https://teams.cloud.microsoft/registrar/prod/V2/registrations";
22const UI_VERSION: &str = "1415/26091712213";
23const CLIENT_VERSION: &str = "2026.36.01.1";
24const PING_EVERY: Duration = Duration::from_secs(30);
25const SILENCE_LIMIT: Duration = Duration::from_secs(100);
26const REREGISTER_AFTER: Duration = Duration::from_secs(40 * 60);
27const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
28const MAX_BACKOFF: Duration = Duration::from_secs(30);
29const ACTIVITY_DEBOUNCE: Duration = Duration::from_secs(1);
30const ACTIVITY_ACK_TIMEOUT: Duration = Duration::from_secs(10);
31const CALLBACK_REPLY_TIMEOUT: Duration = Duration::from_secs(5);
32const STOP_STEP_TIMEOUT: Duration = Duration::from_secs(10);
33const CALLBACK_PREFIX: &str = "callAgent/";
34const MAX_PRESENCE_ENTRIES: usize = 1000;
35const MAX_PRESENCE_FIELD: usize = 128;
36const MAX_SENDER_NAME: usize = 256;
37const MAX_RESOURCE_TYPE: usize = 64;
38const MAX_LOSS_DETAIL: usize = 200;
39const TOKEN_BODY: &str = "return token;";
40
41type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;
42
43/// One Trouter frame: `type:id:endpoint:data`.
44#[derive(Debug, PartialEq, Eq)]
45pub(super) struct Frame<'a> {
46 pub kind: char,
47 pub data: &'a str,
48}
49
50pub(super) fn parse_frame(text: &str) -> Option<Frame<'_>> {
51 let mut parts = text.splitn(4, ':');
52 let kind = parts.next()?;
53 let (Some(_id), Some(_endpoint)) = (parts.next(), parts.next()) else { return None };
54 let mut chars = kind.chars();
55 let kind = chars.next().filter(|kind| kind.is_ascii_digit() && chars.next().is_none())?;
56 Some(Frame { kind, data: parts.next().unwrap_or("") })
57}
58
59pub(super) fn socket_url(host: &str, endpoint_id: &str, correlation: &str, now_ms: u128) -> String {
60 let client_info = json!({"cv": CLIENT_VERSION, "ua": "TeamsCDL", "hr": "", "v": UI_VERSION}).to_string();
61 format!(
62 "wss://{host}/v4/c?tc={}&timeout=40&epid={endpoint_id}&ccid=&cor_id={correlation}&con_num={now_ms}_0",
63 percent_encode(&client_info)
64 )
65}
66
67const URI_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'_').remove(b'.').remove(b'!').remove(b'~').remove(b'*').remove(b'\'').remove(b'(').remove(b')');
68
69fn percent_encode(text: &str) -> String {
70 utf8_percent_encode(text, URI_COMPONENT).to_string()
71}
72
73pub(super) fn registration_body(ringable: bool, endpoint_id: &str, surl: &str) -> Value {
74 let (app_id, template_key) = if ringable { ("SkypeSpacesWeb", "SkypeSpacesWeb_2.6") } else { ("TeamsCDLWebWorker", "TeamsCDLWebWorker_2.6") };
75 let mut description = json!({
76 "appId": app_id, "aesKey": "", "languageId": "en-US", "platform": "chrome",
77 "templateKey": template_key, "platformUIVersion": UI_VERSION,
78 });
79 if ringable {
80 description["productContext"] = json!("");
81 }
82 json!({
83 "clientDescription": description,
84 "registrationId": endpoint_id, "nodeId": "",
85 "transports": {"TROUTER": [{"context": "", "path": surl, "ttl": 3600}]},
86 })
87}
88
89fn header_value(headers: &Value, name: &str) -> Option<String> {
90 let headers = headers.as_object()?;
91 headers.iter().find(|(key, _)| key.eq_ignore_ascii_case(name)).map(|(_, value)| match value {
92 Value::String(text) => text.clone(),
93 other => other.to_string(),
94 })
95}
96
97/// Headers a callback reply echoes back to Trouter.
98pub(super) fn echoed_headers(headers: &Value) -> Value {
99 let mut echoed = Map::new();
100 for name in ["X-Microsoft-Skype-Chain-ID", "trouter-request"] {
101 if let Some(value) = header_value(headers, name) {
102 echoed.insert(name.to_owned(), Value::String(value));
103 }
104 }
105 if let Some(correlation) = header_value(headers, "MS-CV") {
106 echoed.insert("MS-CV".to_owned(), Value::String(format!("{correlation}.0")));
107 }
108 Value::Object(echoed)
109}
110
111fn request_path(url: &str) -> String {
112 let Some(rest) = url.strip_prefix("/v4/f/") else { return url.to_owned() };
113 match rest.split_once('/') {
114 Some((_, path)) => path.to_owned(),
115 None => url.to_owned(),
116 }
117}
118
119fn conversation_of(resource: &Value) -> String {
120 let link = ["conversationLink", "to", "id"]
121 .iter()
122 .find_map(|key| resource.get(key).and_then(Value::as_str).filter(|value| !value.is_empty()))
123 .unwrap_or("");
124 let raw = match link.find("conversations/") {
125 Some(start) => {
126 let after = &link[start + "conversations/".len()..];
127 after.split([';', '/', '?']).next().unwrap_or("")
128 }
129 None => link.split(';').next().unwrap_or(""),
130 };
131 percent_decode(raw).unwrap_or_else(|| raw.to_owned())
132}
133
134fn percent_decode(text: &str) -> Option<String> {
135 percent_decode_str(text).decode_utf8().ok().map(|decoded| decoded.into_owned())
136}
137
138fn classify(resource_type: &str, message_type: &str) -> &'static str {
139 match resource_type {
140 "NewMessage" => {
141 if message_type.starts_with("Control/Typing") || message_type.starts_with("Control/ClearTyping") {
142 "typing"
143 } else if message_type == "ThreadActivity/MemberConsumptionHorizonUpdate" {
144 "read_receipt"
145 } else if message_type == "ThreadActivity/PinnedItemsUpdate" {
146 "pins_changed"
147 } else if message_type.starts_with("ThreadActivity/") {
148 "thread_activity"
149 } else if message_type.starts_with("Control/") {
150 "control"
151 } else {
152 "new_message"
153 }
154 }
155 "MessageUpdate" => "message_update",
156 "ThreadUpdate" => "thread_update",
157 _ => "other",
158 }
159}
160
161fn cut(text: &str, limit: usize) -> String {
162 text.chars().take(limit).collect()
163}
164
165fn typing_sender(from: &str) -> Option<String> {
166 let lower = from.to_ascii_lowercase();
167 let start = lower.rfind("/contacts/8:orgid:")? + "/contacts/8:orgid:".len();
168 let id = from[start..].trim_end_matches('/');
169 (!id.is_empty() && id.len() <= 64 && id.chars().all(|character| character.is_ascii_hexdigit() || character == '-')).then(|| id.to_owned())
170}
171
172/// The same message the page worker forwards for a Trouter notification.
173pub(super) fn notification_payload(path: &str, body: Option<&Value>, received_at_ms: i64) -> Option<Value> {
174 if path == "unifiedPresenceService" {
175 let entries: Vec<Value> = body
176 .and_then(|body| body.get("presence"))
177 .and_then(Value::as_array)
178 .into_iter()
179 .flatten()
180 .take(MAX_PRESENCE_ENTRIES)
181 .filter_map(|entry| {
182 let text = |pointer: &str| entry.pointer(pointer).and_then(Value::as_str).map(|value| cut(value, MAX_PRESENCE_FIELD));
183 let mri = text("/mri")?;
184 let availability = text("/presence/availability")?;
185 Some(json!({
186 "mri": mri, "availability": availability, "activity": text("/presence/activity"),
187 "outOfOffice": entry.pointer("/presence/calendarData/isOutOfOffice").and_then(Value::as_bool).unwrap_or(false),
188 }))
189 })
190 .collect();
191 return (!entries.is_empty()).then(|| json!({"channel": "presence", "entries": entries}));
192 }
193 let resource = body.and_then(|body| body.get("resource")).filter(|resource| !resource.is_null());
194 let resource_type = body
195 .and_then(|body| body.get("resourceType"))
196 .and_then(Value::as_str)
197 .filter(|value| !value.is_empty())
198 .unwrap_or(if path.is_empty() { "unknown" } else { path });
199 let resource_type = cut(resource_type, MAX_RESOURCE_TYPE);
200 let message_type = resource.and_then(|resource| resource.get("messagetype")).and_then(Value::as_str).unwrap_or("");
201 let event_kind = if path == "messaging" { classify(&resource_type, message_type) } else { "other" };
202 let message_like = matches!(event_kind, "new_message" | "message_update");
203 let mut payload = json!({
204 "channel": "event", "resourceType": resource_type, "eventKind": event_kind, "receivedAt": received_at_ms,
205 "conversationId": resource.map(conversation_of).filter(|id| !id.is_empty()),
206 "messageId": resource.filter(|_| message_like).and_then(|resource| resource.get("id")).map(|id| match id {
207 Value::String(text) => text.clone(),
208 other => other.to_string(),
209 }),
210 });
211 if event_kind == "typing"
212 && let Some(resource) = resource
213 {
214 payload["typing"] = json!(if message_type.starts_with("Control/ClearTyping") { "clear" } else { "start" });
215 payload["senderId"] = json!(resource.get("from").and_then(Value::as_str).and_then(typing_sender));
216 payload["senderName"] = json!(resource.get("imdisplayname").and_then(Value::as_str).map(|name| cut(name, MAX_SENDER_NAME)));
217 }
218 Some(payload)
219}
220
221fn now_ms() -> i64 {
222 SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_millis() as i64)
223}
224
225fn status_payload(kind: &str, detail: &str) -> String {
226 json!({"channel": "status", "kind": kind, "detail": detail}).to_string()
227}
228
229struct PendingReply {
230 headers: Value,
231 deadline: tokio::time::Instant,
232}
233
234enum Ended {
235 Stopped(Option<oneshot::Sender<()>>),
236 Lost { was_ready: bool },
237}
238
239/// Trouter over a websocket of its own; only the token lookup and the registrar calls run in the app tab, which may stay parked.
240pub(super) struct NativeTrouter {
241 pub session: Session,
242 pub config: RealtimeConfig,
243 pub host: String,
244 pub output: mpsc::UnboundedSender<RealtimeEvent>,
245 pub callbacks: CallbackPipes,
246 pub activity: watch::Receiver<bool>,
247 pub resend: Arc<Notify>,
248 pub endpoint_id: String,
249 force_refresh: bool,
250 retry: u32,
251 ack_counter: u64,
252 surl: String,
253 registered_at: Option<Instant>,
254}
255
256struct Connection {
257 socket: Socket,
258 token: String,
259 ready: bool,
260 last_frame: Instant,
261 sent_activity: Option<bool>,
262 activity_ack_id: u64,
263 activity_due: Option<tokio::time::Instant>,
264 activity_resend_due: Option<tokio::time::Instant>,
265 pending: HashMap<i64, PendingReply>,
266}
267
268fn far_future() -> tokio::time::Instant {
269 tokio::time::Instant::now() + Duration::from_secs(365 * 24 * 3600)
270}
271
272impl NativeTrouter {
273 pub(super) fn new(
274 session: Session,
275 config: RealtimeConfig,
276 host: String,
277 output: mpsc::UnboundedSender<RealtimeEvent>,
278 callbacks: CallbackPipes,
279 activity: watch::Receiver<bool>,
280 resend: Arc<Notify>,
281 ) -> Self {
282 NativeTrouter {
283 session,
284 config,
285 host,
286 output,
287 callbacks,
288 activity,
289 resend,
290 endpoint_id: uuid::Uuid::new_v4().to_string(),
291 force_refresh: false,
292 retry: 0,
293 ack_counter: 0,
294 surl: String::new(),
295 registered_at: None,
296 }
297 }
298
299 pub(super) async fn token(&mut self) -> session::Result<String> {
300 let value = self.session.run_with_token(App::Teams, &ic3_scope(), TOKEN_BODY, &json!({}), self.force_refresh).await?;
301 self.force_refresh = false;
302 value.as_str().map(str::to_owned).ok_or_else(|| session::Error::Cdp("token lookup gave no text".into()))
303 }
304
305 pub(super) async fn run(mut self, mut stop: oneshot::Receiver<oneshot::Sender<()>>) {
306 loop {
307 let connected = tokio::select! {
308 connected = self.connect() => connected,
309 done = &mut stop => Err(done.ok()),
310 };
311 let ended = match connected {
312 Ok(connection) => self.drive(connection, &mut stop).await,
313 Err(Some(done)) => Ended::Stopped(Some(done)),
314 Err(None) => Ended::Lost { was_ready: false },
315 };
316 match ended {
317 Ended::Stopped(done) => {
318 self.unregister().await;
319 if let Some(done) = done {
320 let _ = done.send(());
321 }
322 return;
323 }
324 Ended::Lost { was_ready } => {
325 if was_ready {
326 self.forward(&status_payload("disconnected", "closed"));
327 }
328 self.retry += 1;
329 let delay = Duration::from_secs(1u64 << self.retry.min(5)).min(MAX_BACKOFF);
330 tokio::select! {
331 _ = sleep(delay) => {}
332 done = &mut stop => {
333 self.unregister().await;
334 if let Ok(done) = done {
335 let _ = done.send(());
336 }
337 return;
338 }
339 _ = self.output.closed() => return,
340 }
341 }
342 }
343 }
344 }
345
346 async fn connect(&mut self) -> Result<Connection, Option<oneshot::Sender<()>>> {
347 let token = match self.token().await {
348 Ok(token) => token,
349 Err(error) => {
350 self.forward(&status_payload("disconnected", &format!("token_failed: {}", short(&error.to_string()))));
351 return Err(None);
352 }
353 };
354 let url = socket_url(&self.host, &self.endpoint_id, &uuid::Uuid::new_v4().to_string(), now_ms() as u128);
355 let Ok(Ok((socket, _))) = timeout(CONNECT_TIMEOUT, connect_async(url.as_str())).await else {
356 self.forward(&status_payload("disconnected", "connect_failed"));
357 return Err(None);
358 };
359 Ok(Connection {
360 socket,
361 token,
362 ready: false,
363 last_frame: Instant::now(),
364 sent_activity: None,
365 activity_ack_id: 0,
366 activity_due: None,
367 activity_resend_due: None,
368 pending: HashMap::new(),
369 })
370 }
371
372 async fn drive(&mut self, mut connection: Connection, stop: &mut oneshot::Receiver<oneshot::Sender<()>>) -> Ended {
373 let mut ping = interval(PING_EVERY);
374 ping.set_missed_tick_behavior(MissedTickBehavior::Delay);
375 ping.tick().await;
376 let connect_deadline = tokio::time::Instant::now() + CONNECT_TIMEOUT;
377 loop {
378 let next_reply = connection.pending.values().map(|pending| pending.deadline).min().unwrap_or_else(far_future);
379 tokio::select! {
380 frame = connection.socket.next() => {
381 let Some(Ok(message)) = frame else { return Ended::Lost { was_ready: connection.ready } };
382 let text = match message {
383 Message::Text(text) => text.to_string(),
384 Message::Close(_) => return Ended::Lost { was_ready: connection.ready },
385 _ => continue,
386 };
387 connection.last_frame = Instant::now();
388 if !self.on_frame(&mut connection, &text).await {
389 let _ = connection.socket.close(None).await;
390 return Ended::Lost { was_ready: connection.ready };
391 }
392 }
393 _ = sleep_until(connect_deadline), if !connection.ready => {
394 let _ = connection.socket.close(None).await;
395 return Ended::Lost { was_ready: false };
396 }
397 _ = ping.tick() => {
398 if connection.last_frame.elapsed() > SILENCE_LIMIT {
399 let _ = connection.socket.close(None).await;
400 return Ended::Lost { was_ready: connection.ready };
401 }
402 self.send_event(&mut connection, "ping", json!([])).await;
403 if connection.ready && self.registered_at.is_some_and(|at| at.elapsed() > REREGISTER_AFTER) {
404 let surl = self.surl.clone();
405 if let Err(detail) = self.register(&surl).await {
406 self.forward(&status_payload("error", &detail));
407 }
408 }
409 }
410 changed = self.activity.changed() => {
411 if changed.is_ok() {
412 let wanted = *self.activity.borrow_and_update();
413 connection.activity_due = (connection.ready && connection.sent_activity != Some(wanted)).then(|| tokio::time::Instant::now() + ACTIVITY_DEBOUNCE);
414 }
415 }
416 _ = sleep_until(connection.activity_due.unwrap_or_else(far_future)), if connection.activity_due.is_some() => {
417 self.transmit_activity(&mut connection, false).await;
418 }
419 _ = sleep_until(connection.activity_resend_due.unwrap_or_else(far_future)), if connection.activity_resend_due.is_some() => {
420 self.transmit_activity(&mut connection, true).await;
421 }
422 _ = self.resend.notified() => self.transmit_activity(&mut connection, false).await,
423 Some(reply) = self.callbacks.replies.recv() => self.answer(&mut connection, reply).await,
424 _ = sleep_until(next_reply), if !connection.pending.is_empty() => {
425 let now = tokio::time::Instant::now();
426 let due: Vec<i64> = connection.pending.iter().filter(|(_, pending)| pending.deadline <= now).map(|(id, _)| *id).collect();
427 for request_id in due {
428 self.answer(&mut connection, CallbackReply { request_id, status: 200, body: String::new() }).await;
429 }
430 }
431 done = &mut *stop => {
432 let _ = connection.socket.close(None).await;
433 return Ended::Stopped(done.ok());
434 }
435 _ = self.output.closed() => {
436 let _ = connection.socket.close(None).await;
437 return Ended::Stopped(None);
438 }
439 }
440 }
441 }
442
443 /// Answers whether the connection should stay open.
444 async fn on_frame(&mut self, connection: &mut Connection, text: &str) -> bool {
445 let Some(frame) = parse_frame(text) else { return true };
446 match frame.kind {
447 '1' => {
448 let authenticate = json!({"name": "user.authenticate", "args": [{"headers": {
449 "X-Ms-Test-User": "False", "Authorization": format!("Bearer {}", connection.token), "X-MS-Migration": "True",
450 }}]});
451 send(connection, format!("5:::{authenticate}")).await;
452 }
453 '2' => send(connection, "2::".to_owned()).await,
454 '5' => {
455 let Ok(event) = serde_json::from_str::<Value>(frame.data) else { return true };
456 match event.get("name").and_then(Value::as_str) {
457 Some("trouter.connected") => {
458 let surl = event.pointer("/args/0/surl").and_then(Value::as_str).unwrap_or_default().to_owned();
459 if let Err(detail) = self.register(&surl).await {
460 self.forward(&status_payload("error", &detail));
461 return false;
462 }
463 connection.ready = true;
464 self.retry = 0;
465 self.transmit_activity(connection, false).await;
466 let endpoint = json!({"channel": "endpoint", "endpointId": self.endpoint_id, "trouterUri": format!("{}/unifiedPresenceService", self.surl)});
467 self.forward(&endpoint.to_string());
468 self.forward(&status_payload("connected", ""));
469 }
470 Some("trouter.message_loss") => {
471 let args = event.get("args").cloned().unwrap_or(Value::Null);
472 let dropped: Vec<String> = args
473 .pointer("/0/droppedIndicators")
474 .and_then(Value::as_array)
475 .into_iter()
476 .flatten()
477 .map(|indicator| indicator.get("tag").map(|tag| tag.as_str().map_or_else(|| tag.to_string(), str::to_owned)).unwrap_or_default())
478 .collect();
479 self.send_event(connection, "trouter.processed_message_loss", args).await;
480 self.forward(&status_payload("message_loss", &cut(&dropped.join(","), MAX_LOSS_DETAIL)));
481 }
482 _ => {}
483 }
484 }
485 '6' => {
486 if frame.data.split('+').next().and_then(|id| id.parse::<u64>().ok()) == Some(connection.activity_ack_id) {
487 connection.activity_resend_due = None;
488 }
489 }
490 '3' => {
491 let Ok(request) = serde_json::from_str::<Value>(frame.data) else { return true };
492 let Some(request_id) = request.get("id").and_then(Value::as_i64) else { return true };
493 let path = request_path(request.get("url").and_then(Value::as_str).unwrap_or(""));
494 let raw_body = match request.get("body") {
495 Some(Value::String(text)) => text.clone(),
496 Some(Value::Null) | None => "null".to_owned(),
497 Some(other) => other.to_string(),
498 };
499 let headers = request.get("headers").cloned().unwrap_or(Value::Null);
500 if self.config.forward_callbacks && path.starts_with(CALLBACK_PREFIX) {
501 connection.pending.insert(request_id, PendingReply { headers: echoed_headers(&headers), deadline: tokio::time::Instant::now() + CALLBACK_REPLY_TIMEOUT });
502 let callback = json!({"channel": "callback", "requestId": request_id, "path": path,
503 "contentEncoding": header_value(&headers, "X-Microsoft-Skype-Content-Encoding"), "body": raw_body});
504 self.forward(&callback.to_string());
505 return true;
506 }
507 send(connection, format!("3:::{}", json!({"id": request_id, "status": 200, "headers": {}, "body": ""}))).await;
508 let body = serde_json::from_str::<Value>(&raw_body).ok();
509 if self.config.forward_callbacks && body.as_ref().is_some_and(|body| body.get("evt").is_some_and(Value::is_number)) {
510 let callback = json!({"channel": "callback", "requestId": request_id, "path": "", "contentEncoding": null, "body": raw_body});
511 self.forward(&callback.to_string());
512 return true;
513 }
514 if let Some(payload) = notification_payload(&path, body.as_ref(), now_ms()) {
515 self.forward(&payload.to_string());
516 }
517 }
518 _ => {}
519 }
520 true
521 }
522
523 async fn answer(&mut self, connection: &mut Connection, reply: CallbackReply) {
524 let Some(pending) = connection.pending.remove(&reply.request_id) else { return };
525 let frame = json!({"id": reply.request_id, "status": reply.status, "headers": pending.headers, "body": reply.body});
526 send(connection, format!("3:::{frame}")).await;
527 }
528
529 async fn send_event(&mut self, connection: &mut Connection, name: &str, args: Value) {
530 self.ack_counter += 1;
531 send(connection, format!("5:{}+::{}", self.ack_counter, json!({"name": name, "args": args}))).await;
532 }
533
534 async fn transmit_activity(&mut self, connection: &mut Connection, resend: bool) {
535 connection.activity_due = None;
536 connection.activity_resend_due = None;
537 if !connection.ready {
538 return;
539 }
540 let active = *self.activity.borrow();
541 let label = if active { "active" } else { "inactive" };
542 self.send_event(connection, "user.activity", json!([{"state": label, "cv": uuid::Uuid::new_v4().to_string()}])).await;
543 connection.sent_activity = Some(active);
544 connection.activity_ack_id = self.ack_counter;
545 if !resend {
546 connection.activity_resend_due = Some(tokio::time::Instant::now() + ACTIVITY_ACK_TIMEOUT);
547 }
548 }
549
550 async fn register(&mut self, surl: &str) -> Result<(), String> {
551 if !surl.is_empty() {
552 self.surl = surl.to_owned();
553 }
554 let mut request = Request::with_body(Method::Post, REGISTRAR, registration_body(self.config.ringable, &self.endpoint_id, &self.surl));
555 request.headers.extend([("X-MS-Migration".to_owned(), "True".to_owned()), ("Accept".to_owned(), "application/json, text/javascript".to_owned())]);
556 match self.session.send(request, &ic3_scope()).await {
557 Ok(_) => {
558 self.registered_at = Some(Instant::now());
559 Ok(())
560 }
561 Err(session::Error::Api { status, .. }) => {
562 if matches!(status, 401 | 403) {
563 self.force_refresh = true;
564 }
565 Err(format!("registrar_http_{status}"))
566 }
567 Err(_) => Err("registrar_failed".to_owned()),
568 }
569 }
570
571 async fn unregister(&self) {
572 if self.registered_at.is_none() {
573 return;
574 }
575 let mut request = Request::get(format!("{REGISTRAR}/{}", self.endpoint_id));
576 request.method = Method::Delete;
577 request.headers.push(("X-MS-Migration".to_owned(), "True".to_owned()));
578 let _ = timeout(STOP_STEP_TIMEOUT, self.session.send(request, &ic3_scope())).await;
579 }
580
581 fn forward(&mut self, payload: &str) {
582 if let Some(callback) = decode_callback(payload) {
583 let _ = self.callbacks.output.send(callback);
584 return;
585 }
586 if let Ok(event) = decode_payload(payload) {
587 if let RealtimeEvent::Status(StatusEvent { kind: StatusKind::Error, detail }) = &event
588 && matches!(detail.as_str(), "registrar_http_401" | "registrar_http_403")
589 {
590 self.force_refresh = true;
591 }
592 let _ = self.output.send(event);
593 }
594 }
595}
596
597async fn send(connection: &mut Connection, text: String) {
598 let _ = connection.socket.send(Message::Text(text.into())).await;
599}
600
601fn short(text: &str) -> String {
602 text.chars().take(120).collect()
603}
604
605#[cfg(test)]
606mod tests {
607 use super::*;
608
609 #[test]
610 fn frames_split_into_type_and_data() {
611 assert_eq!(parse_frame("1::"), Some(Frame { kind: '1', data: "" }));
612 assert_eq!(parse_frame("5:3+::{\"a\":1}"), Some(Frame { kind: '5', data: "{\"a\":1}" }));
613 assert_eq!(parse_frame("3:::{\"x\":\"a:b\"}"), Some(Frame { kind: '3', data: "{\"x\":\"a:b\"}" }));
614 assert_eq!(parse_frame("garbage"), None);
615 assert_eq!(parse_frame("12::"), None);
616 }
617
618 #[test]
619 fn the_socket_url_carries_the_endpoint_and_encoded_client_info() {
620 let url = socket_url("go-eu.trouter.teams.microsoft.com", "ep-1", "cor-1", 42);
621 assert!(url.starts_with("wss://go-eu.trouter.teams.microsoft.com/v4/c?tc=%7B%22cv%22"), "{url}");
622 assert!(url.ends_with("&timeout=40&epid=ep-1&ccid=&cor_id=cor-1&con_num=42_0"), "{url}");
623 }
624
625 #[test]
626 fn ringable_registration_uses_the_calling_app() {
627 let calling = registration_body(true, "ep", "https://surl/");
628 assert_eq!(calling["clientDescription"]["appId"], "SkypeSpacesWeb");
629 assert_eq!(calling["clientDescription"]["productContext"], "");
630 let worker = registration_body(false, "ep", "https://surl/");
631 assert_eq!(worker["clientDescription"]["templateKey"], "TeamsCDLWebWorker_2.6");
632 assert!(worker["clientDescription"].get("productContext").is_none());
633 assert_eq!(worker["transports"]["TROUTER"][0]["path"], "https://surl/");
634 }
635
636 #[test]
637 fn callback_replies_echo_chain_request_and_correlation() {
638 let echoed = echoed_headers(&json!({"x-microsoft-skype-chain-id": "c", "Trouter-Request": "r", "ms-cv": "abc", "Other": "o"}));
639 assert_eq!(echoed, json!({"X-Microsoft-Skype-Chain-ID": "c", "trouter-request": "r", "MS-CV": "abc.0"}));
640 }
641
642 #[test]
643 fn request_paths_drop_the_forwarding_prefix() {
644 assert_eq!(request_path("/v4/f/abc123/messaging"), "messaging");
645 assert_eq!(request_path("/v4/f/abc/callAgent/x/y"), "callAgent/x/y");
646 assert_eq!(request_path("messaging"), "messaging");
647 }
648
649 #[test]
650 fn a_message_notification_becomes_the_page_event() {
651 let body = json!({"resourceType": "NewMessage", "resource": {"messagetype": "RichText/Html", "id": "177",
652 "conversationLink": "https://emea.ng.msg.teams.microsoft.com/v1/users/ME/conversations/19%3Aabc%40thread.v2"}});
653 let payload = notification_payload("messaging", Some(&body), 5).unwrap();
654 assert_eq!(payload["eventKind"], "new_message");
655 assert_eq!(payload["conversationId"], "19:abc@thread.v2");
656 assert_eq!(payload["messageId"], "177");
657 assert!(matches!(decode_payload(&payload.to_string()), Ok(RealtimeEvent::Message(_))));
658 }
659
660 #[test]
661 fn typing_names_the_sender() {
662 let body = json!({"resourceType": "NewMessage", "resource": {"messagetype": "Control/Typing", "imdisplayname": "Ada",
663 "from": "https://x/v1/users/ME/contacts/8:orgid:0a1b2c3d-0000-0000-0000-000000000000", "conversationLink": "conversations/19:t@thread.v2"}});
664 let payload = notification_payload("messaging", Some(&body), 5).unwrap();
665 assert_eq!(payload["eventKind"], "typing");
666 assert_eq!(payload["typing"], "start");
667 assert_eq!(payload["senderId"], "0a1b2c3d-0000-0000-0000-000000000000");
668 assert_eq!(payload["senderName"], "Ada");
669 assert!(payload["messageId"].is_null());
670 }
671
672 #[test]
673 fn presence_keeps_entries_with_an_availability() {
674 let body = json!({"presence": [{"mri": "8:orgid:a", "presence": {"availability": "Available", "activity": "Available"}}, {"mri": "8:orgid:b"}]});
675 let payload = notification_payload("unifiedPresenceService", Some(&body), 5).unwrap();
676 assert_eq!(payload["entries"].as_array().unwrap().len(), 1);
677 assert!(notification_payload("unifiedPresenceService", Some(&json!({"presence": []})), 5).is_none());
678 }
679}
crates/chatsvc/tests/realtime.rs +1 −0
@@ -83,6 +83,7 @@ async fn serve(mut stream: TcpStream, port: u16, calls: Calls) {
83 83 fn quiet_config() -> RealtimeConfig {
84 84 RealtimeConfig {
85 85 ensure_interval: Duration::from_secs(3600),
86 native: false,
86 87 ..RealtimeConfig::default()
87 88 }
88 89 }
@@ -83,6 +83,7 @@ async fn serve(mut stream: TcpStream, port: u16, calls: Calls) {
83fn quiet_config() -> RealtimeConfig {
83fn quiet_config() -> RealtimeConfig {
84 RealtimeConfig {
84 RealtimeConfig {
85 ensure_interval: Duration::from_secs(3600),
85 ensure_interval: Duration::from_secs(3600),
86 native: false,
86 ..RealtimeConfig::default()
87 ..RealtimeConfig::default()
87 }
88 }
88}
89}