Skip to main content

teams_cli/
desktop.rs

1//! Existing-endpoint diagnostics, chat reading through the Teams client's own cache, and
2//! sending plain-text chat messages through the Teams window's own client. The WSL TUI
3//! can restart Teams with explicit confirmation; evaluates only the fixed scripts in `desktop.js` and `desktop_send.js`.
4//!
5//! On Windows the CLI verifies the endpoint and reads in-process. Under WSL it drives the
6//! Windows build of itself as a long-lived helper (`teams.exe desktop-helper`).
7#[cfg(any(target_os = "macos", target_os = "linux", windows, test))]
8mod avatars;
9#[cfg(any(target_os = "macos", target_os = "linux", windows, test))]
10mod cdp;
11pub mod connection;
12pub mod helper;
13#[cfg(not(windows))]
14pub mod install;
15#[cfg(any(target_os = "macos", test))]
16mod macos;
17#[cfg(any(windows, test))]
18mod owner;
19#[cfg(any(target_os = "macos", target_os = "linux", windows, test))]
20pub mod session;
21#[cfg(windows)]
22pub mod windows;
23
24use crate::config::{DesktopAccount, DesktopClientKind, Profile};
25#[cfg(any(target_os = "macos", target_os = "linux"))]
26pub mod browser;
27#[cfg(any(target_os = "macos", target_os = "linux"))]
28mod browser_core;
29#[cfg(any(target_os = "macos", target_os = "linux"))]
30mod browser_install;
31#[cfg(any(target_os = "macos", target_os = "linux"))]
32pub mod browser_setup;
33use crate::{error::AppError, graph::Page};
34use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
35use serde::{Deserialize, Serialize};
36use serde_json::{Value, json};
37#[cfg(any(target_os = "macos", target_os = "linux", windows, test))]
38use std::time::Duration;
39#[cfg(any(target_os = "macos", target_os = "linux", windows, test))]
40const MAX_METADATA: usize = 1024 * 1024;
41const MAX_READ: usize = 8 * 1024 * 1024;
42/// Teams' own limit for one chat message.
43pub const MAX_BODY: usize = 28_000;
44
45/// A read-only startup check owned by the inbox; dropping it cancels the task.
46pub struct ConnectionWatch {
47    pub(crate) receiver: std::sync::mpsc::Receiver<Result<(), AppError>>,
48    pub(crate) task: tokio::task::JoinHandle<()>,
49}
50
51impl ConnectionWatch {
52    pub(crate) fn result(&self) -> Option<Result<(), AppError>> {
53        match self.receiver.try_recv() {
54            Ok(result) => Some(result),
55            Err(std::sync::mpsc::TryRecvError::Empty) => None,
56            Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(Err(AppError::Desktop(
57                "The Teams startup check stopped unexpectedly. Reopen the inbox to retry; your browser and sign-in were preserved.".into(),
58            ))),
59        }
60    }
61}
62
63impl Drop for ConnectionWatch {
64    fn drop(&mut self) {
65        self.task.abort();
66    }
67}
68
69pub fn messaging_unsupported() -> AppError {
70    AppError::Unsupported("the experimental desktop backend reads chats and chat messages and sends plain-text chat messages only (macOS/Windows/WSL); teams, channels and identity need a Graph profile".into())
71}
72
73fn account_selection_error() -> AppError {
74    AppError::Desktop("Both personal and work/school Teams are open; use `init --backend desktop --desktop-account personal` or `--desktop-account work-school` to select one".into())
75}
76
77fn cached_accounts_error() -> AppError {
78    AppError::Desktop("Teams holds cached data for more than one account, organization or display language, and Teams does not record which one is signed in. For a work/school account, Microsoft Graph works instead: `teams init --backend graph`".into())
79}
80
81#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
82#[serde(rename_all = "snake_case")]
83pub enum ProbeStatus {
84    NoListener,
85    UnsafeListenerRefused,
86    NonTeamsListenerRefused,
87    MetadataProbeFailed,
88    MetadataOk,
89}
90
91impl ProbeStatus {
92    pub fn detail(self) -> &'static str {
93        match self {
94            Self::NoListener => {
95                "No endpoint on this port: Teams is not running with its debugging port open. `teams desktop connect` opens it by restarting Teams after confirmation (it ends any call in progress)."
96            }
97            Self::UnsafeListenerRefused => "Refused a listener bound beyond loopback.",
98            Self::NonTeamsListenerRefused => {
99                "Refused a listener not owned by this user's installed Teams application."
100            }
101            Self::MetadataProbeFailed => {
102                "Desktop metadata could not be verified; no session access was attempted."
103            }
104            Self::MetadataOk => {
105                "Teams connection metadata is available. Sign-in and chat access remain unverified."
106            }
107        }
108    }
109}
110
111#[derive(Debug, Serialize, Deserialize)]
112pub struct BrowserVersion {
113    pub browser: String,
114    pub protocol: String,
115}
116
117#[derive(Debug, Serialize, Deserialize)]
118pub struct TargetMetadata {
119    #[serde(rename = "type")]
120    pub kind: String,
121    pub url_scheme: String,
122    pub url_origin: String,
123    pub teams_origin: bool,
124    pub websocket_advertised: bool,
125}
126
127#[derive(Debug, Serialize, Deserialize)]
128pub struct ConnectionMetadata {
129    pub port: u16,
130    pub status: ProbeStatus,
131    pub loopback_only: Option<bool>,
132    pub teams_owned: Option<bool>,
133    pub version: Option<BrowserVersion>,
134    pub browser_websocket_advertised: bool,
135    pub targets: Vec<TargetMetadata>,
136    /// Executable names of the applications hosting refused listeners.
137    #[serde(default, skip_serializing_if = "Vec::is_empty")]
138    pub foreign_listeners: Vec<String>,
139    /// The user-wide WebView2 arguments open a debugging port in every WebView2 app.
140    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
141    pub user_debugging_flags: bool,
142}
143
144impl ConnectionMetadata {
145    #[cfg(any(target_os = "macos", target_os = "linux", windows, test))]
146    fn empty(port: u16) -> Self {
147        Self {
148            port,
149            status: ProbeStatus::NoListener,
150            loopback_only: None,
151            teams_owned: None,
152            version: None,
153            browser_websocket_advertised: false,
154            targets: vec![],
155            foreign_listeners: vec![],
156            user_debugging_flags: false,
157        }
158    }
159    pub fn endpoint_available(&self) -> bool {
160        self.status == ProbeStatus::MetadataOk
161            && self.loopback_only == Some(true)
162            && self.teams_owned == Some(true)
163    }
164
165    /// The verified browser shows web pages but no Teams page: Teams was sent to sign-in.
166    #[cfg(any(target_os = "macos", target_os = "linux", test))]
167    pub fn signed_out(&self) -> bool {
168        let pages: Vec<_> = self.targets.iter().filter(|t| t.kind == "page").collect();
169        self.endpoint_available()
170            && pages.iter().any(|t| t.url_scheme == "https")
171            && !pages.iter().any(|t| t.teams_origin)
172    }
173
174    /// The status explanation plus what is known about a refused listener.
175    pub fn detail(&self) -> String {
176        let mut detail = self.status.detail().to_string();
177        if self.status != ProbeStatus::NonTeamsListenerRefused {
178            return detail;
179        }
180        if !self.foreign_listeners.is_empty() {
181            detail.push_str(&format!(
182                " Port {} is also served by {}.",
183                self.port,
184                self.foreign_listeners.join(", ")
185            ));
186        }
187        if self.user_debugging_flags {
188            detail.push_str(" A user-wide WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS setting opens a debugging port in every WebView2 application. Run `teams desktop clear-flags` to remove only its debugging flags, then fully quit and reopen those applications.");
189        }
190        detail
191    }
192
193    /// Applications to quit and reopen after the user-wide flags are cleared.
194    pub fn stray_debugging_flags(&self) -> Option<&[String]> {
195        (self.status == ProbeStatus::NonTeamsListenerRefused && self.user_debugging_flags)
196            .then_some(self.foreign_listeners.as_slice())
197    }
198}
199
200pub struct DesktopClient {
201    port: u16,
202    account: DesktopAccount,
203    kind: DesktopClientKind,
204    #[cfg(any(target_os = "macos", target_os = "linux"))]
205    browser: tokio::sync::Mutex<session::Session<browser::BrowserSystem>>,
206    /// The verified page connection, reused across reads.
207    #[cfg(windows)]
208    session: tokio::sync::Mutex<session::Session<windows::WindowsSystem>>,
209    #[cfg(target_os = "macos")]
210    session: tokio::sync::Mutex<session::Session<macos::MacSystem>>,
211    /// The Windows helper under WSL, started on first use.
212    #[cfg(not(any(windows, target_os = "macos")))]
213    helper: tokio::sync::Mutex<helper::HelperClient>,
214}
215
216impl std::fmt::Debug for DesktopClient {
217    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218        f.debug_struct("DesktopClient")
219            .field("port", &self.port)
220            .field("account", &self.account)
221            .finish_non_exhaustive()
222    }
223}
224
225impl DesktopClient {
226    pub fn new(port: u16) -> Result<Self, AppError> {
227        Self::with_account(port, DesktopAccount::Auto)
228    }
229
230    pub fn with_account(port: u16, account: DesktopAccount) -> Result<Self, AppError> {
231        if port < 1024 {
232            return Err(AppError::InvalidInput(
233                "desktop port must be between 1024 and 65535".into(),
234            ));
235        }
236        Ok(Self {
237            port,
238            account,
239            kind: DesktopClientKind::Native,
240            #[cfg(any(target_os = "macos", target_os = "linux"))]
241            browser: tokio::sync::Mutex::new(session::Session::new(browser::BrowserSystem {
242                core: false,
243            })),
244            #[cfg(windows)]
245            session: tokio::sync::Mutex::new(session::Session::new(windows::WindowsSystem)),
246            #[cfg(target_os = "macos")]
247            session: tokio::sync::Mutex::new(session::Session::new(macos::MacSystem)),
248            #[cfg(not(any(windows, target_os = "macos")))]
249            helper: Default::default(),
250        })
251    }
252
253    pub fn from_profile(profile: &Profile) -> Result<Self, AppError> {
254        Self::with_client(
255            profile.desktop_port,
256            profile.desktop_account,
257            profile.desktop_client,
258        )
259    }
260
261    pub fn with_client(
262        port: u16,
263        account: DesktopAccount,
264        kind: DesktopClientKind,
265    ) -> Result<Self, AppError> {
266        kind.validate_account(account)?;
267        let mut client = Self::with_account(port, account)?;
268        if kind.is_browser() && !cfg!(any(target_os = "macos", target_os = "linux")) {
269            return Err(AppError::Unsupported(
270                "the browser desktop client currently requires macOS or Linux (including WSL2)"
271                    .into(),
272            ));
273        }
274        #[cfg(any(target_os = "macos", target_os = "linux"))]
275        if kind == DesktopClientKind::BrowserCore {
276            client.browser =
277                tokio::sync::Mutex::new(session::Session::new(browser::BrowserSystem {
278                    core: true,
279                }));
280        }
281        client.kind = kind;
282        Ok(client)
283    }
284
285    #[cfg(any(target_os = "macos", target_os = "linux"))]
286    async fn browser_lease(&self) -> Result<bool, AppError> {
287        self.prerequisites().map_err(|error| {
288            AppError::Desktop(format!(
289                "Browser prerequisites are not ready; no session access was attempted: {error}"
290            ))
291        })?;
292        let port = self.port;
293        tokio::task::spawn_blocking(move || browser::lifetime::attach(port))
294            .await
295            .map_err(|_| {
296                AppError::Desktop("browser lease could not be established: worker stopped".into())
297            })?
298            .map_err(|error| {
299                AppError::Desktop(format!("browser lease could not be established: {error}"))
300            })
301    }
302
303    #[cfg(any(target_os = "macos", target_os = "linux"))]
304    async fn require_browser_lease(&self) -> Result<(), AppError> {
305        if self.browser_lease().await? {
306            Ok(())
307        } else {
308            Err(AppError::Desktop(format!(
309                "No endpoint on this port: connect the browser on port {} before retrying",
310                self.port
311            )))
312        }
313    }
314
315    pub fn debugging_setup(&self) -> Option<DebuggingSetup> {
316        if self.kind.is_browser() {
317            let mut setup = DebuggingSetup::for_shell("bash", self.port);
318            setup.open = format!(
319                "teams desktop login --desktop-client {} --port {}",
320                self.kind.as_str(),
321                self.port
322            );
323            setup.close = format!(
324                "teams desktop disconnect --desktop-client {} --port {}",
325                self.kind.as_str(),
326                self.port
327            );
328            Some(setup)
329        } else {
330            DebuggingSetup::new(self.port)
331        }
332    }
333
334    pub fn prerequisites(&self) -> Result<&'static str, AppError> {
335        #[cfg(any(target_os = "macos", target_os = "linux"))]
336        if self.kind.is_browser() {
337            browser::prerequisites_for(self.kind == DesktopClientKind::BrowserCore)?;
338            return Ok("browser_loopback");
339        }
340        local_prerequisites()
341    }
342
343    /// Only offered by the TUI after a verified no-listener probe on WSL.
344    pub async fn needs_debugging_restart(&self) -> bool {
345        self.kind == DesktopClientKind::Native
346            && platform().ok() == Some("wsl_windows_helper")
347            && self
348                .probe()
349                .await
350                .is_ok_and(|probe| probe.status == ProbeStatus::NoListener)
351    }
352
353    /// Applications serving the port because of user-wide debugging flags, offered
354    /// for cleanup by the TUI after a failed read.
355    pub async fn stray_debugging_flags(&self) -> Option<Vec<String>> {
356        if self.kind != DesktopClientKind::Native {
357            return None;
358        }
359        let probe = self.probe().await.ok()?;
360        probe.stray_debugging_flags().map(<[String]>::to_vec)
361    }
362
363    /// Called only after the person confirms the cleanup in the TUI.
364    pub async fn clear_debugging_flags(&self) -> Result<(), AppError> {
365        connection::clear_flags(self).await.map(|_| ())
366    }
367
368    /// Called only after the person confirms the restart in the TUI.
369    pub async fn restart_with_debugging(&self) -> Result<(), AppError> {
370        if !self.needs_debugging_restart().await {
371            return Err(AppError::Desktop(
372                "Connection changed; press r to retry before restarting Teams".into(),
373            ));
374        }
375        connection::manage(self, connection::Action::Connect)
376            .await
377            .map(|_| ())
378    }
379
380    pub async fn probe(&self) -> Result<ConnectionMetadata, AppError> {
381        #[cfg(any(target_os = "macos", target_os = "linux"))]
382        if self.kind.is_browser() {
383            self.browser_lease().await?;
384            return self.browser.lock().await.probe(self.port).await;
385        }
386        platform()?;
387        #[cfg(any(windows, target_os = "macos"))]
388        return self.session.lock().await.probe(self.port).await;
389        #[cfg(not(any(windows, target_os = "macos")))]
390        {
391            let metadata = self
392                .helper
393                .lock()
394                .await
395                .call(json!({"op": "probe", "port": self.port}))
396                .await?;
397            serde_json::from_value(metadata)
398                .map_err(|_| AppError::Desktop("Windows helper returned invalid metadata".into()))
399        }
400    }
401
402    /// Install the lightweight browser pair without launching or changing sign-in.
403    pub async fn prepare_browser(&self, quiet: bool) -> Result<(), AppError> {
404        #[cfg(any(target_os = "macos", target_os = "linux"))]
405        if self.kind == DesktopClientKind::BrowserCore {
406            browser_install::ensure_with_progress(quiet).await?;
407        }
408        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
409        let _ = quiet;
410        Ok(())
411    }
412
413    /// Authenticate visibly, then verify the same dedicated profile headless.
414    pub async fn login(&self) -> Result<Value, AppError> {
415        self.login_with_progress(false).await
416    }
417
418    pub async fn login_with_progress(&self, quiet: bool) -> Result<Value, AppError> {
419        self.login_with_recovery(quiet, true).await
420    }
421
422    /// Guided setup supplies its own profile-aware recovery instructions.
423    pub async fn login_for_setup(&self, quiet: bool) -> Result<Value, AppError> {
424        self.login_with_recovery(quiet, false).await
425    }
426
427    async fn login_with_recovery(&self, quiet: bool, recovery: bool) -> Result<Value, AppError> {
428        if !self.kind.is_browser() {
429            return Err(AppError::InvalidInput(
430                "desktop login requires --desktop-client browser".into(),
431            ));
432        }
433        #[cfg(any(target_os = "macos", target_os = "linux"))]
434        return browser::login_with_recovery(
435            self.port,
436            self.account,
437            self.kind == DesktopClientKind::BrowserCore,
438            quiet,
439            recovery,
440        )
441        .await;
442        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
443        let _ = (quiet, recovery);
444        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
445        Err(AppError::Unsupported(
446            "browser login requires macOS or Linux (including WSL2)".into(),
447        ))
448    }
449
450    pub async fn chats(&self, limit: u16, cursor: Option<&str>) -> Result<Page, AppError> {
451        self.read(None, limit, cursor).await
452    }
453
454    pub async fn search_people(&self, query: &str, limit: u16) -> Result<Page, AppError> {
455        crate::graph::validate_people_query(query, usize::from(limit))?;
456        let value = self
457            .people(json!({"op":"search","query":query.trim(),"limit":limit}))
458            .await?;
459        let items = value["items"]
460            .as_array()
461            .ok_or_else(|| AppError::Desktop("Invalid recipient-search response".into()))?
462            .clone();
463        Ok(Page {
464            items,
465            next_cursor: None,
466            next_offset: None,
467            truncated: value["truncated"] == true,
468            source: Some("desktop_people"),
469            viewer: None,
470        })
471    }
472
473    pub async fn create_chat(&self, recipient: &str) -> Result<Value, AppError> {
474        check_recipient(recipient)?;
475        let value = self
476            .people(json!({"op":"create","recipient":recipient}))
477            .await?;
478        if !value["id"].as_str().is_some_and(chat_id) {
479            return Err(AppError::Unconfirmed("Teams may have created the conversation; check Teams before trying again. No message was sent".into()));
480        }
481        Ok(value)
482    }
483
484    async fn people(&self, mut request: Value) -> Result<Value, AppError> {
485        let create = request["op"] == "create";
486        request["port"] = json!(self.port);
487        request["account_type"] = json!(self.account);
488        #[cfg(any(target_os = "macos", target_os = "linux"))]
489        if self.kind.is_browser() {
490            self.require_browser_lease().await?;
491            return people_result(&self.browser.lock().await.people(&request).await?, create);
492        }
493        platform()?;
494        #[cfg(any(windows, target_os = "macos"))]
495        let reply = self.session.lock().await.people(&request).await?;
496        #[cfg(not(any(windows, target_os = "macos")))]
497        let reply = {
498            let mut helper = self.helper.lock().await;
499            let op = json!({"op":"people","request":request});
500            if create {
501                helper.call_once(op).await?
502            } else {
503                helper.call(op).await?
504            }
505        };
506        people_result(&reply, create)
507    }
508
509    pub async fn messages(
510        &self,
511        chat: &str,
512        limit: u16,
513        cursor: Option<&str>,
514    ) -> Result<Page, AppError> {
515        self.read(Some(chat), limit, cursor).await
516    }
517
518    async fn read(
519        &self,
520        chat: Option<&str>,
521        limit: u16,
522        cursor: Option<&str>,
523    ) -> Result<Page, AppError> {
524        let mut request = read_request(self.port, chat, limit, cursor)?;
525        request["account_type"] = json!(self.account);
526        #[cfg(any(target_os = "macos", target_os = "linux"))]
527        if self.kind.is_browser() {
528            self.require_browser_lease().await?;
529            let mut browser = self.browser.lock().await;
530            return match read_page(&browser.read(&request).await?) {
531                Ok(page) => Ok(page),
532                Err(error) => {
533                    let hint = format!(
534                        "Sign in again: `teams desktop login --desktop-client {} --port {}`.",
535                        self.kind.as_str(),
536                        self.port
537                    );
538                    let signed_out = browser
539                        .probe(self.port)
540                        .await
541                        .is_ok_and(|metadata| metadata.signed_out());
542                    Err(if signed_out {
543                        AppError::Desktop(format!(
544                            "Teams in the dedicated browser was sent back to Microsoft sign-in. {hint}"
545                        ))
546                    } else {
547                        error.with_hint(&hint)
548                    })
549                }
550            };
551        }
552        platform()?;
553        #[cfg(any(windows, target_os = "macos"))]
554        let reply = self.session.lock().await.read(&request).await?;
555        #[cfg(not(any(windows, target_os = "macos")))]
556        let reply = self
557            .helper
558            .lock()
559            .await
560            .call(json!({"op": "read", "request": request}))
561            .await?;
562        read_page(&reply)
563    }
564
565    /// Sends one plain-text chat message as the signed-in Teams user. Never retried: a lost
566    /// answer is reported as unconfirmed, because Teams may already have the message.
567    pub async fn send(&self, chat: &str, body: &str) -> Result<Value, AppError> {
568        self.send_with_id(chat, body, &crate::delivery::client_message_id())
569            .await
570    }
571
572    /// Uses one preallocated correlation ID. This is not an idempotency/retry key.
573    pub async fn send_with_id(&self, chat: &str, body: &str, id: &str) -> Result<Value, AppError> {
574        let mut request = send_request(self.port, chat, body)?;
575        if !crate::delivery::valid_client_message_id(id) {
576            return Err(AppError::InvalidInput("invalid client message ID".into()));
577        }
578        request["client_message_id"] = json!(id);
579        request["account_type"] = json!(self.account);
580        #[cfg(any(target_os = "macos", target_os = "linux"))]
581        if self.kind.is_browser() {
582            self.require_browser_lease().await?;
583            let reply = self.browser.lock().await.send(&request).await?;
584            return self.send_result(&reply, chat, id);
585        }
586        platform()?;
587        #[cfg(any(windows, target_os = "macos"))]
588        let reply = self.session.lock().await.send(&request).await?;
589        #[cfg(not(any(windows, target_os = "macos")))]
590        let reply = self
591            .helper
592            .lock()
593            .await
594            .call_once(json!({"op": "send", "request": request}))
595            .await?;
596        self.send_result(&reply, chat, id)
597    }
598
599    fn send_result(&self, reply: &Value, chat: &str, id: &str) -> Result<Value, AppError> {
600        sent_message(reply, chat).map_err(|error| match error {
601            AppError::Unconfirmed(message) => AppError::UnconfirmedSend {
602                message,
603                chat_id: chat.into(),
604                client_message_id: id.into(),
605            },
606            other => other,
607        })
608    }
609
610    /// Checks only the newest 50 cached messages; absence is not proof of failure.
611    pub async fn delivery(&self, chat: &str, id: &str) -> Result<Value, AppError> {
612        check_chat(chat)?;
613        if !crate::delivery::valid_client_message_id(id) {
614            return Err(AppError::InvalidInput(
615                "client message ID must contain 18 digits".into(),
616            ));
617        }
618        let page = self.messages(chat, 50, None).await?;
619        Ok(crate::delivery::reconcile(chat, id, &page.items))
620    }
621
622    /// Whether the Teams window that sends messages is reachable; sends nothing.
623    pub async fn send_check(&self) -> Result<(), AppError> {
624        #[cfg(any(target_os = "macos", target_os = "linux"))]
625        if self.kind.is_browser() {
626            self.require_browser_lease().await?;
627            let reply = self
628                .browser
629                .lock()
630                .await
631                .send_check(self.port, self.account)
632                .await?;
633            return check_send_reply(&reply);
634        }
635        platform()?;
636        #[cfg(any(windows, target_os = "macos"))]
637        let reply = self
638            .session
639            .lock()
640            .await
641            .send_check(self.port, self.account)
642            .await?;
643        #[cfg(not(any(windows, target_os = "macos")))]
644        let reply = self
645            .helper
646            .lock()
647            .await
648            .call(json!({"op": "send_check", "port": self.port, "account_type": self.account}))
649            .await?;
650        check_send_reply(&reply)
651    }
652}
653
654pub fn check_recipient(id: &str) -> Result<(), AppError> {
655    if id.starts_with("8:") && valid_id(id) && id.len() > 2 {
656        Ok(())
657    } else {
658        Err(AppError::InvalidInput("Select an exact recipient ID from `teams people search`; desktop recipient IDs start with 8:".into()))
659    }
660}
661
662fn people_result(reply: &Value, create: bool) -> Result<Value, AppError> {
663    let invalid = || {
664        if create {
665            AppError::Unconfirmed("Teams may have created the conversation; check Teams before trying again. No message was sent".into())
666        } else {
667            AppError::Desktop(
668                "Recipient search failed. Check the Teams connection and try again".into(),
669            )
670        }
671    };
672    let value = if reply["error"].is_string() {
673        reply.clone()
674    } else {
675        reply["result"]["result"]["value"]
676            .as_str()
677            .and_then(|s| serde_json::from_str::<Value>(s).ok())
678            .ok_or_else(invalid)?
679    };
680    if let Some(code) = value["error"].as_str() {
681        return Err(match code {
682            "account_ambiguous" => account_selection_error(),
683            "cache_ambiguous" => cached_accounts_error(),
684            "permission_denied" => AppError::Permission("Teams policy does not allow a chat with this recipient".into()),
685            "search_failed" => AppError::Desktop("Teams could not resolve this person. Check sign-in and try their full email address".into()),
686            "layout" => AppError::Unsupported("This Teams version does not expose a supported recipient interface".into()),
687            "unconfirmed" => invalid(),
688            _ => send_error(code),
689        });
690    }
691    Ok(value)
692}
693
694fn check_send_reply(reply: &Value) -> Result<(), AppError> {
695    refused(reply)?;
696    match reply["error"].as_str() {
697        None if reply["ok"] == true => Ok(()),
698        code => Err(send_error(code.unwrap_or_default())),
699    }
700}
701
702fn valid_id(id: &str) -> bool {
703    (1..=256).contains(&id.len())
704        && id
705            .bytes()
706            .all(|b| b.is_ascii_alphanumeric() || b"_.:@-".contains(&b))
707}
708
709fn read_request(
710    port: u16,
711    chat: Option<&str>,
712    limit: u16,
713    cursor: Option<&str>,
714) -> Result<Value, AppError> {
715    if let Some(chat) = chat {
716        check_chat(chat)?;
717    }
718    let after = cursor.map(decode_cursor).transpose()?;
719    Ok(json!({
720        "operation": "read",
721        "port": port,
722        "query": if chat.is_some() { "messages" } else { "chats" },
723        "chat_id": chat,
724        "limit": limit,
725        "after": after,
726    }))
727}
728
729/// A chat id as `teams chats` lists them; `48:notes` is the chat with yourself.
730fn chat_id(id: &str) -> bool {
731    id == NOTES || id.starts_with("19:") && valid_id(id)
732}
733
734const NOTES: &str = "48:notes";
735
736/// Refuses anything but a chat id as `teams chats` lists them.
737pub fn check_chat(chat: &str) -> Result<(), AppError> {
738    if chat_id(chat) {
739        Ok(())
740    } else {
741        Err(AppError::InvalidInput(
742            "desktop chat ids look like `19:...@thread.v2`, `19:...@unq.gbl.spaces` or `48:notes`"
743                .into(),
744        ))
745    }
746}
747
748/// Plain text Teams accepts as one message.
749fn valid_body(body: &str) -> bool {
750    !body.trim().is_empty() && body.chars().count() <= MAX_BODY && !body.contains('\0')
751}
752
753/// A send request with a fresh client message id, which Teams uses to recognise the message.
754fn send_request(port: u16, chat: &str, body: &str) -> Result<Value, AppError> {
755    check_chat(chat)?;
756    if !valid_body(body) {
757        return Err(AppError::InvalidInput(format!(
758            "message body must be non-empty plain text of at most {MAX_BODY} characters"
759        )));
760    }
761    let id: u64 = rand::Rng::random_range(
762        &mut rand::rng(),
763        100_000_000_000_000_000..1_000_000_000_000_000_000,
764    );
765    Ok(json!({
766        "operation": "send",
767        "port": port,
768        "chat_id": chat,
769        "body": body,
770        "client_message_id": id.to_string(),
771    }))
772}
773
774/// A listener refusal that carries its diagnosis explains itself in full.
775fn refused(reply: &Value) -> Result<(), AppError> {
776    match reply
777        .get("connection")
778        .cloned()
779        .map(serde_json::from_value::<ConnectionMetadata>)
780    {
781        Some(Ok(metadata)) if reply.get("error").is_some() => {
782            Err(AppError::Desktop(metadata.detail()))
783        }
784        _ => Ok(()),
785    }
786}
787
788fn send_error(code: &str) -> AppError {
789    match code {
790        "not_found" => AppError::NotFound("chat not found in the Teams desktop cache".into()),
791        "account_ambiguous" => account_selection_error(),
792        "cache_ambiguous" => cached_accounts_error(),
793        "unconfirmed" => AppError::Unconfirmed(
794            "Teams did not confirm the message; it may still be delivered. Check the chat before sending again".into(),
795        ),
796        "layout" => AppError::Desktop(
797            "The Teams window's send interface was not recognised; this Teams version is not supported for sending yet".into(),
798        ),
799        "no_target" => AppError::Desktop(
800            "No Teams window is available on the debugging endpoint; open Teams and sign in.".into(),
801        ),
802        code => match serde_json::from_value::<ProbeStatus>(json!(code)) {
803            Ok(status) => AppError::Desktop(status.detail().into()),
804            Err(_) => AppError::Desktop(
805                "The message was not sent; the Teams page could not be reached. Run `teams doctor`".into(),
806            ),
807        },
808    }
809}
810
811/// Maps a send reply to the Graph send shape, plus Teams' own status label.
812fn sent_message(reply: &Value, chat: &str) -> Result<Value, AppError> {
813    refused(reply)?;
814    if let Some(code) = reply.get("error").and_then(Value::as_str) {
815        return Err(send_error(code));
816    }
817    let result = &reply["result"];
818    if let Some(details) = result.get("exceptionDetails") {
819        // The script reports every failure after handing the message to Teams itself, so an
820        // exception means nothing was sent.
821        let layout = details["exception"]["description"]
822            .as_str()
823            .is_some_and(|d| d.starts_with("Error: layout"));
824        return Err(send_error(if layout { "layout" } else { "" }));
825    }
826    let value: Value = result["result"]["value"]
827        .as_str()
828        .and_then(|v| serde_json::from_str(v).ok())
829        .ok_or_else(|| send_error("unconfirmed"))?;
830    if let Some(code) = value["error"].as_str() {
831        return Err(send_error(code));
832    }
833    let id = value["id"]
834        .as_str()
835        .filter(|id| valid_id(id))
836        .ok_or_else(|| send_error("unconfirmed"))?;
837    let label = |key: &str| {
838        value[key]
839            .as_str()
840            .filter(|v| v.len() <= 64 && valid_id(v))
841            .map(String::from)
842    };
843    let arrival = &value["originalArrivalTime"];
844    let created = arrival
845        .as_i64()
846        .or_else(|| arrival.as_str().and_then(|t| t.parse().ok()))
847        .and_then(|ms| jiff::Timestamp::from_millisecond(ms).ok())
848        .or_else(|| arrival.as_str().and_then(|t| t.parse().ok()))
849        .map(|t| t.to_string());
850    let mut message = json!({
851        "id": id,
852        "chatId": chat,
853        "createdDateTime": created,
854        "webUrl": null,
855        "clientMessageId": label("clientMessageId"),
856        "status": label("status"),
857        "source": "desktop",
858    });
859    message["delivery_state"] = json!(crate::delivery::State::from_message(&message));
860    Ok(message)
861}
862
863/// Cursors are opaque to callers: base64 of the last item's sort key.
864fn encode_cursor(next: &Value) -> Result<String, AppError> {
865    let t = next.get("t").and_then(Value::as_i64);
866    let id = next.get("id").and_then(Value::as_str);
867    match (t, id) {
868        (Some(t), Some(id)) if valid_id(id) => {
869            Ok(URL_SAFE_NO_PAD.encode(json!({"t":t,"id":id}).to_string()))
870        }
871        _ => Err(AppError::Desktop(
872            "Teams cache returned an invalid page position".into(),
873        )),
874    }
875}
876
877fn decode_cursor(cursor: &str) -> Result<Value, AppError> {
878    let invalid = || AppError::InvalidInput("invalid desktop cursor".into());
879    let bytes = URL_SAFE_NO_PAD
880        .decode(cursor.as_bytes())
881        .map_err(|_| invalid())?;
882    let value: Value = serde_json::from_slice(&bytes).map_err(|_| invalid())?;
883    let t = value.get("t").and_then(Value::as_i64).ok_or_else(invalid)?;
884    let id = value
885        .get("id")
886        .and_then(Value::as_str)
887        .ok_or_else(invalid)?;
888    if t < 0 || !valid_id(id) {
889        return Err(invalid());
890    }
891    Ok(json!({"t":t,"id":id}))
892}
893
894/// Maps a session reply: a refusal code, or the raw `Runtime.evaluate` result.
895fn read_page(reply: &Value) -> Result<Page, AppError> {
896    let invalid = || AppError::Desktop("the Teams page returned an invalid chat response".into());
897    refused(reply)?;
898    if let Some(code) = reply.get("error").and_then(Value::as_str) {
899        let status = serde_json::from_value::<ProbeStatus>(json!(code)).ok();
900        if code == "account_ambiguous" {
901            return Err(account_selection_error());
902        }
903        if code == "cache_ambiguous" {
904            return Err(cached_accounts_error());
905        }
906        return Err(AppError::Desktop(match (status, code) {
907            (Some(status), _) => status.detail().into(),
908            (None, "no_target") => {
909                "No Teams window is available on the debugging endpoint; open Teams and sign in."
910                    .into()
911            }
912            _ => "The Teams page could not be read over the debugging endpoint; run `teams doctor`"
913                .into(),
914        }));
915    }
916    let result = &reply["result"];
917    if let Some(details) = result.get("exceptionDetails") {
918        let layout = details["exception"]["description"]
919            .as_str()
920            .is_some_and(|d| d.starts_with("Error: layout"));
921        return Err(AppError::Desktop(if layout {
922            "The Teams cache layout was not recognised; this Teams version is not supported yet"
923                .into()
924        } else {
925            "The Teams page could not read its local cache; run `teams doctor`".into()
926        }));
927    }
928    let value: Value = result["result"]["value"]
929        .as_str()
930        .and_then(|v| serde_json::from_str(v).ok())
931        .ok_or_else(invalid)?;
932    if value["error"] == "not_found" {
933        return Err(AppError::NotFound(
934            "chat not found in the Teams desktop cache".into(),
935        ));
936    }
937    if value["error"] == "account_ambiguous" {
938        return Err(account_selection_error());
939    }
940    if value["error"] == "cache_ambiguous" {
941        return Err(cached_accounts_error());
942    }
943    let items = value["items"].as_array().ok_or_else(invalid)?.clone();
944    let next_cursor = match &value["next"] {
945        Value::Null => None,
946        next => Some(encode_cursor(next)?),
947    };
948    Ok(Page {
949        items,
950        truncated: next_cursor.is_some(),
951        next_cursor,
952        next_offset: None,
953        source: Some("desktop_cache"),
954        viewer: value["me"]
955            .as_str()
956            .filter(|me| valid_id(me))
957            .map(String::from),
958    })
959}
960
961pub fn platform() -> Result<&'static str, AppError> {
962    if cfg!(target_os = "macos") {
963        Ok("macos_loopback")
964    } else if cfg!(windows) {
965        Ok("windows_native")
966    } else if cfg!(target_os = "linux")
967        && std::fs::read_to_string("/proc/sys/kernel/osrelease")
968            .unwrap_or_default()
969            .to_ascii_lowercase()
970            .contains("microsoft")
971    {
972        Ok("wsl_windows_helper")
973    } else {
974        Err(AppError::Unsupported(
975            "desktop diagnostics require macOS, Windows, or WSL with Windows executable interop"
976                .into(),
977        ))
978    }
979}
980
981/// Commands for manual setup and the confirmed WSL TUI restart. macOS uses
982/// process-only environment; Windows/WSL set the flags only for the Teams launch.
983#[derive(Debug, Serialize)]
984pub struct DebuggingSetup {
985    /// `zsh` on macOS, `wsl` for a WSL shell, `powershell` on Windows.
986    pub shell: &'static str,
987    pub open: String,
988    pub close: String,
989}
990
991impl DebuggingSetup {
992    pub fn new(port: u16) -> Option<Self> {
993        let shell = match platform().ok()? {
994            "wsl_windows_helper" => "wsl",
995            "windows_native" => "powershell",
996            "macos_loopback" => "zsh",
997            _ => return None,
998        };
999        Some(Self::for_shell(shell, port))
1000    }
1001
1002    fn for_shell(shell: &'static str, port: u16) -> Self {
1003        Self {
1004            shell,
1005            open: format!("teams desktop connect --port {port}"),
1006            close: format!("teams desktop disconnect --port {port}"),
1007        }
1008    }
1009
1010    pub fn text(&self) -> String {
1011        if self.shell == "bash" {
1012            return format!(
1013                "Sign in once, then continue with a hidden Teams browser:\n  {}\nThe window closes automatically after sign-in is verified. Close the hidden browser:\n  {}\nThe sign-in profile is retained. While its debugging port is open, local programs can read chats and send as you.",
1014                self.open, self.close
1015            );
1016        }
1017        let shell = match self.shell {
1018            "wsl" => "this WSL shell",
1019            "zsh" => "Terminal (zsh or bash)",
1020            _ => "PowerShell",
1021        };
1022        format!(
1023            "To open Teams' debugging port, run this in {shell}. It restarts Teams, which ends any call in progress:\n  {}\nTo close it again:\n  {}\nThe flags apply only to that Teams launch; other apps and your settings are unchanged. If setup is interrupted, run `teams desktop recover`. While the port is open, any program running as you can read your chats and send as you.",
1024            self.open, self.close
1025        )
1026    }
1027}
1028
1029/// The hidden `desktop-helper` command: answers the Linux CLI under WSL until stdin closes.
1030pub async fn serve_helper() -> Result<(), AppError> {
1031    #[cfg(windows)]
1032    {
1033        helper::serve(
1034            tokio::io::BufReader::new(tokio::io::stdin()),
1035            tokio::io::stdout(),
1036            &mut session::Session::new(windows::WindowsSystem),
1037        )
1038        .await
1039    }
1040    #[cfg(not(windows))]
1041    Err(AppError::Unsupported(
1042        "the desktop helper runs only on Windows".into(),
1043    ))
1044}
1045
1046/// The WSL helper's install state for `doctor` as (status, detail); `None` where no
1047/// helper is involved. Never downloads.
1048pub fn helper_check() -> Option<(&'static str, String)> {
1049    #[cfg(not(windows))]
1050    if platform().ok() == Some("wsl_windows_helper") {
1051        return Some(match install::state() {
1052            Ok(install::HelperState::Override(path)) if !path.is_file() => (
1053                "fail",
1054                format!(
1055                    "TEAMS_DESKTOP_HELPER points to {}, which does not exist",
1056                    path.display()
1057                ),
1058            ),
1059            Ok(state @ install::HelperState::Missing(_)) => ("skip", state.describe()),
1060            Ok(state) => ("pass", state.describe()),
1061            Err(error) => ("fail", error.to_string()),
1062        });
1063    }
1064    None
1065}
1066
1067pub fn local_prerequisites() -> Result<&'static str, AppError> {
1068    let transport = platform()?;
1069    if transport == "macos_loopback" {
1070        if !std::path::Path::new("/usr/sbin/lsof").is_file() {
1071            return Err(AppError::Desktop(
1072                "lsof is required for Teams listener ownership checks".into(),
1073            ));
1074        }
1075    } else if transport == "wsl_windows_helper"
1076        && !["WSLInterop", "WSLInterop-late"].iter().any(|name| {
1077            std::path::Path::new("/proc/sys/fs/binfmt_misc")
1078                .join(name)
1079                .exists()
1080        })
1081    {
1082        return Err(AppError::Desktop(
1083            "WSL cannot run Windows executables; enable interop in /etc/wsl.conf".into(),
1084        ));
1085    }
1086    Ok(transport)
1087}
1088
1089/// Reads endpoint metadata into `metadata` for an already-verified listener and returns
1090/// the raw targets, which stay in-process.
1091#[cfg(any(target_os = "macos", target_os = "linux", windows, test))]
1092async fn fill_metadata(metadata: &mut ConnectionMetadata) -> Vec<Value> {
1093    let Ok((version, targets)) = read_metadata(metadata.port).await else {
1094        metadata.status = ProbeStatus::MetadataProbeFailed;
1095        return vec![];
1096    };
1097    let text = |key: &str| {
1098        version
1099            .get(key)
1100            .and_then(Value::as_str)
1101            .unwrap_or_default()
1102            .to_string()
1103    };
1104    metadata.version = Some(BrowserVersion {
1105        browser: text("Browser"),
1106        protocol: text("Protocol-Version"),
1107    });
1108    metadata.browser_websocket_advertised = !text("webSocketDebuggerUrl").is_empty();
1109    metadata.targets = targets.iter().map(sanitize_target).collect();
1110    metadata.status = ProbeStatus::MetadataOk;
1111    targets
1112}
1113
1114#[cfg(any(target_os = "macos", target_os = "linux", windows, test))]
1115async fn read_metadata(port: u16) -> Result<(Value, Vec<Value>), AppError> {
1116    let http = reqwest::Client::builder()
1117        .no_proxy()
1118        .redirect(reqwest::redirect::Policy::none())
1119        .timeout(Duration::from_secs(5))
1120        .user_agent("TeamsCLI-DesktopProbe/0.1")
1121        .build()
1122        .map_err(|_| AppError::Desktop("could not create metadata reader".into()))?;
1123    async fn read(http: &reqwest::Client, port: u16, route: &str) -> Result<Value, AppError> {
1124        let mut response = http
1125            .get(format!("http://127.0.0.1:{port}{route}"))
1126            .send()
1127            .await
1128            .map_err(|_| AppError::Desktop("metadata endpoint is unavailable".into()))?;
1129        if response.status() != reqwest::StatusCode::OK {
1130            return Err(AppError::Desktop(
1131                "metadata endpoint returned an unexpected status".into(),
1132            ));
1133        }
1134        let mut bytes = Vec::new();
1135        while let Some(chunk) = response
1136            .chunk()
1137            .await
1138            .map_err(|_| AppError::Desktop("metadata response failed".into()))?
1139        {
1140            if bytes.len() + chunk.len() > MAX_METADATA {
1141                return Err(AppError::Desktop("metadata size limit exceeded".into()));
1142            }
1143            bytes.extend_from_slice(&chunk);
1144        }
1145        serde_json::from_slice(&bytes)
1146            .map_err(|_| AppError::Desktop("invalid endpoint metadata".into()))
1147    }
1148    let version = read(&http, port, "/json/version").await?;
1149    let targets = read(&http, port, "/json/list").await?;
1150    if !version.is_object() {
1151        return Err(AppError::Desktop("invalid browser metadata".into()));
1152    }
1153    Ok((
1154        version,
1155        targets
1156            .as_array()
1157            .ok_or_else(|| AppError::Desktop("invalid target list".into()))?
1158            .clone(),
1159    ))
1160}
1161
1162#[cfg(any(target_os = "macos", target_os = "linux", windows, test))]
1163fn sanitize_target(target: &Value) -> TargetMetadata {
1164    let uri = target
1165        .get("url")
1166        .and_then(Value::as_str)
1167        .and_then(|u| url::Url::parse(u).ok());
1168    let scheme = uri.as_ref().map(|u| u.scheme()).unwrap_or("");
1169    let host = uri.as_ref().and_then(|u| u.host_str()).unwrap_or("");
1170    let secure =
1171        scheme == "https" && uri.as_ref().and_then(|u| u.port_or_known_default()) == Some(443);
1172    let teams = secure
1173        && matches!(
1174            host,
1175            "teams.microsoft.com" | "teams.cloud.microsoft" | "teams.live.com"
1176        );
1177    let origin =
1178        if teams || (secure && matches!(host, "login.microsoftonline.com" | "login.live.com")) {
1179            format!("https://{host}")
1180        } else if matches!(scheme, "about" | "blob" | "file") {
1181            format!("{scheme}:")
1182        } else {
1183            "[other origin omitted]".into()
1184        };
1185    TargetMetadata {
1186        kind: target
1187            .get("type")
1188            .and_then(Value::as_str)
1189            .unwrap_or("other")
1190            .into(),
1191        url_scheme: scheme.into(),
1192        url_origin: origin,
1193        teams_origin: teams,
1194        websocket_advertised: target
1195            .get("webSocketDebuggerUrl")
1196            .and_then(Value::as_str)
1197            .is_some_and(|s| !s.is_empty()),
1198    }
1199}
1200
1201#[cfg(test)]
1202mod tests {
1203    use super::macos::{loopback_address, parse_listeners};
1204    use super::*;
1205    use wiremock::{
1206        Mock, MockServer, ResponseTemplate,
1207        matchers::{header, method, path},
1208    };
1209
1210    const CHAT: &str = "19:a@thread.v2";
1211
1212    fn page_reply(value: Value) -> Value {
1213        json!({"result": {"result": {"type": "string", "value": value.to_string()}}})
1214    }
1215
1216    #[test]
1217    fn debugging_setup_uses_managed_commands_on_every_shell() {
1218        for shell in ["wsl", "powershell", "zsh"] {
1219            let setup = DebuggingSetup::for_shell(shell, 9333);
1220            assert_eq!(setup.open, "teams desktop connect --port 9333");
1221            assert_eq!(setup.close, "teams desktop disconnect --port 9333");
1222            assert!(setup.text().contains("teams desktop recover"));
1223            assert!(setup.text().contains("any program running as you"));
1224        }
1225    }
1226
1227    /// Helpers and CLIs of different versions talk to each other whenever their protocol
1228    /// numbers match, so everything that crosses between them is pinned here: the
1229    /// requests the CLI builds and the page scripts whose results it parses. When this
1230    /// fails, bump `helper::PROTOCOL` if a helper or CLI of the old protocol would misread
1231    /// the new one; otherwise just update the expectations.
1232    #[test]
1233    fn the_protocol_is_pinned() {
1234        assert_eq!(helper::PROTOCOL, 5);
1235        let cursor = encode_cursor(&json!({"t": 1, "id": "m1"})).unwrap();
1236        assert_eq!(
1237            read_request(9222, Some(NOTES), 20, Some(&cursor)).unwrap(),
1238            json!({"operation": "read", "port": 9222, "query": "messages",
1239                   "chat_id": NOTES, "limit": 20, "after": {"t": 1, "id": "m1"}})
1240        );
1241        assert_eq!(
1242            read_request(9222, None, 20, None).unwrap(),
1243            json!({"operation": "read", "port": 9222, "query": "chats",
1244                   "chat_id": null, "limit": 20, "after": null})
1245        );
1246        let mut send = send_request(9222, NOTES, "hi").unwrap();
1247        assert!(
1248            send["client_message_id"]
1249                .as_str()
1250                .is_some_and(|id| id.len() == 18)
1251        );
1252        send["client_message_id"] = json!("<id>");
1253        assert_eq!(
1254            send,
1255            json!({"operation": "send", "port": 9222, "chat_id": NOTES,
1256                   "body": "hi", "client_message_id": "<id>"})
1257        );
1258        let scripts = [
1259            include_str!("desktop.js"),
1260            include_str!("desktop_send.js"),
1261            include_str!("desktop_cache.js"),
1262            include_str!("desktop_people.js"),
1263        ]
1264        .map(|script| {
1265            use sha2::Digest;
1266            // Line endings depend on the checkout, not on the script.
1267            let digest = sha2::Sha256::digest(script.replace('\r', ""));
1268            digest[..6]
1269                .iter()
1270                .map(|b| format!("{b:02x}"))
1271                .collect::<String>()
1272        });
1273        // Protocol 5 selects the signed-in cache and reports remaining ambiguity apart from surface selection.
1274        // Older same-account caches are optional; a helper without them reads as before.
1275        assert_eq!(
1276            scripts,
1277            [
1278                "9c000776f04a",
1279                "baa0bc29c44b",
1280                "7d2b70751d6a",
1281                "23b1a0e4b293"
1282            ]
1283        );
1284    }
1285
1286    #[test]
1287    fn recipient_scripts_keep_search_readonly_and_creation_once_only() {
1288        let output = std::process::Command::new("node")
1289            .args(["--test", "tests/js/people.test.mjs"])
1290            .current_dir(env!("CARGO_MANIFEST_DIR"))
1291            .output()
1292            .expect("Node.js 20 or newer is required for desktop script tests");
1293        assert!(
1294            output.status.success(),
1295            "{}",
1296            String::from_utf8_lossy(&output.stdout)
1297        );
1298    }
1299
1300    #[test]
1301    fn recipient_replies_preserve_uncertainty_and_account_errors() {
1302        assert!(matches!(
1303            people_result(&json!({"error":"unconfirmed"}), true),
1304            Err(AppError::Unconfirmed(_))
1305        ));
1306        assert!(matches!(
1307            people_result(&json!({"result":{}}), true),
1308            Err(AppError::Unconfirmed(_))
1309        ));
1310        assert!(matches!(
1311            people_result(&page_reply(json!({"error":"permission_denied"})), true),
1312            Err(AppError::Permission(_))
1313        ));
1314        assert!(matches!(
1315            people_result(&page_reply(json!({"error":"account_ambiguous"})), false),
1316            Err(AppError::Desktop(m)) if m.contains("--desktop-account")
1317        ));
1318        assert!(matches!(
1319            people_result(&page_reply(json!({"error":"cache_ambiguous"})), false),
1320            Err(AppError::Desktop(m)) if !m.contains("--desktop-account")
1321        ));
1322        for id in [
1323            "someone@example.invalid",
1324            "8:bad id",
1325            "8:",
1326            "8:bad/extra",
1327            "",
1328        ] {
1329            assert!(check_recipient(id).is_err());
1330        }
1331        assert!(check_recipient("8:live:.cid.012345").is_ok());
1332    }
1333
1334    #[test]
1335    fn send_requests_validate_and_carry_a_fresh_client_message_id() {
1336        let request = send_request(9222, CHAT, "hello\nthere").unwrap();
1337        assert_eq!(request["operation"], "send");
1338        assert_eq!(request["chat_id"], CHAT);
1339        assert_eq!(request["body"], "hello\nthere");
1340        let id = request["client_message_id"].as_str().unwrap();
1341        assert!(id.len() == 18 && id.bytes().all(|b| b.is_ascii_digit()));
1342        assert_ne!(
1343            send_request(9222, CHAT, "x").unwrap()["client_message_id"],
1344            request["client_message_id"]
1345        );
1346        for (chat, body) in [
1347            ("fixture", "hello"),
1348            ("19:a b@thread.v2", "hello"),
1349            ("48:notes2", "hello"),
1350            ("48:other", "hello"),
1351            (CHAT, ""),
1352            (CHAT, " \n\t"),
1353            (CHAT, "a\0b"),
1354            (CHAT, &"x".repeat(MAX_BODY + 1)),
1355        ] {
1356            assert!(
1357                matches!(
1358                    send_request(9222, chat, body),
1359                    Err(AppError::InvalidInput(_))
1360                ),
1361                "{chat:?} accepted"
1362            );
1363        }
1364        assert!(send_request(9222, CHAT, &"é".repeat(MAX_BODY)).is_ok());
1365        assert!(send_request(9222, NOTES, "hello").is_ok());
1366    }
1367
1368    #[test]
1369    fn sent_messages_map_to_the_graph_shape() {
1370        let reply = page_reply(
1371            json!({"id": "1760000000000", "clientMessageId": "123456789012345678",
1372            "originalArrivalTime": "1760000000000", "status": "Sent"}),
1373        );
1374        let message = sent_message(&reply, CHAT).unwrap();
1375        assert_eq!(message["id"], "1760000000000");
1376        assert_eq!(message["chatId"], CHAT);
1377        assert_eq!(message["createdDateTime"], "2025-10-09T08:53:20Z");
1378        assert_eq!(message["clientMessageId"], "123456789012345678");
1379        assert_eq!(message["status"], "Sent");
1380        assert_eq!(message["source"], "desktop");
1381        for arrival in [json!(1760000000000_i64), json!("2025-10-09T08:53:20Z")] {
1382            let reply = page_reply(json!({"id": "1", "originalArrivalTime": arrival}));
1383            assert_eq!(
1384                sent_message(&reply, CHAT).unwrap()["createdDateTime"],
1385                "2025-10-09T08:53:20Z"
1386            );
1387        }
1388        let reply = page_reply(json!({"id": "1", "status": "<b>not a label</b>"}));
1389        let message = sent_message(&reply, CHAT).unwrap();
1390        assert!(message["status"].is_null() && message["createdDateTime"].is_null());
1391    }
1392
1393    #[test]
1394    fn send_failures_say_whether_the_message_may_have_gone() {
1395        let unconfirmed = |error: AppError| error.to_string().contains("may still be delivered");
1396        for reply in [
1397            json!({"error": "unconfirmed"}),
1398            page_reply(json!({"error": "unconfirmed"})),
1399            page_reply(json!({"id": "bad id"})),
1400            page_reply(json!({})),
1401            json!({"result": {"result": {"type": "undefined"}}}),
1402        ] {
1403            assert!(
1404                unconfirmed(sent_message(&reply, CHAT).unwrap_err()),
1405                "{reply}"
1406            );
1407        }
1408        assert!(matches!(
1409            sent_message(&page_reply(json!({"error": "not_found"})), CHAT),
1410            Err(AppError::NotFound(_))
1411        ));
1412        let thrown =
1413            json!({"result": {"exceptionDetails": {"exception": {"description": "TypeError: x"}}}});
1414        let error = sent_message(&thrown, CHAT).unwrap_err();
1415        assert!(
1416            !unconfirmed(error)
1417                && sent_message(&thrown, CHAT)
1418                    .unwrap_err()
1419                    .to_string()
1420                    .contains("not sent")
1421        );
1422        for code in [
1423            "layout",
1424            "no_target",
1425            "non_teams_listener_refused",
1426            "something_else",
1427        ] {
1428            let error = sent_message(&json!({"error": code}), CHAT).unwrap_err();
1429            assert!(
1430                matches!(error, AppError::Desktop(_)) && !unconfirmed(error),
1431                "{code}"
1432            );
1433        }
1434    }
1435
1436    #[test]
1437    fn read_requests_validate_chat_ids_and_cursors() {
1438        let request = read_request(9222, None, 5, None).unwrap();
1439        assert_eq!(request["query"], "chats");
1440        assert!(request["after"].is_null());
1441        let cursor = encode_cursor(&json!({"t": 42, "id": "19:a@thread.v2"})).unwrap();
1442        let request = read_request(9222, Some("19:a@thread.v2"), 5, Some(&cursor)).unwrap();
1443        assert_eq!(request["query"], "messages");
1444        assert_eq!(request["chat_id"], "19:a@thread.v2");
1445        assert_eq!(request["after"], json!({"t": 42, "id": "19:a@thread.v2"}));
1446        for chat in ["fixture", "19:a b", "19:a'); x", ""] {
1447            assert!(matches!(
1448                read_request(9222, Some(chat), 5, None),
1449                Err(AppError::InvalidInput(_))
1450            ));
1451        }
1452        let negative = URL_SAFE_NO_PAD.encode(r#"{"t":-1,"id":"x"}"#);
1453        for cursor in ["%%%", "e30", negative.as_str()] {
1454            assert!(matches!(
1455                read_request(9222, None, 5, Some(cursor)),
1456                Err(AppError::InvalidInput(_))
1457            ));
1458        }
1459    }
1460
1461    fn reply(value: Value) -> Value {
1462        json!({"result":{"result":{"type":"string","value":value.to_string()}}})
1463    }
1464
1465    #[test]
1466    fn read_pages_map_cache_results_and_failures() {
1467        let page = read_page(&reply(json!({
1468            "me": "0f0e-guid",
1469            "items": [{"id": "19:a@thread.v2", "topic": null}],
1470            "next": {"t": 7, "id": "19:a@thread.v2"}
1471        })))
1472        .unwrap();
1473        assert_eq!(page.items.len(), 1);
1474        assert_eq!(page.viewer.as_deref(), Some("0f0e-guid"));
1475        assert!(serde_json::to_value(&page).unwrap().get("viewer").is_none());
1476        assert!(page.truncated);
1477        assert_eq!(page.source, Some("desktop_cache"));
1478        assert_eq!(
1479            decode_cursor(page.next_cursor.as_deref().unwrap()).unwrap(),
1480            json!({"t": 7, "id": "19:a@thread.v2"})
1481        );
1482        let last = read_page(&reply(json!({"me": "a b", "items": [], "next": null}))).unwrap();
1483        assert!(!last.truncated && last.next_cursor.is_none() && last.viewer.is_none());
1484        assert!(matches!(
1485            read_page(&reply(json!({"error": "not_found"}))),
1486            Err(AppError::NotFound(_))
1487        ));
1488        let layout = json!({"result":{"exceptionDetails":{"exception":{"description":"Error: layout\n    at x"}}}});
1489        // Mixed personal and work/school windows are resolved by choosing a surface.
1490        for ambiguous in [
1491            json!({"error": "account_ambiguous"}),
1492            reply(json!({"error": "account_ambiguous"})),
1493        ] {
1494            assert!(
1495                matches!(read_page(&ambiguous), Err(AppError::Desktop(m)) if m.contains("--desktop-account"))
1496            );
1497            assert!(
1498                matches!(sent_message(&ambiguous, CHAT), Err(AppError::Desktop(m)) if m.contains("--desktop-account"))
1499            );
1500        }
1501        // Several caches within one surface are not, so no flag is suggested.
1502        for ambiguous in [
1503            json!({"error": "cache_ambiguous"}),
1504            reply(json!({"error": "cache_ambiguous"})),
1505        ] {
1506            for result in [
1507                read_page(&ambiguous).map(|_| ()),
1508                sent_message(&ambiguous, CHAT).map(|_| ()),
1509            ] {
1510                assert!(
1511                    matches!(result, Err(AppError::Desktop(m)) if m.contains("cached") && !m.contains("--desktop-account"))
1512                );
1513            }
1514        }
1515        assert!(matches!(read_page(&layout), Err(AppError::Desktop(m)) if m.contains("layout")));
1516        for reply in [
1517            json!({"error": "no_target"}),
1518            json!({"error": "non_teams_listener_refused"}),
1519            json!({"error": "read_failed"}),
1520            json!("not an object"),
1521            reply(json!({"items": [], "next": {"t": 1, "id": "bad id"}})),
1522        ] {
1523            assert!(matches!(read_page(&reply), Err(AppError::Desktop(_))));
1524        }
1525    }
1526
1527    #[test]
1528    fn listener_parser_keeps_every_binding_and_refuses_non_loopback() {
1529        let listeners =
1530            parse_listeners("p12\nn127.0.0.1:9222\nn[::1]:9222\np13\nn*:9222\n").unwrap();
1531        assert_eq!(listeners.len(), 3);
1532        assert!(loopback_address(&listeners[0].1, 9222));
1533        assert!(loopback_address(&listeners[1].1, 9222));
1534        assert!(!loopback_address(&listeners[2].1, 9222));
1535        assert!(!loopback_address("127.0.0.1:19222", 9222));
1536        assert!(parse_listeners("n127.0.0.1:9222").is_err());
1537    }
1538
1539    #[test]
1540    fn origins_are_exact_and_private_metadata_is_removed() {
1541        let cases = [
1542            (
1543                "https://teams.microsoft.com/v2/?account=PRIVATE",
1544                true,
1545                "https://teams.microsoft.com",
1546            ),
1547            (
1548                "https://teams.cloud.microsoft/path",
1549                true,
1550                "https://teams.cloud.microsoft",
1551            ),
1552            (
1553                "https://teams.live.com/PRIVATE",
1554                true,
1555                "https://teams.live.com",
1556            ),
1557            (
1558                "https://teams.microsoft.com.evil.example/PRIVATE",
1559                false,
1560                "[other origin omitted]",
1561            ),
1562            (
1563                "https://teams.microsoft.com:444/PRIVATE",
1564                false,
1565                "[other origin omitted]",
1566            ),
1567            (
1568                "http://teams.microsoft.com/PRIVATE",
1569                false,
1570                "[other origin omitted]",
1571            ),
1572            ("file:///Users/PRIVATE/SECRET.html", false, "file:"),
1573            ("blob:https://private-tenant.example/SECRET", false, "blob:"),
1574            (
1575                "https://login.microsoftonline.com/PRIVATE",
1576                false,
1577                "https://login.microsoftonline.com",
1578            ),
1579        ];
1580        for (url, teams, origin) in cases {
1581            let target = sanitize_target(
1582                &json!({"type":"page","url":url,"title":"PRIVATE","id":"SECRET","webSocketDebuggerUrl":"ws://127.0.0.1/SECRET"}),
1583            );
1584            assert_eq!(target.teams_origin, teams);
1585            assert_eq!(target.url_origin, origin);
1586            let output = serde_json::to_string(&target).unwrap();
1587            assert!(!output.contains("PRIVATE") && !output.contains("SECRET"));
1588        }
1589    }
1590
1591    #[test]
1592    fn sign_out_means_web_pages_without_a_teams_page() {
1593        let metadata = |pages: &[(&str, &str)]| {
1594            let mut metadata = ConnectionMetadata::empty(9224);
1595            metadata.status = ProbeStatus::MetadataOk;
1596            metadata.loopback_only = Some(true);
1597            metadata.teams_owned = Some(true);
1598            metadata.targets = pages
1599                .iter()
1600                .map(|(kind, url)| sanitize_target(&json!({"type":kind,"url":url})))
1601                .collect();
1602            metadata
1603        };
1604        let login = ("page", "https://login.microsoftonline.com/common/oauth2");
1605        let federated = ("page", "https://adfs.example.com/adfs/ls/wia");
1606        let teams = ("page", "https://teams.cloud.microsoft/");
1607        let worker = ("service_worker", "https://teams.cloud.microsoft/sw.js");
1608        assert!(metadata(&[login, worker]).signed_out());
1609        assert!(metadata(&[federated]).signed_out());
1610        assert!(!metadata(&[teams, worker]).signed_out());
1611        assert!(!metadata(&[teams, login]).signed_out());
1612        // A starting browser or the lightweight client's blank page is not a sign-out.
1613        assert!(!metadata(&[]).signed_out());
1614        assert!(!metadata(&[("page", "about:blank")]).signed_out());
1615        let mut refused = metadata(&[login]);
1616        refused.teams_owned = Some(false);
1617        assert!(!refused.signed_out());
1618    }
1619
1620    #[tokio::test]
1621    async fn metadata_reader_uses_only_the_two_read_routes_and_generic_user_agent() {
1622        let server = MockServer::start().await;
1623        Mock::given(method("GET"))
1624            .and(path("/json/version"))
1625            .and(header("User-Agent", "TeamsCLI-DesktopProbe/0.1"))
1626            .respond_with(
1627                ResponseTemplate::new(200)
1628                    .set_body_json(json!({"Browser":"Edg/fixture","Protocol-Version":"1.3"})),
1629            )
1630            .expect(1)
1631            .mount(&server)
1632            .await;
1633        Mock::given(method("GET"))
1634            .and(path("/json/list"))
1635            .respond_with(
1636                ResponseTemplate::new(200)
1637                    .set_body_json(json!([{"type":"page","url":"https://teams.live.com/PRIVATE"}])),
1638            )
1639            .expect(1)
1640            .mount(&server)
1641            .await;
1642        let (version, targets) = read_metadata(server.address().port()).await.unwrap();
1643        assert_eq!(version["Protocol-Version"], "1.3");
1644        assert_eq!(
1645            sanitize_target(&targets[0]).url_origin,
1646            "https://teams.live.com"
1647        );
1648        let mut connection = ConnectionMetadata::empty(server.address().port());
1649        connection.status = ProbeStatus::MetadataOk;
1650        assert!(!connection.endpoint_available());
1651        connection.loopback_only = Some(true);
1652        connection.teams_owned = Some(true);
1653        assert!(connection.endpoint_available());
1654    }
1655
1656    #[tokio::test]
1657    async fn metadata_reader_refuses_redirects_and_oversized_responses() {
1658        let server = MockServer::start().await;
1659        let sink = MockServer::start().await;
1660        Mock::given(method("GET"))
1661            .respond_with(ResponseTemplate::new(200))
1662            .expect(0)
1663            .mount(&sink)
1664            .await;
1665        Mock::given(path("/json/version"))
1666            .respond_with(ResponseTemplate::new(302).insert_header("Location", sink.uri()))
1667            .mount(&server)
1668            .await;
1669        assert!(read_metadata(server.address().port()).await.is_err());
1670        server.reset().await;
1671        Mock::given(path("/json/version"))
1672            .respond_with(ResponseTemplate::new(200).set_body_string("x".repeat(MAX_METADATA + 1)))
1673            .mount(&server)
1674            .await;
1675        assert!(read_metadata(server.address().port()).await.is_err());
1676    }
1677}