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.

feat(web): let a server switch reaching other machines on and off

RoversXe645a4f42e57
diff --git a/config/src/web.rs b/config/src/web.rs
index 8451664a..7d0d8c2c 100644
--- a/config/src/web.rs
+++ b/config/src/web.rs
@@ -9,7 +9,8 @@ use wezterm_dynamic::{FromDynamic, ToDynamic};
/// unix socket and the TLS credentials.
///
/// Like `tls_servers`, these are read when the server starts; a config
-/// reload does not open or close web ports.
+/// reload does not open or close web ports. The `relay` permission is read
+/// again after reload, including for connections already open.
#[derive(Debug, Clone, FromDynamic, ToDynamic)]
pub struct WebServer {
/// The address:port to listen on. Loopback by default: browsers only
@@ -50,6 +51,16 @@ pub struct WebServer {
/// `ssh -L` to reach a remote server instead.
#[dynamic(default = "default_true")]
pub require_tls_off_loopback: bool,
+
+ /// Let a page opened here reach the machines this server can SSH to --
+ /// its `~/.ssh/config`, the desktop's saved hosts, and ones added in the
+ /// browser -- signing in for the page with this server's own SSH
+ /// settings and keys. Off by default. The desktop's Settings → Web has
+ /// a switch that turns it on for every listener; this is the same for a
+ /// server with no desktop. Changes take effect on config reload;
+ /// turning both permissions off ends existing relays within two seconds.
+ #[dynamic(default)]
+ pub relay: bool,
}
fn default_web_bind_address() -> String {
@@ -67,6 +78,7 @@ impl Default for WebServer {
token_file: None,
allowed_origins: vec![],
require_tls_off_loopback: true,
+ relay: false,
}
}
}
diff --git a/docs/thinkterm/web-access.md b/docs/thinkterm/web-access.md
index 0b7bd91a..0af1a013 100644
--- a/docs/thinkterm/web-access.md
+++ b/docs/thinkterm/web-access.md
@@ -46,6 +46,11 @@ config.web_servers = {
-- Refuse to start without TLS when bind_address is not loopback.
-- require_tls_off_loopback = true,
+
+ -- Let a page opened here reach the machines this server can SSH to
+ -- (see "Other machines" below). Off by default; the desktop's
+ -- Settings → Web has the same switch.
+ -- relay = true,
},
}
```
@@ -112,6 +117,40 @@ 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.
+## Other machines
+
+The page's Remote Hosts tab opens other machines through the server it was
+loaded from, which is all a browser-only setup can reach. It is off until it
+is turned on: "Reach other machines" in the desktop's Settings → Web, or
+`relay = true` in the listener's `web_servers` entry on a server with no
+desktop. The desktop switch enables it for every listener; turning that
+switch off leaves only the listeners whose own `relay` setting is true.
+Unlike the listener's bind address, `relay` changes take effect on config
+reload, without restarting the listener. Once both permissions are off,
+the tab lists nothing and existing relays end within two seconds.
+
+The machines are the ones the server knows: its `~/.ssh/config` (folded
+under "System SSH", as on the desktop), the desktop's saved remote hosts,
+and any added in the browser, which are kept on the server. Opening one, the
+server signs in over SSH with its own settings and keys; a password, a host
+key or a one-time code is asked in the page, and a password can be kept on
+the server, encrypted. Then the server runs `thinkterm cli --prefer-mux
+proxy` there and relays the page's mux connection to that machine's own mux
+server, byte for byte, as the desktop's SSHMUX domains do. Each machine is a
+client of its own in the page, and the Space menu groups the Spaces by
+machine.
+
+Where ThinkTerm is not installed, the page asks once, then the server puts it
+in `~/.local/bin` there; an older one is updated and its sessions handed over
+to the new server. A desktop install is never replaced. Where ThinkTerm
+cannot run, or the answer is no, the page offers a plain SSH terminal from
+the server instead, which lasts as long as the server's SSH connection.
+
+The relay is not end-to-end encrypted: TLS ends at the server and SSH starts
+there, so the server can see what passes through it, though it does not
+decode it. That is the trust the token already carries: it is a shell on the
+server, and the server's own keys reach those machines.
+
## The page's chrome
Everything around the terminal is the model's data drawn by the page:
@@ -234,7 +273,8 @@ local rows, to keep or delete there.
Images (kitty, sixel, iTerm2) are not drawn; the cursor does not blink. The
input method's hidden field follows the terminal cursor, including
scrolling and resizing, so the browser can place its candidate window
-there; pre-edit text and its underline are not yet drawn in the grid.
+there, and the text being composed is drawn at the cursor in the cursor's
+colours, as on the desktop.
A dropped socket is reopened by the page itself, with a backoff, on the same
tab; the remark stays while it is down. It gives up only when there is
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftl
index 35293cf9..d2ca94ba 100644
--- a/thinkterm-i18n/i18n/de-DE.ftl
+++ b/thinkterm-i18n/i18n/de-DE.ftl
@@ -909,6 +909,8 @@ settings-web-no-listener = Nichts lauscht, also gibt es kein Ziel für einen Lin
settings-web-reachable = Von anderen Geräten erreichbar
settings-web-reachable-description = Lauscht auf allen Netzwerkadressen mit einem eigenen Zertifikat; ein Telefon im selben Netzwerk oder Tailnet kann den Link öffnen. Schalten Sie es nur in Netzwerken ein, denen Sie vertrauen. Aus kommt nur die Maschine heran, auf der er läuft.
settings-web-reachable-restart = Der Browserzugriff wurde aus- und unter der neuen Adresse wieder eingeschaltet.
+settings-web-relay = Andere Rechner erreichen
+settings-web-relay-description = Aktiviert alle Web-Listener; aus bleiben nur Listener mit relay = true aktiv. Der Zugriff nutzt die SSH-Einstellungen und Schlüssel dieses Computers. Änderungen an relay in thinkterm.lua gelten nach dem Neuladen der Konfiguration.
settings-web-qr = Mit dem Telefon scannen
settings-web-qr-description = Erzeugt einen Link und zeigt ihn als Code; vergleichen Sie vor dem Fortfahren den Zertifikat-Fingerabdruck.
settings-web-qr-show = Code zeigen
@@ -1157,7 +1159,6 @@ session-import-result-unavailable = Die Verbindung wurde unterbrochen. Prüfen S
web-machines-title = Remote-Hosts
web-machines-here = Dieser Server
web-machines-connected = Verbunden
-web-machines-others = Andere Rechner
web-machines-empty = Noch keine anderen Rechner. Fügen Sie hier einen hinzu oder tragen Sie ihn auf diesem Server in ~/.ssh/config ein.
web-machines-connect = Verbinden
web-machines-show = Anzeigen
@@ -1214,5 +1215,8 @@ web-machines-failed-same-server = Das ist dieser Server
web-machines-failed-failed = Verbindung fehlgeschlagen
web-machines-failed-desktop = Die Desktop-App dort muss zuerst aktualisiert werden
web-machines-failed-gone = Nicht mehr in der Liste dieses Servers
+web-machines-off = Andere Rechner zu erreichen ist auf diesem Server aus
+web-machines-off-hint = Schalten Sie „Andere Rechner erreichen“ unter Einstellungen → Web in der Desktop-App dieses Servers ein, oder setzen Sie relay = true in seinem web_servers-Eintrag in thinkterm.lua.
+web-machines-failed-off = Auf diesem Server ausgeschaltet
web-machines-bad-port = Ein Port ist eine Zahl von 1 bis 65535
web-machines-details = Details
diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftl
index 2df05b25..280a715f 100644
--- a/thinkterm-i18n/i18n/en-US.ftl
+++ b/thinkterm-i18n/i18n/en-US.ftl
@@ -1012,6 +1012,8 @@ web-settings-close = Close
settings-web-reachable = Reachable from other devices
settings-web-reachable-description = Listens on every network address with a certificate of its own; a phone on the same network or tailnet can open the link. Turn it on only on networks you trust. Off, only the machine it runs on can.
settings-web-reachable-restart = Turned browser access off and on again at the new address.
+settings-web-relay = Reach other machines
+settings-web-relay-description = Enables every web listener; off leaves only relay = true listeners enabled. Uses this computer’s SSH settings and keys to reach other machines. Changes to relay in thinkterm.lua take effect on config reload.
settings-web-qr = Scan on your phone
settings-web-qr-description = Makes a link and shows it as a code; compare the certificate fingerprint before continuing.
settings-web-qr-show = Show code
@@ -1157,7 +1159,6 @@ session-import-result-unavailable = The connection was interrupted. Check the im
web-machines-title = Remote Hosts
web-machines-here = This server
web-machines-connected = Connected
-web-machines-others = Other machines
web-machines-empty = No other machines yet. Add one here, or list it in ~/.ssh/config on this server.
web-machines-connect = Connect
web-machines-show = Show
@@ -1214,5 +1215,8 @@ web-machines-failed-same-server = That is this server
web-machines-failed-failed = Could not connect
web-machines-failed-desktop = The desktop app there needs updating first
web-machines-failed-gone = No longer on this server’s list
+web-machines-off = Reaching other machines is off on this server
+web-machines-off-hint = Turn on “Reach other machines” in Settings → Web on this server’s desktop, or set relay = true in its web_servers entry in thinkterm.lua.
+web-machines-failed-off = Turned off on this server
web-machines-bad-port = A port is a number from 1 to 65535
web-machines-details = Details
diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftl
index c06eee3d..77ae1074 100644
--- a/thinkterm-i18n/i18n/fr-FR.ftl
+++ b/thinkterm-i18n/i18n/fr-FR.ftl
@@ -906,6 +906,8 @@ settings-web-no-listener = Rien n'écoute, un lien ne pointerait nulle part. Act
settings-web-reachable = Accessible depuis d'autres appareils
settings-web-reachable-description = Écoute sur toutes les adresses réseau avec un certificat à lui ; un téléphone sur le même réseau ou tailnet peut ouvrir le lien. Ne l'activez que sur des réseaux de confiance. Désactivé, seule la machine qui l'exécute le peut.
settings-web-reachable-restart = L'accès par navigateur a été coupé puis rétabli à la nouvelle adresse.
+settings-web-relay = Joindre d’autres machines
+settings-web-relay-description = Active tous les ports Web ; désactivé, seuls ceux avec relay = true autorisent encore l’accès. Utilise les réglages et clés SSH de cet ordinateur. Les changements de relay dans thinkterm.lua s’appliquent au rechargement de la configuration.
settings-web-qr = Scanner sur votre téléphone
settings-web-qr-description = Crée un lien et l'affiche sous forme de code ; comparez l'empreinte du certificat avant de continuer.
settings-web-qr-show = Afficher le code
@@ -1154,7 +1156,6 @@ session-import-result-unavailable = La connexion a été interrompue. Vérifiez
web-machines-title = Hôtes distants
web-machines-here = Ce serveur
web-machines-connected = Connectées
-web-machines-others = Autres machines
web-machines-empty = Aucune autre machine pour l’instant. Ajoutez-en une ici, ou indiquez-la dans ~/.ssh/config sur ce serveur.
web-machines-connect = Se connecter
web-machines-show = Afficher
@@ -1211,5 +1212,8 @@ web-machines-failed-same-server = C’est ce serveur
web-machines-failed-failed = Connexion impossible
web-machines-failed-desktop = L’application de bureau doit d’abord y être mise à jour
web-machines-failed-gone = N’est plus dans la liste de ce serveur
+web-machines-off = Joindre d’autres machines est désactivé sur ce serveur
+web-machines-off-hint = Activez « Joindre d’autres machines » dans Réglages → Web de l’application de bureau de ce serveur, ou mettez relay = true dans son entrée web_servers de thinkterm.lua.
+web-machines-failed-off = Désactivé sur ce serveur
web-machines-bad-port = Un port est un nombre de 1 à 65535
web-machines-details = Détails
diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftl
index 8111a27f..cf568546 100644
--- a/thinkterm-i18n/i18n/ja-JP.ftl
+++ b/thinkterm-i18n/i18n/ja-JP.ftl
@@ -881,6 +881,8 @@ settings-web-no-listener = 待ち受けていないため、リンクの向き
settings-web-reachable = 他のデバイスから接続できる
settings-web-reachable-description = すべてのネットワークアドレスで、自前の証明書を使って待ち受けます。同じネットワークや tailnet のスマートフォンからリンクを開けます。信頼できるネットワークでだけオンにしてください。オフなら、それが動いているマシンだけです。
settings-web-reachable-restart = ブラウザアクセスを切り、新しいアドレスで入れ直しました。
+settings-web-relay = ほかのマシンに接続
+settings-web-relay-description = すべての Web リスナーで接続を許可します。オフでも relay = true のリスナーは接続を許可します。このコンピュータの SSH 設定と鍵を使います。thinkterm.lua の relay の変更は構成の再読み込みで反映されます。
settings-web-qr = スマートフォンで読み取る
settings-web-qr-description = リンクを作り、コードとして表示します。進む前に証明書の指紋を照合してください。
settings-web-qr-show = コードを表示
@@ -1129,7 +1131,6 @@ session-import-result-unavailable = 接続が中断されました。「イン
web-machines-title = リモートホスト
web-machines-here = このサーバー
web-machines-connected = 接続済み
-web-machines-others = ほかのマシン
web-machines-empty = ほかのマシンはまだありません。ここで追加するか、このサーバーの ~/.ssh/config に書いてください。
web-machines-connect = 接続
web-machines-show = 表示
@@ -1186,5 +1187,8 @@ web-machines-failed-same-server = このサーバー自身です
web-machines-failed-failed = 接続できませんでした
web-machines-failed-desktop = そのマシンのデスクトップ版を先に更新してください
web-machines-failed-gone = このサーバーの一覧にもうありません
+web-machines-off = このサーバーでは、ほかのマシンへの接続がオフです
+web-machines-off-hint = このサーバーのデスクトップ版で 設定 → Web の「ほかのマシンに接続」をオンにするか、thinkterm.lua の web_servers の項目に relay = true を加えてください。
+web-machines-failed-off = このサーバーでオフになっています
web-machines-bad-port = ポートは 1 から 65535 までの数字です
web-machines-details = 詳細
diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftl
index 1bc9de40..b948b1e7 100644
--- a/thinkterm-i18n/i18n/zh-CN.ftl
+++ b/thinkterm-i18n/i18n/zh-CN.ftl
@@ -881,6 +881,8 @@ settings-web-no-listener = 没有在监听,链接无处指向。请先打开浏
settings-web-reachable = 其他设备也能访问
settings-web-reachable-description = 在所有网络地址上监听,并使用自己的证书;同一网络或 tailnet 里的手机就能打开链接。只在你信任的网络里打开。关闭时只有它所在的那台机器能访问。
settings-web-reachable-restart = 已把浏览器访问关掉再打开,换到了新地址。
+settings-web-relay = 连接其他机器
+settings-web-relay-description = 为所有网页监听器开启访问;关闭后,只有 relay = true 的监听器仍允许连接其他机器。使用这台电脑的 SSH 设置和密钥。thinkterm.lua 中的 relay 修改在配置重载后生效。
settings-web-qr = 用手机扫码
settings-web-qr-description = 生成一个链接,并显示成二维码;继续之前,请先核对证书指纹。
settings-web-qr-show = 显示二维码
@@ -1129,7 +1131,6 @@ session-import-result-unavailable = 连接已中断。请使用“检查导入
web-machines-title = 远程主机
web-machines-here = 这台服务器
web-machines-connected = 已连接
-web-machines-others = 其他机器
web-machines-empty = 还没有其他机器。可以在这里添加,或写进这台服务器的 ~/.ssh/config。
web-machines-connect = 连接
web-machines-show = 显示
@@ -1186,5 +1187,8 @@ web-machines-failed-same-server = 这就是当前这台服务器
web-machines-failed-failed = 连接失败
web-machines-failed-desktop = 那台机器上的桌面版需要先更新
web-machines-failed-gone = 这台服务器的列表里已经没有它了
+web-machines-off = 这台服务器没有开启连接其他机器
+web-machines-off-hint = 在这台服务器桌面版的设置 → 网页里打开“连接其他机器”,或者在它的 thinkterm.lua 里给 web_servers 那一项加上 relay = true。
+web-machines-failed-off = 这台服务器已关闭此功能
web-machines-bad-port = 端口是 1 到 65535 之间的数字
web-machines-details = 详情
diff --git a/thinkterm-web/src/views.rs b/thinkterm-web/src/views.rs
index 287c011f..ef869a73 100644
--- a/thinkterm-web/src/views.rs
+++ b/thinkterm-web/src/views.rs
@@ -89,9 +89,12 @@ pub struct Card {
/// confirmation words), keyed by their catalogue id, in the active locale.
pub const STRING_KEYS: &[&str] = &[
"web-machines-title",
+ "web-machines-off",
+ "web-machines-off-hint",
+ "web-machines-failed-off",
+ "ssh-group-hosts",
"web-machines-here",
"web-machines-connected",
- "web-machines-others",
"web-machines-empty",
"web-machines-connect",
"web-machines-show",
@@ -271,9 +274,21 @@ pub const STRING_KEYS: &[&str] = &[
];
pub fn strings() -> std::collections::BTreeMap<&'static str, String> {
- STRING_KEYS.iter().map(|key| (*key, thinkterm_i18n::tr(key))).collect()
+ let mut strings: std::collections::BTreeMap<&'static str, String> =
+ STRING_KEYS.iter().map(|key| (*key, thinkterm_i18n::tr(key))).collect();
+ let mut args = thinkterm_i18n::FluentArgs::new();
+ args.set("count", COUNT_SLOT);
+ for key in COUNTED_KEYS {
+ strings.insert(*key, thinkterm_i18n::tr_args(key, &args));
+ }
+ strings
}
+/// Labels with a number in them: sent with `COUNT_SLOT` where it goes, for
+/// the page to fill in (`sCount` in client.svelte.ts).
+pub const COUNTED_KEYS: &[&str] = &["ssh-system-hosts"];
+pub const COUNT_SLOT: &str = "{count}";
+
#[cfg(test)]
mod tests {
use super::*;
@@ -362,7 +377,7 @@ mod tests {
let key_like = quoted.starts_with(|c: char| c.is_ascii_lowercase())
&& quoted.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
if key_like && thinkterm_i18n::has_key(quoted) {
- if !STRING_KEYS.contains(&quoted) {
+ if !STRING_KEYS.contains(&quoted) && !COUNTED_KEYS.contains(&quoted) {
missing.push(format!("{name}: {quoted}"));
}
at += len + 1;
diff --git a/thinkterm-web/ui/src/MachinesPanel.svelte b/thinkterm-web/ui/src/MachinesPanel.svelte
index f775b331..c1190cb9 100644
--- a/thinkterm-web/ui/src/MachinesPanel.svelte
+++ b/thinkterm-web/ui/src/MachinesPanel.svelte
@@ -5,7 +5,7 @@
// page, for a page whose only way out is its server, and a tab of its
// own as that one is: in the terminal's place while it is on show, kept
// as it was while another tab is.
- import { s } from './client.svelte';
+ import { s, sCount } from './client.svelte';
import { check, chevronRight, download, house, keyRound, plus, search, server, shieldAlert, unplug, x } from './icons';
import {
addMachine, answer, close, closePanel, connect, forgetMachine, HERE, machines, openPlainSsh, showMachine,
@@ -20,9 +20,17 @@
return q === '' || label.toLowerCase().includes(q) || endpoint.toLowerCase().includes(q);
}
- /** The machines open here, and the ones not, in the server's order. */
+ /** The machines open here, and the ones not, in the server's order: the
+ hosts saved on the desktop or added here, and the ones from
+ `~/.ssh/config`, which the desktop's page groups apart and folds. */
const opened = $derived(machines.open.filter((m) => found(m.label, endpointOf(m.id))));
const others = $derived(machines.list.filter((m) => !machines.open.some((o) => o.id === m.id) && found(m.label, m.endpoint)));
+ const own = $derived(others.filter((m) => m.source !== 'ssh-config'));
+ const system = $derived(others.filter((m) => m.source === 'ssh-config'));
+ /** The `~/.ssh/config` group is unfolded: folded by default, as on the
+ desktop, and open while a search could find something in it. */
+ let systemOpen = $state(false);
+ const systemShown = $derived(systemOpen || query.trim() !== '');
const SOURCE: Record<string, string> = {
'ssh-config': 'web-machines-from-ssh-config',
@@ -59,9 +67,17 @@
form = { label: '', host: '', port: '', user: '', password: '' };
});
- // A tab closed starts the next one afresh: no search left in its field.
+ // A tab closed starts the next one afresh: no search left in its field,
+ // and the `~/.ssh/config` group folded again.
$effect(() => {
- if (!machines.tab) query = '';
+ if (machines.tab) return;
+ query = '';
+ systemOpen = false;
+ });
+
+ // Reaching other machines turned off: no host can be added.
+ $effect(() => {
+ if (!machines.enabled) machines.adding = false;
});
// On show, the page takes the keys -- unless a field in it already has
@@ -188,7 +204,7 @@
<div id="machines" class:adding={machines.adding} hidden={!machines.panel} tabindex="-1" onkeydown={onKeydown} bind:this={page}>
<div class="lists">
<div class="tools">
- <button class="pillbtn primary addbtn" type="button" data-action="add-machine" onclick={() => (machines.adding = true)}>{@html plus}<span>{s('ssh-new-host')}</span></button>
+ {#if machines.enabled}<button class="pillbtn primary addbtn" type="button" data-action="add-machine" onclick={() => (machines.adding = true)}>{@html plus}<span>{s('ssh-new-host')}</span></button>{/if}
<label class="find">{@html search}<input type="search" bind:value={query} placeholder={s('ssh-search')} spellcheck="false" autocapitalize="off" autocomplete="off" /></label>
</div>
<div class="body">
@@ -279,30 +295,42 @@
{/each}
</div>
- {#if others.length > 0 || (machines.listed && machines.list.length === 0)}<div class="label">{s('web-machines-others')}</div>{/if}
- {#if others.length > 0}
- <div class="grid">
- {#each others as m (m.id)}
- <div class="hcard">
- <div class="mrow" data-machine={m.id}>
- <span class="logo">{@html server}</span>
- <div class="tx">
- <div class="lab">{m.label}</div>
- <div class="desc"><span>{m.endpoint}</span><span>{sourceOf(m)}</span>{#if m.password}<span>{s('web-machines-password-kept')}</span>{/if}</div>
- </div>
- <div class="ctl">
- <button class="pillbtn" type="button" data-action="connect" onclick={(ev) => go(ev, m.id)}>{s('web-machines-connect')}</button>
- {#if m.forgettable}
- <button class="iconbtn" type="button" title={s('web-machines-forget')} data-action="forget" onclick={() => void forgetMachine(m.id)}>{@html x}</button>
- {/if}
- </div>
- </div>
+ {#snippet hostCard(m: MachineEntry)}
+ <div class="hcard">
+ <div class="mrow" data-machine={m.id}>
+ <span class="logo">{@html server}</span>
+ <div class="tx">
+ <div class="lab">{m.label}</div>
+ <div class="desc"><span>{m.endpoint}</span><span>{sourceOf(m)}</span>{#if m.password}<span>{s('web-machines-password-kept')}</span>{/if}</div>
</div>
- {/each}
+ <div class="ctl">
+ <button class="pillbtn" type="button" data-action="connect" onclick={(ev) => go(ev, m.id)}>{s('web-machines-connect')}</button>
+ {#if m.forgettable}
+ <button class="iconbtn" type="button" title={s('web-machines-forget')} data-action="forget" onclick={() => void forgetMachine(m.id)}>{@html x}</button>
+ {/if}
+ </div>
+ </div>
</div>
- {:else if machines.listed && machines.list.length === 0}
- <!-- The desktop's empty page: the server glyph over one line. -->
- <div class="empty">{@html server}<span>{s('web-machines-empty')}</span></div>
+ {/snippet}
+ {#if machines.listed && !machines.enabled}
+ <!-- Turned off at the server: what to turn on, and where. -->
+ <div class="empty off" data-machines="off">{@html server}<span class="offt">{s('web-machines-off')}</span><span>{s('web-machines-off-hint')}</span></div>
+ {:else}
+ <!-- The desktop's groups: the hosts saved there or added here, then
+ `~/.ssh/config`'s under a caption that folds them, folded at
+ first and open while searching. -->
+ {#if own.length > 0}
+ <div class="label">{s('ssh-group-hosts')}</div>
+ <div class="grid">{#each own as m (m.id)}{@render hostCard(m)}{/each}</div>
+ {/if}
+ {#if system.length > 0}
+ <button class="label fold" class:open={systemShown} type="button" data-action="system-hosts" aria-expanded={systemShown} onclick={() => (systemOpen = !systemOpen)}>{@html chevronRight}<span>{sCount('ssh-system-hosts', system.length)}</span></button>
+ {#if systemShown}<div class="grid">{#each system as m (m.id)}{@render hostCard(m)}{/each}</div>{/if}
+ {/if}
+ {#if machines.listed && machines.list.length === 0}
+ <!-- The desktop's empty page: the server glyph over one line. -->
+ <div class="empty">{@html server}<span>{s('web-machines-empty')}</span></div>
+ {/if}
{/if}
{#if machines.error !== ''}<div class="err">{machines.error}</div>{/if}
</div>
diff --git a/thinkterm-web/ui/src/client.svelte.ts b/thinkterm-web/ui/src/client.svelte.ts
index 50615936..2721c048 100644
--- a/thinkterm-web/ui/src/client.svelte.ts
+++ b/thinkterm-web/ui/src/client.svelte.ts
@@ -56,6 +56,12 @@ export function s(id: string): string {
return views.strings[id] ?? id;
}
+/** A label with a number in it: the wasm sends it with `{count}` where the
+ number goes (`COUNTED_KEYS` in views.rs). */
+export function sCount(id: string, count: number): string {
+ return s(id).replace('{count}', String(count));
+}
+
/** The boot's progress, and the probes' one-line results. */
export function setBoot(text: string, failed = false, stage?: number) {
views.boot = text;
diff --git a/thinkterm-web/ui/src/machines.svelte.ts b/thinkterm-web/ui/src/machines.svelte.ts
index 65f167a9..bd1b7b9c 100644
--- a/thinkterm-web/ui/src/machines.svelte.ts
+++ b/thinkterm-web/ui/src/machines.svelte.ts
@@ -70,6 +70,9 @@ export const machines = $state({
here: '',
list: [] as MachineEntry[],
listed: false,
+ /** Reaching other machines is turned on at this server; off, the list
+ is empty and the page says how to turn it on. */
+ enabled: true,
/** Why the list or the last change to it failed; empty when it did not. */
error: '',
open: [] as OpenMachine[],
@@ -153,6 +156,7 @@ function request(message: object): Promise<string | null> {
const reply = JSON.parse(ev.data);
if (reply.op === 'machines') {
machines.here = reply.here;
+ machines.enabled = reply.enabled !== false;
machines.list = reply.machines;
machines.listed = true;
for (const m of machines.open) m.label = machines.list.find((e) => e.id === m.id)?.label ?? m.label;
diff --git a/thinkterm-web/ui/src/tokens.css b/thinkterm-web/ui/src/tokens.css
index 4547b9a4..8c74e816 100644
--- a/thinkterm-web/ui/src/tokens.css
+++ b/thinkterm-web/ui/src/tokens.css
@@ -677,6 +677,12 @@ body[data-mobile] .nav > .caps, body[data-mobile] .nav > .acts { margin-top: 6px
#machines .more.open svg { transform: rotate(90deg); }
/* The desktop's empty page: its server glyph over the one line. */
#machines .empty { display: flex; flex-direction: column; align-items: center; gap: 12px; padding: 28px 24px 34px 24px; color: var(--muted); font-size: 13px; line-height: 1.4; text-align: center; }
+#machines .empty.off .offt { color: var(--text); font-weight: 600; }
+/* The `~/.ssh/config` group's caption folds it, as the desktop's does. */
+#machines .label.fold { display: flex; align-items: center; gap: 4px; width: calc(100% - 4px); padding: 0; border: 0; background: transparent; text-align: left; cursor: default; font: 600 13px var(--ui); transition: var(--fade); }
+#machines .label.fold:hover { color: var(--text); }
+#machines .label.fold svg { width: 14px; height: 14px; flex: none; transition: transform .15s; }
+#machines .label.fold.open svg { transform: rotate(90deg); }
#machines .empty svg { width: 28px; height: 28px; stroke-width: 1.6; }
#machines .err { margin: -8px 2px 16px 2px; color: var(--danger); font-size: 12px; }
#machines .addbtn { display: inline-flex; align-items: center; gap: 6px; padding: 0 14px 0 11px; }
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index 431aaf69..4e2011fb 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -875,6 +875,10 @@ pub(crate) struct NativeWebSettings {
/// Listen on every address (with the server's own certificate) rather
/// than loopback only, so a phone can reach it.
pub(crate) reachable: bool,
+ /// Let a page reach the machines this computer can SSH to, through its
+ /// session server. Read by the server itself each time (web_relay.rs),
+ /// so it takes effect without a restart.
+ pub(crate) relay: bool,
}
impl Default for NativeWebSettings {
@@ -882,6 +886,7 @@ impl Default for NativeWebSettings {
Self {
reachable: false,
link_ttl_secs: Some(DEFAULT_WEB_LINK_TTL_SECS),
+ relay: false,
}
}
}
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index 7b395b8c..8562775d 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -1442,6 +1442,7 @@ enum SettingsAction {
CopyWebLink,
/// Listen on every address (a phone can reach it) or loopback only.
ToggleWebReachable,
+ ToggleWebRelay,
/// 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.
@@ -5840,6 +5841,11 @@ impl SettingsWindow {
crate::web_settings::restart(window.clone(), self.web_bind_address());
}
}
+ SettingsAction::ToggleWebRelay => {
+ self.ui.open_dropdown = None;
+ self.native_settings.web.relay = !self.native_settings.web.relay;
+ self.save_web_settings();
+ }
SettingsAction::ToggleWebQr => {
self.ui.open_dropdown = None;
if crate::web_settings::state().qr.is_some() {
@@ -9214,6 +9220,25 @@ impl SettingsWindow {
SettingsAction::ToggleWebReachable,
rows.rule(),
)?);
+ let (tx, tw) = this.paint_row_tile(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ SvgIcon::Server,
+ TileColor::Purple,
+ )?;
+ rows.add(this.paint_toggle_setting_row(
+ layers,
+ tx,
+ rows.y,
+ tw,
+ &crate::i18n::tr("settings-web-relay"),
+ &crate::i18n::tr("settings-web-relay-description"),
+ this.native_settings.web.relay,
+ SettingsAction::ToggleWebRelay,
+ rows.rule(),
+ )?);
let (tx, tw) = this.paint_row_tile(
layers,
row_x,
diff --git a/wezterm-mux-server-impl/src/web_http.rs b/wezterm-mux-server-impl/src/web_http.rs
index 16c11bf8..eb6c8ea4 100644
--- a/wezterm-mux-server-impl/src/web_http.rs
+++ b/wezterm-mux-server-impl/src/web_http.rs
@@ -808,8 +808,12 @@ where
site.describe,
admission.token_id
);
- crate::web_relay::serve(Prefixed::new(leftover, stream), admission.revoked.clone())
- .await;
+ crate::web_relay::serve(
+ Prefixed::new(leftover, stream),
+ admission.revoked.clone(),
+ site.describe.clone(),
+ )
+ .await;
drop(admission);
return;
}
diff --git a/wezterm-mux-server-impl/src/web_relay.rs b/wezterm-mux-server-impl/src/web_relay.rs
index 311d00fe..12b12281 100644
--- a/wezterm-mux-server-impl/src/web_relay.rs
+++ b/wezterm-mux-server-impl/src/web_relay.rs
@@ -20,7 +20,10 @@
//!
//! The token already gives a shell on this server, and through it whatever
//! this server's ssh setup reaches; the relay adds no reach of its own, so
-//! there is no list of allowed hosts.
+//! there is no list of allowed hosts. It is off until it is turned on --
+//! by the desktop's Settings → Web, or by `relay = true` in the listener's
+//! `web_servers` entry on a server with no desktop -- and turning it off
+//! ends the machines open through it.
//!
//! The same socket is also where the page asks for this machine's tab icon
//! cards: they are edited in the desktop's settings, and a page only draws
@@ -70,6 +73,11 @@ const MAX_HELLO_FRAME: u64 = 1024 * 1024;
const CLOSE_GRACE: Duration = Duration::from_secs(5);
/// Bytes of a host command's error output kept for the page.
const STDERR_TAIL: usize = 4096;
+/// What a page is told when reaching other machines is turned off here.
+const OFF: &str = "reaching other machines is turned off on this server";
+/// How often a machine open through the relay looks at the switch again,
+/// so turning it off ends the machine within this long.
+const SWITCH_CHECK: Duration = Duration::from_secs(2);
/// The most a host command may print before it is given up on. What is run
/// prints a few lines; a login script that never stops printing must not
/// fill this server's memory in the minute the command has.
@@ -154,6 +162,9 @@ enum Reply {
Machines {
/// This server's own name, for the page to head its own Spaces.
here: String,
+ /// Reaching other machines is turned on here. Off, the list is
+ /// empty: nothing about the machines is told to the page.
+ enabled: bool,
machines: Vec<MachineView>,
},
Saved {
@@ -244,6 +255,8 @@ enum Reason {
SameServer,
/// Not on this server's list any more.
Gone,
+ /// Reaching other machines is turned off on this server.
+ Off,
Failed,
}
@@ -534,14 +547,74 @@ fn machines() -> Vec<Machine> {
machines_from(&kept, saved, system, resolved_address)
}
-fn machines_reply() -> Reply {
+fn machines_reply(enabled: bool) -> Reply {
Reply::Machines {
here: hostname::get()
.ok()
.and_then(|h| h.into_string().ok())
.unwrap_or_default(),
- machines: machines().iter().map(Machine::view).collect(),
+ enabled,
+ machines: if enabled {
+ machines().iter().map(Machine::view).collect()
+ } else {
+ vec![]
+ },
+ }
+}
+
+/// Whether the desktop's Settings → Web turned reaching other machines on,
+/// as its settings file at `path` says. A file that is not there, or does
+/// not read, leaves it off.
+fn desktop_allows_at(path: &Path) -> bool {
+ #[derive(Default, Deserialize)]
+ struct Web {
+ #[serde(default)]
+ relay: bool,
}
+ #[derive(Default, Deserialize)]
+ struct Settings {
+ #[serde(default)]
+ web: Web,
+ }
+ std::fs::read_to_string(path)
+ .ok()
+ .and_then(|text| serde_json::from_str::<Settings>(&text).ok())
+ .is_some_and(|settings| settings.web.relay)
+}
+
+/// Whether a page may reach other machines through this server: the
+/// listener's current `relay = true`, or the desktop's switch. Neither is
+/// captured at listener startup, so a config reload also reaches open relays.
+fn relay_allowed(listener: &str) -> bool {
+ relay_allowed_at(
+ &config::configuration().web_servers,
+ listener,
+ &config::native_settings_path(),
+ )
+}
+
+fn relay_allowed_at(servers: &[config::WebServer], listener: &str, settings: &Path) -> bool {
+ servers
+ .iter()
+ .find(|server| server.bind_address == listener)
+ .is_some_and(|server| server.relay)
+ || desktop_allows_at(settings)
+}
+
+/// Ends the relay once reaching other machines is turned off: an open
+/// machine is let go of within `SWITCH_CHECK` of the switch.
+fn watch_switch(attempt: &Attempt, listener: String) -> smol::Task<()> {
+ let attempt = attempt.clone();
+ crate::connections::spawn_task(async move {
+ loop {
+ smol::Timer::after(SWITCH_CHECK).await;
+ let listener = listener.clone();
+ if !smol::unblock(move || relay_allowed(&listener)).await {
+ attempt.stop("reaching other machines was turned off on this server");
+ return;
+ }
+ }
+ })
}
/// The tab icon cards of the desktop on this machine, as a page draws them:
@@ -2291,10 +2364,13 @@ struct Relay<S> {
sender: Sender<S>,
incoming: smol::channel::Receiver<Incoming>,
attempt: Attempt,
+ /// The address whose current configuration governs this connection.
+ listener: String,
}
-/// One relay socket, from its first message to its close.
-pub async fn serve<S>(socket: S, revoked: smol::channel::Receiver<()>)
+/// One relay socket, from its first message to its close. `listener` is
+/// its bind address, used to read the current policy (see `relay_allowed`).
+pub async fn serve<S>(socket: S, revoked: smol::channel::Receiver<()>, listener: String)
where
S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
@@ -2336,6 +2412,7 @@ where
sender,
incoming,
attempt,
+ listener,
};
if relay.run().await.is_err() {
log::debug!("web relay ended with an error");
@@ -2397,6 +2474,31 @@ where
continue;
}
};
+ let listener = self.listener.clone();
+ let enabled = smol::unblock(move || relay_allowed(&listener)).await;
+ if !enabled {
+ // Off: no machine is listed, saved, forgotten or opened. The
+ // tab icon cards are this machine's own and still answered.
+ match &request {
+ Request::Open { .. } => {
+ return self
+ .reply(&Reply::Failed {
+ reason: Reason::Off,
+ message: OFF.to_string(),
+ ssh_domain: None,
+ })
+ .await;
+ }
+ Request::Save { .. } | Request::Forget { .. } => {
+ self.reply(&Reply::Error {
+ message: OFF.to_string(),
+ })
+ .await?;
+ continue;
+ }
+ Request::List | Request::TabIcons | Request::Answer { .. } => {}
+ }
+ }
match request {
Request::List => {}
Request::Save { machine } => match smol::unblock(move || save_machine(machine)).await {
@@ -2427,12 +2529,15 @@ where
// Nothing was asked.
Request::Answer { .. } => continue,
}
- let list = smol::unblock(machines_reply).await;
+ let list = smol::unblock(move || machines_reply(enabled)).await;
self.reply(&list).await?;
}
}
async fn open(&mut self, id: &str) -> anyhow::Result<()> {
+ // For as long as the machine is open, through its questions and
+ // then its bytes: turned off meanwhile, it ends.
+ let _switch = watch_switch(&self.attempt, self.listener.clone());
let all = smol::unblock(machines).await;
let Some(machine) = all.into_iter().find(|m| m.id == id) else {
return self
@@ -2847,6 +2952,66 @@ mod tests {
}
}
+ #[test]
+ fn reaching_other_machines_is_off_until_turned_on() {
+ let dir = tempfile::tempdir().unwrap();
+ let settings = dir.path().join("settings.json");
+ // No desktop here, or one that never touched the switch: off.
+ assert!(!desktop_allows_at(&settings));
+ std::fs::write(&settings, r#"{"theme":"x","web":{"reachable":true}}"#).unwrap();
+ assert!(!desktop_allows_at(&settings));
+ std::fs::write(&settings, r#"{"theme":"x","web":{"reachable":true,"relay":true}}"#).unwrap();
+ assert!(desktop_allows_at(&settings));
+ // A file that does not read is no go-ahead.
+ std::fs::write(&settings, "{").unwrap();
+ assert!(!desktop_allows_at(&settings));
+ // Off, the page hears so, and of no machine.
+ let text = serde_json::to_string(&Reply::Machines {
+ here: "server-a".into(),
+ enabled: false,
+ machines: vec![],
+ })
+ .unwrap();
+ assert_eq!(text, r#"{"op":"machines","here":"server-a","enabled":false,"machines":[]}"#);
+ assert_eq!(serde_json::to_string(&Reason::Off).unwrap(), r#""off""#);
+ }
+
+ #[test]
+ fn relay_policy_tracks_each_listener_and_the_desktop_switch() {
+ let dir = tempfile::tempdir().unwrap();
+ let settings = dir.path().join("settings.json");
+ let mut servers = vec![
+ config::WebServer {
+ bind_address: "server-a:8088".into(),
+ relay: true,
+ ..Default::default()
+ },
+ config::WebServer {
+ bind_address: "server-b:8088".into(),
+ ..Default::default()
+ },
+ ];
+ assert!(relay_allowed_at(&servers, "server-a:8088", &settings));
+ assert!(!relay_allowed_at(&servers, "server-b:8088", &settings));
+ assert!(!relay_allowed_at(&servers, "server-c:8088", &settings));
+
+ // The desktop switch can change the other listeners independently.
+ std::fs::write(&settings, r#"{"web":{"relay":true}}"#).unwrap();
+ assert!(relay_allowed_at(&servers, "server-b:8088", &settings));
+ assert!(relay_allowed_at(&servers, "server-c:8088", &settings));
+ std::fs::write(&settings, r#"{"web":{"relay":false}}"#).unwrap();
+ assert!(relay_allowed_at(&servers, "server-a:8088", &settings));
+ assert!(!relay_allowed_at(&servers, "server-b:8088", &settings));
+
+ // A reloaded entry, or its removal, must replace the startup policy.
+ servers[0].relay = false;
+ assert!(!relay_allowed_at(&servers, "server-a:8088", &settings));
+ servers[1].relay = true;
+ assert!(relay_allowed_at(&servers, "server-b:8088", &settings));
+ servers.clear();
+ assert!(!relay_allowed_at(&servers, "server-b:8088", &settings));
+ }
+
#[test]
fn replies_are_tagged_for_the_page() {
let text = serde_json::to_string(&Reply::Step {