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
security: migrate Windows credentials without losing local state
RoversX7bc997c28109
diff --git a/config/Cargo.toml b/config/Cargo.tomlindex 369d2387..a2b464a4 100644--- a/config/Cargo.toml+++ b/config/Cargo.toml@@ -9,12 +9,12 @@ publish = false[dev-dependencies]env_logger.workspace = true-tempfile.workspace = true[features]distro-defaults = [][dependencies]+tempfile.workspace = trueif-addrs.workspace = truewezterm-color-types.workspace = trueanyhow.workspace = truediff --git a/config/src/config.rs b/config/src/config.rsindex c5844bf1..f66d261b 100644--- a/config/src/config.rs+++ b/config/src/config.rs@@ -1989,6 +1989,23 @@ pub(crate) fn compute_data_dir() -> anyhow::Result<PathBuf> {Ok(data_dir)}+/// Resolve the web listener's private files outside a Windows roaming profile.+/// Failure is propagated so callers cannot silently generate a new identity.+pub fn local_data_path(item: &str) -> anyhow::Result<PathBuf> {+ #[cfg(windows)]+ {+ let local = dirs_next::data_local_dir()+ .ok_or_else(|| anyhow::anyhow!("cannot locate local application data"))?+ .join(PRODUCT_DIR_NAME).join(item);+ crate::migrate_private_files(+ &crate::DATA_DIR.join(item), &local, &["cert.pem", "key.pem", "sans.txt"],+ )?;+ return Ok(local);+ }+ #[cfg(not(windows))]+ Ok(crate::DATA_DIR.join(item))+}+pub(crate) fn compute_runtime_dir() -> anyhow::Result<PathBuf> {if let Some(runtime) = dirs_next::runtime_dir() {return Ok(runtime.join(PRODUCT_DIR_NAME));diff --git a/config/src/lib.rs b/config/src/lib.rsindex 9287d60f..a4cc6ef1 100644--- a/config/src/lib.rs+++ b/config/src/lib.rs@@ -33,6 +33,8 @@ pub mod keyassignment;mod keys;pub mod lua;pub mod meta;+mod private_data;+pub use private_data::migrate_private_files;pub mod scheme_data;mod thinkterm_schemes;mod serial;diff --git a/config/src/private_data.rs b/config/src/private_data.rsnew file mode 100644index 00000000..0904e684--- /dev/null+++ b/config/src/private_data.rs@@ -0,0 +1,107 @@+use anyhow::{bail, Context, Result};+use std::fs;+use std::path::Path;+use std::sync::Mutex;++/// Copy a related set of private files across volumes, publish the directory+/// atomically, then remove the old copies. Never mix an existing destination+/// with a source key/catalog pair or fall back to roaming on failure.+pub fn migrate_private_files(from: &Path, to: &Path, files: &[&str]) -> Result<()> {+ static MIGRATION: Mutex<()> = Mutex::new(());+ let _lock = MIGRATION.lock().unwrap_or_else(|err| err.into_inner());+ if from == to {+ return Ok(());+ }+ if !to.try_exists()? {+ let parent = to+ .parent()+ .context("private data directory has no parent")?;+ crate::create_user_owned_dirs(parent)?;+ let staging = tempfile::Builder::new()+ .prefix(".private-migration-")+ .tempdir_in(parent)?;+ for name in files {+ let source = from.join(name);+ if source.try_exists()? {+ let target = staging.path().join(name);+ fs::copy(&source, &target).with_context(|| format!("copy private file {name}"))?;+ fs::File::open(&target)?.sync_all()?;+ }+ }+ fs::rename(staging.path(), to).context("publish migrated private data")?;+ }+ // Check the entire group before deleting any old file. This also safely+ // resumes cleanup after a previous run published the directory but stopped.+ for name in files {+ let source = from.join(name);+ if source.try_exists()? && fs::read(&source)? != fs::read(to.join(name))? {+ bail!("private data migration conflict for {name}; preserve both copies for recovery");+ }+ }+ for name in files {+ let source = from.join(name);+ if source.try_exists()? {+ fs::remove_file(source).with_context(|| format!("remove roaming copy of {name}"))?;+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn private_migration_preserves_pairs_and_unrelated_gui_state() {+ let dir = tempfile::tempdir().unwrap();+ let from = dir.path().join("roaming");+ let to = dir.path().join("local/ssh");+ fs::create_dir(&from).unwrap();+ for (name, value) in [+ ("secret.key", "key"),+ ("ssh_hosts.json", "catalog"),+ ("workspace_threads.json", "workspace"),+ ("snippets.json", "snippets"),+ ] {+ fs::write(from.join(name), value).unwrap();+ }+ let files = &["secret.key", "ssh_hosts.json"];+ migrate_private_files(&from, &to, files).unwrap();+ migrate_private_files(&from, &to, files).unwrap();+ assert_eq!(fs::read(to.join("secret.key")).unwrap(), b"key");+ assert_eq!(fs::read(to.join("ssh_hosts.json")).unwrap(), b"catalog");+ assert!(!from.join("secret.key").exists());+ assert!(!from.join("ssh_hosts.json").exists());+ assert!(from.join("workspace_threads.json").is_file());+ assert!(from.join("snippets.json").is_file());+ }++ #[test]+ fn private_migration_does_not_publish_a_partial_pair() {+ let dir = tempfile::tempdir().unwrap();+ let from = dir.path().join("roaming");+ let to = dir.path().join("local/ssh");+ fs::create_dir(&from).unwrap();+ fs::write(from.join("secret.key"), "key").unwrap();+ fs::create_dir(from.join("ssh_hosts.json")).unwrap();+ assert!(migrate_private_files(&from, &to, &["secret.key", "ssh_hosts.json"]).is_err());+ assert!(!to.exists());+ assert!(from.join("secret.key").is_file());+ }++ #[test]+ fn private_migration_refuses_conflicting_destinations() {+ let dir = tempfile::tempdir().unwrap();+ let from = dir.path().join("roaming");+ let to = dir.path().join("local");+ fs::create_dir(&from).unwrap();+ fs::create_dir(&to).unwrap();+ fs::write(from.join("secret.key"), "old").unwrap();+ fs::write(to.join("secret.key"), "new").unwrap();+ fs::write(from.join("ssh_hosts.json"), "catalog").unwrap();+ assert!(migrate_private_files(&from, &to, &["secret.key", "ssh_hosts.json"]).is_err());+ assert_eq!(fs::read(from.join("secret.key")).unwrap(), b"old");+ assert_eq!(fs::read(to.join("secret.key")).unwrap(), b"new");+ assert!(!to.join("ssh_hosts.json").exists());+ }+}diff --git a/thinkterm-core/src/lib.rs b/thinkterm-core/src/lib.rsindex 323cade4..67ed5d6e 100644--- a/thinkterm-core/src/lib.rs+++ b/thinkterm-core/src/lib.rs@@ -15,6 +15,24 @@ pub fn frontend_data_dir() -> std::path::PathBuf {.join("ThinkTerm")}+/// Keep credentials local without moving unrelated workspace/snippet state.+/// Publish the key and catalog together; a migration error must not create a+/// replacement key or an empty catalog in a different location.+pub fn credential_data_dir() -> anyhow::Result<std::path::PathBuf> {+ #[cfg(windows)]+ {+ let local = dirs_next::data_local_dir()+ .ok_or_else(|| anyhow::anyhow!("cannot locate local application data"))?+ .join("ThinkTerm").join("ssh");+ config::migrate_private_files(+ &frontend_data_dir(), &local, &["secret.key", "ssh_hosts.json"],+ )?;+ return Ok(local);+ }+ #[cfg(not(windows))]+ Ok(frontend_data_dir())+}+#[cfg(test)]mod tests {#[test]diff --git a/thinkterm-core/src/secret.rs b/thinkterm-core/src/secret.rsindex 208deb4d..419288a3 100644--- a/thinkterm-core/src/secret.rs+++ b/thinkterm-core/src/secret.rs@@ -12,12 +12,12 @@ const MARKER: &str = "enc:v1:";const IV_LEN: usize = 12;const TAG_LEN: usize = 16;-fn key_path() -> std::path::PathBuf {- crate::frontend_data_dir().join("secret.key")+fn key_path() -> Result<std::path::PathBuf> {+ Ok(crate::credential_data_dir()?.join("secret.key"))}fn load_or_create_key() -> Result<[u8; 32]> {- load_or_create_key_at(&key_path())+ load_or_create_key_at(&key_path()?)}fn load_or_create_key_at(path: &Path) -> Result<[u8; 32]> {diff --git a/thinkterm-core/src/ssh_hosts.rs b/thinkterm-core/src/ssh_hosts.rsindex b02a6157..72039119 100644--- a/thinkterm-core/src/ssh_hosts.rs+++ b/thinkterm-core/src/ssh_hosts.rs@@ -74,12 +74,12 @@ struct SshHostStore {hosts: Vec<SshHostRecord>,}-pub fn saved_hosts_path() -> std::path::PathBuf {- crate::frontend_data_dir().join("ssh_hosts.json")+pub fn saved_hosts_path() -> Result<std::path::PathBuf> {+ Ok(crate::credential_data_dir()?.join("ssh_hosts.json"))}pub fn list_saved_hosts() -> Result<Vec<SshHostEntry>> {- list_saved_hosts_from_path(&saved_hosts_path())+ list_saved_hosts_from_path(&saved_hosts_path()?)}pub fn list_saved_hosts_from_path(path: &Path) -> Result<Vec<SshHostEntry>> {diff --git a/wezterm-gui/src/ssh_hosts.rs b/wezterm-gui/src/ssh_hosts.rsindex d73a6a62..df4106bf 100644--- a/wezterm-gui/src/ssh_hosts.rs+++ b/wezterm-gui/src/ssh_hosts.rs@@ -54,19 +54,34 @@ fn store_version() -> u32 {}lazy_static::lazy_static! {- static ref SSH_HOST_STORE: Mutex<SshHostStore> =- Mutex::new(load_ssh_host_store().unwrap_or_else(|err| {- log::warn!("failed to load ThinkTerm SSH host store: {err:#}");- SshHostStore::default()- }));+ static ref SSH_HOST_STORE: Mutex<Option<SshHostStore>> = Mutex::new(None);}-pub fn ssh_hosts_store_path() -> PathBuf {- crate::native_paths::data_file("ssh_hosts.json")+fn ensure_store_loaded(+ cached: &mut Option<SshHostStore>,+ load: impl FnOnce() -> Result<SshHostStore>,+) -> Result<()> {+ if cached.is_none() {+ *cached = Some(load()?);+ }+ Ok(())+}++fn host_store() -> Result<parking_lot::MappedMutexGuard<'static, SshHostStore>> {+ let mut store = SSH_HOST_STORE.lock();+ ensure_store_loaded(&mut store, load_ssh_host_store).map_err(|err| {+ log::warn!("failed to load ThinkTerm SSH host store: {err:#}");+ err+ })?;+ Ok(parking_lot::MutexGuard::map(store, |store| store.as_mut().unwrap()))+}++pub fn ssh_hosts_store_path() -> Result<PathBuf> {+ thinkterm_core::ssh_hosts::saved_hosts_path()}fn load_ssh_host_store() -> Result<SshHostStore> {- load_ssh_host_store_from_path(&ssh_hosts_store_path())+ load_ssh_host_store_from_path(&ssh_hosts_store_path()?)}fn load_ssh_host_store_from_path(path: &Path) -> Result<SshHostStore> {@@ -78,7 +93,7 @@ fn load_ssh_host_store_from_path(path: &Path) -> Result<SshHostStore> {}fn save_ssh_host_store(store: &SshHostStore) -> Result<()> {- save_ssh_host_store_to_path(&ssh_hosts_store_path(), store)+ save_ssh_host_store_to_path(&ssh_hosts_store_path()?, store)}fn save_ssh_host_store_to_path(path: &Path, store: &SshHostStore) -> Result<()> {@@ -108,7 +123,7 @@ fn save_ssh_host_store_to_path(path: &Path, store: &SshHostStore) -> Result<()>}pub fn list_hosts() -> Vec<(SshHostId, SshHostSpec)> {- let store = SSH_HOST_STORE.lock();+ let Ok(store) = host_store() else { return vec![]; };store.hosts.iter()@@ -130,8 +145,7 @@ pub fn list_all_hosts() -> Vec<SshHostEntry> {}pub fn host_spec(host_id: &str) -> Option<SshHostSpec> {- {- let store = SSH_HOST_STORE.lock();+ if let Ok(store) = host_store() {if let Some(record) = store.hosts.iter().find(|record| record.id == host_id) {return Some(record.spec.clone());}@@ -143,11 +157,7 @@ pub fn host_spec(host_id: &str) -> Option<SshHostSpec> {}pub fn host_exists(host_id: &str) -> bool {- SSH_HOST_STORE- .lock()- .hosts- .iter()- .any(|record| record.id == host_id)+ host_store().map(|store| store.hosts.iter().any(|record| record.id == host_id)).unwrap_or(false)}pub fn try_create_host(spec: SshHostSpec) -> Result<SshHostId> {@@ -156,7 +166,7 @@ pub fn try_create_host(spec: SshHostSpec) -> Result<SshHostId> {// host already uses used to overwrite that host's whole record -- its// saved password included -- and leave one card behind wearing the new// name.- if host_exists(&host_id_for_host(&spec)) {+ if host_store()?.hosts.iter().any(|record| record.id == host_id_for_host(&spec)) {bail!("a saved host already uses {}", endpoint(&spec));}let (host_id, spec) = upsert_host(spec)?;@@ -165,7 +175,7 @@ pub fn try_create_host(spec: SshHostSpec) -> Result<SshHostId> {}pub fn try_import_legacy_host(spec: SshHostSpec) -> Result<SshHostId> {- let mut store = SSH_HOST_STORE.lock();+ let mut store = host_store()?;let host_id = host_id_for_host(&spec);if store.hosts.iter().any(|record| record.id == host_id) {return Ok(host_id);@@ -179,7 +189,7 @@ pub fn try_import_legacy_host(spec: SshHostSpec) -> Result<SshHostId> {}fn upsert_host(spec: SshHostSpec) -> Result<(SshHostId, SshHostSpec)> {- let mut store = SSH_HOST_STORE.lock();+ let mut store = host_store()?;let host_id = host_id_for_host(&spec);if let Some(record) = store.hosts.iter_mut().find(|record| record.id == host_id) {record.spec = spec;@@ -208,7 +218,7 @@ pub fn try_update_host(host_id: &str, spec: SshHostSpec) -> Result<Option<SshHosif is_system_host_id(host_id) {return Ok(None);}- let mut store = SSH_HOST_STORE.lock();+ let mut store = host_store()?;// The same invariant `try_create_host` enforces, and for the same reason:// one record per endpoint. Editing a host onto an endpoint another record// already owns would leave two records dialing it, both registering a@@ -239,7 +249,7 @@ pub fn try_remove_host(host_id: &str) -> Result<bool> {if is_system_host_id(host_id) {return Ok(false);}- let mut store = SSH_HOST_STORE.lock();+ let mut store = host_store()?;let before = store.hosts.len();store.hosts.retain(|record| record.id != host_id);if store.hosts.len() == before {@@ -253,7 +263,7 @@ pub fn set_host_distro(host_id: &str, distro_id: &str) -> bool {if is_system_host_id(host_id) {return false;}- let mut store = SSH_HOST_STORE.lock();+ let Ok(mut store) = host_store() else { return false; };let Some(record) = store.hosts.iter_mut().find(|record| record.id == host_id) else {return false;};@@ -746,6 +756,24 @@ fn system_host_id(alias: &str) -> SshHostId {mod tests {use super::*;+ #[test]+ fn a_failed_catalog_load_is_retried_before_editing() {+ let mut cached = None;+ assert!(ensure_store_loaded(&mut cached, || anyhow::bail!("migration cleanup temporarily failed")).is_err());+ assert!(cached.is_none());+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("ssh_hosts.json");+ let original = SshHostRecord { id: "original".into(), spec: spec_with_options(HashMap::new()) };+ save_ssh_host_store_to_path(&path, &SshHostStore { version: 1, hosts: vec![original.clone()] }).unwrap();+ ensure_store_loaded(&mut cached, || load_ssh_host_store_from_path(&path)).unwrap();+ let store = cached.as_mut().unwrap();+ store.hosts.push(SshHostRecord { id: "new".into(), ..original });+ save_ssh_host_store_to_path(&path, store).unwrap();+ let saved = load_ssh_host_store_from_path(&path).unwrap();+ assert_eq!(saved.hosts.len(), 2);+ assert_eq!(saved.hosts[0].id, "original");+ }+#[test]fn system_hosts_preserve_ssh_config_alias_as_remote_address() {let entries = parse_system_ssh_config_str(diff --git a/wezterm-mux-server-impl/src/web_tls.rs b/wezterm-mux-server-impl/src/web_tls.rsindex 0697534a..4df67e81 100644--- a/wezterm-mux-server-impl/src/web_tls.rs+++ b/wezterm-mux-server-impl/src/web_tls.rs@@ -19,8 +19,9 @@ pub struct WebTls {pub generated: bool,}-fn dir() -> PathBuf {- config::DATA_DIR.join("web-tls")+fn dir() -> anyhow::Result<PathBuf> {+ // The private key must not leave this machine with a roaming profile.+ config::local_data_path("web-tls")}fn names(addresses: &[IpAddr]) -> (Vec<String>, Vec<IpAddr>) {@@ -62,7 +63,7 @@ fn write_private(path: &Path, bytes: &[u8]) -> anyhow::Result<()> {/// The listener's certificate: the stored one when it still names every/// address the machine has, else a fresh one.pub fn ensure(addresses: &[IpAddr]) -> anyhow::Result<WebTls> {- let dir = dir();+ let dir = dir()?;std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;let cert_path = dir.join("cert.pem");let key_path = dir.join("key.pem");