//! The broker's routing: many DevTools clients over the ONE pipe Cotton's//! Chrome was started with, each speaking only through sessions it holds.//!//! **What this does NOT promise:** that one client cannot see another's//! tabs. Every client is one of the owner's own hosted sessions, admitted by//! its token, driving the same signed-in profile: any of them can list every//! target (`Target.getTargets`) and attach a session of ITS OWN to any page,//! including one another session opened, and read every cookie besides. What//! the router keeps apart is sessions, answers and events — a client cannot//! use, or hear, a session id it does not hold.//!//! Chrome started with `--remote-debugging-pipe` has exactly one DevTools//! connection — the pipe — and no port. Every session that drives the browser//! goes through the broker ([`crate::browser_broker`]), which holds that pipe,//! and this is the part of the broker with the rules in it. It is pure: text//! in, text out, no sockets, so every rule is a unit test.//!//! ## How several clients share one connection//!//! **Each client gets a browser-target session of its own.** When a client//! connects, the broker sends `Target.attachToBrowserTarget` down the pipe and//! the answer is a flat `sessionId` for a session on the BROWSER target. A//! command sent with that session id is Chrome's to scope as if a separate//! client had sent it — its `Target.setAutoAttach`, its discovered targets,//! its attached pages are that session's own — which is exactly how DevTools//! itself shares one browser between several front ends. So a client speaks//! plain CDP as if it had the browser to itself://!//! - A command WITHOUT a `sessionId` is the client talking to "the browser",//! and is sent under its own browser session.//! - A command WITH a `sessionId` is sent only if that session is this//! client's: its browser session, or one Chrome attached under it//! (`Target.attachedToTarget`), or one a command of its own returned//! (`Target.attachToTarget`). Anything else is answered, by the broker, with//! Chrome's own "Session with given id not found" — a client cannot drive//! another session's page by guessing an id.//! - Command ids are the client's own; the broker gives each forwarded command//! a fresh id and puts the client's back on the answer.//! - An event is delivered only to the client that owns its session. An event//! with no session is the pipe's own and goes to nobody.//!//! **What no client may send** ([`REFUSED`]), because the browser is shared//! and signed in: `Browser.close` and the two crash commands would take the//! browser from every other session, and `Target.exposeDevToolsProtocol`//! hands a PAGE's own JavaScript a DevTools channel to the browser target — a//! web page driving the signed-in browser, which is the one thing the broker//! exists to stop.use std::collections::HashMap;use serde_json::{json, Value};/// A connected client, numbered by the broker.pubtypeClientId = u64;/// Methods the broker answers with a refusal instead of sending (module doc).pubconst REFUSED: [&str; 4] = ["Browser.close","Browser.crash","Browser.crashGpuProcess","Target.exposeDevToolsProtocol",];/// Chrome's own code for "no such session", reused so a client's library/// reads the refusal the way it reads Chrome's.const NO_SUCH_SESSION: i64 = -32001;/// A command that is waiting for Chrome's answer.#[derive(Debug, Clone, PartialEq)]enumPending {/// A client's command: its own id goes back on the answer.Client { client: ClientId, id: Value },/// The broker's `Target.attachToBrowserTarget` for a client.Attach { client: ClientId },/// The broker's own clean-up; the answer goes to nobody.Internal,}/// Where a client's message goes.#[derive(Debug, Clone, PartialEq)]pubenumFromClient {/// Down the pipe, rewritten.ToChrome(String),/// Straight back to the client — a refusal the broker answers itself.ToClient(String),}/// What one message from Chrome produced.#[derive(Debug, Default, Clone, PartialEq)]pubstructRouted {/// Messages for clients, each already rewritten for its client.pub deliveries: Vec<(ClientId, String)>,/// A client's browser session was answered: attached, or why not.pub attached: Option<(ClientId, Result<(), String>)>,}/// The routing state for one pipe.#[derive(Debug, Default)]pubstructRouter { next_id: u64, pending: HashMap<u64, Pending>,/// The browser-target session each attached client drives. browser_sessions: HashMap<ClientId, String>,/// Every session a client may address, and that client. owners: HashMap<String, ClientId>,}implRouter {/// An empty router.pubfn new() -> Self {Self::default() }fn fresh_id(&mutself, pending: Pending) -> u64 {self.next_id += 1;self.pending.insert(self.next_id, pending);self.next_id }/// The command that gives `client` its browser session — to be sent/// before anything the client says.pubfn attach(&mutself, client: ClientId) -> String {let id = self.fresh_id(Pending::Attach { client }); json!({ "id": id, "method": "Target.attachToBrowserTarget" }).to_string() }/// The browser session `client` drives, once attached.pubfn browser_session(&self, client: ClientId) -> Option<&str> {self.browser_sessions.get(&client).map(String::as_str) }/// Whether `client` may address `session`.pubfn owns(&self, client: ClientId, session: &str) -> bool {self.owners.get(session) == Some(&client) }/// One message from a client.pubfn from_client(&mutself, client: ClientId, text: &str) -> FromClient {letOk(Value::Object(mut message)) = serde_json::from_str::<Value>(text) else {returnFromClient::ToClient( json!({ "error": { "code": -32700, "message": "Message must be a JSON object" } }) .to_string(), ); };let id = message.get("id").cloned().unwrap_or(Value::Null);let refuse = |message: String| {FromClient::ToClient( json!({ "id": id, "error": { "code": NO_SUCH_SESSION, "message": message } }) .to_string(), ) };let method = message.get("method").and_then(Value::as_str).unwrap_or("");if REFUSED.contains(&method) {return refuse(format!("{method} is refused by Cotton's browser broker: the browser is shared by \ every session" )); }letSome(browser_session) = self.browser_sessions.get(&client).cloned() else {return refuse("This client is not attached to the browser".to_string()); };match message.get("sessionId").and_then(Value::as_str) {None => { message.insert("sessionId".to_string(), Value::String(browser_session)); }Some(session) ifself.owns(client, session) => {}Some(_) => return refuse("Session with given id not found.".to_string()), }let forwarded = self.fresh_id(Pending::Client { client, id }); message.insert("id".to_string(), Value::from(forwarded));FromClient::ToChrome(Value::Object(message).to_string()) }/// One message from Chrome.pubfn from_chrome(&mutself, text: &str) -> Routed {letmut routed = Routed::default();letOk(Value::Object(mut message)) = serde_json::from_str::<Value>(text) else {return routed; };ifletSome(id) = message.get("id").and_then(Value::as_u64) {matchself.pending.remove(&id) {Some(Pending::Client { client, id }) => {// A command that ATTACHED something (`Target.attachToTarget`,// a second `attachToBrowserTarget`) answers with the new// session, and that session is the caller's.ifletSome(session) = message .get("result") .and_then(|result| result.get("sessionId")) .and_then(Value::as_str) {self.owners.insert(session.to_string(), client); } message.insert("id".to_string(), id);self.strip_browser_session(client, &mut message); routed .deliveries .push((client, Value::Object(message).to_string())); }Some(Pending::Attach { client }) => {let session = message .get("result") .and_then(|result| result.get("sessionId")) .and_then(Value::as_str); routed.attached = Some(match session {Some(session) => {self.browser_sessions.insert(client, session.to_string());self.owners.insert(session.to_string(), client); (client, Ok(())) }None => ( client,Err(message .get("error") .map_or_else(|| "no session came back".to_string(), Value::to_string)), ), }); }Some(Pending::Internal) | None => {} }return routed; }// An EVENT: its session says whose it is.letSome(session) = message.get("sessionId").and_then(Value::as_str).map(str::to_string)else {return routed; };letSome(&client) = self.owners.get(&session) else {return routed; };let child = message .get("params") .and_then(|params| params.get("sessionId")) .and_then(Value::as_str) .map(str::to_string);match message.get("method").and_then(Value::as_str) {Some("Target.attachedToTarget") => {ifletSome(child) = &child {self.owners.insert(child.clone(), client); } }Some("Target.detachedFromTarget") => {ifletSome(child) = &child {self.owners.remove(child); } } _ => {} }self.strip_browser_session(client, &mut message); routed .deliveries .push((client, Value::Object(message).to_string())); routed }/// A client's own browser session is invisible to it: it sent those/// commands with no session, so the answers carry none either.fn strip_browser_session(&self, client: ClientId, message: &mut serde_json::Map<String, Value>) {let is_browser = message.get("sessionId").and_then(Value::as_str) == self.browser_sessions.get(&client).map(String::as_str);if is_browser { message.remove("sessionId"); } }/// `client` went away: forget everything it held, and the commands that/// detach its sessions — the children first, then its browser session.pubfn detach(&mutself, client: ClientId) -> Vec<String> {for pending inself.pending.values_mut() {let theirs = match pending {Pending::Client { client: owner, .. } | Pending::Attach { client: owner } => { *owner == client }Pending::Internal => false, };if theirs { *pending = Pending::Internal; } }let browser = self.browser_sessions.remove(&client);letmut children: Vec<String> = self .owners .iter() .filter(|(session, owner)| **owner == client && Some(*session) != browser.as_ref()) .map(|(session, _)| session.clone()) .collect(); children.sort();self.owners.retain(|_, owner| *owner != client); children .into_iter() .chain(browser) .map(|session| {let id = self.fresh_id(Pending::Internal); json!({ "id": id, "method": "Target.detachFromTarget","params": { "sessionId": session } }) .to_string() }) .collect() }}#[cfg(test)]#[path = "browser_router_tests.rs"]mod browser_router_tests;