A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
codec 69: turn the web listener on and off at runtime
RoversXede4579b8188
diff --git a/codec/src/lib.rs b/codec/src/lib.rsindex 1301c97a..26c07083 100644--- a/codec/src/lib.rs+++ b/codec/src/lib.rs@@ -576,7 +576,7 @@ macro_rules! pdu {/// 67: Web tokens: the credential a browser presents at the server's web/// port is minted, listed and revoked over the mux connection/// (WebTokenMint/List/Revoke), the way TLS credentials are obtained.-pub const CODEC_VERSION: usize = 67;+pub const CODEC_VERSION: usize = 69;// Defines the Pdu enum.// Each struct has an explicit identifying number.@@ -665,6 +665,9 @@ pdu! {WebTokenListResponse: 88,WebTokenRevoke: 89,WebTokenRevokeResponse: 90,+ GetWebServerStatus: 91,+ SetWebServer: 92,+ WebServerStatus: 93,}impl Pdu {@@ -865,7 +868,7 @@ pub struct WebTokenMint {#[derive(Deserialize, Serialize, PartialEq, Debug)]pub struct WebTokenMintResponse {pub id: String,- pub label: String,+ pub label: Option<String>,/// The secret. Shown once; the server keeps only a digest.pub token: String,/// Unix seconds.@@ -882,11 +885,16 @@ pub struct WebTokenList {}#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]pub struct WebTokenInfo {pub id: String,- pub label: String,+ /// What a person called it, if anyone did.+ pub label: Option<String>,/// Unix seconds.pub created_at: u64,pub expires_at: Option<u64>,pub last_used_at: Option<u64>,+ /// What the browser said it was, last time this link was used, e.g.+ /// "iPad · Safari". Self-reported by the client: a description to tell+ /// your own devices apart, never a credential.+ pub last_device: Option<String>,pub live_connections: u32,}@@ -895,6 +903,35 @@ pub struct WebTokenListResponse {pub tokens: Vec<WebTokenInfo>,}+/// Where the server is accepting browser clients, if anywhere.+#[derive(Deserialize, Serialize, PartialEq, Debug)]+pub struct GetWebServerStatus {}++/// Start or stop the browser listener while the server runs.+///+/// `bind_address` is consulted only when starting, and falls back to the+/// first configured `web_servers` entry. Stopping stops every listener, so+/// a client that does not know which address is up still turns it off.+#[derive(Deserialize, Serialize, PartialEq, Debug)]+pub struct SetWebServer {+ pub enabled: bool,+ pub bind_address: Option<String>,+}++/// The answer to both of the above, so a client that changes the state and+/// a client that only asks read the same shape.+#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]+pub struct WebServerStatus {+ /// Accepting right now. Empty means no browser can reach this server.+ pub listening: Vec<String>,+ /// One page URL per live listener, without a token: minting is+ /// separate, and a URL here is safe to show and to log.+ pub urls: Vec<String>,+ /// What `web_servers` names in the configuration, up or not. A client+ /// offering to start one uses this rather than inventing an address.+ pub configured: Vec<String>,+}+/// Revoke one token by id, or every token when `id` is None. Connections/// admitted by a revoked token are dropped at once.#[derive(Deserialize, Serialize, PartialEq, Debug)]@@ -2383,7 +2420,7 @@ mod test {// The exact assertion is the tripwire: whoever bumps the codec must// come here, confirm the round-trips still cover the new version,// and advance it deliberately.- assert_eq!(CODEC_VERSION, 67);+ assert_eq!(CODEC_VERSION, 69);use thinkterm_proto::{AgentEvidence, AgentState, AgentStatus};fn round_trip(pdu: Pdu) {diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rsindex b4e2d0bf..9f2d0fe8 100644--- a/wezterm-client/src/client.rs+++ b/wezterm-client/src/client.rs@@ -2315,6 +2315,8 @@ impl Client {rpc!(web_token_mint, WebTokenMint, WebTokenMintResponse);rpc!(web_token_list, WebTokenList = (), WebTokenListResponse);rpc!(web_token_revoke, WebTokenRevoke, WebTokenRevokeResponse);+ rpc!(get_web_server_status, GetWebServerStatus = (), WebServerStatus);+ rpc!(set_web_server, SetWebServer, WebServerStatus);rpc!(search_scrollback,SearchScrollbackRequest,diff --git a/wezterm-mux-server-impl/src/lib.rs b/wezterm-mux-server-impl/src/lib.rsindex 920f781c..9f2a84b9 100644--- a/wezterm-mux-server-impl/src/lib.rs+++ b/wezterm-mux-server-impl/src/lib.rs@@ -18,6 +18,7 @@ pub mod thinkterm_layout;pub mod thinkterm_session;pub mod thinkterm_tree;pub mod web_auth;+pub mod web_control;pub mod web_http;pub mod web_stream;diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rsindex 04faf045..b4006f64 100644--- a/wezterm-mux-server-impl/src/sessionhandler.rs+++ b/wezterm-mux-server-impl/src/sessionhandler.rs@@ -2292,10 +2292,8 @@ impl SessionHandler {label,ttl_secs.map(Duration::from_secs),)?;- let urls = config::configuration()- .web_servers- .iter()- .flat_map(|server| server.urls())+ let urls = web_urls(&crate::web_control::listening())+ .into_iter()// In the fragment: never sent to any server, never// in a Referer, never in an access log..map(|url| format!("{url}#token={}", minted.token))@@ -2322,6 +2320,53 @@ impl SessionHandler {revoked,})));}+ Pdu::GetWebServerStatus(_) => {+ send_response(Ok(Pdu::WebServerStatus(web_server_status())));+ }+ Pdu::SetWebServer(SetWebServer {+ enabled,+ bind_address,+ }) => {+ catch(+ move || {+ let Some(control) = crate::web_control::get() else {+ anyhow::bail!(+ "this server has no web listener to turn on or off"+ );+ };+ if enabled {+ let server = web_server_to_start(bind_address.as_deref())?;+ if !crate::web_control::listening().contains(&server.bind_address) {+ // The token store is set up by whoever starts+ // the first listener. A server configured with+ // no `web_servers` never did it at startup, and+ // an unconfigured store keeps tokens in memory+ // and never sweeps the expired ones. A second+ // call is a no-op; see `WebTokenStore::configure`.+ (control.configure_tokens)(std::slice::from_ref(&server))?;+ // The listener resumes admissions itself once+ // the port is up; see `spawn_web_listener`.+ (control.start)(&server)?;+ }+ } else {+ // Every listener, not just the named one: a client+ // that only knows "off" must not leave a second+ // port open behind it.+ for address in crate::web_control::listening() {+ (control.stop)(&address);+ }+ // Closing the port only stops the next browser.+ // Off has to mean the ones already inside, too.+ let cut = crate::web_auth::WEB_TOKENS.disconnect_all();+ if cut > 0 {+ log::info!("web listener stopped; cut {cut} live browsers");+ }+ }+ Ok(Pdu::WebServerStatus(web_server_status()))+ },+ send_response,+ );+ }Pdu::GetTlsCreds(_) => {catch(move || {@@ -2458,6 +2503,7 @@ impl SessionHandler {| Pdu::WebTokenMintResponse { .. }| Pdu::WebTokenListResponse { .. }| Pdu::WebTokenRevokeResponse { .. }+ | Pdu::WebServerStatus { .. }| Pdu::GetClientListResponse { .. }| Pdu::PaneRemoved { .. }| Pdu::PaneFocused { .. }@@ -3031,3 +3077,89 @@ mod tests {assert!(!answered.lock().unwrap().iter().any(|(tag, _)| *tag == "d"));}}++/// What a client is told about the browser listener.+///+/// `urls` names only the listeners that are actually up: a URL for a port+/// nobody is accepting on is worse than no URL, because it looks like the+/// feature is on.+fn web_server_status() -> WebServerStatus {+ let listening = crate::web_control::listening();+ let configured = config::configuration()+ .web_servers+ .iter()+ .map(|server| server.bind_address.clone())+ .collect();+ WebServerStatus {+ urls: web_urls(&listening),+ listening,+ configured,+ }+}++/// The pages a browser can open, one per live listener.+///+/// Built from what is accepting rather than from what is configured, and in+/// both directions: a listener started at runtime is in no `web_servers`+/// entry and would otherwise have no URL at all, and a URL for a configured+/// port nobody is accepting on is worse than none -- it reads as though the+/// feature were on.+fn web_urls(listening: &[String]) -> Vec<String> {+ let config = config::configuration();+ listening+ .iter()+ .flat_map(|address| {+ config+ .web_servers+ .iter()+ .find(|server| &server.bind_address == address)+ .cloned()+ .unwrap_or_else(|| config::WebServer {+ bind_address: address.clone(),+ ..Default::default()+ })+ .urls()+ })+ .collect()+}++/// The listener a `SetWebServer { enabled: true }` should bring up.+///+/// A configured entry is used whole, so its TLS, origins and bundle+/// directory come with it. An address that is not in the configuration gets+/// the defaults, which is what lets a server with no `web_servers` at all+/// be switched on from a settings window.+///+/// Two of those defaults are borrowed from the first configured entry when+/// there is one, because they describe *this server's* resources rather+/// than how one address is exposed: where the page lives, and where tokens+/// are kept. Without the first, a switch flipped on an ad-hoc port serves+/// no page at all when the bundle is somewhere non-standard.+fn web_server_to_start(bind_address: Option<&str>) -> anyhow::Result<config::WebServer> {+ let config = config::configuration();+ if let Some(address) = bind_address {+ if let Some(server) = config+ .web_servers+ .iter()+ .find(|server| server.bind_address == address)+ {+ return Ok(server.clone());+ }+ let first = config.web_servers.first();+ return Ok(config::WebServer {+ bind_address: address.to_string(),+ static_dir: first.and_then(|s| s.static_dir.clone()),+ token_file: first.and_then(|s| s.token_file.clone()),+ ..Default::default()+ });+ }+ // A server with no `web_servers` at all is the ordinary case now that+ // the switch lives in a settings window, so "on" means the same+ // loopback address a bare `web_servers = { {} }` would have produced+ // rather than an error about configuration the user never wrote.+ Ok(config+ .web_servers+ .first()+ .cloned()+ .unwrap_or_default())+}diff --git a/wezterm-mux-server-impl/src/web_auth.rs b/wezterm-mux-server-impl/src/web_auth.rsindex 67a607d6..2789c2d7 100644--- a/wezterm-mux-server-impl/src/web_auth.rs+++ b/wezterm-mux-server-impl/src/web_auth.rs@@ -30,23 +30,55 @@ pub struct WebTokenStore {inner: Arc<Mutex<Inner>>,}-#[derive(Default)]struct Inner {tokens: Vec<TokenRecord>,live: Vec<LiveConnection>,persist: Option<PathBuf>,next_connection: u64,+ /// Whether `configure` has already run. It used to run once, at+ /// startup; a runtime listener start calls it again, and a second run+ /// that reloaded the file would throw away every token minted since.+ configured: bool,+ /// Set false while the listener is off, so a connection whose handshake+ /// was already in flight when the port closed cannot still be let in.+ admitting: bool,+ /// A use was recorded that has not been written out. Kept so the sweep+ /// can persist `last_used_at` and `last_device` without a file write+ /// per connection.+ used_since_save: bool,+}++impl Default for Inner {+ fn default() -> Self {+ Self {+ tokens: Vec::new(),+ live: Vec::new(),+ persist: None,+ next_connection: 0,+ configured: false,+ // A server with a configured listener is admitting from the+ // moment it starts; nothing has to turn this on first.+ admitting: true,+ used_since_save: false,+ }+ }}#[derive(Debug, Clone, Serialize, Deserialize)]struct TokenRecord {id: String,- label: String,+ /// What a person called it, if a person called it anything. `None` is+ /// not a failure to name: a link minted from the settings window has no+ /// name to give, and inventing one ("token-a1b2c3") only made the list+ /// look like it knew something it did not.+ label: Option<String>,/// sha256 of the token, hex.digest: String,created_at: u64,expires_at: Option<u64>,last_used_at: Option<u64>,+ /// What the browser said it was, the last time this link was used.+ last_device: Option<String>,}struct LiveConnection {@@ -55,11 +87,64 @@ struct LiveConnection {kill: smol::channel::Sender<()>,}+/// A short description of the browser that connected, from its User-Agent.+///+/// This is what the browser *says* it is. It is a description, not an+/// identity: a User-Agent is set by the client and can say anything. It is+/// here so a person can tell their own two devices apart in a list, which+/// is a different job from deciding who gets in -- the token does that.+///+/// `None` when nothing recognisable is there, so a caller can say "unknown"+/// rather than print somebody's raw header back at them.+pub fn describe_user_agent(ua: &str) -> Option<String> {+ // Order matters twice over. Platform: iPad before Macintosh, because+ // iPadOS Safari claims both. Browser: the Chromium family before+ // Safari, because every one of them still carries "Safari" at the end.+ // An iPad with "Request Desktop Website" on (the default for Safari on+ // a large iPad) sends a Macintosh User-Agent with no "iPad" in it at+ // all, and is reported here as a Mac. Nothing in the header+ // distinguishes them; this is the limit of asking the client what it+ // is, and the reason this is a description and not an identity.+ let platform = [+ ("iPhone", "iPhone"),+ ("iPad", "iPad"),+ ("Android", "Android"),+ ("CrOS", "ChromeOS"),+ ("Macintosh", "Mac"),+ ("Mac OS X", "Mac"),+ ("Windows", "Windows"),+ ("Linux", "Linux"),+ ]+ .iter()+ .find(|(needle, _)| ua.contains(needle))+ .map(|(_, name)| *name);+ // The iOS variants come first for the same reason: Chrome on iOS is+ // "CriOS", not "Chrome", and every one of them still ends in "Safari".+ let browser = [+ ("CriOS/", "Chrome"),+ ("FxiOS/", "Firefox"),+ ("EdgiOS/", "Edge"),+ ("Edg/", "Edge"),+ ("OPR/", "Opera"),+ ("Firefox/", "Firefox"),+ ("Chrome/", "Chrome"),+ ("Safari/", "Safari"),+ ]+ .iter()+ .find(|(needle, _)| ua.contains(needle))+ .map(|(_, name)| *name);+ match (platform, browser) {+ (Some(platform), Some(browser)) => Some(format!("{platform} · {browser}")),+ (Some(one), None) | (None, Some(one)) => Some(one.to_string()),+ (None, None) => None,+ }+}+/// What `mint` hands back; the token itself is shown once and not kept.#[derive(Debug)]pub struct MintedToken {pub id: String,- pub label: String,+ pub label: Option<String>,pub token: String,pub expires_at: Option<u64>,}@@ -68,7 +153,7 @@ pub struct MintedToken {/// connection; `revoked` fires if its token is revoked while it lives.pub struct Admission {pub token_id: String,- pub label: String,+ pub label: Option<String>,pub revoked: smol::channel::Receiver<()>,connection: u64,store: Arc<Mutex<Inner>>,@@ -120,8 +205,21 @@ impl WebTokenStore {/// A store that cannot be read is an empty store, said loudly: the/// server must start whatever state a cache file is in, and a corrupt/// file is moved aside so it can be looked at.+ ///+ /// **The first call wins.** This is called once at startup and again by+ /// every runtime listener start, and the later calls must change+ /// nothing: reloading the file would replace tokens minted since with+ /// the stale set on disk, and a start at an address that is not in+ /// `web_servers` arrives with `persist: None`, which would turn a+ /// persistent store into a memory-only one -- so a revoke would report+ /// success, never reach the file, and the token would be admitted again+ /// after a restart.pub fn configure(&self, persist: Option<PathBuf>) -> anyhow::Result<()> {let mut inner = self.lock();+ if inner.configured {+ return Ok(());+ }+ inner.configured = true;if let Some(path) = &persist {match std::fs::read(path) {Ok(bytes) => match serde_json::from_slice::<Vec<TokenRecord>>(&bytes) {@@ -166,9 +264,7 @@ impl WebTokenStore {let id = uuid::Uuid::new_v4().simple().to_string()[..12].to_string();let now = now_secs();let expires_at = ttl.map(|ttl| now.saturating_add(ttl.as_secs()));- let label = label- .filter(|l| !l.trim().is_empty())- .unwrap_or_else(|| format!("token-{id}"));+ let label = label.filter(|l| !l.trim().is_empty());let record = TokenRecord {id: id.clone(),label: label.clone(),@@ -176,6 +272,7 @@ impl WebTokenStore {created_at: now,expires_at,last_used_at: None,+ last_device: None,};let mut inner = self.lock();Self::expire(&mut inner, now);@@ -191,10 +288,16 @@ impl WebTokenStore {/// Check a presented token. On success the connection is registered/// so that revoking the token can drop it.- pub fn verify(&self, presented: &str) -> Option<Admission> {+ pub fn verify(&self, presented: &str, device: Option<String>) -> Option<Admission> {let digest = digest_hex(presented);let now = now_secs();let mut inner = self.lock();+ // The listener is off. This connection was accepted before the port+ // closed and finished its handshake afterwards; letting it in would+ // hand out a shell the switch says is not on offer.+ if !inner.admitting {+ return None;+ }if Self::expire(&mut inner, now) {if let Err(err) = Self::save(&inner) {log::warn!("web token store not saved: {err:#}");@@ -209,9 +312,15 @@ impl WebTokenStore {}}let idx = found?;- // Recorded in memory; written out with the next mint, revoke or- // sweep rather than on every connection.+ // Recorded in memory; written out by the next sweep, mint or+ // revoke rather than on every connection.inner.tokens[idx].last_used_at = Some(now);+ inner.used_since_save = true;+ // Only overwritten by a connection that said something: a client+ // with no User-Agent should not erase what the last one told us.+ if device.is_some() {+ inner.tokens[idx].last_device = device.clone();+ }let token_id = inner.tokens[idx].id.clone();let label = inner.tokens[idx].label.clone();let (kill, revoked) = smol::channel::bounded(1);@@ -234,9 +343,23 @@ impl WebTokenStore {/// Drop expired tokens and cut their connections. The listener runs/// this on a timer: a token's lifetime ends when it says, not when/// someone next happens to mint or list.+ /// Let connections in again. Called when a listener starts, so the+ /// refusal `disconnect_all` put in place lasts exactly as long as the+ /// listener is down.+ pub fn resume_admitting(&self) {+ self.lock().admitting = true;+ }+pub fn sweep(&self) {let mut inner = self.lock();- if Self::expire(&mut inner, now_secs()) {+ // Expiry is not the only thing worth writing: `verify` records+ // `last_used_at` and `last_device` in memory, and the settings list+ // names a link after the browser that used it. Without this they+ // survived only until the next mint or revoke -- and a store whose+ // tokens have no expiry never had one of those forced on it.+ let expired = Self::expire(&mut inner, now_secs());+ if expired || inner.used_since_save {+ inner.used_since_save = false;if let Err(err) = Self::save(&inner) {log::warn!("web token store not saved: {err:#}");}@@ -259,6 +382,7 @@ impl WebTokenStore {created_at: record.created_at,expires_at: record.expires_at,last_used_at: record.last_used_at,+ last_device: record.last_device.clone(),live_connections: inner.live.iter()@@ -294,6 +418,30 @@ impl WebTokenStore {revoked}+ /// Cut every live browser connection, leaving the tokens alone.+ ///+ /// What "stop accepting browser clients" has to mean: closing the port+ /// only stops the next browser, and someone already inside would keep+ /// a shell for as long as they held the socket. The links stay valid,+ /// so turning the listener back on does not make everyone re-mint --+ /// `revoke` is the one that ends links.+ pub fn disconnect_all(&self) -> u32 {+ let mut inner = self.lock();+ // Closed first, and in the same lock: a connection accepted before+ // the port went away can still be in its handshake, and `verify`+ // has to refuse it after this returns. Cutting only what is already+ // live would let that one through and leave a browser inside a+ // server whose switch reads off.+ inner.admitting = false;+ let mut cut = 0;+ for live in inner.live.iter() {+ if live.kill.try_send(()).is_ok() {+ cut += 1;+ }+ }+ cut+ }+fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {self.inner.lock().unwrap_or_else(|e| e.into_inner())}@@ -348,6 +496,65 @@ fn write_private(path: &Path, bytes: &[u8]) -> anyhow::Result<()> {#[cfg(test)]mod tests {+ use super::describe_user_agent as describe;++ #[test]+ fn a_browser_is_described_by_platform_and_engine() {+ assert_eq!(+ describe("Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) \+ AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1")+ .as_deref(),+ Some("iPhone · Safari")+ );+ assert_eq!(+ describe("Mozilla/5.0 (iPad; CPU OS 17_5 like Mac OS X) AppleWebKit/605.1.15 \+ (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1")+ .as_deref(),+ Some("iPad · Safari")+ );+ assert_eq!(+ describe("Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 \+ (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36")+ .as_deref(),+ Some("Android · Chrome")+ );+ }++ #[test]+ fn the_chromium_family_is_not_reported_as_safari() {+ // Every one of these ends in "Safari/537.36", and Edge and Opera+ // also carry "Chrome/". Matching in the wrong order calls all of+ // them Safari, which is exactly the kind of wrong that looks right.+ let base = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 \+ (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36";+ assert_eq!(describe(base).as_deref(), Some("Mac · Chrome"));+ assert_eq!(+ describe(&format!("{base} Edg/125.0.0.0")).as_deref(),+ Some("Mac · Edge")+ );+ assert_eq!(+ describe(&format!("{base} OPR/111.0.0.0")).as_deref(),+ Some("Mac · Opera")+ );+ // Chrome on iOS is CriOS, and still ends in Safari.+ assert_eq!(+ describe("Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) \+ AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/125.0.0.0 Mobile/15E148 Safari/604.1")+ .as_deref(),+ Some("iPhone · Chrome")+ );+ }++ #[test]+ fn half_an_answer_is_still_worth_showing_and_none_is_not() {+ assert_eq!(describe("Firefox/126.0").as_deref(), Some("Firefox"));+ assert_eq!(describe("Mozilla/5.0 (Windows NT 10.0)").as_deref(), Some("Windows"));+ // Nothing recognisable: the caller says "unknown" rather than+ // printing a stranger's raw header into a settings window.+ assert_eq!(describe(""), None);+ assert_eq!(describe("curl/8.6.0"), None);+ }+use super::*;fn fresh() -> WebTokenStore {@@ -358,13 +565,13 @@ mod tests {fn a_minted_token_verifies_and_a_stranger_does_not() {let store = fresh();let minted = store.mint(Some("laptop".into()), None).unwrap();- let admitted = store.verify(&minted.token).expect("the real token");+ let admitted = store.verify(&minted.token, None).expect("the real token");assert_eq!(admitted.token_id, minted.id);- assert_eq!(admitted.label, "laptop");- assert!(store.verify("not-a-token").is_none());+ assert_eq!(admitted.label.as_deref(), Some("laptop"));+ assert!(store.verify("not-a-token", None).is_none());let mut wrong = minted.token.clone();wrong.replace_range(0..1, if minted.token.starts_with('A') { "B" } else { "A" });- assert!(store.verify(&wrong).is_none());+ assert!(store.verify(&wrong, None).is_none());assert_eq!(store.list()[0].live_connections, 1);drop(admitted);assert_eq!(store.list()[0].live_connections, 0);@@ -374,10 +581,10 @@ mod tests {fn revoking_drops_the_live_connection_and_forgets_the_token() {let store = fresh();let minted = store.mint(None, None).unwrap();- let admitted = store.verify(&minted.token).unwrap();+ let admitted = store.verify(&minted.token, None).unwrap();assert_eq!(store.revoke(Some(&minted.id)), 1);assert!(admitted.revoked.try_recv().is_ok(), "the kill switch fired");- assert!(store.verify(&minted.token).is_none());+ assert!(store.verify(&minted.token, None).is_none());assert_eq!(store.revoke(Some(&minted.id)), 0);}@@ -391,7 +598,7 @@ mod tests {let brief = store.mint(Some("brief".into()), Some(Duration::from_secs(0))).unwrap();- assert!(store.verify(&brief.token).is_none(), "already expired");+ assert!(store.verify(&brief.token, None).is_none(), "already expired");let on_disk = std::fs::read_to_string(&path).unwrap();assert!(on_disk.contains("keep"));assert!(!on_disk.contains(&keep.token), "the token itself is never written");@@ -399,7 +606,79 @@ mod tests {let reloaded = fresh();reloaded.configure(Some(path)).unwrap();- assert!(reloaded.verify(&keep.token).is_some());+ assert!(reloaded.verify(&keep.token, None).is_some());+ }++ #[test]+ fn a_second_configure_changes_nothing() {+ // The runtime listener switch calls configure again on every "on".+ // Reloading there would replace tokens minted since with the stale+ // set on disk, and a start at an address that is not in the+ // configuration arrives with `persist: None` -- which used to turn+ // a persistent store into a memory-only one, so a later revoke+ // reported success, never reached the file, and the token was+ // admitted again after a restart.+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("web-tokens.json");+ let store = fresh();+ store.configure(Some(path.clone())).unwrap();+ let first = store.mint(Some("first".into()), None).unwrap();++ // A start at an unconfigured address: persist must survive it.+ store.configure(None).unwrap();+ assert!(store.verify(&first.token, None).is_some(), "the token is still here");+ assert_eq!(store.revoke(Some(&first.id)), 1);+ let on_disk = std::fs::read_to_string(&path).unwrap();+ assert!(!on_disk.contains("first"), "the revoke reached the file");++ // And a start back at the configured address must not reload the+ // file over what is in memory.+ let second = store.mint(Some("second".into()), None).unwrap();+ store.configure(Some(path)).unwrap();+ assert!(store.verify(&second.token, None).is_some(), "a live token was not dropped");+ }++ #[test]+ fn turning_the_listener_off_refuses_a_handshake_that_was_already_in_flight() {+ // Cutting only the connections already admitted let a socket that+ // was accepted before the port closed finish its handshake+ // afterwards and become a full session -- a browser inside a server+ // whose switch reads off.+ let store = fresh();+ let token = store.mint(None, None).unwrap();+ let admitted = store.verify(&token.token, None).unwrap();+ assert_eq!(store.disconnect_all(), 1, "the live one is cut");+ drop(admitted);+ assert!(+ store.verify(&token.token, None).is_none(),+ "no admissions while the listener is down"+ );+ store.resume_admitting();+ assert!(+ store.verify(&token.token, None).is_some(),+ "and they resume when it comes back up"+ );+ }++ #[test]+ fn a_sweep_writes_out_a_use_even_when_nothing_expired() {+ // The settings list names a link after the browser that used it, so+ // losing `last_device` on every restart made the list forget which+ // device each link belonged to. Nothing expires here, which is the+ // case the old sweep never saved in.+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("web-tokens.json");+ let store = fresh();+ store.configure(Some(path.clone())).unwrap();+ let token = store.mint(Some("phone".into()), None).unwrap();+ assert!(!std::fs::read_to_string(&path).unwrap().contains("iPad"));++ drop(store.verify(&token.token, Some("iPad · Safari".into())).unwrap());+ store.sweep();+ assert!(+ std::fs::read_to_string(&path).unwrap().contains("iPad · Safari"),+ "the device that used the link survives a restart"+ );}#[test]diff --git a/wezterm-mux-server-impl/src/web_control.rs b/wezterm-mux-server-impl/src/web_control.rsnew file mode 100644index 00000000..e2a6b10d--- /dev/null+++ b/wezterm-mux-server-impl/src/web_control.rs@@ -0,0 +1,40 @@+//! The handle the session handler uses to start and stop the web listener.+//!+//! The listener lives in the `wezterm-mux-server` binary, and the binary+//! depends on this crate rather than the other way round, so it hands these+//! in at startup. A build that never installs them -- a test, or a client+//! linking this crate -- answers "no web listener here" rather than+//! pretending to have one.++use std::sync::OnceLock;++pub struct WebControl {+ pub start: fn(&config::WebServer) -> anyhow::Result<()>,+ /// Point the token store at its file and start the expiry sweep. Safe+ /// to call again; the first listener to run wins.+ pub configure_tokens: fn(&[config::WebServer]) -> anyhow::Result<()>,+ /// `false` when nothing was listening on that address.+ pub stop: fn(&str) -> bool,+ /// The bind addresses currently accepting.+ pub listening: fn() -> Vec<String>,+}++static CONTROL: OnceLock<WebControl> = OnceLock::new();++/// Installed once, by the server binary, before it answers any client.+pub fn install(control: WebControl) {+ if CONTROL.set(control).is_err() {+ log::warn!("the web listener controls were installed twice; keeping the first");+ }+}++pub fn get() -> Option<&'static WebControl> {+ CONTROL.get()+}++/// What is accepting right now. Empty when the controls are absent, which+/// is indistinguishable from "nothing is listening" and means the same to+/// every caller.+pub fn listening() -> Vec<String> {+ get().map(|c| (c.listening)()).unwrap_or_default()+}diff --git a/wezterm-mux-server-impl/src/web_http.rs b/wezterm-mux-server-impl/src/web_http.rsindex 8223f39e..22c9d298 100644--- a/wezterm-mux-server-impl/src/web_http.rs+++ b/wezterm-mux-server-impl/src/web_http.rs@@ -736,7 +736,13 @@ where.await}Route::Upgrade { key, token } => {- let Some(admission) = WEB_TOKENS.verify(&token) else {+ // Taken here and nowhere else: the header belongs to the+ // connection being admitted, and there is no second chance to+ // read it once the socket becomes a mux stream.+ let device = request+ .header("user-agent")+ .and_then(crate::web_auth::describe_user_agent);+ let Some(admission) = WEB_TOKENS.verify(&token, device) else {log::warn!("web socket from origin {:?} refused: unknown or expired token",request.header("origin")@@ -766,15 +772,21 @@ wherereturn;}let _ = stream.flush().await;+ // The token id when the link has no name of its own: a peer+ // has to be called something in `list-clients`, and the id is+ // the one handle that is always there and always unique.+ let peer_label = admission+ .label+ .clone()+ .unwrap_or_else(|| admission.token_id.clone());log::info!(- "web client admitted on {} with token {} ({})",+ "web client admitted on {} with token {} ({peer_label})",site.describe,admission.token_id,- admission.label);let peer = ConnectionPeer::Web(WebPeer {token_id: admission.token_id.clone(),- label: admission.label.clone(),+ label: peer_label,username: site.username.clone(),revoked: admission.revoked.clone(),});diff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rsindex c2d136ff..192d1f0c 100644--- a/wezterm-mux-server/src/main.rs+++ b/wezterm-mux-server/src/main.rs@@ -338,6 +338,26 @@ fn run() -> anyhow::Result<()> {let executor = promise::spawn::SimpleExecutor::new();+ // The listener lives in this binary; the session handler that answers a+ // settings window lives in the impl crate, which cannot call up into+ // this one, so the controls are handed down here.+ //+ // Ahead of the branch below, and not inside `spawn_listener`, because+ // only the non-takeover path calls that. A server started with+ // `--takeover` -- which is what an in-place update does -- bound the+ // port from its own thread and then had no controls at all: the+ // settings switch read Off while browsers were connecting, pressing it+ // said there was no listener to turn off, and "Copy link" minted a+ // token, got no URL back and revoked the token it had just made.+ wezterm_mux_server_impl::web_control::install(+ wezterm_mux_server_impl::web_control::WebControl {+ start: web::spawn_web_listener,+ configure_tokens: web::configure_tokens,+ stop: web::stop_web_listener,+ listening: web::listening,+ },+ );+if takeover.is_none() {spawn_listener().map_err(|e| {log::error!("problem spawning listeners: {:?}", e);diff --git a/wezterm-mux-server/src/web.rs b/wezterm-mux-server/src/web.rsindex efc4a112..137024e9 100644--- a/wezterm-mux-server/src/web.rs+++ b/wezterm-mux-server/src/web.rs@@ -6,9 +6,11 @@ use async_ossl::AsyncSslStream;use config::WebServer;use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};use smol::Async;-use std::net::TcpListener;+use std::collections::BTreeMap;+use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, TcpListener, TcpStream};use std::path::PathBuf;-use std::sync::Arc;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};use std::time::Duration;use wezterm_mux_server_impl::web_auth::WEB_TOKENS;use wezterm_mux_server_impl::web_http::{serve, serve_seated, PreAuthSeat, WebSite};@@ -19,6 +21,66 @@ const TLS_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);/// How often expired tokens are swept and their connections dropped.const TOKEN_SWEEP_INTERVAL: Duration = Duration::from_secs(30);+/// The listeners that are up, and the flag that ends each one.+///+/// Stopping is two moves, because the accept loop blocks inside+/// `accept()` and owns its listener: raise the flag, then open one+/// connection to the port so the loop wakes and sees it. Dropping the+/// listener from another thread is not available to us.+static LISTENERS: Mutex<BTreeMap<String, Listening>> = Mutex::new(BTreeMap::new());++struct Listening {+ stop: Arc<AtomicBool>,+ /// The address `accept()` actually returned, not the configured+ /// string: an unspecified bind has to be woken through a real address.+ local: SocketAddr,+}++/// The bind addresses currently accepting, in configuration order.+pub fn listening() -> Vec<String> {+ LISTENERS.lock().map_or_else(|e| e.into_inner(), |g| g).keys().cloned().collect()+}++pub fn is_listening(bind_address: &str) -> bool {+ LISTENERS+ .lock()+ .map_or_else(|e| e.into_inner(), |g| g)+ .contains_key(bind_address)+}++/// The address to knock on to wake a blocking `accept`. A listener bound to+/// every address is not reachable *at* that address, so knock on loopback.+fn wake_address(local: SocketAddr) -> SocketAddr {+ if !local.ip().is_unspecified() {+ return local;+ }+ match local {+ SocketAddr::V4(_) => SocketAddr::from((Ipv4Addr::LOCALHOST, local.port())),+ SocketAddr::V6(_) => SocketAddr::from((Ipv6Addr::LOCALHOST, local.port())),+ }+}++/// Stop the listener on this address. `false` if nothing was listening.+///+/// The port is free once this returns: the loop is woken, sees the flag and+/// drops the listener before the knock is answered.+pub fn stop_web_listener(bind_address: &str) -> bool {+ let Some(entry) = LISTENERS+ .lock()+ .map_or_else(|e| e.into_inner(), |g| g)+ .remove(bind_address)+ else {+ return false;+ };+ entry.stop.store(true, Ordering::SeqCst);+ // The knock is refused by the loop, which is the point: it is only+ // there to return from `accept`. A failure here means nobody was+ // blocked on it any more, which is equally fine.+ let _ = TcpStream::connect_timeout(&wake_address(entry.local), Duration::from_secs(1));+ log::error!("stopped listening for web clients on {bind_address}");+ true+}+/// Point the token store at its file. One store serves every web listener,/// so the first entry's choice wins; the others are told.pub fn configure_tokens(servers: &[WebServer]) -> anyhow::Result<()> {@@ -39,12 +101,20 @@ pub fn configure_tokens(servers: &[WebServer]) -> anyhow::Result<()> {}// A token's lifetime ends when it says, whether or not anyone touches// the store again.- wezterm_mux_server_impl::connections::spawn(async {- loop {- smol::Timer::after(TOKEN_SWEEP_INTERVAL).await;- WEB_TOKENS.sweep();- }- });+ //+ // Once per process. This used to run at startup only; the settings+ // switch calls it again on every "on", and each of those left another+ //ever-running sweep behind -- more timers doing the same work, and one+ // more every time the switch is flipped.+ static SWEEPING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+ if !SWEEPING.swap(true, std::sync::atomic::Ordering::SeqCst) {+ wezterm_mux_server_impl::connections::spawn(async {+ loop {+ smol::Timer::after(TOKEN_SWEEP_INTERVAL).await;+ WEB_TOKENS.sweep();+ }+ });+ }Ok(())}@@ -144,25 +214,68 @@ pub fn spawn_web_listener(server: &WebServer) -> anyhow::Result<()> {let listener = TcpListener::bind(&server.bind_address).with_context(|| format!("binding web server to {}", server.bind_address))?;+ let local = listener+ .local_addr()+ .with_context(|| format!("reading the address of the web server on {}", server.bind_address))?;log::error!("listening for web clients on {}{}",server.bind_address,if acceptor.is_some() { " with TLS" } else { "" });- std::thread::Builder::new()+ let stop = Arc::new(AtomicBool::new(false));+ // Registered before the thread starts, so a stop that arrives in the+ // same breath as the start still finds it.+ LISTENERS.lock().map_or_else(|e| e.into_inner(), |g| g).insert(+ server.bind_address.clone(),+ Listening {+ stop: Arc::clone(&stop),+ local,+ },+ );+ let bind_address = server.bind_address.clone();+ match std::thread::Builder::new().name(format!("web-accept-{}", server.bind_address))- .spawn(move || accept_loop(listener, acceptor, site))- .context("spawning the web accept thread")?;- Ok(())+ .spawn(move || accept_loop(listener, acceptor, site, stop))+ {+ Ok(_) => {+ // The other half of `disconnect_all`, which stops admissions+ // when a listener goes down. Done here, on every path that+ // opens a port -- startup, the takeover thread, the settings+ // switch -- because an "off" that lands before the takeover's+ // listener is up would otherwise leave a port open on which+ // every token is refused.+ wezterm_mux_server_impl::web_auth::WEB_TOKENS.resume_admitting();+ Ok(())+ }+ Err(err) => {+ // Nothing is accepting, so nothing may claim to be.+ LISTENERS+ .lock()+ .map_or_else(|e| e.into_inner(), |g| g)+ .remove(&bind_address);+ Err(err).context("spawning the web accept thread")+ }+ }}/// How long the accept loop pauses after a failed accept. A refused/// peer costs nothing; an exhausted descriptor table would otherwise spin.const ACCEPT_RETRY: Duration = Duration::from_millis(100);-fn accept_loop(listener: TcpListener, acceptor: Option<SslAcceptor>, site: Arc<WebSite>) {+fn accept_loop(+ listener: TcpListener,+ acceptor: Option<SslAcceptor>,+ site: Arc<WebSite>,+ stop: Arc<AtomicBool>,+) {for stream in listener.incoming() {+ // Checked before the connection is looked at, so the knock that+ // woke us is dropped rather than served.+ if stop.load(Ordering::SeqCst) {+ log::info!("web accept loop for {} is done", site.describe);+ return;+ }let stream = match stream {Ok(stream) => stream,Err(err) => {diff --git a/wezterm/src/cli/mod.rs b/wezterm/src/cli/mod.rsindex 4c1870b9..b4dc7757 100644--- a/wezterm/src/cli/mod.rs+++ b/wezterm/src/cli/mod.rs@@ -22,6 +22,7 @@ mod set_window_title;mod spawn_command;mod split_pane;mod tls_creds;+mod web_server;mod web_token;mod zoom_pane;@@ -94,6 +95,10 @@ enum CliSubCommand {#[command(name = "web-token", rename_all = "kebab")]WebToken(web_token::WebTokenCommand),+ /// Turn the browser listener on and off, and see where it is accepting+ #[command(name = "web-server", rename_all = "kebab")]+ WebServer(web_server::WebServerCommand),+#[command(name = "move-pane-to-new-tab",rename_all = "kebab",@@ -210,6 +215,7 @@ async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()>CliSubCommand::SpawnCommand(cmd) => cmd.run(client, &crate::init_config(opts)?).await,CliSubCommand::Proxy(cmd) => cmd.run(client, &crate::init_config(opts)?).await,CliSubCommand::TlsCreds(cmd) => cmd.run(client).await,+ CliSubCommand::WebServer(cmd) => cmd.run(client).await,CliSubCommand::WebToken(cmd) => cmd.run(client).await,CliSubCommand::ActivatePaneDirection(cmd) => cmd.run(client).await,CliSubCommand::GetPaneDirection(cmd) => cmd.run(client).await,diff --git a/wezterm/src/cli/web_server.rs b/wezterm/src/cli/web_server.rsnew file mode 100644index 00000000..84e370dc--- /dev/null+++ b/wezterm/src/cli/web_server.rs@@ -0,0 +1,107 @@+//! `thinkterm cli web-server …`: turn the browser listener on and off, and+//! see where it is accepting.+//!+//! The port is bound by the mux server, so this is the only way to change+//! it without restarting one: `web_servers` in the configuration is read at+//! startup and nothing re-reads it.++use anyhow::bail;+use clap::Parser;+use wezterm_client::client::Client;++#[derive(Debug, Parser, Clone)]+pub struct WebServerCommand {+ #[command(subcommand)]+ sub: WebServerSubCommand,+}++#[derive(Debug, Parser, Clone)]+enum WebServerSubCommand {+ /// Show whether the server is accepting browser clients, and where.+ #[command(name = "status")]+ Status,++ /// Start accepting browser clients.+ ///+ /// Nobody gets in without a token: mint one with+ /// `thinkterm cli web-token mint`.+ #[command(name = "on")]+ On(OnCommand),++ /// Stop accepting browser clients and close the port.+ ///+ /// Live browsers lose their connection. Tokens are left alone; revoke+ /// them separately if that is what you meant.+ #[command(name = "off")]+ Off,+}++#[derive(Debug, Parser, Clone)]+struct OnCommand {+ /// The address to listen on, such as `127.0.0.1:8088`. Defaults to the+ /// first `web_servers` entry in the server's configuration.+ ///+ /// An address that is in the configuration brings its TLS, allowed+ /// origins and bundle directory with it; one that is not gets the+ /// defaults, which is loopback-only and plain HTTP.+ #[arg(long)]+ bind_address: Option<String>,+}++fn report(status: &codec::WebServerStatus) {+ if status.listening.is_empty() {+ println!("not accepting browser clients");+ } else {+ for address in &status.listening {+ println!("accepting browser clients on {address}");+ }+ for url in &status.urls {+ println!(" {url}");+ }+ if status.urls.is_empty() {+ // Listening on an address the configuration does not name, so+ // there is no `urls()` to build one from.+ println!(" (no page URL: this address is not in web_servers)");+ }+ }+ let extra: Vec<&String> = status+ .configured+ .iter()+ .filter(|address| !status.listening.contains(address))+ .collect();+ for address in extra {+ println!("configured but not accepting: {address}");+ }+}++impl WebServerCommand {+ pub async fn run(&self, client: Client) -> anyhow::Result<()> {+ match &self.sub {+ WebServerSubCommand::Status => {+ report(&client.get_web_server_status().await?);+ }+ WebServerSubCommand::On(cmd) => {+ let status = client+ .set_web_server(codec::SetWebServer {+ enabled: true,+ bind_address: cmd.bind_address.clone(),+ })+ .await?;+ if status.listening.is_empty() {+ bail!("the server did not start a web listener");+ }+ report(&status);+ }+ WebServerSubCommand::Off => {+ let status = client+ .set_web_server(codec::SetWebServer {+ enabled: false,+ bind_address: None,+ })+ .await?;+ report(&status);+ }+ }+ Ok(())+ }+}diff --git a/wezterm/src/cli/web_token.rs b/wezterm/src/cli/web_token.rsindex 76ca493c..a4b53d8b 100644--- a/wezterm/src/cli/web_token.rs+++ b/wezterm/src/cli/web_token.rs@@ -134,7 +134,10 @@ impl MintCommand {}return Ok(());}- println!("Token {} ({}) minted.", minted.id, minted.label);+ match &minted.label {+ Some(label) => println!("Token {} ({label}) minted.", minted.id),+ None => println!("Token {} minted.", minted.id),+ }match minted.expires_at {Some(at) => println!("Expires {}.", local_time(at)),None => println!("Does not expire; revoke it with `thinkterm cli web-token revoke {}`.", minted.id),@@ -159,10 +162,12 @@ impl MintCommand {#[derive(serde::Serialize)]struct CliWebTokenItem {id: String,- label: String,+ label: Option<String>,created_at: u64,expires_at: Option<u64>,last_used_at: Option<u64>,+ /// What the browser said it was, last time this link was used.+ last_device: Option<String>,live_connections: u32,}@@ -181,6 +186,7 @@ impl ListCommand {created_at: t.created_at,expires_at: t.expires_at,last_used_at: t.last_used_at,+ last_device: t.last_device,live_connections: t.live_connections,}).collect();@@ -191,6 +197,7 @@ impl ListCommand {let columns = [Column { name: "ID".into(), alignment: Alignment::Left },Column { name: "LABEL".into(), alignment: Alignment::Left },+ Column { name: "LAST DEVICE".into(), alignment: Alignment::Left },Column { name: "CREATED".into(), alignment: Alignment::Left },Column { name: "EXPIRES".into(), alignment: Alignment::Left },Column { name: "LAST USED".into(), alignment: Alignment::Left },@@ -202,7 +209,8 @@ impl ListCommand {.map(|t| {vec![t.id.clone(),- t.label.clone(),+ t.label.clone().unwrap_or_else(|| "-".into()),+ t.last_device.clone().unwrap_or_else(|| "-".into()),local_time(t.created_at),t.expires_at.map(local_time).unwrap_or_else(|| "never".into()),t.last_used_at.map(local_time).unwrap_or_else(|| "-".into()),