Skip to content

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.

web server: self-signed https, LAN and Tailscale URLs, QR code

RoversXcc6a43b10450
diff --git a/config/Cargo.toml b/config/Cargo.toml
index 47fff60e..369d2387 100644
--- a/config/Cargo.toml
+++ b/config/Cargo.toml
@@ -15,6 +15,7 @@ tempfile.workspace = true
distro-defaults = []
[dependencies]
+if-addrs.workspace = true
wezterm-color-types.workspace = true
anyhow.workspace = true
bitflags.workspace = true
diff --git a/config/src/web.rs b/config/src/web.rs
index 2305393f..11d56f23 100644
--- a/config/src/web.rs
+++ b/config/src/web.rs
@@ -108,6 +108,42 @@ pub fn default_port(scheme: &str) -> Option<u16> {
}
}
+/// Whether an address is on a Tailscale network (CGNAT 100.64/10, or its
+/// IPv6 prefix): worth naming first, since it reaches the machine from
+/// anywhere the tailnet does.
+pub fn is_tailscale(ip: &std::net::IpAddr) -> bool {
+ match ip {
+ std::net::IpAddr::V4(v4) => {
+ let o = v4.octets();
+ o[0] == 100 && (64..128).contains(&o[1])
+ }
+ std::net::IpAddr::V6(v6) => {
+ let s = v6.segments();
+ s[0] == 0xfd7a && s[1] == 0x115c && s[2] == 0xa1e0
+ }
+ }
+}
+
+/// The machine's addresses a browser elsewhere can reach: every interface
+/// address that is not loopback or link-local, Tailscale ones first, then
+/// IPv4 before IPv6. Empty when the interfaces cannot be listed.
+pub fn local_addresses() -> Vec<std::net::IpAddr> {
+ use std::net::IpAddr;
+ let mut addrs: Vec<IpAddr> = if_addrs::get_if_addrs()
+ .map(|list| list.into_iter().map(|i| i.ip()).collect())
+ .unwrap_or_default();
+ addrs.retain(|ip| match ip {
+ IpAddr::V4(v4) => !v4.is_loopback() && !v4.is_link_local() && !v4.is_unspecified(),
+ IpAddr::V6(v6) => {
+ let s = v6.segments();
+ !v6.is_loopback() && !v6.is_unspecified() && (s[0] & 0xffc0) != 0xfe80
+ }
+ });
+ addrs.sort_by_key(|ip| (!is_tailscale(ip), ip.is_ipv6(), *ip));
+ addrs.dedup();
+ addrs
+}
+
/// A name that can only ever mean this machine.
pub fn is_loopback_host(host: &str) -> bool {
match host.parse::<std::net::IpAddr>() {
@@ -186,9 +222,16 @@ impl WebServer {
}
/// The `host[:port]` values a browser will send in `Host:` and use in
- /// a URL. A loopback listener answers to both spellings of itself.
- /// A scheme's default port is left out, as a browser leaves it out.
+ /// a URL. A loopback listener answers to both spellings of itself; a
+ /// listener bound everywhere to the loopback spellings and every
+ /// address the machine has. A scheme's default port is left out, as
+ /// a browser leaves it out.
pub fn url_hosts(&self) -> Vec<String> {
+ self.url_hosts_with(&local_addresses())
+ }
+
+ /// `url_hosts` given the machine's addresses.
+ pub fn url_hosts_with(&self, addresses: &[std::net::IpAddr]) -> Vec<String> {
let (host, port) = self.host_and_port();
let shown = port.filter(|p| Some(*p) != default_port(self.scheme()));
let with_port = |h: &str| match shown {
@@ -204,11 +247,23 @@ impl WebServer {
hosts.push(with_port("[::1]"));
}
Some(ip) if ip.is_unspecified() => {
- // Bound everywhere: any name reaches it, and the listener
- // cannot enumerate them. Loopback spellings at least.
+ // Bound everywhere: the loopback spellings, then every
+ // address the machine has (names it may also have are
+ // not ours to guess; `allowed_origins` lists those).
hosts.push(with_port("127.0.0.1"));
hosts.push(with_port("localhost"));
hosts.push(with_port("[::1]"));
+ for addr in addresses {
+ if addr.is_ipv6() && ip.is_ipv4() {
+ // An IPv4 bind does not answer on IPv6 addresses.
+ continue;
+ }
+ let spelled = match addr {
+ std::net::IpAddr::V6(v6) => format!("[{v6}]"),
+ std::net::IpAddr::V4(v4) => v4.to_string(),
+ };
+ hosts.push(with_port(&spelled));
+ }
}
Some(std::net::IpAddr::V6(v6)) => hosts.push(with_port(&format!("[{v6}]"))),
_ => hosts.push(with_port(&host)),
@@ -266,6 +321,20 @@ mod tests {
);
}
+ #[test]
+ fn a_listener_bound_everywhere_names_the_machine_s_addresses() {
+ let server = WebServer { bind_address: "0.0.0.0:8443".into(), ..WebServer::default() };
+ let addrs = vec!["192.168.1.7".parse().unwrap(), "100.100.5.5".parse().unwrap(), "fd7a:115c:a1e0::1".parse().unwrap()];
+ assert_eq!(
+ server.url_hosts_with(&addrs),
+ vec!["127.0.0.1:8443", "localhost:8443", "[::1]:8443", "192.168.1.7:8443", "100.100.5.5:8443"]
+ );
+ let v6 = WebServer { bind_address: "[::]:8443".into(), ..WebServer::default() };
+ assert!(v6.url_hosts_with(&addrs).contains(&"[fd7a:115c:a1e0::1]:8443".to_string()));
+ assert!(is_tailscale(&"100.100.5.5".parse().unwrap()));
+ assert!(!is_tailscale(&"192.168.1.7".parse().unwrap()));
+ }
+
#[test]
fn a_named_host_with_tls_is_https_and_only_itself() {
let server = WebServer {
diff --git a/docs/thinkterm/web-access.md b/docs/thinkterm/web-access.md
index 1c3b4d3c..a33cd81c 100644
--- a/docs/thinkterm/web-access.md
+++ b/docs/thinkterm/web-access.md
@@ -63,11 +63,13 @@ machine; anyone holding it can open a shell and read every pane. Revoking a
token drops the browsers it admitted at once. The server keeps digests only,
so a copied token file reveals nothing.
-## Reaching a remote server
+## Reaching a remote server, or this one from a phone
-The recommended way to use a server on another machine is to keep it on
-loopback and forward the port over ssh, which makes it a loopback origin on
-your side too and needs no certificate:
+Two ways, and both end with the page in a secure context, which is what a
+browser needs before it exposes WebGPU.
+
+**Over ssh** (nothing to trust): keep the listener on loopback and forward
+the port, which makes it a loopback origin on your side too:
```console
$ ssh -L 8088:127.0.0.1:8088 server.hostname
@@ -77,18 +79,82 @@ $ thinkterm cli --prefer-mux web-token mint # on the server, or over ssh
The local port need not match: with `ssh -L 9000:127.0.0.1:8088` the page is
at `http://localhost:9000/`, and a loopback listener accepts any loopback
name on any port, because the port a forward uses is the client's choice.
-Put the minted URL's token fragment on that address. A listener that is
-reached under some other name (a reverse proxy, a non-loopback bind) must
-list that name in `allowed_origins`; the minted URLs then point there.
+Put the minted URL's token fragment on that address.
+
+**Directly, over https** (a phone on the same Wi-Fi, a tailnet, a LAN):
+bind the listener to every address --
+
+```console
+$ thinkterm cli --prefer-mux web-server on --bind-address 0.0.0.0:8088
+$ thinkterm cli --prefer-mux web-token mint
+```
-Serving TLS directly needs a certificate the browser trusts; the server's own
-TLS PKI is regenerated every time it starts and is not suitable for that.
+-- and the server makes itself a certificate: self-signed, for the
+machine's hostname and every address it has, kept under
+`~/.local/share/thinkterm/web-tls/` and remade only when an address it
+does not name appears. `mint` then prints one URL per address, Tailscale
+ones first, and `--url-only` picks the first that another device can use.
+The browser warns once about the certificate; continuing puts the page in
+a secure context. Two things to know: a name or address the machine gains
+later is not in the certificate until the server restarts, and iOS Safari
+has been known to refuse the WebSocket behind a certificate it was told to
+continue past -- if the page attaches on a laptop but not on the phone,
+that is why, and the ssh forward or a certificate the phone trusts (set
+`pem_cert`/`pem_private_key` to one) are the ways around it.
+
+A listener that is reached under some other name (a reverse proxy) must
+list that name in `allowed_origins`; the minted URLs then point there. A
+non-loopback listener with `require_tls_off_loopback = false` serves plain
+http and no certificate is made; a browser reaching it has no WebGPU.
+
+## The page's chrome
+
+Everything around the terminal is the model's data drawn by the page:
+the Rust side (`thinkterm-web/src/{tree,menu,palette,settings,agents}.rs`)
+decides what the sidebar lists, what a context menu offers, what the
+search finds and what a pick does; the Svelte page (`thinkterm-web/ui`)
+only draws it and hands clicks back. A native client draws the same data
+with its own widgets.
+
+- **Spaces.** The sidebar shows one Space; the `…` beside its name lists
+ the others, makes a new one, renames or deletes the current one (never the
+ last). The page remembers the Space it was showing.
+- **Context menus** on a pane (copy, paste, the four splits, the frontend
+ access mode), a tab (close the tabs to the left/right/others, a new tab,
+ zoom), a thread (pin, rename, delete, mark unread), a project (rename,
+ new thread, collapse, archive -- with a warning when it would end
+ programs -- remove) and an archived project (unarchive, delete for good).
+ Tab rename/move and Reset Terminal have no server operation and are not
+ offered.
+- **Search** (Cmd+K, or Ctrl+Shift+P; the shortcut is a setting): threads
+ in every Space, this window's tabs and panes, Spaces, and commands, ranked
+ as the desktop's palette ranks them, recent picks first for an empty query.
+- **Settings** (the gear): language (the desktop's catalogues, now under
+ `thinkterm-i18n/`, English, 简体中文, 日本語, Français, Deutsch), theme
+ (dark, light, follow the system), font size (follow the desktop's cell, or
+ a fixed size), sidebar hover reveal, the Agents panel, the search
+ shortcut. Kept in this browser's storage; the URL's `?lang=`, `?theme=`
+ and `?font=` override them for one load.
+- **Agents panel** (right, toggle at the tab row's end): one row per pane an
+ agent runs in, with its state, as the desktop's panel shows them; a row
+ brings that pane on show.
+- **Phone.** A coarse pointer or a narrow window puts the page in its phone
+ layout: the sidebar and the Agents panel become drawers, a key bar above
+ the soft keyboard carries Esc, Tab, sticky Ctrl/Alt, the arrows, Home/End,
+ PgUp/PgDn and the symbols a shell wants, a finger scrolls, a long press
+ opens the pane's menu. Reach the server over https first (above).
## Building and serving the bundle
`ci/build-web.sh` builds `thinkterm-web` for `wasm32-unknown-unknown`, runs
-`wasm-bindgen` (the CLI must match the version pinned in `Cargo.toml`) and
-copies the fonts into `thinkterm-web/www`. The release workflow builds it once
+`wasm-bindgen` (the CLI must match the version pinned in `Cargo.toml`),
+copies the fonts into `thinkterm-web/www`, and builds the page around the
+terminal from `thinkterm-web/ui` with Vite (Svelte 5 and TypeScript; Node 22
+or newer with npm is needed, `npm ci` runs from the committed lockfile).
+The page is only the chrome -- the tab row, the pane bars, the sidebar, the
+toasts -- and reads what it shows from the wasm through the `Client` handle
+`start()` returns; the terminal itself is the canvas, untouched by it.
+`npm run check` in `thinkterm-web/ui` type-checks the page. The release workflow builds it once
and every package carries that directory: `share/thinkterm/web` in the
tarballs, deb and rpm, `Contents/Resources/web` in the macOS app, `web` beside
the executables on Windows. Those are where the server looks by default;
@@ -106,7 +172,10 @@ every pane like the desktop's pane nav bar (the pane's capsule with its
title -- a bare shell is "Terminal" -- and, on the right, new tab, split
down, split right and zoom; a stack's members are its capsules), and on the
left the sidebar described below. The palette is the desktop's dark set;
-`?theme=light` picks the other. There is no status line: refusals and
+`?theme=light` picks the other. The page speaks the desktop's languages
+(the catalogues in `thinkterm-i18n/i18n/`, shared with the desktop): the
+browser's own language list picks one, `?lang=de-DE` picks for this load.
+There is no status line: refusals and
reconnects are a passing remark at the bottom right, and a page that does
not hold the terminal in Handoff mode sees the desktop's card ("Terminal is
being used on another device -- Click or scroll to continue") over the
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index 1fd2882d..b232cc35 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -432,11 +432,15 @@ pub(crate) const DEFAULT_WEB_LINK_TTL_SECS: u64 = 8 * 60 * 60;
pub(crate) struct NativeWebSettings {
/// Seconds, or `None` for "until revoked".
pub(crate) link_ttl_secs: Option<u64>,
+ /// Listen on every address (with the server's own certificate) rather
+ /// than loopback only, so a phone can reach it.
+ pub(crate) reachable: bool,
}
impl Default for NativeWebSettings {
fn default() -> Self {
Self {
+ reachable: false,
link_ttl_secs: Some(DEFAULT_WEB_LINK_TTL_SECS),
}
}
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index 21903a85..2b61ed77 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -802,6 +802,10 @@ enum SettingsAction {
SetWebLinkTtl(Option<u64>),
/// Mint a link and put it straight on the clipboard.
CopyWebLink,
+ /// Listen on every address (a phone can reach it) or loopback only.
+ ToggleWebReachable,
+ /// Mint a link and show it as a QR code, or hide the one shown.
+ ToggleWebQr,
/// Index into the token rows cached at paint time.
/// Carries `web_token_key(id)`, not the row's index: the press is
/// remembered at mouse-down and compared by value with the action under
@@ -3468,10 +3472,30 @@ impl SettingsWindow {
/// Shared by the sidebar click and by an external request to open a
/// particular page, so a page reached from the app menu arrives in the
/// same state as one clicked into.
+ /// Where the listener binds: every address when the page is to be
+ /// reachable from other devices, else the configured or default one.
+ fn web_bind_address(&self) -> String {
+ let state = crate::web_settings::state();
+ let configured = state
+ .status
+ .as_ref()
+ .and_then(|status| status.configured.first().cloned())
+ .unwrap_or_else(|| config::WebServer::default().bind_address);
+ if self.native_settings.web.reachable {
+ let port = configured.rsplit_once(':').and_then(|(_, p)| p.parse::<u16>().ok()).unwrap_or(8088);
+ format!("0.0.0.0:{port}")
+ } else {
+ configured
+ }
+ }
+
fn enter_section(&mut self, section: SettingsSection) {
self.selected = section;
self.ui.content_scroll.reset();
self.ui.open_dropdown = None;
+ // A code on screen carries a live token; it does not outlast the
+ // section it was asked for in.
+ crate::web_settings::hide_qr();
if section == SettingsSection::Agents {
// Probe PATH on entry so painting never touches the filesystem.
crate::agent_status::refresh_path_probe();
@@ -3933,15 +3957,7 @@ impl SettingsWindow {
.status
.as_ref()
.is_some_and(|status| !status.listening.is_empty());
- // Turning it on with nothing configured is the ordinary
- // case, so fall back to the same loopback address a bare
- // `web_servers = { {} }` would have produced.
- let address = state
- .status
- .as_ref()
- .and_then(|status| status.configured.first().cloned())
- .or_else(|| Some(config::WebServer::default().bind_address));
- crate::web_settings::set_enabled(window.clone(), !on, address);
+ crate::web_settings::set_enabled(window.clone(), !on, Some(self.web_bind_address()));
}
SettingsAction::ToggleWebLinkTtlMenu => {
self.ui.open_dropdown = if self.ui.open_dropdown == Some(SettingsDropdown::WebLinkTtl)
@@ -3961,6 +3977,24 @@ impl SettingsWindow {
crate::web_settings::mint(window.clone(), self.native_settings.web.link_ttl_secs);
self.schedule_copied_state_clear(window);
}
+ SettingsAction::ToggleWebReachable => {
+ self.ui.open_dropdown = None;
+ self.native_settings.web.reachable = !self.native_settings.web.reachable;
+ self.save_web_settings();
+ let state = crate::web_settings::state();
+ let on = state.status.as_ref().is_some_and(|status| !status.listening.is_empty());
+ if on {
+ crate::web_settings::restart(window.clone(), self.web_bind_address());
+ }
+ }
+ SettingsAction::ToggleWebQr => {
+ self.ui.open_dropdown = None;
+ if crate::web_settings::state().qr.is_some() {
+ crate::web_settings::hide_qr();
+ } else {
+ crate::web_settings::show_qr(window.clone(), self.native_settings.web.link_ttl_secs);
+ }
+ }
SettingsAction::RevokeWebToken(key) => {
self.ui.open_dropdown = None;
if let Some(token) = self
@@ -5668,18 +5702,31 @@ impl SettingsWindow {
palette.muted_text,
max_width,
)?;
- let (card_y, first_row_y) = self.settings_card_geometry(section_y, 3);
- let card_height = self.settings_card_height(3);
+ // Five rows: the switch, reachable, the link's life, copy, the
+ // code -- plus the code itself below the last when one is shown.
+ let qr_modules = state.qr.as_ref().map(|q| q.len()).unwrap_or(0);
+ let qr_scale = self.ui_px(4.0);
+ let qr_side = qr_modules as f32 * qr_scale;
+ let qr_extra = if qr_modules > 0 { qr_side + self.ui_px(24.0) } else { 0.0 };
+ let (card_y, first_row_y) = self.settings_card_geometry(section_y, 5);
+ let card_height = self.settings_card_height(5) + qr_extra;
self.paint_group_card(layers, x, card_y, max_width, card_height)?;
// The error takes the description slot rather than a line of its
// own: it is always about the thing the toggle just tried to do,
// and a row that appears and disappears moves everything below it.
+ // Every address the listener answers on, as the server lists them
+ // (the ones another device can use first).
+ let urls = state
+ .status
+ .as_ref()
+ .map(|status| status.urls.iter().map(|u| u.trim_end_matches('/').to_string()).collect::<Vec<_>>())
+ .unwrap_or_default();
let description = match (&state.error, &address) {
(Some(error), _) => error.clone(),
(None, Some(address)) => {
let mut args = FluentArgs::new();
- args.set("address", address.clone());
+ args.set("address", if urls.is_empty() { address.clone() } else { urls.join(" · ") });
crate::i18n::tr_args("settings-web-on-at", &args)
}
(None, None) => crate::i18n::tr("settings-web-enable-description"),
@@ -5696,10 +5743,23 @@ impl SettingsWindow {
false,
)?;
- let ttl_y = first_row_y + row_step;
+ let reachable_y = first_row_y + row_step;
+ self.paint_toggle_setting_row(
+ layers,
+ row_x,
+ reachable_y,
+ row_width,
+ &crate::i18n::tr("settings-web-reachable"),
+ &crate::i18n::tr("settings-web-reachable-description"),
+ self.native_settings.web.reachable,
+ SettingsAction::ToggleWebReachable,
+ true,
+ )?;
+
+ let ttl_y = first_row_y + row_step * 2.0;
self.paint_web_link_ttl_row(layers, row_x, ttl_y, row_width, true)?;
- let copy_y = first_row_y + row_step * 2.0;
+ let copy_y = first_row_y + row_step * 3.0;
self.paint_separator(layers, row_x, copy_y - self.ui_px(28.0), row_width)?;
let copy_label = if state.copied {
crate::i18n::tr("settings-web-copied")
@@ -5736,6 +5796,60 @@ impl SettingsWindow {
SettingsAction::CopyWebLink,
)?;
+ // --- the code ---------------------------------------------------
+ let qr_y = first_row_y + row_step * 4.0;
+ self.paint_separator(layers, row_x, qr_y - self.ui_px(28.0), row_width)?;
+ let qr_label = if qr_modules > 0 {
+ crate::i18n::tr("settings-web-qr-hide")
+ } else {
+ crate::i18n::tr("settings-web-qr-show")
+ };
+ let qr_button_width = self.button_width_for_label(&qr_label, 190.0);
+ let qr_button_x = row_x + row_width - qr_button_width;
+ let qr_text_width = qr_button_x - row_x - self.ui_px(24.0);
+ self.draw_text(layers, &ui_font, row_x, qr_y, &crate::i18n::tr("settings-web-qr"), palette.text, qr_text_width)?;
+ self.draw_text(
+ layers,
+ &body_font,
+ row_x,
+ self.settings_row_description_y(qr_y),
+ &crate::i18n::tr("settings-web-qr-description"),
+ palette.secondary_text,
+ qr_text_width,
+ )?;
+ self.draw_button(layers, qr_button_x, qr_y + self.ui_px(4.0), qr_button_width, &qr_label, SettingsAction::ToggleWebQr)?;
+ if let Some(rows) = &state.qr {
+ // White behind, dark modules on it, a quiet zone of four modules:
+ // a scanner wants the contrast, whatever the theme.
+ let quiet = qr_scale * 4.0;
+ let top = self.settings_row_description_y(qr_y) + self.ui_px(30.0);
+ let white = LinearRgba::with_components(1.0, 1.0, 1.0, 1.0);
+ let black = LinearRgba::with_components(0.0, 0.0, 0.0, 1.0);
+ self.draw_rect(layers, 0, row_x - quiet, top - quiet, qr_side + quiet * 2.0, qr_side + quiet * 2.0, white)?;
+ for (yy, row) in rows.iter().enumerate() {
+ let mut x0: Option<usize> = None;
+ for xx in 0..=row.len() {
+ let dark = xx < row.len() && row[xx];
+ match (dark, x0) {
+ (true, None) => x0 = Some(xx),
+ (false, Some(start)) => {
+ self.draw_rect(
+ layers,
+ 0,
+ row_x + start as f32 * qr_scale,
+ top + yy as f32 * qr_scale,
+ (xx - start) as f32 * qr_scale,
+ qr_scale,
+ black,
+ )?;
+ x0 = None;
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+
// --- the links --------------------------------------------------
// One extra row for "every link" only when there is more than
// nothing to revoke; an empty list gets the placeholder row alone.
diff --git a/wezterm-gui/src/web_settings.rs b/wezterm-gui/src/web_settings.rs
index 0b52b6a3..d97c9fb6 100644
--- a/wezterm-gui/src/web_settings.rs
+++ b/wezterm-gui/src/web_settings.rs
@@ -32,6 +32,9 @@ pub struct WebState {
/// A link was just put on the clipboard. The URL itself is not kept:
/// it carries a live token, and nothing here needs to read it back.
pub copied: bool,
+ /// A minted link as a QR code (rows of dark modules), shown until the
+ /// section is left. The code carries the token, as a copied link does.
+ pub qr: Option<Vec<Vec<bool>>>,
/// Whether anything has been asked yet, so the first paint of the
/// section can ask without a button.
pub loaded: bool,
@@ -281,6 +284,97 @@ pub fn set_enabled(window: Window, enabled: bool, bind_address: Option<String>)
.detach();
}
+/// Turn the listener off and on again at another address: the settings
+/// switch flipped where it listens while it was up.
+pub fn restart(window: Window, bind_address: String) {
+ if with_state(|s| std::mem::replace(&mut s.busy, true)) {
+ return;
+ }
+ let Some(client) = client() else {
+ finish(&window, Some(crate::i18n::tr("settings-web-no-server")), Gate::Action);
+ return;
+ };
+ promise::spawn::spawn_into_main_thread(async move {
+ let off = client
+ .set_web_server(codec::SetWebServer { enabled: false, bind_address: None })
+ .await;
+ let outcome = match off {
+ Ok(_) => client
+ .set_web_server(codec::SetWebServer { enabled: true, bind_address: Some(bind_address) })
+ .await,
+ Err(err) => Err(err),
+ };
+ match outcome {
+ Ok(status) => {
+ with_state(|s| {
+ s.status = Some(status);
+ s.qr = None;
+ });
+ finish(&window, None, Gate::Action);
+ refresh(window);
+ }
+ Err(err) => finish(&window, Some(format!("{err:#}")), Gate::Action),
+ }
+ })
+ .detach();
+}
+
+/// Mint a link and show it as a QR code, for a phone to scan. Prefers a
+/// URL another device can use; a loopback-only listener gets a remark.
+pub fn show_qr(window: Window, ttl_secs: Option<u64>) {
+ if with_state(|s| std::mem::replace(&mut s.busy, true)) {
+ return;
+ }
+ let Some(client) = client() else {
+ finish(&window, Some(crate::i18n::tr("settings-web-no-server")), Gate::Action);
+ return;
+ };
+ promise::spawn::spawn_into_main_thread(async move {
+ match client.web_token_mint(codec::WebTokenMint { label: None, ttl_secs }).await {
+ Ok(minted) => {
+ let reachable = minted.urls.iter().find(|url| {
+ url.split("://")
+ .nth(1)
+ .and_then(|rest| rest.split('/').next())
+ .and_then(config::split_authority)
+ .is_some_and(|(host, _)| !config::is_loopback_host(&host))
+ });
+ match reachable.or(minted.urls.first()) {
+ Some(url) => {
+ let code = qrcode::QrCode::new(url.as_bytes());
+ match code {
+ Ok(code) => {
+ let width = code.width();
+ let colors = code.to_colors();
+ let rows: Vec<Vec<bool>> = (0..width)
+ .map(|y| (0..width).map(|x| colors[y * width + x] == qrcode::Color::Dark).collect())
+ .collect();
+ let remark = reachable.is_none().then(|| crate::i18n::tr("settings-web-qr-loopback"));
+ with_state(|s| s.qr = Some(rows));
+ finish(&window, remark, Gate::Action);
+ refresh(window);
+ }
+ Err(err) => finish(&window, Some(format!("{err}")), Gate::Action),
+ }
+ }
+ None => {
+ let _ = client
+ .web_token_revoke(codec::WebTokenRevoke { id: Some(minted.id.clone()) })
+ .await;
+ finish(&window, Some(crate::i18n::tr("settings-web-no-listener")), Gate::Action);
+ }
+ }
+ }
+ Err(err) => finish(&window, Some(format!("{err:#}")), Gate::Action),
+ }
+ })
+ .detach();
+}
+
+pub fn hide_qr() {
+ with_state(|s| s.qr = None);
+}
+
/// Mint a link and put it on the clipboard.
///
/// Straight to the clipboard rather than onto the screen: a token on screen
diff --git a/wezterm-mux-server-impl/src/lib.rs b/wezterm-mux-server-impl/src/lib.rs
index 9f2a84b9..701c32ea 100644
--- a/wezterm-mux-server-impl/src/lib.rs
+++ b/wezterm-mux-server-impl/src/lib.rs
@@ -21,6 +21,7 @@ pub mod web_auth;
pub mod web_control;
pub mod web_http;
pub mod web_stream;
+pub mod web_tls;
fn client_domains(config: &config::ConfigHandle) -> Vec<ClientDomainConfig> {
let mut domains = vec![];
diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rs
index 8c13b191..5070196c 100644
--- a/wezterm-mux-server-impl/src/sessionhandler.rs
+++ b/wezterm-mux-server-impl/src/sessionhandler.rs
@@ -3113,11 +3113,14 @@ fn web_urls(listening: &[String]) -> Vec<String> {
listening
.iter()
.flat_map(|address| {
- config
- .web_servers
- .iter()
- .find(|server| &server.bind_address == address)
- .cloned()
+ crate::web_control::effective(address)
+ .or_else(|| {
+ config
+ .web_servers
+ .iter()
+ .find(|server| &server.bind_address == address)
+ .cloned()
+ })
.unwrap_or_else(|| config::WebServer {
bind_address: address.clone(),
..Default::default()
diff --git a/wezterm-mux-server-impl/src/web_control.rs b/wezterm-mux-server-impl/src/web_control.rs
index e2a6b10d..71b76927 100644
--- a/wezterm-mux-server-impl/src/web_control.rs
+++ b/wezterm-mux-server-impl/src/web_control.rs
@@ -17,6 +17,10 @@ pub struct WebControl {
pub stop: fn(&str) -> bool,
/// The bind addresses currently accepting.
pub listening: fn() -> Vec<String>,
+ /// The entry a listener is running with -- the configured one, or the
+ /// defaults, plus whatever the listener filled in itself (a generated
+ /// certificate) -- so URLs and origins are told the scheme in use.
+ pub effective: fn(&str) -> Option<config::WebServer>,
}
static CONTROL: OnceLock<WebControl> = OnceLock::new();
@@ -38,3 +42,8 @@ pub fn get() -> Option<&'static WebControl> {
pub fn listening() -> Vec<String> {
get().map(|c| (c.listening)()).unwrap_or_default()
}
+
+/// The entry a live listener runs with, when it is up.
+pub fn effective(bind_address: &str) -> Option<config::WebServer> {
+ get().and_then(|c| (c.effective)(bind_address))
+}
diff --git a/wezterm-mux-server-impl/src/web_http.rs b/wezterm-mux-server-impl/src/web_http.rs
index 22c9d298..9199370a 100644
--- a/wezterm-mux-server-impl/src/web_http.rs
+++ b/wezterm-mux-server-impl/src/web_http.rs
@@ -184,6 +184,16 @@ impl WebSite {
if self.allowed_origins.iter().any(|o| o.same_as(&origin)) {
return true;
}
+ // An address of this machine that came up after the listener did
+ // (a tailnet joined, a new network): an IP literal cannot be a
+ // DNS-rebinding name, and at our scheme and port it is this page.
+ if !self.configured_origins
+ && origin.scheme == self.scheme
+ && origin.port == self.port
+ && origin.host.parse::<std::net::IpAddr>().is_ok_and(|ip| !ip.is_loopback())
+ {
+ return true;
+ }
if self.configured_origins || !self.loopback || !is_loopback_host(&origin.host) {
return false;
}
diff --git a/wezterm-mux-server-impl/src/web_tls.rs b/wezterm-mux-server-impl/src/web_tls.rs
new file mode 100644
index 00000000..f17b7286
--- /dev/null
+++ b/wezterm-mux-server-impl/src/web_tls.rs
@@ -0,0 +1,174 @@
+//! A certificate for the web listener when the configuration names none:
+//! self-signed, kept in the data directory, good for the machine's names
+//! and addresses. A browser warns once and is then in a secure context,
+//! which is what WebGPU needs; nothing here is a trust anchor.
+
+use anyhow::Context;
+use rcgen::{Certificate, CertificateParams, DistinguishedName, DnType, SanType};
+use sha2::{Digest, Sha256};
+use std::net::IpAddr;
+use std::path::{Path, PathBuf};
+
+/// The certificate and key for the web listener, made when missing or
+/// when the machine has an address the stored one does not name.
+pub struct WebTls {
+ pub cert: PathBuf,
+ pub key: PathBuf,
+ /// Hex SHA-256 of the certificate, for the log and the docs.
+ pub fingerprint: String,
+ pub generated: bool,
+}
+
+fn dir() -> PathBuf {
+ config::DATA_DIR.join("web-tls")
+}
+
+fn names(addresses: &[IpAddr]) -> (Vec<String>, Vec<IpAddr>) {
+ let mut dns = vec!["localhost".to_string()];
+ if let Ok(host) = hostname::get() {
+ if let Ok(host) = host.into_string() {
+ if !host.is_empty() {
+ dns.push(host.clone());
+ if !host.contains('.') {
+ dns.push(format!("{host}.local"));
+ }
+ }
+ }
+ }
+ dns.sort();
+ dns.dedup();
+ let mut ips: Vec<IpAddr> = vec!["127.0.0.1".parse().unwrap(), "::1".parse().unwrap()];
+ ips.extend(addresses.iter().copied());
+ ips.sort();
+ ips.dedup();
+ (dns, ips)
+}
+
+fn sans_text(dns: &[String], ips: &[IpAddr]) -> String {
+ let mut lines: Vec<String> = dns.iter().cloned().collect();
+ lines.extend(ips.iter().map(|ip| ip.to_string()));
+ lines.join("\n")
+}
+
+fn fingerprint(der: &[u8]) -> String {
+ let digest = Sha256::digest(der);
+ digest.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join(":")
+}
+
+fn write_private(path: &Path, bytes: &[u8]) -> anyhow::Result<()> {
+ let tmp = path.with_extension("tmp");
+ {
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let mut file = options.open(&tmp).with_context(|| format!("writing {}", tmp.display()))?;
+ std::io::Write::write_all(&mut file, bytes)?;
+ }
+ std::fs::rename(&tmp, path).with_context(|| format!("renaming into {}", path.display()))?;
+ Ok(())
+}
+
+/// 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();
+ 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");
+ let sans_path = dir.join("sans.txt");
+ let (dns, ips) = names(addresses);
+ let wanted = sans_text(&dns, &ips);
+ let stored = std::fs::read_to_string(&sans_path).unwrap_or_default();
+ let stale = stored != wanted;
+ if cert_path.is_file() && key_path.is_file() && !stale {
+ let pem = std::fs::read(&cert_path)?;
+ let der = pem_to_der(&pem).unwrap_or_default();
+ return Ok(WebTls { cert: cert_path, key: key_path, fingerprint: fingerprint(&der), generated: false });
+ }
+ let mut params = CertificateParams::new(dns.clone());
+ for ip in &ips {
+ params.subject_alt_names.push(SanType::IpAddress(*ip));
+ }
+ let mut dn = DistinguishedName::new();
+ dn.push(DnType::CommonName, dns.iter().find(|n| *n != "localhost").cloned().unwrap_or_else(|| "ThinkTerm".into()));
+ dn.push(DnType::OrganizationName, "ThinkTerm web listener");
+ params.distinguished_name = dn;
+ params.not_before = rcgen::date_time_ymd(2024, 1, 1);
+ params.not_after = rcgen::date_time_ymd(2040, 1, 1);
+ let cert = Certificate::from_params(params).context("generating the web certificate")?;
+ let der = cert.serialize_der().context("encoding the web certificate")?;
+ write_private(&key_path, cert.serialize_private_key_pem().as_bytes())?;
+ write_private(&cert_path, cert.serialize_pem()?.as_bytes())?;
+ write_private(&sans_path, wanted.as_bytes())?;
+ Ok(WebTls { cert: cert_path, key: key_path, fingerprint: fingerprint(&der), generated: true })
+}
+
+/// The DER inside a PEM certificate, for the fingerprint of a stored one.
+fn pem_to_der(pem: &[u8]) -> Option<Vec<u8>> {
+ let text = std::str::from_utf8(pem).ok()?;
+ let body: String = text
+ .lines()
+ .filter(|l| !l.starts_with("-----"))
+ .collect::<Vec<_>>()
+ .join("");
+ base64_decode(&body)
+}
+
+fn base64_decode(s: &str) -> Option<Vec<u8>> {
+ let mut out = Vec::with_capacity(s.len() * 3 / 4);
+ let mut buf = 0u32;
+ let mut bits = 0;
+ for c in s.bytes() {
+ let v = match c {
+ b'A'..=b'Z' => c - b'A',
+ b'a'..=b'z' => c - b'a' + 26,
+ b'0'..=b'9' => c - b'0' + 52,
+ b'+' => 62,
+ b'/' => 63,
+ b'=' => break,
+ _ => return None,
+ } as u32;
+ buf = (buf << 6) | v;
+ bits += 6;
+ if bits >= 8 {
+ bits -= 8;
+ out.push(((buf >> bits) & 0xff) as u8);
+ }
+ }
+ Some(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_names_always_carry_loopback_and_the_addresses() {
+ let (dns, ips) = names(&["192.168.1.7".parse().unwrap()]);
+ assert!(dns.contains(&"localhost".to_string()));
+ assert!(ips.contains(&"127.0.0.1".parse().unwrap()));
+ assert!(ips.contains(&"192.168.1.7".parse().unwrap()));
+ assert_eq!(base64_decode("aGVsbG8="), Some(b"hello".to_vec()));
+ }
+
+ #[test]
+ fn a_pem_certificate_decodes_to_its_der() {
+ let (dns, ips) = names(&[]);
+ let mut params = CertificateParams::new(dns);
+ for ip in &ips {
+ params.subject_alt_names.push(SanType::IpAddress(*ip));
+ }
+ let cert = Certificate::from_params(params).unwrap();
+ let pem = cert.serialize_pem().unwrap();
+ let der = pem_to_der(pem.as_bytes()).unwrap();
+ // A DER certificate is one outer SEQUENCE; the signature inside is
+ // fresh on every serialisation, so only the shape is compared.
+ assert_eq!(&der[..2], &[0x30, 0x82]);
+ assert!((der.len() as i64 - cert.serialize_der().unwrap().len() as i64).abs() <= 4);
+ assert_eq!(fingerprint(&der).len(), 32 * 3 - 1);
+ }
+}
diff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rs
index 192d1f0c..73428dfa 100644
--- a/wezterm-mux-server/src/main.rs
+++ b/wezterm-mux-server/src/main.rs
@@ -355,6 +355,7 @@ fn run() -> anyhow::Result<()> {
configure_tokens: web::configure_tokens,
stop: web::stop_web_listener,
listening: web::listening,
+ effective: web::effective,
},
);
diff --git a/wezterm-mux-server/src/web.rs b/wezterm-mux-server/src/web.rs
index 5e97f097..d065a4f4 100644
--- a/wezterm-mux-server/src/web.rs
+++ b/wezterm-mux-server/src/web.rs
@@ -30,6 +30,9 @@ const TOKEN_SWEEP_INTERVAL: Duration = Duration::from_secs(30);
static LISTENERS: Mutex<BTreeMap<String, Listening>> = Mutex::new(BTreeMap::new());
struct Listening {
+ /// What the listener runs with: the entry as given, plus the
+ /// certificate it made for itself when the entry named none.
+ effective: WebServer,
stop: Arc<AtomicBool>,
/// The address `accept()` actually returned, not the configured
/// string: an unspecified bind has to be woken through a real address.
@@ -41,6 +44,15 @@ pub fn listening() -> Vec<String> {
LISTENERS.lock().map_or_else(|e| e.into_inner(), |g| g).keys().cloned().collect()
}
+/// The entry a live listener runs with.
+pub fn effective(bind_address: &str) -> Option<WebServer> {
+ LISTENERS
+ .lock()
+ .map_or_else(|e| e.into_inner(), |g| g)
+ .get(bind_address)
+ .map(|l| l.effective.clone())
+}
+
pub fn is_listening(bind_address: &str) -> bool {
LISTENERS
.lock()
@@ -177,26 +189,26 @@ pub fn spawn_web_listener(server: &WebServer) -> anyhow::Result<()> {
server.bind_address
);
}
- let (host, _) = server.host_and_port();
- let unspecified = host
- .parse::<std::net::IpAddr>()
- .is_ok_and(|ip| ip.is_unspecified());
- if unspecified && server.allowed_origins.is_empty() {
- bail!(
- "web server {} listens on every address but names no allowed_origins; \
- a browser reaching it by hostname would be refused. List the origins \
- (e.g. \"https://host.example:port\") or bind one address",
- server.bind_address
- );
- }
+ // Off loopback a browser needs https for WebGPU. Without a
+ // certificate of the user's, the listener makes its own: self-signed,
+ // for the machine's names and addresses, kept across restarts. The
+ // browser warns once; a name it cannot verify is still a secure
+ // context once accepted.
+ let mut effective = server.clone();
if !server.is_loopback() && !server.uses_tls() && server.require_tls_off_loopback {
- bail!(
- "web server {} is not on loopback and has no TLS; browsers only expose WebGPU \
- to secure contexts, so it could not render. Add pem_cert/pem_private_key, \
- reach it through `ssh -L`, or set require_tls_off_loopback = false",
- server.bind_address
+ let tls = wezterm_mux_server_impl::web_tls::ensure(&config::local_addresses())
+ .with_context(|| format!("web server {}: making its certificate", server.bind_address))?;
+ log::error!(
+ "web server {}: {} self-signed certificate {} (SHA-256 {}); browsers warn once, then continue",
+ server.bind_address,
+ if tls.generated { "made a" } else { "using the" },
+ tls.cert.display(),
+ tls.fingerprint
);
+ effective.pem_cert = Some(tls.cert);
+ effective.pem_private_key = Some(tls.key);
}
+ let server = &effective;
let acceptor = if server.uses_tls() {
Some(build_acceptor(server)?)
} else {
@@ -232,6 +244,7 @@ pub fn spawn_web_listener(server: &WebServer) -> anyhow::Result<()> {
LISTENERS.lock().map_or_else(|e| e.into_inner(), |g| g).insert(
server.bind_address.clone(),
Listening {
+ effective: effective.clone(),
stop: Arc::clone(&stop),
local,
},
diff --git a/wezterm/src/cli/web_token.rs b/wezterm/src/cli/web_token.rs
index a4b53d8b..197e4546 100644
--- a/wezterm/src/cli/web_token.rs
+++ b/wezterm/src/cli/web_token.rs
@@ -119,7 +119,16 @@ impl MintCommand {
})
.await?;
if self.url_only {
- match minted.urls.first() {
+ // The one address another device can use, when there is one;
+ // a loopback URL is only good on this machine.
+ let reachable = minted.urls.iter().find(|url| {
+ url.split("://")
+ .nth(1)
+ .and_then(|rest| rest.split('/').next())
+ .and_then(config::split_authority)
+ .is_some_and(|(host, _)| !config::is_loopback_host(&host))
+ });
+ match reachable.or(minted.urls.first()) {
Some(url) => println!("{url}"),
None => {
// A script asked for a URL and there is none: do not