Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(machines): reach a machine — connect it, proxy its API, browse it (#574)

Myriad-Dreamin37540b6af398
diff --git a/changelog/unreleased/2026-09-01-machines-reach.md b/changelog/unreleased/2026-09-01-machines-reach.md
new file mode 100644
index 00000000..e3bb9ac2
--- /dev/null
+++ b/changelog/unreleased/2026-09-01-machines-reach.md
@@ -0,0 +1,39 @@
+# Reaching a machine: connect it, proxy it, browse it
+
+- **Date:** 2026-09-01
+- **Type:** feature
+- **Scope:** `server`, `docs`
+- **PR:** [#574](https://github.com/Prism-Shadow/penguin-harness/pull/574)
+
+[中文版](2026-09-01-machines-reach.zh.md)
+
+An installed machine can now be **connected**: this server brings its `penguin server` up over ssh and keeps the connection to it open, through which its API answers at `/server/<machineId>/api/…` on this origin. Nothing new listens anywhere, and nothing new is opened — the one connection a machine already has carries it.
+
+## Connect, and what it costs
+
+Connecting is a job: ask the machine what is running over there, start its server when nothing is, and keep the connection open. The connection itself is the one this server already holds per machine — an `ssh -T -D` session — so connecting opens nothing new; what it does is make sure the far side has a server to answer, and remember the port it is on.
+
+## Facts that name the layer they measured
+
+Two new facts on a machine, deliberately not merged with the one [#568](https://github.com/Prism-Shadow/penguin-harness/pull/568) added:
+
+- `connection` — this server holds its session to it. A fact about a process on **this** side, which outlives the far server.
+- `api` — the machine's API answered, or did not, when this server's proxy last carried a request to it. Stamped by traffic that flows anyway rather than by a probe of its own: no timer, no loop, and a machine nobody asks about is simply not measured.
+
+Reading one of these for the other is the connect loop of [#561](https://github.com/Prism-Shadow/penguin-harness/pull/561): a live connection to a dead server read as connected, so every caller that found the machine silent asked for another connect and was told "already connected", forever. **Connect now asks what is actually running over there even when the connection is held**, and starts the server when nothing is — which is also what makes reconnecting, to pick up a new key or retry, cost one probe instead of a refusal.
+
+## The same-origin proxy
+
+`/server/<machineId>/api/…` is dialled through the session to the machine's server. Only `/api` paths — the frontend stays local, so nothing here can leave a window unable to say whether anyone is logged in.
+
+Addressed by the machine's **own id** ([#568](https://github.com/Prism-Shadow/penguin-harness/pull/568)'s), not by its ssh alias: an alias is a line in one config file, so keying URLs on it would break them the moment someone renamed a host, and being base64url, an id needs no percent-encoding in a path.
+
+**One identity.** The caller is this server's admin, and this server's admin is that machine's admin — the ssh access that installed the program there is what authorizes both. The session presented over there is minted through that access (`penguin auth token` on the machine, over the held connection) and reused until near its TTL. The browser's cookies never travel, and the machine's never come back. The proxy mounts inside this server's own auth middleware, admins only.
+
+## What the routes gained
+
+`POST …/connect` is a job of the same shape as an install, `job.kind` telling them apart. `POST …/disconnect` drops the connection and leaves the remote server running — it is that machine's own, and other people may be on it. `GET …/dirs?path=` lists a machine's subdirectories over the connection, so choosing a directory on it costs one command and no round trip to its API.
+
+A held connection stays held: it never idles out, and one that drops — a network blip, keepalives giving up on a dead link — is re-established by the transport itself, with a backoff, until a disconnect lets it go. Connections belong to the generation that opened them: a hot push closes every one this generation holds on its way out, and the next re-holds each the record says was held, five machines at a time, starting a remote server that is down on the way. Nothing is ever closed by a pid remembered from before.
+
+A Windows machine cannot be connected yet — its sshd hands commands to cmd.exe, and there is no shell to hold a session on — and `POST …/connect` says so up front (`409` `connect_unsupported`) rather than failing a POSIX command in the job's log. Browsing a machine's directories requires a held connection: `GET …/dirs` is `404` on a disconnected machine and opens nothing.
diff --git a/changelog/unreleased/2026-09-01-machines-reach.zh.md b/changelog/unreleased/2026-09-01-machines-reach.zh.md
new file mode 100644
index 00000000..42cfe4c3
--- /dev/null
+++ b/changelog/unreleased/2026-09-01-machines-reach.zh.md
@@ -0,0 +1,39 @@
+# 连上一台机器:连接它、代理它、浏览它
+
+- **Date:** 2026-09-01
+- **Type:** feature
+- **Scope:** `server`, `docs`
+- **PR:** [#574](https://github.com/Prism-Shadow/penguin-harness/pull/574)
+
+[English](2026-09-01-machines-reach.md)
+
+已安装的机器现在可以**连接**:本服务端通过 ssh 把它的 `penguin server` 拉起来,并让通往它的那条连接保持打开,它的 API 经此在本源上以 `/server/<machineId>/api/…` 应答。没有任何新的东西在任何地方监听,也没有任何新的连接被打开——机器本就持有的那唯一一条连接承载了它。
+
+## 连接,以及它的代价
+
+连接是一个任务:问那边究竟在跑什么,没在跑就把它的服务端启动,然后让连接保持打开。连接本身就是本服务端对每台机器本来就持有的那一条——一个 `ssh -T -D` 会话——所以「连接」不会新开任何东西;它做的是确保对面有一个能应答的服务端,并记住它所在的端口。
+
+## 每个事实都写明它量的是哪一层
+
+机器上新增了两个事实,并且刻意不与 [#568](https://github.com/Prism-Shadow/penguin-harness/pull/568) 加的那个合并:
+
+- `connection` —— 本服务端对它持有会话。这是关于**本侧**某个进程的事实,它比对面的服务端活得更久。
+- `api` —— 本服务端的代理最近一次把请求送过去时,那台机器的 API 答了、或没答。它由本来就要流动的流量盖章,而不是由一次专门的探测:没有定时器,没有轮询,没人问起的机器就干脆不被测量。
+
+把其中一个当成另一个来读,就是 [#561](https://github.com/Prism-Shadow/penguin-harness/pull/561) 的那个连接死循环:对着已死服务端的活连接被读成「已连接」,于是每一个发现机器不作声的调用者都再请求一次连接,又被告知「已经连上了」,永远如此。**现在即便连接已经持有,连接操作仍然会去问那边究竟在跑什么**,没有在跑就把它启动——这也让「换一把新钥匙」或「重试一次」这类重连只花一次探测,而不是被一句拒绝挡回来。
+
+## 同源代理
+
+`/server/<machineId>/api/…` 经会话拨到那台机器的服务端。只转发 `/api` 路径——前端始终是本地那一份,所以这里不可能出现「整个窗口连自己是否登录都答不上来」的情况。
+
+按机器**自身的 id**([#568](https://github.com/Prism-Shadow/penguin-harness/pull/568) 引入的那个)寻址,而不是按 ssh 别名:别名只是某一台机器配置文件里的一行,用它做 URL 的键,会在有人给主机改名的那一刻全部失效;而 id 是 base64url 的,放进路径里不需要百分号转义。
+
+**只有一个身份。** 调用者是本服务端的管理员,而本服务端的管理员就是那台机器的管理员——授权二者的是同一样东西:当初把程序装过去的那份 ssh 访问权。呈给对面的会话通过这份访问权铸出(在持有的连接上执行机器自己的 `penguin auth token`),并复用到接近其 TTL 为止。浏览器的 cookie 从不过去,机器的也从不回来。代理挂在本服务端自己的鉴权中间件里面,仅限管理员。
+
+## 路由新增了什么
+
+`POST …/connect` 是与安装同一形状的任务,靠 `job.kind` 区分。`POST …/disconnect` 撤掉连接,远端服务端保持运行——那是那台机器自己的服务端,别人可能正在上面。`GET …/dirs?path=` 经这条连接列出机器上的子目录,因此在它上面选一个目录只花一条命令,不必往它的 API 跑一趟。
+
+持有的连接会一直持有:不会因空闲而关闭;断了——网络抖动、keepalive 判定链路已死——由传输层自己带退避重建,直到 disconnect 放手。连接属于打开它的那一代:热推时这一代在退出前关掉自己持有的每一条,下一代按记录把原本持有的逐台重新持有,并发 5,途中把没在跑的远端服务端拉起来。从不按事先记下的 pid 去关任何东西。
+
+Windows 机器目前无法连接——它的 sshd 把命令交给 cmd.exe,没有可以持有会话的 shell——`POST …/connect` 会直接说明(`409` `connect_unsupported`),而不是让一条 POSIX 命令在任务日志里失败。浏览机器目录需要已持有的连接:机器未连接时 `GET …/dirs` 返回 `404`,且不会打开任何东西。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 2f7f2c6b..71731a78 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -112,20 +112,31 @@ In every on-state the effective NO_PROXY always includes `localhost,127.0.0.1,::
| Method | Path | Description |
| --- | --- | --- |
-| GET | /api/projects/:projectId/machines | This machine and the host aliases of the SERVER's own `~/.ssh/config` with what THIS PROJECT has installed on each, the last status probed for each, the version this server would install, and the running or last install job: `{machines: [{id, alias, machineId, installed, elsewhere?, local, status}], imageVersion, job}`. `elsewhere` is a host another Project installed — a machine to adopt rather than install |
+| GET | /api/projects/:projectId/machines | This machine and the host aliases of the SERVER's own `~/.ssh/config` with what THIS PROJECT has installed on each, the last status probed for each, the version this server would install, and the running or last job: `{machines: [{id, alias, machineId, installed, elsewhere?, local, connection, api, status}], imageVersion, job}`. `elsewhere` is a host another Project installed — a machine to adopt rather than install |
| POST | /api/projects/:projectId/machines/probe | Ask this Project's installed machines what they are doing (one ssh round trip each, five at a time) and answer the list with the fresh statuses |
| POST | /api/projects/:projectId/machines/:machineId/install | Start installing this build on that host and give it to this Project; `202` with the same body, the job now running |
+| POST | /api/projects/:projectId/machines/:machineId/connect | Bring that machine's server up and HOLD the one connection to it — an `ssh -T -D` session that never idles out, is re-established on its own if it drops, and is restored after a restart or a hot push; `202` with the same body, the connect job now running. A Windows machine is `409` `connect_unsupported`: there is no shell to hold a session on |
+| POST | /api/projects/:projectId/machines/:machineId/disconnect | Drop the connection. The remote server is left running — it is that machine's own, and other people may be on it |
+| GET | /api/projects/:projectId/machines/:machineId/dirs?path= | The subdirectories of `path` on that machine, over the held connection — what the workspace picker browses. Addressed by the machine's OWN id, like the proxy. `404` when the machine is not connected: a read never opens ssh on its own |
| POST | /api/projects/:projectId/machines/:machineId/release | Drop that machine from this Project; the install on it stays |
-Admin only on a personal server as much as a multi-user one: the install spawns ssh with the **server account's** keys and writes a program directory on another machine, which is an owner's capability rather than a visitor's. Nothing writes to the ssh config — it is read for the aliases it declares, so a config naming hundreds of hosts costs one file read. What an alias means is ssh's own to resolve from that same file, every time it is used, so nothing here can go stale against a config a person edits.
+Admin only on a personal server as much as a multi-user one: the install spawns ssh with the **server account's** keys and writes a program directory on another machine, which is an owner's capability rather than a visitor's. Nothing writes to the ssh config, and nothing resolves it: the list is the config's text (one file read, however many hosts it declares), and an alias is handed to ssh as written — what it means is ssh's to apply, from its own config, every time.
`imageVersion` is what would be pushed, or `null` when this server has no image at all (a development checkout that has never been hot-pushed to is the one such shape) — every install then refuses with `409` `no_install_image`. The version is the running install's own: a hot-pushed server sends the bundle it runs (`0.0.0-hmr.<cli>.<web>`), a tarball or packaged one sends its own tree, so the two ends match by construction.
`installed` is the last install THIS server carried out on that machine — `{version, at}`, or `null` when it never has. It is persisted under the data root, so it survives a restart, a hot push, and installing on some other machine; a record of what was done rather than a survey of the far side, so a machine wiped by hand still reads as installed until the next install corrects it. A failed install records nothing.
-An install is a job, not a request: it probes the far side, may fetch and verify a Node runtime, and copies an image over scp — minutes in the bad case. `POST` starts it and returns at once; the client polls `GET` for `job.log`, which carries the far side's own words (ssh's diagnostics, the remote installer's output). `job.result` is `null` while running, then `{ok: true, kind: "installed" | "already-installed", version}` or `{ok: false, step, message}`. One job at a time; the job lives in memory and does not survive a hot push or a restart, and re-running is the recovery — every step is idempotent.
+`machineId` is that machine's OWN id — 16 base64url characters minted by the server running there (its `machine` table), stable across renames, re-aliasing and reinstalls, and the thing stored references should point at. It is `null` until a server has started on that machine, since nothing has minted one yet; it is learned on the same round trip as `status` and remembered beside the install record. Two aliases for one host report the same `machineId`.
-Refusals decided before any ssh runs have their own codes: `409` `install_running`, `404` `unknown_machine`, `409` `no_install_image`, and `409` `self_install` — the machine this server runs on, which it will not push this build over the program directory it is running from. `self_install` covers an alias pointing back home (`Host localhost`, a second name for this host) as well as the local row, once a probe has heard this server's own id from it.
+`local` marks the machine this server runs on. It is always listed, always installed, always running — it is the thing answering — and is never an install target: `POST …/install` on it is `409` `self_install`.
+
+`status` is `{state, checkedAt, port?, detail?}` with `state` one of `running` / `stopped` / `unreachable`, or `null` when that machine has not been probed. There is no separate ssh status: ssh is the transport, so a machine it cannot reach is `unreachable` and carries OpenSSH's own message in `detail`. `GET` never probes — it reports the last answer — because a probe is an ssh round trip per machine while the list itself is only the config's text. `POST /api/machines/probe` is what spends them, and only on machines something was installed on.
+
+A connected machine's API is reachable at `/server/<machineId>/api/…` on THIS origin, dialled through the one ssh session this server holds to it — a channel inside that session, via its SOCKS port, never a second connection. Addressed by the machine's own id rather than the ssh alias it was reached through: an alias lives in one config file, so keying on it would change a machine's URLs the moment someone renamed a host — and being base64url, an id needs no percent-encoding in a path. **Admin only**, and one identity: the request is made over there as that machine's admin, with a session this server mints through its own ssh access (`penguin auth token` on the machine) — the browser's cookies never cross, and the machine's never come back. Only `/api` is forwarded — the frontend stays local.
+
+An install is a job, not a request: it probes the far side, may fetch and verify a Node runtime, and copies an image over scp — minutes in the bad case. `POST` starts it and returns at once; the client polls `GET` for `job.log`, which carries the far side's own words (ssh's diagnostics, the remote installer's output). A connect (`POST …/connect`) is a job of the same shape, `job.kind` telling the two apart. `job.result` is `null` while running, then `{ok: true, installed: "installed" | "already-installed", version}` for an install, `{ok: true, connected: true}` for a connect, or `{ok: false, step, message}`. One job at a time; the job lives in memory and does not survive a hot push or a restart, and re-running is the recovery — every step is idempotent.
+
+Refusals decided before any ssh runs have their own codes: `409` `install_running`, `404` `unknown_machine`, `409` `no_install_image`, and `409` `self_install` — this server will not push this build over the program directory it is running from. Besides the `local` row, that covers an alias pointing back home (`Host localhost`, a second name for this host) once a probe has heard this server's own id from it.
### Version and Self-Update
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 9940ce4b..561162bf 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -112,20 +112,31 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /api/projects/:projectId/machines | 本机,加上**服务端自身** `~/.ssh/config` 中的主机别名,附带**本 Project** 在每台上安装了什么、每台最近一次探测到的状态、本服务端会安装的版本,以及正在运行或最近一次的安装任务:`{machines: [{id, alias, machineId, installed, elsewhere?, local, status}], imageVersion, job}`。`elsewhere` 表示该主机由别的 Project 装过——可以纳入,不必重装 |
+| GET | /api/projects/:projectId/machines | 本机,加上**服务端自身** `~/.ssh/config` 中的主机别名,附带**本 Project** 在每台上安装了什么、每台最近一次探测到的状态、本服务端会安装的版本,以及正在运行或最近一次的任务:`{machines: [{id, alias, machineId, installed, elsewhere?, local, connection, api, status}], imageVersion, job}`。`elsewhere` 表示该主机由别的 Project 装过——可以纳入,不必重装 |
| POST | /api/projects/:projectId/machines/probe | 询问本 Project 已安装的机器各自的状态(每台一次 ssh 往返,并发 5)并返回带有最新状态的列表 |
| POST | /api/projects/:projectId/machines/:machineId/install | 在该主机上安装当前构建,并把它归入本 Project;返回 `202` 与同样的响应体,此时任务已在运行 |
+| POST | /api/projects/:projectId/machines/:machineId/connect | 把该机器的服务端拉起来,并**持有**对它的那唯一一条连接——一个 `ssh -T -D` 会话,不会因空闲而关闭,断了会自行重建,服务端重启或热推之后也会恢复;返回 `202` 与同样的响应体,此时连接任务已在运行。Windows 机器返回 `409` `connect_unsupported`:那边没有可以持有会话的 shell |
+| POST | /api/projects/:projectId/machines/:machineId/disconnect | 断开连接。远端服务端**保持运行**——那是那台机器自己的服务端,别人可能正在上面 |
+| GET | /api/projects/:projectId/machines/:machineId/dirs?path= | 该机器上 `path` 的子目录,经由持有的连接读取——工作区选择器浏览的就是它。与代理一样,按机器**自身的 id** 寻址。机器未连接时返回 `404`:读取从不自行打开 ssh |
| POST | /api/projects/:projectId/machines/:machineId/release | 把该机器移出本 Project;机器上已安装的程序保持不动 |
-无论个人服务端还是多用户服务端都仅限管理员:安装会以**服务端账户**的密钥派生 ssh,并在另一台机器上写入程序目录——这是所有者的能力,而非访客的。ssh 配置只读不写——只读其中声明的别名,因此哪怕配置声明了几百台主机,列表也只是一次文件读取。别名到底指向什么,每次都由 ssh 自己按同一份文件解析,因此这里不存在与人手改过的配置对不上的陈旧信息。
+无论个人服务端还是多用户服务端都仅限管理员:安装会以**服务端账户**的密钥派生 ssh,并在另一台机器上写入程序目录——这是所有者的能力,而非访客的。ssh 配置只读不写,也从不解析:列表就是配置的文本(无论声明了几百台主机都只是一次文件读取),而别名原样交给 ssh——它的含义由 ssh 自己按自己的配置、每次都重新决定。
`imageVersion` 是将被推送的版本;为 `null` 表示本服务端根本没有安装镜像(只有从未被热推过的源码检出会是这种形态),此时任何安装都会以 `409` `no_install_image` 拒绝。该版本取自当前运行的安装自身:热推过的服务端推送它正在运行的 bundle(`0.0.0-hmr.<cli>.<web>`),tarball 或打包安装则推送自己的程序树,因此两端的一致是构造性的。
`installed` 是**本服务端**最近一次在该机器上完成的安装——`{version, at}`,从未安装过则为 `null`。它持久化在数据根目录下,因此能跨重启、跨热推、跨「在别的机器上安装」而保留;它记录的是本端做过什么,而非对远端的实地探查,所以被手工清空的远端仍显示为已安装,直到下一次安装将其修正。安装失败不写入任何记录。
-安装是任务而非请求:它要探测对端,可能下载并校验一份 Node 运行时,再经 scp 复制镜像——最坏情况以分钟计。`POST` 启动后立即返回,客户端轮询 `GET` 读取 `job.log`,其中是对端自己的原话(ssh 的诊断、远端安装器的输出)。运行期间 `job.result` 为 `null`,结束后为 `{ok: true, kind: "installed" | "already-installed", version}` 或 `{ok: false, step, message}`。同一时刻只允许一个任务;任务存于内存,热推与重启都不保留,重跑即是恢复手段——每一步都是幂等的。
+`machineId` 是该机器**自身**的 id——由运行在那里的服务端铸造的 16 位 base64url 字符(其 `machine` 表),跨改名、改别名与重装都保持不变,是所有存储引用应当指向的东西。该机器上的服务端尚未启动过时为 `null`,因为还没有任何东西铸造过它;它与 `status` 在同一次往返中获取,并记录在安装记录旁。同一主机的两个别名会报告相同的 `machineId`。
-在任何 ssh 运行之前就能判定的拒绝各有错误码:`409` `install_running`、`404` `unknown_machine`、`409` `no_install_image`,以及 `409` `self_install`——本服务端自己所在的那台机器,它不会把这份构建盖到自己正在运行的程序目录上。`self_install` 不只覆盖本机那一行:指回本机的别名(`Host localhost`、本机的第二个名字)一旦被探测到报出本服务端自己的 id,同样会被拒绝。
+`local` 标记服务端自身所在的机器。它始终出现在列表中、始终是已安装、始终在运行——它就是正在应答的那一个——并且永远不是安装目标:对它 `POST …/install` 返回 `409` `self_install`。
+
+`status` 为 `{state, checkedAt, port?, detail?}`,`state` 取 `running` / `stopped` / `unreachable` 之一;该机器尚未被探测时为 `null`。没有单独的 ssh 状态:ssh 是传输方式,因此连不上的机器就是 `unreachable`,并在 `detail` 中保留 OpenSSH 自己的原话。`GET` 从不发起探测——它只报告最近一次的答案——因为一次探测是每台机器一次 ssh 往返,而列表本身只是配置文件的文本。真正花费这些往返的是 `POST /api/machines/probe`,且只针对安装过的机器。
+
+已连接机器的 API 可通过本源上的 `/server/<machineId>/api/…` 访问,经由本服务端持有的那一条 ssh 会话拨达——是该会话内部的一个 channel(走它的 SOCKS 端口),从不是第二条连接。以机器自身的 id 而非它被访问时所用的 ssh 别名寻址:别名只存在于某一份配置文件中,若以它为键,一旦有人重命名主机,该机器的 URL 就会随之改变;而 id 是 base64url,放在路径中无需任何百分号编码。**仅限管理员**,且只有一个身份:请求在对端以那台机器的管理员身份发出,会话由本服务端通过自己的 ssh 权限铸造(在机器上执行 `penguin auth token`)——浏览器的 cookie 不会过去,机器的 cookie 也不会回来。只有 `/api` 会被转发——前端始终是本地的。
+
+安装是任务而非请求:它要探测对端,可能下载并校验一份 Node 运行时,再经 scp 复制镜像——最坏情况以分钟计。`POST` 启动后立即返回,客户端轮询 `GET` 读取 `job.log`,其中是对端自己的原话(ssh 的诊断、远端安装器的输出)。连接(`POST …/connect`)是同一形状的任务,以 `job.kind` 区分。运行期间 `job.result` 为 `null`,结束后安装为 `{ok: true, installed: "installed" | "already-installed", version}`、连接为 `{ok: true, connected: true}`,失败为 `{ok: false, step, message}`。同一时刻只允许一个任务;任务存于内存,热推与重启都不保留,重跑即是恢复手段——每一步都是幂等的。
+
+在任何 ssh 运行之前就能判定的拒绝各有错误码:`409` `install_running`、`404` `unknown_machine`、`409` `no_install_image`,以及 `409` `self_install`——本服务端不会把这份构建盖到自己正在运行的程序目录上。除 `local` 那一行之外,指回本机的别名(`Host localhost`、本机的第二个名字)一旦被探测到报出本服务端自己的 id,同样会被拒绝。
### 版本与在线更新
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index b2ab9434..fb150ac3 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -3348,6 +3348,25 @@ export interface MachineInfo {
machineId: string | null;
/** The host this server itself runs on. Always present, always installed, never a target. */
local: boolean;
+ /**
+ * The connection this server holds to it — the one ssh session everything to the machine
+ * rides (machines/transport/ssh-session.ts): a fact about a process on THIS side, which
+ * outlives the far server. Present means `/server/<id>/api/…` has somewhere to go; whether
+ * a server ANSWERS over there is `status`'s word, from the last probe — and the two must not
+ * be read for each other: taking the connection for the machine's liveness is the mistake
+ * behind the connect loop (#561). Always null for `local`, which needs no connection.
+ */
+ connection: { pid: number } | null;
+ /**
+ * The machine's API as last seen by this server's proxy — stamped by traffic passing
+ * through, never by a probe of its own. `answeredAt` when the last forwarded request got
+ * an HTTP answer (any status: a server that refuses is still answering); `failedAt` and
+ * the transport's own words when the connection had nowhere to deliver. Null until a first
+ * request flows, and only as fresh as the last one — no traffic, no measurement, which is
+ * honest: nothing burns ssh for a page nobody is looking at. Always null for `local`;
+ * this server answering the request that fetched this list is that measurement.
+ */
+ api: { answeredAt: string } | { failedAt: string; detail: string } | null;
/**
* What the last probe found over there, or null when none has been taken. Never filled in
* at list time: a probe costs an ssh round trip per machine, so the list reports the last
@@ -3357,9 +3376,9 @@ export interface MachineInfo {
}
/**
- * A machine's server as of one probe. There is deliberately no separate "ssh" state — ssh is
- * the transport, so a machine it cannot reach reads as `unreachable` with OpenSSH's own
- * diagnostic in `detail` rather than as two states a reader has to combine.
+ * One machine's server state. There is deliberately no separate "ssh" status: ssh is the
+ * transport, so a machine it cannot reach reads as `unreachable` with OpenSSH's own
+ * diagnostic in `detail` rather than as two statuses a reader has to combine.
*/
export interface MachineServerStatus {
state: "running" | "stopped" | "unreachable";
@@ -3372,18 +3391,21 @@ export interface MachineServerStatus {
}
/**
- * The running or last install, polled by GET /api/machines while one runs. `log` carries the
- * far side's own words where there are any: ssh's diagnostics and the remote installer's
- * output say more about a refused key or an unusable Node than a paraphrase would.
+ * The running or last job on a machine — an install, or a connect — polled by GET
+ * /api/machines while one runs. One at a time. `log` carries the far side's own words where
+ * there are any: ssh's diagnostics and the remote installer's output say more about a
+ * refused key or an unusable Node than a paraphrase would.
*/
-export interface MachineInstallJob {
+export interface MachineJob {
+ kind: "install" | "connect";
machineId: string;
alias: string;
running: boolean;
log: string[];
result:
| null
- | { ok: true; kind: "installed" | "already-installed"; version: string | null }
+ | { ok: true; installed: "installed" | "already-installed"; version: string | null }
+ | { ok: true; connected: true }
| { ok: false; step: string; message: string };
}
@@ -3396,5 +3418,5 @@ export interface MachinesResponse {
* checkout, which stands on no release the remote could download.
*/
imageVersion: string | null;
- job: MachineInstallJob | null;
+ job: MachineJob | null;
}
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 13c17fb0..07a712f2 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -168,6 +168,7 @@ import { machinesRoutes } from "./http/routes/machines.js";
import { UsageRecorder } from "./runtime/usage-recorder.js";
import { previewRoutes } from "./http/routes/preview.js";
import { MachinesService } from "./machines/service.js";
+import { SERVER_PROXY_PREFIX, machinesProxy } from "./machines/proxy.js";
export interface AppDeps {
config: ServerConfig;
@@ -1195,6 +1196,25 @@ export function createApp(
// For that reason /api/install is deliberately absent from RUNTIME_PREFIXES above — the
// platform must serve it, not decline it.
app.route("/api/install", installRoutes(deps));
+ // `/server/<machineId>/api/…` — a connected machine's API, forwarded over the forward held
+ // to it and addressed by the machine's OWN id. Admins only: the request is made over there
+ // as that machine's admin, with a session this server minted over the ssh access that
+ // installed it, so this server's admin session is the one credential involved.
+ const serverProxy = machinesProxy(
+ (machineId) => deps.machines.proxyTarget(machineId),
+ (machineId, outcome) => deps.machines.noteApiSeen(machineId, outcome),
+ );
+ app.all(
+ `${SERVER_PROXY_PREFIX}*`,
+ authMiddleware(deps.authService, deps.config.trustProxy),
+ async (c) => {
+ if (!c.var.user.isAdmin) {
+ throw new HttpError(403, "admin_required", "Only an admin can reach a machine's API.");
+ }
+ const answer = await serverProxy(c.req.raw);
+ return answer ?? c.notFound();
+ },
+ );
// Protected routes: cookie -> auth_session -> user, over the runtime's auth service.
app.use("/api/*", authMiddleware(deps.authService, deps.config.trustProxy));
diff --git a/packages/server/src/db/repos/machines.ts b/packages/server/src/db/repos/machines.ts
index fb2b351a..d7962c29 100644
--- a/packages/server/src/db/repos/machines.ts
+++ b/packages/server/src/db/repos/machines.ts
@@ -1,12 +1,9 @@
/**
* What this server remembers about machines: its own identity, one row per machine it has
- * installed on, and which machines each Project uses. In web.db, so a hot swap or a restart reads back exactly
+ * installed on or reached (what is installed there, the session held to it), and which
+ * machines each Project uses. All in web.db, so a hot swap or a restart reads back exactly
* what the last generation wrote — the JSON file this replaces could not survive a schema
* change, and nothing else this server remembers lives outside the database.
- *
- * `MachineRow` mirrors the table rather than the columns written today: the DDL lands in one
- * migration, and the fields nothing reads yet (a machine's own id, the session held to it)
- * are the table's, not this store's opinion of what matters.
*/
import type { DatabaseSync } from "node:sqlite";
import { randomBytes } from "node:crypto";
@@ -19,7 +16,12 @@ export interface MachineRow {
/** What this server last installed there; null when it never has. */
version: string | null;
installedAt: string | null;
- /** The ssh session this server holds to it — recorded so a successor generation can close it. */
+ /**
+ * Non-null while a connection to it is HELD: the pid of the session as of the last connect.
+ * A record of intent, not a handle — a restart or a hot push re-holds every machine with one,
+ * and a disconnect clears it. It is never used to kill anything: a pid read back from a file
+ * may by then be anyone's.
+ */
sessionPid: number | null;
/** The port its server was bound to over there, as of the last connect. */
remotePort: number | null;
@@ -63,6 +65,20 @@ export class MachinesRepo {
return row === undefined ? null : toRow(row);
}
+ /**
+ * Every row answering to a machine's own id — two aliases for one host are two rows with
+ * one id. Newest install first, then by address, so the order is the same every time; which
+ * of them to speak through is the service's to decide (it knows which has a session).
+ */
+ byMachineId(machineId: string): MachineRow[] {
+ return this.db
+ .prepare(
+ "SELECT * FROM machines WHERE machine_id = ? ORDER BY installed_at DESC, address ASC",
+ )
+ .all(machineId)
+ .map(toRow);
+ }
+
all(): MachineRow[] {
return this.db.prepare("SELECT * FROM machines").all().map(toRow);
}
diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.ts
index 9f5cd2ac..91257934 100644
--- a/packages/server/src/hmr/platform.ts
+++ b/packages/server/src/hmr/platform.ts
@@ -226,6 +226,12 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
void deps.sessionService.adoptUnmanagedTraceSessions().catch((err: unknown) => {
errors.record({ source: "process", err, code: "trace_adoption_failed" });
});
+ // Machines: re-hold every connection the record says was held, starting a remote
+ // server that is down on the way. Fire-and-forget for the same reason: a host that is
+ // slow to answer must not hold up the App that serves everything else.
+ void deps.machines.start().catch((err: unknown) => {
+ errors.record({ source: "process", err, code: "machines_reconnect_failed" });
+ });
}
// Ordinary code over this App's own auth (terminal/identity.ts): the same object the
@@ -261,6 +267,8 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
// commands (dev servers etc.) that would otherwise run on
// orphaned and invisible to the successor's fresh Session
// - reap timers TerminalManager.quiesce runs them now (dead ptys only)
+ // - machine connections stop() closes every ssh session this generation opened;
+ // successor start() re-holds each the record says was held
// DETACHED (the object survives, this App's grip on it does not):
// - pty exit listeners unsubscribed, so a dead generation never releases a
// registry id the successor owns
@@ -286,6 +294,7 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
if (business !== null) {
business.scheduler.stop();
business.messaging.stop();
+ business.machines.stop();
drains.push(business.manager.shutdown(DRAIN_GRACE_MS));
}
drained = Promise.allSettled(drains).then(() => undefined);
diff --git a/packages/server/src/http/routes/machines.ts b/packages/server/src/http/routes/machines.ts
index 5498fb24..4e0babbe 100644
--- a/packages/server/src/http/routes/machines.ts
+++ b/packages/server/src/http/routes/machines.ts
@@ -1,35 +1,30 @@
/**
- * Machines routes, under a Project (admin only, 403 for non-admins). Relative to
- * `/api/projects/:projectId/machines`:
+ * Machines routes, under a Project (admin only). Relative to `/api/projects/:projectId/machines`:
*
- * POST /probe — refresh the statuses of this Project's machines (one ssh round
- * trip each), then answer the list.
- * POST /:machineId/install — start an install and give the machine to this Project; 202, or
- * 409 when one runs.
- * POST /:machineId/release — drop it from this Project. The install stays.
- * GET / — this machine and the ssh config's host aliases with what this
- * Project has installed on each, the last status probed for each,
- * the version this server would install, and the running or last
- * job.
+ * GET / — this machine and the ssh config's host aliases, the version
+ * this server would install, the last status probed for each,
+ * and the running or last job.
+ * POST /probe — refresh the statuses of this Project's machines (one ssh
+ * round trip each), then answer the list.
+ * POST /:machineId/install — start an install and give the machine to this Project; 202,
+ * or 409 when one runs.
+ * POST /:machineId/release — drop it from this Project. The install stays.
+ * POST /:machineId/connect — bring that machine's server up and hold a tunnel to it; 202,
+ * or 409 when a connect already runs.
+ * POST /:machineId/disconnect — drop the tunnel (the remote server stays up).
+ * GET /:machineId/dirs?path= — browse that machine's directories over ssh.
*
- * Under a Project because the page is, and because a Project's machines are where that
- * Project's work runs. The machine itself is not project-scoped — one host, one program,
- * shared by every Project that adopted it; what a Project owns is the membership.
+ * Under a Project because the page is, and because this Project's Model credentials go to
+ * this Project's machines and no others (machines/models-sync.ts). The machine itself is not
+ * project-scoped: connect, disconnect and dirs act on one host, shared by every Project using
+ * it; what a Project owns is the membership.
*
- * Admin rather than any logged-in user, on a multi-user server as much as a personal one:
- * installing spawns ssh with the SERVER ACCOUNT's keys and writes a program directory on
- * another machine. That is an owner's capability, not a visitor's, and the account whose
- * keys are used is not the account making the request. The Project scope says WHICH
- * machines are answered, never who may reach them.
- *
- * The install is a job because it can take minutes (see ../../machines/service.ts); this
- * route only starts it and reports it. Progress arrives by polling GET rather than over the
- * event channel — the log lines belong to one page that is open while it waits, and a job
- * that dies with its App has nothing to replay to a reconnecting subscriber.
+ * Admin rather than any logged-in user: installing spawns ssh with the SERVER ACCOUNT's keys
+ * and writes a program directory on another machine — an owner's capability, not a visitor's.
*/
import { Hono } from "hono";
import type { Context } from "hono";
-import type { MachinesResponse } from "../../api/types.js";
+import type { DirListResponse, MachinesResponse } from "../../api/types.js";
import { HttpError } from "../errors.js";
import { requireValidId } from "../validate.js";
import type { AppEnv } from "../../auth/middleware.js";
@@ -38,6 +33,9 @@ import type { AppDeps } from "../../app.js";
export function machinesRoutes(deps: AppDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
+ // Admin AND a member of the Project: the Project scope says WHICH machines are answered,
+ // never who may reach them. Installing still spawns ssh with the server account's keys, so
+ // a Project owner who is not an admin does not get that capability by owning a Project.
app.use("*", async (c, next) => {
if (!c.var.user.isAdmin) {
throw new HttpError(403, "admin_required", "Only an admin can install on a machine.");
@@ -54,16 +52,14 @@ export function machinesRoutes(deps: AppDeps): Hono<AppEnv> {
app.get("/", (c) => c.json(state(c)));
+ // Probing is a POST because it spends ssh round trips — a GET that spawns processes is a
+ // GET a proxy or a prefetch may fire on its own. The page drives the schedule, so nothing
+ // here runs when nobody is looking at the page.
app.post("/probe", async (c) => {
await deps.machines.probeInstalled(requireValidId(c, "projectId"));
return c.json(state(c));
});
- app.post("/:machineId/release", (c) => {
- deps.machines.release(requireValidId(c, "projectId"), c.req.param("machineId"));
- return c.json(state(c));
- });
-
app.post("/:machineId/install", async (c) => {
const started = await deps.machines.startInstall(
requireValidId(c, "projectId"),
@@ -94,5 +90,71 @@ export function machinesRoutes(deps: AppDeps): Hono<AppEnv> {
return c.json(state(c), 202);
});
+ app.post("/:machineId/connect", async (c) => {
+ const started = await deps.machines.startConnect(c.req.param("machineId"));
+ if (!started.ok) {
+ if (started.why === "busy") {
+ throw new HttpError(409, "connect_running", "A connect is already running.");
+ }
+ if (started.why === "unknown-machine") {
+ throw new HttpError(404, "unknown_machine", "No such host in this server's ssh config.");
+ }
+ if (started.why === "self") {
+ throw new HttpError(
+ 409,
+ "self_connect",
+ "That is the machine this server runs on — you are already on it.",
+ );
+ }
+ if (started.why === "not-installed") {
+ throw new HttpError(
+ 409,
+ "not_installed",
+ "Nothing is installed on that machine yet. Install it first.",
+ );
+ }
+ if (started.why === "unsupported") {
+ throw new HttpError(
+ 409,
+ "connect_unsupported",
+ "A Windows machine cannot be connected yet: its sshd hands commands to cmd.exe, and there is no shell to hold a session on.",
+ );
+ }
+ throw new HttpError(409, "connect_refused", "That machine cannot be connected to.");
+ }
+ return c.json(state(c), 202);
+ });
+
+ // Addressed by the machine's OWN id, like the proxy: this answers "what is on THAT
+ // machine", and the ssh alias it happens to be reached through is not that machine's name.
+ app.get("/:machineId/dirs", async (c) => {
+ const listing = await deps.machines.listDirs(
+ c.req.param("machineId"),
+ c.req.query("path") ?? "",
+ );
+ if (listing === null) {
+ throw new HttpError(
+ 404,
+ "dir_not_found",
+ "That machine could not be reached, or that directory does not exist on it.",
+ );
+ }
+ return c.json(listing satisfies DirListResponse);
+ });
+
+ /**
+ * Drops a machine from this Project. Deliberately leaves the install alone: another Project
+ * may be using it, and "stop listing this here" is not "go wipe that machine".
+ */
+ app.post("/:machineId/release", (c) => {
+ deps.machines.release(requireValidId(c, "projectId"), c.req.param("machineId"));
+ return c.json(state(c));
+ });
+
+ app.post("/:machineId/disconnect", (c) => {
+ deps.machines.disconnect(c.req.param("machineId"));
+ return c.json(state(c));
+ });
+
return app;
}
diff --git a/packages/server/src/machines/commands.ts b/packages/server/src/machines/commands.ts
index 986c8ea4..e3b3bd80 100644
--- a/packages/server/src/machines/commands.ts
+++ b/packages/server/src/machines/commands.ts
@@ -13,8 +13,8 @@
* everything rides the ONE connection ssh-session.ts holds per machine: commands, the
* installer and the store on its stdin, every TCP connection through its SOCKS port. A POSIX
* install is therefore the installer going in on that stdin, the same shape as the documented
- * `curl … | sh`, which is what lets the scratch directory, the scp and the cleanup disappear
- * entirely.
+ * `curl … | sh`, which is what lets the scratch directory, the scp and the cleanup
+ * disappear entirely.
*
* Two further rules encoded here:
* - **BatchMode.** A GUI app has no terminal: an ssh that decides to ask for a password or a
@@ -40,9 +40,6 @@ export function cmdQuote(value: string): string {
return `"${value}"`;
}
-export const quoteFor = (platform: RemotePlatform, value: string): string =>
- platform === "win32" ? cmdQuote(value) : shQuote(value);
-
export interface RemoteTarget {
/** Alias as written in ~/.ssh/config — what the user picked. */
alias: string;
@@ -177,6 +174,24 @@ export function unpackStoreCommand(platform: RemotePlatform): string {
return `mkdir -p "${root}" && tar -xzf - -C "${root}"`;
}
+/**
+ * Starts the installed server in the background and returns at once; readiness is the
+ * caller's probe. `nohup` and the redirections are what let it outlive the shell that ran it,
+ * and the log is the far side's own words when it comes up and dies.
+ */
+export function startServerCommand(port: number): string {
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`bad port ${port}`);
+ const log = `"${REMOTE_PROGRAM_DIR}/data/server.log"`;
+ // --host is PINNED, not defaulted: the CLI falls back to the HOST environment variable when
+ // it is omitted, so a login shell carrying HOST=0.0.0.0 would put that machine's server on
+ // every interface. This side only ever reaches it as a channel inside the ssh session, at
+ // loopback on the far end, so binding wider is exposure with nothing asking for it.
+ return `mkdir -p "${REMOTE_PROGRAM_DIR}/data" && nohup ${REMOTE_PENGUIN} server --host 127.0.0.1 --port ${port} >> ${log} 2>&1 < /dev/null &`;
+}
+
+/** The last lines of that log, for a start that did not answer. */
+export const SERVER_LOG_TAIL = `tail -n 20 "${REMOTE_PROGRAM_DIR}/data/server.log" 2>/dev/null`;
+
// --- tunnelling to that server ---------------------------------------------------------------
/**
@@ -207,3 +222,28 @@ export function sessionArgs(target: RemoteTarget, socksPort: number): string[] {
"sh",
];
}
+
+/** Marker separating the resolved path from the entries in a directory listing. */
+export const DIR_LIST_MARK = "---penguin-dirs---";
+
+/**
+ * Lists the subdirectories of `dir` on the far side, plus the path it actually resolved to.
+ *
+ * An empty `dir` means that machine's home, which is the picker's starting point. The path
+ * is resolved over THERE (`cd` + `pwd -P`) because only that machine can say what `~` or a
+ * symlink means on it — resolving here would be this machine answering a question about
+ * another one's filesystem.
+ *
+ * Hidden directories are dropped, matching what the local browser shows, and everything is
+ * quoted for the remote shell by the caller's quoting rules.
+ */
+export function listDirsCommand(dir: string): string {
+ const target = dir === "" ? '"$HOME"' : shQuote(dir);
+ return [
+ `cd ${target} 2>/dev/null || exit 3`,
+ `pwd -P`,
+ `echo ${DIR_LIST_MARK}`,
+ // -1 one per line, trailing slash marks directories, then keep only those.
+ `ls -1p 2>/dev/null | grep '/$' | sed 's:/$::' | grep -v '^\\.' || true`,
+ ].join("; ");
+}
diff --git a/packages/server/src/machines/proxy.ts b/packages/server/src/machines/proxy.ts
new file mode 100644
index 00000000..ad2ba573
--- /dev/null
+++ b/packages/server/src/machines/proxy.ts
@@ -0,0 +1,178 @@
+/**
+ * The same-origin server proxy: `/server/<machineId>/api/…` on THIS server forwards to that
+ * machine's server through the forward held to it.
+ *
+ * Addressed by the machine's OWN id, not the ssh alias it was reached through: an alias is a
+ * line in one config file, and renaming it would change every URL below. Only `/api/` paths
+ * are forwarded — the frontend stays local and re-points its API calls by prefix.
+ *
+ * ONE IDENTITY. The caller is this server's admin, and this server's admin is that
+ * machine's admin: the ssh access that installed the program there is what authorizes it,
+ * and the session presented to the machine is one this server mints over that access
+ * (remote-token.ts). The browser's own cookies never travel, and the machine's never come
+ * back — so this mounts INSIDE this server's auth middleware, for admins.
+ */
+import http from "node:http";
+import { Readable } from "node:stream";
+
+/** Path prefix of the proxy: `/server/<id>/api/…`. */
+export const SERVER_PROXY_PREFIX = "/server/";
+
+/** A parsed proxy path: which machine, and the remote-side path to request. */
+interface ProxyPath {
+ machineId: string;
+ /** The path forwarded to the remote, always starting `/api/`. */
+ remotePath: string;
+}
+
+/** Parses `/server/<machineId>/api/…` (query preserved by the caller); null for anything else. */
+export function parseProxyPath(pathname: string): ProxyPath | null {
+ if (!pathname.startsWith(SERVER_PROXY_PREFIX)) return null;
+ const rest = pathname.slice(SERVER_PROXY_PREFIX.length);
+ const slash = rest.indexOf("/");
+ if (slash <= 0) return null;
+ const machineId = decodeURIComponent(rest.slice(0, slash));
+ const remotePath = rest.slice(slash);
+ if (!remotePath.startsWith("/api/") && remotePath !== "/api") return null;
+ return { machineId, remotePath };
+}
+
+/** An absolute-path Location from the remote, re-rooted under the proxy prefix. */
+export function rewriteLocation(header: string, machineId: string): string {
+ return header.startsWith("/")
+ ? `${SERVER_PROXY_PREFIX}${encodeURIComponent(machineId)}${header}`
+ : header;
+}
+
+/**
+ * Hop-by-hop and identity headers that must not cross.
+ *
+ * `authorization` among them: the proxy speaks to the machine as ITS admin, with a session
+ * this server mints over ssh, and a caller's own bearer is a credential for THIS server. Sent
+ * on, it would both hand that credential to another machine and outrank the cookie just
+ * minted, since the remote's auth reads a bearer first.
+ */
+const DROP_REQUEST_HEADERS = new Set([
+ "host",
+ "cookie",
+ "authorization",
+ "connection",
+ "keep-alive",
+ "upgrade",
+]);
+const DROP_RESPONSE_HEADERS = new Set(["set-cookie", "location", "connection", "keep-alive"]);
+
+/**
+ * Forwards one request to the machine's server and streams the answer back — both
+ * directions are pipes, so SSE and long downloads flow as they arrive. The socket is the
+ * agent's: a dial through the machine's session (transport/connection.ts). node:http rather
+ * than fetch: the Host header must be the canonical app host (`localhost:<port>`), and the
+ * socket is not one fetch could be handed.
+ */
+function proxyThroughSession(
+ request: Request,
+ path: ProxyPath,
+ agent: http.Agent,
+ port: number,
+ cookie: string,
+ report?: ProxyReport,
+): Promise<Response> {
+ return new Promise((resolve) => {
+ const url = new URL(request.url);
+ const headers: Record<string, string> = {};
+ request.headers.forEach((value, name) => {
+ if (!DROP_REQUEST_HEADERS.has(name.toLowerCase())) headers[name] = value;
+ });
+ headers["host"] = `localhost:${port}`;
+ headers["cookie"] = cookie;
+
+ const upstream = http.request(
+ {
+ agent,
+ host: "127.0.0.1",
+ port,
+ path: `${path.remotePath}${url.search}`,
+ method: request.method,
+ headers,
+ },
+ (res) => {
+ report?.(path.machineId, { ok: true });
+ const out = new Headers();
+ for (const [name, value] of Object.entries(res.headers)) {
+ if (value === undefined || DROP_RESPONSE_HEADERS.has(name.toLowerCase())) continue;
+ out.set(name, Array.isArray(value) ? value.join(", ") : value);
+ }
+ if (res.headers.location !== undefined) {
+ out.set("location", rewriteLocation(res.headers.location, path.machineId));
+ }
+ resolve(
+ new Response(
+ res.statusCode === 204 || res.statusCode === 304
+ ? null
+ : (Readable.toWeb(res) as ReadableStream),
+ { status: res.statusCode ?? 502, headers: out },
+ ),
+ );
+ },
+ );
+ upstream.on("error", (err) => {
+ report?.(path.machineId, { ok: false, detail: err.message });
+ resolve(
+ Response.json(
+ {
+ error: {
+ code: "server_unreachable",
+ message: `The connection to ${path.machineId} did not answer: ${err.message}`,
+ },
+ },
+ { status: 502 },
+ ),
+ );
+ });
+ if (request.body !== null) {
+ Readable.fromWeb(request.body as import("node:stream/web").ReadableStream).pipe(upstream);
+ } else {
+ upstream.end();
+ }
+ });
+}
+
+/**
+ * The seam handler: `/server/<id>/api/…` → that machine, or a clear answer when there is
+ * nothing to forward to. `resolve` is the machines service's lookup: a dial through the
+ * session, the port over there and a session cookie, or null when it is not connected.
+ */
+/**
+ * Told what each forwarded request learned: the machine's API answered, or the forward had
+ * nowhere to deliver. The machines service stamps it into the list's `api` fact — passive
+ * measurement, riding traffic that flows anyway (api/types.ts on MachineInfo.api).
+ */
+export type ProxyReport = (
+ machineId: string,
+ outcome: { ok: true } | { ok: false; detail: string },
+) => void;
+
+export function machinesProxy(
+ resolve: (
+ machineId: string,
+ ) => Promise<{ agent: http.Agent; port: number; cookie: string } | null>,
+ report?: ProxyReport,
+): (request: Request) => Promise<Response | null> {
+ return async (request) => {
+ const path = parseProxyPath(new URL(request.url).pathname);
+ if (path === null) return null;
+ const target = await resolve(path.machineId);
+ if (target === null) {
+ return Response.json(
+ {
+ error: {
+ code: "not_connected",
+ message: `No live forward to ${path.machineId}; connect to it first.`,
+ },
+ },
+ { status: 503 },
+ );
+ }
+ return proxyThroughSession(request, path, target.agent, target.port, target.cookie, report);
+ };
+}
diff --git a/packages/server/src/machines/remote-token.ts b/packages/server/src/machines/remote-token.ts
new file mode 100644
index 00000000..48fd71ad
--- /dev/null
+++ b/packages/server/src/machines/remote-token.ts
@@ -0,0 +1,78 @@
+/**
+ * Getting a session on a machine by asking its own CLI for one.
+ *
+ * `penguin auth token` mints a short-lived session from the data root the ssh account
+ * already owns. What authorizes it is that access, not a secret — anyone who can run it can
+ * already read every credential on that machine by hand — so it keeps working on a machine
+ * whose admin password a person has set. One command over the shared connection.
+ */
+import { execFailureText } from "./transport/index.js";
+import { REMOTE_PENGUIN } from "./commands.js";
+import type { RemoteTarget } from "./commands.js";
+import type { ExecResult } from "./transport/index.js";
+
+/** Precedes the token on its own line — the same mark the CLI prints (cli/commands/auth.ts). */
+const TOKEN_MARK = "---penguin-auth-token---";
+
+type RemoteTokenOutcome =
+ | { kind: "minted"; token: string }
+ /** The machine could not mint one — most often a build older than the command. Not a failure: the page offers a sign-in by hand. */
+ | { kind: "unsupported"; detail: string }
+ | { kind: "failed"; detail: string };
+
+/**
+ * The command that asks for a token. `--ttl-seconds` is deliberately short: this is used
+ * immediately, and a token still lying in a log an hour from now is worth nothing.
+ */
+export function authTokenCommand(ttlSeconds = 3600): string {
+ if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1) throw new Error(`bad ttl ${ttlSeconds}`);
+ // `--mark` is what makes the output parseable: without it the CLI prints the bare token,
+ // and parseToken has no anchor to find it by in a shell that may print a banner of its own.
+ return `${REMOTE_PENGUIN} auth token --ttl-seconds ${ttlSeconds} --mark 2>&1`;
+}
+
+/**
+ * Reads the token out of the CLI's output.
+ *
+ * Anchored on the marker and taking the FIRST non-empty line after it: the command runs
+ * through a shell whose profile may print anything it likes, and a banner is not a credential.
+ */
+export function parseToken(output: string): string | null {
+ const at = output.indexOf(TOKEN_MARK);
+ if (at === -1) return null;
+ for (const line of output.slice(at + TOKEN_MARK.length).split("\n")) {
+ const value = line.trim();
+ if (value !== "") return value;
+ }
+ return null;
+}
+
+/** Asks a machine's CLI for a session token, over the connection that is already open. */
+export async function mintTokenOnRemote(
+ target: RemoteTarget,
+ runOn: (target: RemoteTarget, command: string) => Promise<ExecResult>,
+ ttlSeconds = 3600,
+): Promise<RemoteTokenOutcome> {
+ // `runOn` rides the machine's shared ssh connection, which can be gone by the time this
+ // asks — and it REJECTS rather than answering when it is. Every other way of not getting a
+ // token is a returned outcome, and the caller reads outcomes: letting this one throw skips
+ // the password fallback below it entirely and reaches the route as a 500, so a machine
+ // whose connection dropped answers "internal error" instead of "could not sign in there".
+ let result: ExecResult;
+ try {
+ result = await runOn(target, authTokenCommand(ttlSeconds));
+ } catch (err) {
+ return { kind: "failed", detail: err instanceof Error ? err.message : String(err) };
+ }
+ const token = parseToken(result.stdout);
+ if (token !== null) return { kind: "minted", token };
+ if (result.timedOut) {
+ return { kind: "failed", detail: execFailureText(result, "it did not answer in time") };
+ }
+ // No marker: an older install whose CLI has no such command, a missing binary, or a data
+ // root with no database. All of them mean "ask another way", which is the caller's move.
+ return {
+ kind: "unsupported",
+ detail: result.stdout.trim().split("\n").slice(-1)[0] ?? "no token came back",
+ };
+}
diff --git a/packages/server/src/machines/server-control.ts b/packages/server/src/machines/server-control.ts
new file mode 100644
index 00000000..0a8b4955
--- /dev/null
+++ b/packages/server/src/machines/server-control.ts
@@ -0,0 +1,42 @@
+/**
+ * Starting the INSTALLED server on a remote machine.
+ *
+ * One command on the shared shell — `nohup penguin server … &` — and then the status probe,
+ * on that same shell, until the server answers. Neither costs a handshake.
+ *
+ * The remote server is a plain `penguin server` process, never supervised from here. A
+ * machine that reboots simply reads as "not running" on the next probe.
+ */
+import { SERVER_LOG_TAIL, startServerCommand } from "./commands.js";
+import type { RemoteTarget } from "./commands.js";
+import type { ExecResult } from "./transport/index.js";
+import { probeServerState } from "./server-state.js";
+
+/** How long a freshly started server gets to answer on its port. */
+const START_TIMEOUT_MS = 30_000;
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/**
+ * Starts the remote server on the given port and waits until it answers there. Failure
+ * carries the far side's own words — its server log's last lines when the process came up
+ * and died, which say more about a port collision or a broken install than "did not start".
+ */
+export async function startRemoteServer(
+ target: RemoteTarget,
+ port: number,
+ exec: (target: RemoteTarget, command: string) => Promise<ExecResult>,
+): Promise<{ ok: true } | { ok: false; detail: string }> {
+ const started = await exec(target, startServerCommand(port));
+ if (started.code !== 0) {
+ return { ok: false, detail: started.stdout.trim() || "the machine could not start it." };
+ }
+ const deadline = Date.now() + START_TIMEOUT_MS;
+ while (Date.now() < deadline) {
+ await sleep(500);
+ const probed = await probeServerState(target, exec);
+ if (probed.state.kind === "running") return { ok: true };
+ }
+ const tail = (await exec(target, SERVER_LOG_TAIL)).stdout.trim();
+ return { ok: false, detail: tail || "it did not answer within 30s." };
+}
diff --git a/packages/server/src/machines/service.ts b/packages/server/src/machines/service.ts
index bd76d669..8aaa4571 100644
--- a/packages/server/src/machines/service.ts
+++ b/packages/server/src/machines/service.ts
@@ -1,11 +1,15 @@
/**
* The machines service: this server's own `~/.ssh/config` as a list of targets, and putting
- * this build on one of them.
+ * this build on one of them, reaching it, and keeping it configured.
*
- * An install is a JOB, not a request. It probes the far side, has it download and install
- * this server's base release, and streams the hmr state across — minutes, in the bad case —
- * so POST starts it and the Web App polls for the progress lines. One at a time: the
- * surface is a person installing on one machine.
+ * ONE JOB at a time — an install or a connect — started by POST and polled by the Web App
+ * for its progress lines. The job lives in this App's memory; what it achieved is in web.db
+ * (MachinesRepo): which machines carry this program, the session held to each, and which
+ * Project uses which. Every word to a machine leaves through its MachineConnection
+ * (transport/connection.ts) — ONE ssh session per machine, carrying commands on its stdin
+ * and every TCP connection as a channel through its SOCKS port — and every request to a
+ * machine's API is made as its admin, with a session this server mints over the ssh access
+ * that installed it.
*
* The JOB is not persisted. It lives in this App's memory and dies with it (see the park
* list in ../hmr/platform.ts — it is on the SUSPENDED side): a hot push during an install
@@ -13,62 +17,79 @@
* step is idempotent — the far side's installer stages, smoke-tests and swaps, and an
* unchanged version is a no-op.
*
- * The RESULT is, in web.db (MachinesRepo): which machines carry this program, and which
- * Project uses which. It has to outlive the job, the process and the next install somewhere
- * else. It is a record of what WE did, not a survey of the far side — a machine someone
- * wiped by hand still reads as installed here, and the install itself is what corrects that,
- * since it probes the remote before deciding anything.
- *
* A machine BELONGS TO A PROJECT. The host is shared — one program, one ssh config entry —
* but which Projects use it is this server's own bookkeeping, because a Project's machines
* are where that Project's work runs. A host installed for another Project is reported as
* `elsewhere` rather than hidden: adopting it costs a row, while re-installing costs a
* 30 MB transfer to reach the same place.
*/
+import fs from "node:fs";
import os from "node:os";
-import { VERSION } from "@prismshadow/penguin-core";
-import type { MachineInfo, MachineInstallJob, MachineServerStatus } from "../api/types.js";
+import { DEFAULT_SERVER_PORT, VERSION } from "@prismshadow/penguin-core";
+import type { MachineInfo, MachineJob, MachineServerStatus } from "../api/types.js";
import { readServerLock } from "../lock.js";
-import { connectionTo, listHostAliases } from "./transport/index.js";
-import type { ExecResult } from "./transport/index.js";
+import { SESSION_COOKIE } from "../auth/middleware.js";
+import http from "node:http";
+import {
+ closeAllConnections,
+ closeConnectionTo,
+ connectionTo,
+ listHostAliases,
+ sessionOf,
+} from "./transport/index.js";
+import type { MachineConnection, ShellSession } from "./transport/index.js";
+import { machineIdentity } from "./ssh-config.js";
+import { DIR_LIST_MARK, listDirsCommand } from "./commands.js";
import type { RemoteTarget } from "./commands.js";
+import type { ExecResult } from "./transport/index.js";
import { installOnRemote, resolvePushPlan } from "./install-server.js";
import { probeServerState } from "./server-state.js";
-import type { MachinesRepo } from "../db/repos/machines.js";
-
-/** The id of the entry standing for the machine this server runs on. */
-const LOCAL_MACHINE_ID = "local";
-
-/** How many machines the probe works on at once. */
-const CONCURRENCY = 5;
+import { mintTokenOnRemote } from "./remote-token.js";
+import { startRemoteServer } from "./server-control.js";
+import type { MachineRow, MachinesRepo } from "../db/repos/machines.js";
-/** Why a start was refused before any ssh ran. */
-export type InstallRefusal = "busy" | "unknown-machine" | "no-image" | "self";
+/** Why an install was refused before any ssh ran. */
+type InstallRefusal = "busy" | "unknown-machine" | "no-image" | "self";
+/** Why a connect was refused before any ssh ran. */
+type ConnectRefusal = "busy" | "unknown-machine" | "not-installed" | "self" | "unsupported";
/**
- * The three things this service does to the world, injectable as a set. Production passes
- * none of them; tests pass all three, because the real ones read the developer's own
- * ~/.ssh/config and spawn ssh against whatever it names. The push path itself is covered
- * where it belongs — machines-push.test.ts drives the real installOnRemote against a fake
- * ssh binary — so what is faked here is only the reaching-out, never the logic under test.
+ * What this service does to the world, injectable as a set. Production passes none of them;
+ * tests fake the reaching-out, because the real ones read the developer's own ~/.ssh/config
+ * and spawn ssh against whatever it names. The push path itself is covered where it belongs
+ * — machines-push.test.ts drives the real installOnRemote against a fake ssh binary — so
+ * what is faked here is only the reaching-out, never the logic under test.
*/
export interface MachinesEffects {
listAliases: typeof listHostAliases;
resolvePlan: typeof resolvePushPlan;
install: typeof installOnRemote;
probe: typeof probeServerState;
- /** One command on a machine, over its own ssh. */
+ /** One command on a machine, over its shared shell. */
runOn: (target: RemoteTarget, command: string) => Promise<ExecResult>;
+ startServer: (target: RemoteTarget, port: number) => ReturnType<typeof startRemoteServer>;
+ /** Brings the one connection to a machine up and HOLDS it (transport/connection.ts). */
+ hold: (target: RemoteTarget) => ReturnType<MachineConnection["hold"]>;
+ /** The connection held to a machine, while it is up. */
+ session: (address: string) => ShellSession | null;
+ /** An http.Agent that dials that machine's server through its session. */
+ agent: (target: RemoteTarget, remotePort: number) => http.Agent;
/** Injected so a test can pin the recorded timestamp instead of asserting around the clock. */
now: () => Date;
}
+/** The id of the entry standing for the machine this server runs on. */
+const LOCAL_MACHINE_ID = "local";
+
+/** How many machines are worked on at once by the automatic sweeps and the probe. */
+const CONCURRENCY = 5;
+
+/** A minted session is used for this long before a fresh one is asked for (its TTL is an hour). */
+const SESSION_REUSE_MS = 50 * 60_000;
+
export class MachinesService {
- #job: MachineInstallJob | null = null;
- /**
- * The last probe per address. In memory on purpose: a status is only true for the moment
- * it was taken, so one that outlived its App would be a claim nobody measured.
- */
+ #job: MachineJob | null = null;
+ /** Last probe per address. In memory on purpose: a status is only true for the moment it was taken. */
readonly #statuses = new Map<string, MachineServerStatus>();
/**
* The probe round in flight per Project. Concurrent askers — every open tab schedules its
@@ -76,13 +97,25 @@ export class MachinesService {
* and five was meant as a bound, not as a unit of multiplication.
*/
readonly #probing = new Map<string, Promise<void>>();
+ /**
+ * Machines with a heavy operation in flight — an install, or the automatic sweep. Two
+ * transfers racing for one host is how a 30-second command times out with nothing to say.
+ */
+ readonly #busy = new Set<string>();
+ /** Sessions minted on machines, by address, reused until near their TTL. */
+ readonly #sessions = new Map<string, { cookie: string; at: number }>();
+ /**
+ * What the proxy's traffic last learned of each machine's API, by address. In memory
+ * like #statuses: a sighting is only true for the moment it was taken.
+ */
+ readonly #apiSeen = new Map<
+ string,
+ { answeredAt: string } | { failedAt: string; detail: string }
+ >();
readonly #effects: MachinesEffects;
- readonly #machineId: string;
-
- /** Where a pushed bundle's assets were unpacked; null in a packaged server (hmr.assetsDir). */
readonly #assets: () => string | null;
+ readonly #machineId: string;
- /** `dataRoot` is the server's own data root: it holds the hmr state a push replicates. */
constructor(
private readonly dataRoot: string,
machineId: string,
@@ -97,45 +130,28 @@ export class MachinesService {
resolvePlan: resolvePushPlan,
install: installOnRemote,
probe: probeServerState,
- // 30s: a probe is one short command, and a machine that cannot answer it in that time
- // is one the list should call unreachable rather than wait on.
- // One at a time per machine (transport/lane.ts): however many askers, a machine sees
- // one of these commands at once, and the rest wait their turn on it.
runOn: (target, command) => connectionTo(target).exec(command),
+ startServer: (target, port) => startRemoteServer(target, port, this.#effects.runOn),
+ hold: (target) => connectionTo(target).hold(),
+ session: (address) => sessionOf(address),
+ agent: (target, remotePort) => connectionTo(target).agent(remotePort),
now: () => new Date(),
...effects,
};
}
+ // --- what is known -----------------------------------------------------------------------
+
/**
- * A machine's ssh target is its alias and nothing else — what the alias means is ssh's to
- * resolve, from its own config, every time it is handed one.
+ * A machine's ssh target is its alias and nothing else. What the alias means — user, host,
+ * port, key, jump host — is ssh's to resolve, from its own config, every time it is handed
+ * the alias; asking ssh for that answer first (`ssh -G`) only to hand it back was a process
+ * per probe that could go stale against a file a person edits, for no fact we used.
*/
#targetOf(alias: string): RemoteTarget {
return { alias, user: "" };
}
- /**
- * This machine: always installed, always up, never a target. Read directly rather than
- * probed — both facts are right here — and absent from the install picker, because a
- * server does not push this build over the program directory it is running from.
- */
- #localMachine(): MachineInfo {
- const lock = readServerLock(this.dataRoot);
- return {
- id: LOCAL_MACHINE_ID,
- alias: os.hostname(),
- machineId: this.#machineId,
- installed: { version: VERSION, at: lock?.startedAt ?? this.#effects.now().toISOString() },
- local: true,
- status: {
- state: "running",
- checkedAt: this.#effects.now().toISOString(),
- ...(lock === null ? {} : { port: lock.port }),
- },
- };
- }
-
/**
* The addresses a Project uses: exactly its own list, empty until an install gives it one.
*
@@ -159,25 +175,91 @@ export class MachinesService {
}
/**
- * The ssh config's host aliases, answered for one Project: `installed` means installed FOR
- * THIS PROJECT, and a host this server installed on but this Project does not use is
- * reported through `elsewhere`. Empty when there is no config, which is not an error.
+ * The connection held to a machine, or null. This generation's own: a hot-swapped platform
+ * starts with none — the generation before closed what it opened on its way out (stop) —
+ * and re-holds every machine the record says was held (start).
*/
- list(projectId: string): MachineInfo[] {
- const members = new Set(this.#members(projectId));
+ #liveSession(address: string): ShellSession | null {
+ return this.#effects.session(address);
+ }
+
+ /**
+ * Holds the connection to a machine — brought up if it is not, promoted if a passing probe
+ * already opened it — and records that it is held. The transport keeps it from here: no
+ * idle timer, reopened on its own when it drops, until disconnect().
+ */
+ async #connection(
+ address: string,
+ target: RemoteTarget,
+ ): Promise<{ ok: true; session: ShellSession } | { ok: false; detail: string }> {
+ const held = await this.#effects.hold(target);
+ if (!held.ok) return held;
+ if (this.repo.get(address)?.sessionPid !== held.session.pid) {
+ this.repo.patch(address, { sessionPid: held.session.pid });
+ }
+ return held;
+ }
+
+ /**
+ * The row to speak to a machine through, by its OWN id. Two aliases for one host are two
+ * rows with one id: the one with a live session is the one to use, and failing that the
+ * repo's own order (newest install first), so the choice is the same on every call rather
+ * than whichever row SQLite happened to return.
+ */
+ #rowFor(machineId: string): MachineRow | null {
+ const rows = this.repo.byMachineId(machineId);
+ return rows.find((row) => this.#liveSession(row.address) !== null) ?? rows[0] ?? null;
+ }
+
+ /**
+ * A session on a machine, as its own cookie — minted by its CLI over the shared shell
+ * (remote-token.ts) and reused until near its TTL. Or why there is none.
+ */
+ async #sessionOn(target: RemoteTarget): Promise<{ cookie: string } | { detail: string }> {
+ const address = `ssh:${target.alias}`;
+ const held = this.#sessions.get(address);
+ if (held !== undefined && Date.now() - held.at < SESSION_REUSE_MS) return held;
+ const minted = await mintTokenOnRemote(target, this.#effects.runOn);
+ if (minted.kind !== "minted") return { detail: minted.detail };
+ const session = { cookie: `${SESSION_COOKIE}=${minted.token}`, at: Date.now() };
+ this.#sessions.set(address, session);
+ return session;
+ }
+
+ /** This machine: always installed, always up, never a target. */
+ #localMachine(): MachineInfo {
+ const lock = readServerLock(this.dataRoot);
+ return {
+ id: LOCAL_MACHINE_ID,
+ alias: os.hostname(),
+ machineId: this.#machineId,
+ installed: { version: VERSION, at: lock?.startedAt ?? this.#effects.now().toISOString() },
+ local: true,
+ connection: null,
+ api: null,
+ status: {
+ state: "running",
+ checkedAt: this.#effects.now().toISOString(),
+ ...(lock === null ? {} : { port: lock.port }),
+ },
+ };
+ }
+
+ /** This machine, then the ssh config's host aliases with what is known about each. */
+ #allMachines(): MachineInfo[] {
const remotes = this.#effects.listAliases().map((alias): MachineInfo => {
const id = `ssh:${alias}`;
const row = this.repo.get(id);
- const installed =
- row?.version == null ? null : { version: row.version, at: row.installedAt ?? "" };
- const mine = members.has(id);
+ const session = this.#liveSession(id);
return {
id,
alias,
machineId: row?.machineId ?? null,
- installed: mine ? installed : null,
- ...(!mine && installed !== null ? { elsewhere: installed } : {}),
+ installed:
+ row?.version == null ? null : { version: row.version, at: row.installedAt ?? "" },
local: false,
+ connection: session === null ? null : { pid: session.pid },
+ api: this.#apiSeen.get(id) ?? null,
status: this.#statuses.get(id) ?? null,
};
});
@@ -185,9 +267,118 @@ export class MachinesService {
}
/**
- * Asks this Project's installed machines what they are doing, five at a time, and keeps
- * each answer. Never at list time: a probe is an ssh round trip per machine, and a page
- * load is not a reason to open one to every host in a config.
+ * The machines this server knows, answered for one Project: `installed` means installed
+ * FOR THIS PROJECT; a host installed for another one is reported through `elsewhere`, so
+ * the page offers an adoption (one row) rather than an install (30 MB over ssh).
+ */
+ list(projectId: string): MachineInfo[] {
+ const members = new Set(this.#members(projectId));
+ return this.#allMachines().map((machine) => {
+ if (machine.local) return machine;
+ const mine = members.has(machine.id);
+ return {
+ ...machine,
+ installed: mine ? machine.installed : null,
+ ...(!mine && machine.installed !== null ? { elsewhere: machine.installed } : {}),
+ };
+ });
+ }
+
+ /** Drops a machine from a Project. The program stays installed; only the membership goes. */
+ release(projectId: string, address: string): void {
+ this.#setMember(projectId, address, false);
+ }
+
+ /**
+ * The version this server would install, or null when it has no image to push — a dev
+ * checkout that has never been pushed to is the one shape with none. The page asks for it
+ * so it can say so up front, rather than letting every install fail at the same step.
+ */
+ imageVersion(): string | null {
+ return this.#effects.resolvePlan(this.dataRoot)?.version ?? null;
+ }
+
+ /** The running or last job; null before the first one. */
+ job(): MachineJob | null {
+ return this.#job;
+ }
+
+ /**
+ * Stamps what a forwarded request just learned (proxy.ts's ProxyReport): the machine's
+ * API answered, or the connection had nowhere to deliver. Passive on purpose — the proxy
+ * carries every request the app makes to a machine, so the fact rides traffic that flows
+ * anyway, and a machine nobody asks about is simply not measured.
+ */
+ noteApiSeen(machineId: string, outcome: { ok: true } | { ok: false; detail: string }): void {
+ const address = this.#rowFor(machineId)?.address;
+ if (address === undefined) return;
+ const at = this.#effects.now().toISOString();
+ this.#apiSeen.set(
+ address,
+ outcome.ok ? { answeredAt: at } : { failedAt: at, detail: outcome.detail },
+ );
+ }
+
+ /**
+ * What the proxy needs to forward a request to a machine addressed by its OWN id: a dial
+ * through the connection, the port its server is on over there, and a session there. Null
+ * when the machine is not connected.
+ */
+ async proxyTarget(
+ machineId: string,
+ ): Promise<{ agent: http.Agent; port: number; cookie: string } | null> {
+ const row = this.#rowFor(machineId);
+ if (row === null || row.remotePort === null || this.#liveSession(row.address) === null) {
+ return null;
+ }
+ const target = this.#targetOf(row.address.slice("ssh:".length));
+ const session = await this.#sessionOn(target);
+ if (!("cookie" in session)) return null;
+ return {
+ agent: this.#effects.agent(target, row.remotePort),
+ port: row.remotePort,
+ cookie: session.cookie,
+ };
+ }
+
+ /**
+ * The subdirectories of `dir` on a machine, over the HELD connection — so picking a
+ * workspace on it costs one command and no round trip to its API. Null when the machine is
+ * not connected: a read must not open ssh on its own, or a disconnected machine would be
+ * reconnected by whoever browsed it.
+ */
+ async listDirs(
+ machineId: string,
+ dir: string,
+ ): Promise<{
+ path: string;
+ parent: string | null;
+ entries: { name: string; path: string }[];
+ } | null> {
+ const row = this.#rowFor(machineId);
+ if (row === null || this.#liveSession(row.address) === null) return null;
+ const target = this.#targetOf(row.address.slice("ssh:".length));
+ const result = await this.#effects.runOn(target, listDirsCommand(dir));
+ if (result.code !== 0) return null;
+ const [head, rest] = result.stdout.split(DIR_LIST_MARK);
+ const path = (head ?? "").trim().split("\n").pop()?.trim() ?? "";
+ if (path === "") return null;
+ const names = (rest ?? "")
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => line !== "");
+ const join = (name: string) => (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`);
+ return {
+ path,
+ parent: path === "/" ? null : path.slice(0, path.lastIndexOf("/")) || "/",
+ entries: names.sort((a, b) => a.localeCompare(b)).map((name) => ({ name, path: join(name) })),
+ };
+ }
+
+ /**
+ * Probes the machines this server has installed on, refreshing their statuses. Only those:
+ * the ssh config can declare hundreds of hosts, and a host nothing was installed on has no
+ * server to ask about. Failures are states, not errors (server-state.ts).
*/
async probeInstalled(projectId: string): Promise<void> {
const inFlight = this.#probing.get(projectId);
@@ -201,26 +392,30 @@ export class MachinesService {
const queue = this.list(projectId).filter((m) => !m.local && m.installed !== null);
const workers = Array.from({ length: Math.min(CONCURRENCY, queue.length) }, async () => {
for (let machine = queue.shift(); machine !== undefined; machine = queue.shift()) {
- const checkedAt = this.#effects.now().toISOString();
- const target = this.#targetOf(machine.alias);
- const probe = await this.#effects.probe(
- target,
- this.#effects.runOn,
- this.repo.get(machine.id)?.platform ?? null,
- );
- const state = probe.state;
- this.#statuses.set(machine.id, {
- state: state.kind,
- checkedAt,
- ...(state.kind === "running" ? { port: state.port } : {}),
- ...(state.kind === "unreachable" ? { detail: state.detail } : {}),
- });
- this.#rememberMachineId(machine.id, probe.machineId);
+ await this.#refreshStatus(machine.id, this.#targetOf(machine.alias));
}
});
await Promise.all(workers);
}
+ /**
+ * Writes down what a probe just said — the status, and the id if it gave one. EVERY probe
+ * goes through here, the scheduled round and a connect's own alike: a connect that started
+ * a server and heard it answer is the freshest fact there is about that machine, and a page
+ * that still showed it stopped until the next scheduled round would be reporting an older
+ * answer over a newer one.
+ */
+ #recordProbe(address: string, probe: Awaited<ReturnType<MachinesEffects["probe"]>>): void {
+ const state = probe.state;
+ this.#statuses.set(address, {
+ state: state.kind,
+ checkedAt: this.#effects.now().toISOString(),
+ ...(state.kind === "running" ? { port: state.port } : {}),
+ ...(state.kind === "unreachable" ? { detail: state.detail } : {}),
+ });
+ this.#rememberMachineId(address, probe.machineId);
+ }
+
/**
* Records an id a probe just heard. An id NEVER changes for a machine, so a probe that
* answers a different one means the alias was repointed — the newer answer is the true one.
@@ -253,123 +448,279 @@ export class MachinesService {
});
}
- /** Drops a machine from a Project. The program stays installed; only the membership goes. */
- release(projectId: string, address: string): void {
- this.#setMember(projectId, address, false);
- }
-
/**
- * The version this server would install, or null when it has no image to push — a dev
- * checkout that has never been pushed to is the one shape with none. The page asks for it
- * so it can say so up front, rather than letting every install fail at the same step.
+ * Asks a machine what it is now and writes down both halves of the answer.
+ *
+ * Called after anything that CHANGES what is running there. A machine mints its id when its
+ * server starts, so the first start of a build that mints one is the moment its identity
+ * comes into existence — and until this side has heard it, the machine is addressable by
+ * nothing: the proxy cannot route to it and the workspace picker will not offer it. Leaving
+ * that to the next scheduled probe means an operation that succeeded still reads as not
+ * having worked.
*/
- imageVersion(): string | null {
- return this.#effects.resolvePlan(this.dataRoot)?.version ?? null;
+ async #refreshStatus(address: string, target: RemoteTarget): Promise<void> {
+ this.#recordProbe(address, await this.#probe(address, target));
}
- /** The running or last job; null before the first one. */
- job(): MachineInstallJob | null {
- return this.#job;
+ /** One probe of a machine, in the dialect its install found it to speak. */
+ #probe(address: string, target: RemoteTarget): ReturnType<MachinesEffects["probe"]> {
+ return this.#effects.probe(
+ target,
+ this.#effects.runOn,
+ this.repo.get(address)?.platform ?? null,
+ );
}
- /**
- * Starts an install, refusing rather than queueing. The refusals that can be decided here —
- * a job already running, an alias this config does not declare, an ssh that cannot resolve
- * it, no image to send — are answered synchronously, so the page distinguishes "did not
- * start" from "started and failed" without reading the log.
- *
- * Success also gives the machine to the Project that asked for it: an install is how a
- * Project acquires a machine, and one that installed but belonged to nobody would not
- * appear in the list it was started from.
- */
- async startInstall(
- projectId: string,
- machineId: string,
- ): Promise<{ ok: true } | { ok: false; why: InstallRefusal }> {
- if (this.#job?.running === true) return { ok: false, why: "busy" };
-
- // Never this machine: a server does not push this build over its own program directory
- // while running from it. The synthetic row is the obvious case. An alias that points
- // back home — `Host localhost`, a second name for this host — is the same machine at
- // another address, and the id a probe once heard from it says so without any ssh; an
- // alias never probed is asked inside the job, before anything is written.
- if (machineId === LOCAL_MACHINE_ID) return { ok: false, why: "self" };
- const alias = this.#effects.listAliases().find((entry) => `ssh:${entry}` === machineId);
- if (alias === undefined) return { ok: false, why: "unknown-machine" };
- if (this.repo.get(machineId)?.machineId === this.#machineId) return { ok: false, why: "self" };
-
- const plan = this.#effects.resolvePlan(this.dataRoot);
- if (plan === null) return { ok: false, why: "no-image" };
+ // --- jobs ---------------------------------------------------------------------------------
- const job: MachineInstallJob = {
- machineId,
- alias,
+ #startJob(
+ kind: MachineJob["kind"],
+ machine: MachineInfo,
+ work: (say: (line: string) => void) => Promise<MachineJob["result"]>,
+ ): void {
+ const job: MachineJob = {
+ kind,
+ machineId: machine.id,
+ alias: machine.alias,
running: true,
log: [],
result: null,
};
this.#job = job;
-
const say = (line: string) => {
job.log.push(line);
};
- // Deliberately not awaited: the caller is an HTTP handler answering 202. Failures land
- // in the job's own result — the catch below is the last resort for a throw the install
- // path does not turn into a `failed` outcome itself.
+ // Not awaited: the caller is an HTTP handler answering 202. Failures land in the job.
void (async () => {
try {
- // The alias IS the target: what it means — user, host, port, key, jump host — is
- // ssh's to resolve, from its own config, every time it is handed the alias.
- const target = { alias, user: "" };
- say(`Installing ${plan.version} on ${alias}…`);
- // Asked before anything is written: only the machine can say whether this alias is
- // this host under another name. Unreachable is not a refusal — a host with nothing
- // installed yet answers exactly that — this server's own id is.
- const heard = await this.#effects.probe(target, this.#effects.runOn, null);
- this.#rememberMachineId(machineId, heard.machineId);
- if (heard.machineId !== null && heard.machineId === this.#machineId) {
- job.result = {
- ok: false,
- step: "connect",
- message:
- "That alias reaches this very machine — it answered with this server's own id. A server does not push this build over the program directory it is running from.",
- };
- return;
- }
- // No identity passed: installOnRemote runs the probe itself as its first step and
- // narrates it, so the page shows what the machine turned out to be.
- const outcome = await this.#effects.install({
- target,
- plan,
- onProgress: say,
- assets: this.#assets,
- });
- if (outcome.kind === "failed") {
- job.result = { ok: false, step: outcome.step, message: outcome.detail };
- return;
- }
- const version = outcome.kind === "already-installed" ? outcome.version : plan.version;
- // Remembered BEFORE the job settles, so the first poll that sees `running: false`
- // already sees the machine marked installed — otherwise the page would flash the
- // verdict and a still-uninstalled row in the same frame.
- this.repo.patch(machineId, {
- version,
- installedAt: this.#effects.now().toISOString(),
- platform: outcome.identity.platform,
- });
- this.#setMember(projectId, machineId, true);
- job.result = { ok: true, kind: outcome.kind, version };
+ this.#busy.add(machine.id);
+ job.result = await work(say);
} catch (err) {
job.result = {
ok: false,
- step: "install",
+ step: kind,
message: err instanceof Error ? err.message : String(err),
};
} finally {
+ this.#busy.delete(machine.id);
job.running = false;
}
})();
+ }
+
+ /**
+ * Starts an install, refusing rather than queueing. The refusals decidable here are
+ * answered synchronously, so the page distinguishes "did not start" from "started and
+ * failed" without reading the log.
+ */
+ async startInstall(
+ projectId: string,
+ address: string,
+ ): Promise<{ ok: true } | { ok: false; why: InstallRefusal }> {
+ if (this.#job?.running === true) return { ok: false, why: "busy" };
+ const machine = this.#allMachines().find((entry) => entry.id === address);
+ if (machine === undefined) return { ok: false, why: "unknown-machine" };
+ // Never this machine: a server does not push this build over its own program directory
+ // while running from it. The synthetic row is the obvious case; an alias that points
+ // back home — `Host localhost`, a second name for this host — is the same machine at
+ // another address, and the id a probe once heard from it says so without any ssh. An
+ // alias never probed is asked inside the job, before anything is written.
+ if (machine.local || (machine.machineId !== null && machine.machineId === this.#machineId)) {
+ return { ok: false, why: "self" };
+ }
+ const plan = this.#effects.resolvePlan(this.dataRoot);
+ if (plan === null) return { ok: false, why: "no-image" };
+ const target = this.#targetOf(machine.alias);
+
+ this.#startJob("install", machine, async (say) => {
+ say(`Installing ${plan.version} on ${machineIdentity(target.alias, target.user)}…`);
+ // Only the machine can say whether this alias is this host under another name.
+ // Unreachable is not a refusal — a host with nothing installed yet answers exactly
+ // that — this server's own id is.
+ const heard = await this.#effects.probe(target, this.#effects.runOn, null);
+ this.#rememberMachineId(address, heard.machineId);
+ if (heard.machineId !== null && heard.machineId === this.#machineId) {
+ return {
+ ok: false,
+ step: "connect",
+ message:
+ "That alias reaches this very machine — it answered with this server's own id. A server does not push this build over the program directory it is running from.",
+ };
+ }
+ const outcome = await this.#effects.install({
+ target,
+ plan,
+ onProgress: say,
+ assets: this.#assets,
+ });
+ if (outcome.kind === "failed") {
+ return { ok: false, step: outcome.step, message: outcome.detail };
+ }
+ const version = outcome.kind === "already-installed" ? outcome.version : plan.version;
+ this.repo.patch(address, {
+ version,
+ installedAt: this.#effects.now().toISOString(),
+ platform: outcome.identity.platform,
+ });
+ // The Project that asked for the install is the Project that gets the machine.
+ this.#setMember(projectId, address, true);
+ return { ok: true, installed: outcome.kind, version };
+ });
+ return { ok: true };
+ }
+ /**
+ * Brings a machine's server up and holds the connection to it, as a job — a start plus a
+ * readiness wait is minutes in the bad case. Every step is idempotent, so a repeat is safe.
+ */
+ async startConnect(address: string): Promise<{ ok: true } | { ok: false; why: ConnectRefusal }> {
+ if (this.#job?.running === true) return { ok: false, why: "busy" };
+ const machine = this.#allMachines().find((entry) => entry.id === address);
+ if (machine === undefined) return { ok: false, why: "unknown-machine" };
+ // The machine's own id is what settles "that is here": the alias may point back home.
+ if (machine.local || (machine.machineId !== null && machine.machineId === this.#machineId)) {
+ return { ok: false, why: "self" };
+ }
+ if (machine.installed === null) return { ok: false, why: "not-installed" };
+ // A Windows remote has no `sh` to hold a session on (transport/connection.ts), so there
+ // is no connection to hold, no SOCKS port to dial its API through, and no shell to browse
+ // it with. Said here, in one sentence, rather than discovered as a POSIX command failing
+ // under cmd.exe in the job's log.
+ if (this.repo.get(address)?.platform === "win32") return { ok: false, why: "unsupported" };
+ this.#startJob("connect", machine, (say) => this.#connect(machine, say));
return { ok: true };
}
+
+ async #connect(machine: MachineInfo, say: (line: string) => void): Promise<MachineJob["result"]> {
+ const address = machine.id;
+ const target = this.#targetOf(machine.alias);
+
+ // Asked even when a forward is already up: the forward is an ssh process on THIS side,
+ // and it outlives the far server. Taking it as the answer reported "connected" over a
+ // dead server — and every caller that then found the machine silent asked for another
+ // connect, which said "already connected" again, forever. Reconnecting (to retry a sync
+ // that failed, or pick up a new key) now costs one probe and stays honest.
+ say("Asking what is running there…");
+ const probed = await this.#probe(address, target);
+ this.#recordProbe(address, probed);
+ if (probed.state.kind === "unreachable") {
+ // Reported in the machine's own words: OpenSSH's diagnostic, or the CLI's. What to do
+ // about a machine whose store holds no CLI this server can talk to is a later problem
+ // — this one is honest about not having reached it.
+ return { ok: false, step: "connect", message: probed.state.detail };
+ }
+ // The refusal startConnect made from the record, made again from what was just heard: an
+ // alias never probed before, or one repointed here since, answers this server's own id
+ // only now — and a connection "to" it would be a tunnel from this server back to itself.
+ if (probed.machineId !== null && probed.machineId === this.#machineId) {
+ return {
+ ok: false,
+ step: "connect",
+ message:
+ "That alias reaches this very machine — it answered with this server's own id. There is nothing to connect to.",
+ };
+ }
+ let remotePort: number;
+ if (probed.state.kind === "running") {
+ remotePort = probed.state.port;
+ say(`Its server is already up on port ${remotePort}.`);
+ } else {
+ remotePort = this.repo.get(address)?.remotePort ?? DEFAULT_SERVER_PORT;
+ say(`Starting its server on port ${remotePort}…`);
+ const started = await this.#effects.startServer(target, remotePort);
+ if (!started.ok) return { ok: false, step: "start its server", message: started.detail };
+ // A machine mints its id when its server starts, so one that was down had none — and
+ // its port and pid are now the freshest fact about it.
+ this.#recordProbe(address, await this.#probe(address, target));
+ }
+
+ say("Opening the connection…");
+ const connection = await this.#connection(address, target);
+ if (!connection.ok) return { ok: false, step: "connect", message: connection.detail };
+ this.repo.patch(address, { remotePort });
+ say(`Connected; its server is on port ${remotePort} over there.`);
+ return { ok: true, connected: true };
+ }
+
+ /**
+ * Drops the connection to a machine. The remote server is left RUNNING: it is that
+ * machine's own server, and other people may be on it.
+ */
+ disconnect(address: string): void {
+ closeConnectionTo(address);
+ this.#sessions.delete(address);
+ if (this.repo.get(address) !== null) {
+ this.repo.patch(address, { sessionPid: null });
+ }
+ }
+
+ // --- the generation's lifetime: what an App does at boot and on its way out ------------------
+
+ /**
+ * Re-holds every connection the record says was held — a restart or a hot push in between
+ * notwithstanding — five machines at a time, starting a server that is down on the way.
+ * Only those: an explicit disconnect cleared its record, and a machine merely installed on
+ * was never asked for. Called by the platform at boot and not awaited there: a host that is
+ * slow to answer must not hold up the App that serves everything else.
+ */
+ async start(): Promise<void> {
+ await this.autoConnect();
+ }
+
+ /**
+ * Closes every connection THIS generation opened — the platform's dispose effect on a hot
+ * push. The record of which were held stays, so the successor's start() brings each back.
+ * Nothing here closes by a remembered pid: the child handles are this generation's own.
+ */
+ stop(): void {
+ closeAllConnections();
+ }
+
+ /** Runs `work` with this machine's slot held, or returns null when it is already busy. */
+ async #withMachine<T>(address: string, work: () => Promise<T>): Promise<T | null> {
+ if (this.#busy.has(address)) return null;
+ this.#busy.add(address);
+ try {
+ return await work();
+ } finally {
+ this.#busy.delete(address);
+ }
+ }
+
+ async #sweep(
+ addresses: string[],
+ work: (address: string, target: RemoteTarget) => Promise<void>,
+ ): Promise<void> {
+ const queue = [...addresses];
+ const workers = Array.from({ length: Math.min(CONCURRENCY, queue.length) }, async () => {
+ for (let address = queue.shift(); address !== undefined; address = queue.shift()) {
+ const target = this.#targetOf(address.slice("ssh:".length));
+ try {
+ await this.#withMachine(address, () => work(address, target));
+ } catch {
+ // Best effort: the page shows the machine as it is.
+ }
+ }
+ });
+ await Promise.all(workers);
+ }
+
+ /** Re-holds every machine recorded as held that this generation does not yet hold. */
+ async autoConnect(): Promise<void> {
+ const unconnected = this.#allMachines().filter(
+ (m) =>
+ !m.local &&
+ m.installed !== null &&
+ m.connection === null &&
+ this.repo.get(m.id)?.sessionPid != null &&
+ this.repo.get(m.id)?.platform !== "win32",
+ );
+ await this.#sweep(
+ unconnected.map((m) => m.id),
+ async (address) => {
+ const machine = unconnected.find((m) => m.id === address)!;
+ await this.#connect(machine, () => {});
+ },
+ );
+ }
}
diff --git a/packages/server/src/machines/transport/connection.ts b/packages/server/src/machines/transport/connection.ts
index e146e67d..b01aeb21 100644
--- a/packages/server/src/machines/transport/connection.ts
+++ b/packages/server/src/machines/transport/connection.ts
@@ -23,10 +23,27 @@
* The handle is stateless on purpose: per-machine state stays in ssh-session.ts, keyed by
* address, so holding a MachineConnection costs nothing and dropping one leaks nothing. The
* address is always `ssh:<alias>` — the one spelling every registry in machines/ uses.
+ *
+ * LIFETIME. A session a passing command opened is transient and idles out; one a connect
+ * asked to HOLD is kept — reopened by the transport itself when it drops, until a disconnect
+ * closes it. Sessions belong to the generation that opened them: a platform generation on its
+ * way out closes all of its own (closeAllConnections), and the next re-holds what the record
+ * says was held. No session is ever closed by a pid remembered from before.
*/
+import http from "node:http";
+import type net from "node:net";
import { run, runWithInput } from "./exec.js";
-import { closeShell, openShell, runOnShell, sessionOf } from "./ssh-session.js";
+import {
+ closeAllShells,
+ closeShell,
+ holdShell,
+ isHeld,
+ openShell,
+ runOnShell,
+ sessionOf,
+} from "./ssh-session.js";
import type { ShellSession } from "./ssh-session.js";
+import { dialThroughSocks } from "./socks.js";
import { inLane } from "./lane.js";
import { scpArgs, sshArgs } from "../commands.js";
import type { ExecResult } from "./exec.js";
@@ -78,16 +95,49 @@ export class MachineConnection implements MachineChannel {
return { code: result.code, stdout: result.output, stderr: "", timedOut: false };
}
- /** Brings the session up, or says why it cannot be. */
+ /** Brings the session up, or says why it cannot be. Transient: it idles out unused. */
open(): Promise<{ ok: true; session: ShellSession } | { ok: false; detail: string }> {
return openShell(this.address, this.target);
}
+ /** Brings the session up and KEEPS it — see the module doc — or says why it cannot be. */
+ hold(): Promise<{ ok: true; session: ShellSession } | { ok: false; detail: string }> {
+ return holdShell(this.address, this.target);
+ }
+
+ /** Whether the session to this machine is a held one. */
+ held(): boolean {
+ return isHeld(this.address);
+ }
+
/** The session while it is up. */
session(): ShellSession | null {
return sessionOf(this.address);
}
+ /** A TCP connection to `127.0.0.1:<remotePort>` as seen from the machine — a channel in the session. */
+ async dial(remotePort: number): Promise<net.Socket> {
+ const opened = await this.open();
+ if (!opened.ok) throw new Error(opened.detail);
+ return dialThroughSocks(opened.session.socksPort, "127.0.0.1", remotePort);
+ }
+
+ /** An http.Agent whose every socket is a dial through the session — for node:http callers. */
+ agent(remotePort: number): http.Agent {
+ const agent = new http.Agent({ keepAlive: false });
+ // createConnection is documented on Agent (and overridable); the typings omit it.
+ (agent as unknown as { createConnection: unknown }).createConnection = (
+ _options: unknown,
+ callback: (err: Error | null, socket?: net.Socket) => void,
+ ) => {
+ this.dial(remotePort).then(
+ (socket) => callback(null, socket),
+ (err: unknown) => callback(err instanceof Error ? err : new Error(String(err))),
+ );
+ };
+ return agent;
+ }
+
/**
* WINDOWS REMOTES ONLY (see the module doc): a command on its own ssh connection, with an
* optional stdin payload. Serialised per machine.
@@ -116,10 +166,16 @@ export function connectionTo(target: RemoteTarget): MachineConnection {
}
/**
- * Lets go of the connection to a machine. By address rather than on the handle: a disconnect
- * can outlive the resolvability of its target (an alias removed from the ssh config still
- * has a session to close).
+ * Lets go of the connection to a machine, held or not. By address rather than on the handle:
+ * a disconnect can outlive the resolvability of its target (an alias removed from the ssh
+ * config still has a session to close). Only this generation's own registry is consulted —
+ * there is deliberately no way to close a session by a pid remembered from before.
*/
export function closeConnectionTo(address: string): void {
closeShell(address);
}
+
+/** Every connection this generation opened, closed — the platform's dispose effect. */
+export function closeAllConnections(): void {
+ closeAllShells();
+}
diff --git a/packages/server/src/machines/transport/index.ts b/packages/server/src/machines/transport/index.ts
index 4cc9950e..07d4c4c1 100644
--- a/packages/server/src/machines/transport/index.ts
+++ b/packages/server/src/machines/transport/index.ts
@@ -1,18 +1,24 @@
/**
* The transport directory's one door. Everything machines/ needs from the transport layer
- * — the connection handle, target listing, and the result vocabulary — comes through here;
- * the modules behind it (exec.ts, ssh-session.ts, socks.ts, lane.ts, targets.ts) are
+ * — the connection handle, target resolution, and the result vocabulary — comes through
+ * here; the modules behind it (exec.ts, ssh-session.ts, socks.ts, lane.ts, targets.ts) are
* private, pinned by machines-transport-boundary.test.ts. See connection.ts for why.
*
* THE STRUCTURE. Per machine ONE connection: an `ssh -T -D` session whose stdin carries the
* commands, the scripts and the tarballs, and whose SOCKS port carries every TCP connection
* to the machine as a channel inside it. Not a budget: there is no count of open connections
* and no number to tune, because there is nothing that could open a second one; a second ask
- * waits for the first.
+ * waits for the first. A trigger — a probe request, a boot sweep, an install — never brings a
+ * connection of its own.
*/
-export { MachineConnection, closeConnectionTo, connectionTo } from "./connection.js";
+export {
+ MachineConnection,
+ closeAllConnections,
+ closeConnectionTo,
+ connectionTo,
+} from "./connection.js";
export type { MachineChannel } from "./connection.js";
-export { openShell, sessionOf } from "./ssh-session.js";
+export { sessionOf } from "./ssh-session.js";
export type { ShellSession } from "./ssh-session.js";
export { execFailureText, looksLikeAuthFailure, runBytes } from "./exec.js";
export type { ExecResult } from "./exec.js";
diff --git a/packages/server/src/machines/transport/ssh-session.ts b/packages/server/src/machines/transport/ssh-session.ts
index e5b502b3..d70db2d7 100644
--- a/packages/server/src/machines/transport/ssh-session.ts
+++ b/packages/server/src/machines/transport/ssh-session.ts
@@ -25,7 +25,12 @@
* base64 because a heredoc carries text, and the terminator cannot occur in its alphabet.
* <decode> is DECODE below, which settles the flag on the far side rather than here.
*
- * UNSUPERVISED: a session that dies is dropped and the next command opens a new one.
+ * TWO LIFETIMES. A session opened by a passing command — a probe, a listing — is TRANSIENT:
+ * it is let go after IDLE_MS without another command. A session someone asked to HOLD (a
+ * connect) is kept: it never idles out, and if it dies — a network blip, keepalives giving
+ * up on a dead link, a command that timed out — it is reopened on its own, with a backoff,
+ * until it is explicitly closed. The proxy's dials ride the held session and never touch a
+ * timer, so traffic alone is neither what keeps it nor what could lose it.
*/
import { spawn } from "node:child_process";
import type { ChildProcessWithoutNullStreams } from "node:child_process";
@@ -68,6 +73,10 @@ const COMMAND_TIMEOUT_MS = 60_000;
/** Opening is a handshake to a host that may be far away or loaded. */
const OPEN_TIMEOUT_MS = 30_000;
+/** A held session that dropped is reopened after this long, doubling per failure up to the cap. */
+const RECONNECT_MIN_MS = 1_000;
+const RECONNECT_MAX_MS = 60_000;
+
/**
* Decoding the heredoc, on either base64 there is. GNU coreutils spells decode `-d` and
* rejects `-D`; the BSD base64 macOS ships spells it `-D`, and releases before Ventura reject
@@ -107,9 +116,24 @@ class MachineShell {
#pending: Pending | null = null;
#queue: Promise<unknown> = Promise.resolve();
#idle: NodeJS.Timeout | null = null;
+ /** Held: never idles out, reopened when it drops, until close(). */
+ #held = false;
+ #reopen: NodeJS.Timeout | null = null;
+ #backoffMs = RECONNECT_MIN_MS;
constructor(private readonly target: RemoteTarget) {}
+ /** Keeps the session from here on: a session opened transiently is promoted in place. */
+ hold(): void {
+ this.#held = true;
+ if (this.#idle !== null) clearTimeout(this.#idle);
+ this.#idle = null;
+ }
+
+ held(): boolean {
+ return this.#held;
+ }
+
/** Runs one command, opening the session if needed. Never throws; a dead session is a failure. */
run(command: string, opts: ShellRunOptions = {}): Promise<ShellResult> {
const next = this.#queue.then(() => this.#runExclusive(command, opts));
@@ -126,13 +150,39 @@ class MachineShell {
: null;
}
+ /** Lets go for good: a held session stops being held, and nothing reopens it. */
close(): void {
+ this.#held = false;
+ if (this.#reopen !== null) clearTimeout(this.#reopen);
+ this.#reopen = null;
+ this.#reset();
+ }
+
+ /** Ends the child and answers what was pending. A held session comes back on its own. */
+ #reset(): void {
if (this.#idle !== null) clearTimeout(this.#idle);
this.#idle = null;
this.#child?.kill();
this.#drop();
}
+ /**
+ * A held session that is gone is scheduled back. The wait doubles per consecutive failure
+ * and is reset by the first command that completes over a live child, so a machine that is
+ * down for an hour costs a spawn a minute, and one that blinked is back in a second.
+ */
+ #scheduleReopen(): void {
+ if (this.#reopen !== null) return;
+ const wait = this.#backoffMs;
+ this.#backoffMs = Math.min(this.#backoffMs * 2, RECONNECT_MAX_MS);
+ this.#reopen = setTimeout(() => {
+ this.#reopen = null;
+ if (!this.#held || this.#child !== null) return;
+ void this.run(":", { timeoutMs: OPEN_TIMEOUT_MS });
+ }, wait);
+ this.#reopen.unref?.();
+ }
+
#drop(): void {
this.#child = null;
this.#socksPort = null;
@@ -153,6 +203,7 @@ class MachineShell {
});
}
this.#stderr = "";
+ if (this.#held) this.#scheduleReopen();
}
async #open(): Promise<ChildProcessWithoutNullStreams> {
@@ -247,7 +298,7 @@ class MachineShell {
// spend this command's one answer on "the connection ended", losing the more precise
// fact that the machine simply never replied.
this.#pending = null;
- this.close();
+ this.#reset();
resolve({ code: 255, output: "the machine did not answer in time" });
}, opts.timeoutMs ?? COMMAND_TIMEOUT_MS);
this.#pending = { resolve, timer, onLine: opts.onLine };
@@ -262,6 +313,10 @@ class MachineShell {
`( ${DECODE} | ( ${command} ) ) <<'${end}' 2>&1 ; ${mark}\n${body}\n${end}\n`,
);
}).finally(() => {
+ // A command completed over a live child: whatever the last drop cost, the next starts
+ // from the shortest wait again.
+ if (this.#child !== null) this.#backoffMs = RECONNECT_MIN_MS;
+ if (this.#held) return;
this.#idle = setTimeout(() => this.close(), IDLE_MS);
this.#idle.unref?.();
});
@@ -273,11 +328,13 @@ class MachineShell {
* not reopen a connection it already has.
*
* A hot push DOES lose them: the platform bundle is re-imported cache-busted (hmr/host.ts),
- * so this map starts empty in the successor and the previous generation's ssh children have
- * nothing holding them. What collects them is the idle timer — a scheduled timeout belongs
- * to the process, not to the module that scheduled it, so it still fires and still closes the
- * child it was created for. The cost of a push is one reconnect per machine, within IDLE_MS,
- * and never a child nobody ever kills.
+ * so this map starts empty in the successor. The generation on its way out closes what it
+ * opened — closeAllShells, from the platform's dispose effect — because it is the one that
+ * holds the child handles; the successor then re-holds every connection the record says was
+ * held (machines/service.ts). A transient session that was never closed that way is collected
+ * by its idle timer, which belongs to the process rather than to the module that armed it.
+ * Nothing is ever killed by a pid read back from a file: a pid is reused by the OS, and the
+ * process at a remembered number may by then be anyone's.
*/
const sessions = new Map<string, MachineShell>();
@@ -319,6 +376,32 @@ export async function openShell(
return { ok: true, session };
}
+/**
+ * Brings the session up AND keeps it: no idle timer, reopened on its own when it drops, until
+ * closeShell. Idempotent, and promotes a session a passing command already opened.
+ */
+export function holdShell(
+ machineAddress: string,
+ target: RemoteTarget,
+): Promise<{ ok: true; session: ShellSession } | { ok: false; detail: string }> {
+ shellFor(machineAddress, target).hold();
+ return openShell(machineAddress, target);
+}
+
+/** Whether a machine's session is a held one. */
+export function isHeld(machineAddress: string): boolean {
+ return sessions.get(machineAddress)?.held() ?? false;
+}
+
+/**
+ * Every session this module opened, closed — what a platform generation does on its way out,
+ * so that its successor starts with nothing of its to collect.
+ */
+export function closeAllShells(): void {
+ for (const shell of sessions.values()) shell.close();
+ sessions.clear();
+}
+
/** The session held to a machine, while it is up. */
export function sessionOf(machineAddress: string): ShellSession | null {
return sessions.get(machineAddress)?.session() ?? null;
diff --git a/packages/server/test/machines-api.test.ts b/packages/server/test/machines-api.test.ts
index db35a7e3..0b43248f 100644
--- a/packages/server/test/machines-api.test.ts
+++ b/packages/server/test/machines-api.test.ts
@@ -9,6 +9,7 @@
* binary and the real installOnRemote.
*/
import fs from "node:fs";
+import http from "node:http";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { MachinesResponse } from "../src/api/types.js";
@@ -29,7 +30,7 @@ import {
} from "./helpers.js";
import type { TestApp } from "./helpers.js";
-/** Every route is under a Project now; the seeded one every server has. */
+/** Every route is under a Project; the seeded one every server has. */
const PROJECT = "default_project";
/** This machine's id. Minted from the `machine` table in the real server; fixed here. */
@@ -42,15 +43,31 @@ const IDENTITY: RemoteIdentity = {
harness: null,
};
+/** Addresses the fake transport holds a session to. */
+const connected = new Set<string>();
+
/** An effects set that names two hosts and installs successfully, with the parts a test cares about overridden. */
function effects(over: Partial<MachinesEffects> = {}): Partial<MachinesEffects> {
return {
listAliases: () => ["build-box", "nas"],
resolvePlan: () => ({ baseVersion: "9.9.9", harness: null, hmrDir: null, version: "9.9.9" }),
now: () => new Date("2026-08-24T12:00:00.000Z"),
- // An install asks the machine who it is before writing anything; a host with nothing on
- // it yet answers stopped with no id, which is the shape that refuses nothing.
- probe: async () => ({ state: { kind: "stopped" as const }, machineId: null }),
+ startServer: async () => ({ ok: true }),
+ runOn: async () => ({
+ code: 0,
+ stdout: "---penguin-auth-token---\nremote-token\n",
+ stderr: "",
+ timedOut: false,
+ }),
+ // The connection: a fake registry this suite marks machines connected in, the way the
+ // transport's own registry answers `session` for a held ssh session.
+ hold: async (target) => {
+ connected.add(`ssh:${target.alias}`);
+ return { ok: true, session: { pid: process.pid, socksPort: 1 } };
+ },
+ session: (address) => (connected.has(address) ? { pid: process.pid, socksPort: 1 } : null),
+ agent: () => new http.Agent(),
+ probe: async () => ({ state: { kind: "running", port: 7364, pid: 4242 }, machineId: null }),
install: async (opts): Promise<RemoteInstallOutcome> => {
opts.onProgress?.("Pushing…");
return { kind: "installed", output: "done", identity: IDENTITY };
@@ -62,13 +79,13 @@ function effects(over: Partial<MachinesEffects> = {}): Partial<MachinesEffects>
describe("machines API", () => {
let t: TestApp;
let admin: ReturnType<typeof apiClient>;
- /** The service's own data root — where the pushable image would live. */
+ /** The service's own data root — where it writes the install records this suite reads back. */
let machinesRoot: string;
- /** The store the service records installs and memberships in; this suite reads it back. */
let machinesRepo: MachinesRepo;
let store: DatabaseSync;
const boot = async (over: Partial<MachinesEffects> = {}) => {
+ connected.clear();
machinesRoot = await makeTempRoot();
// The store is the service's own here, not the App's, so it needs the Project row the
// membership table's foreign key points at — a membership follows its Project out.
@@ -108,14 +125,14 @@ describe("machines API", () => {
it("is admin-only: a provisioned user gets 403", async () => {
const user = await provisionUser(t.app, "member");
const member = apiClient(t.app, user.cookie);
- expect((await member.get(`/api/projects/${PROJECT}/machines`)).status).toBe(403);
- expect((await member.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`)).status).toBe(
- 403,
- );
+ expect((await member.get("/api/projects/default_project/machines")).status).toBe(403);
+ expect(
+ (await member.post("/api/projects/default_project/machines/ssh:nas/install")).status,
+ ).toBe(403);
});
it("needs a session at all", async () => {
- expect((await t.app.request(`/api/projects/${PROJECT}/machines`)).status).toBe(401);
+ expect((await t.app.request("/api/projects/default_project/machines")).status).toBe(401);
});
});
@@ -123,15 +140,14 @@ describe("machines API", () => {
it("is the ssh config's aliases, with the version this server would push", async () => {
await boot();
const body = (await (
- await admin.get(`/api/projects/${PROJECT}/machines`)
+ await admin.get("/api/projects/default_project/machines")
).json()) as MachinesResponse;
- // This machine leads the list: always present, always up, never a target.
expect(body.machines[0]).toMatchObject({
id: "local",
local: true,
- machineId: LOCAL_ID,
status: { state: "running" },
});
+ expect(body.machines[0]?.installed).not.toBeNull();
expect(body.machines.slice(1)).toEqual([
{
id: "ssh:build-box",
@@ -139,6 +155,8 @@ describe("machines API", () => {
machineId: null,
installed: null,
local: false,
+ connection: null,
+ api: null,
status: null,
},
{
@@ -147,6 +165,8 @@ describe("machines API", () => {
machineId: null,
installed: null,
local: false,
+ connection: null,
+ api: null,
status: null,
},
]);
@@ -154,18 +174,18 @@ describe("machines API", () => {
expect(body.job).toBeNull();
});
- it("an empty or unreadable ssh config is a list of none, not an error", async () => {
+ it("an empty or unreadable ssh config leaves this machine alone in the list, not an error", async () => {
await boot({ listAliases: () => [] });
- const res = await admin.get(`/api/projects/${PROJECT}/machines`);
+ const res = await admin.get("/api/projects/default_project/machines");
expect(res.status).toBe(200);
- // Not empty: this machine is always in the list, whatever the config says.
- expect(((await res.json()) as MachinesResponse).machines.map((m) => m.id)).toEqual(["local"]);
+ const machines = ((await res.json()) as MachinesResponse).machines;
+ expect(machines.map((m) => m.id)).toEqual(["local"]);
});
it("reports no image when this server has none to push", async () => {
await boot({ resolvePlan: () => null });
const body = (await (
- await admin.get(`/api/projects/${PROJECT}/machines`)
+ await admin.get("/api/projects/default_project/machines")
).json()) as MachinesResponse;
expect(body.imageVersion).toBeNull();
});
@@ -173,8 +193,6 @@ describe("machines API", () => {
describe("installing", () => {
it("starts a job, narrates it, and finishes", async () => {
- // Held open so the 202 is observed mid-flight, which is the real shape: a push takes
- // minutes, and the page has to render a running job from this very body.
let release = () => {};
const held = new Promise<void>((resolve) => {
release = resolve;
@@ -186,7 +204,7 @@ describe("machines API", () => {
return { kind: "installed", output: "done", identity: IDENTITY };
},
});
- const started = await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ const started = await admin.post("/api/projects/default_project/machines/ssh:nas/install");
expect(started.status).toBe(202);
expect(((await started.json()) as MachinesResponse).job).toMatchObject({
machineId: "ssh:nas",
@@ -198,10 +216,9 @@ describe("machines API", () => {
release();
await waitFor(() => t.deps.machines.job()?.running === false);
const body = (await (
- await admin.get(`/api/projects/${PROJECT}/machines`)
+ await admin.get("/api/projects/default_project/machines")
).json()) as MachinesResponse;
- expect(body.job?.result).toEqual({ ok: true, kind: "installed", version: "9.9.9" });
- // The first line is this server's own, the rest are the push's.
+ expect(body.job?.result).toEqual({ ok: true, installed: "installed", version: "9.9.9" });
expect(body.job?.log[0]).toBe("Installing 9.9.9 on nas…");
expect(body.job?.log).toContain("Pushing…");
});
@@ -214,7 +231,7 @@ describe("machines API", () => {
detail: "Permission denied (publickey).",
}),
});
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");
await waitFor(() => t.deps.machines.job()?.running === false);
expect(t.deps.machines.job()?.result).toEqual({
ok: false,
@@ -227,11 +244,11 @@ describe("machines API", () => {
await boot({
install: async () => ({ kind: "already-installed", version: "9.9.9", identity: IDENTITY }),
});
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");
await waitFor(() => t.deps.machines.job()?.running === false);
expect(t.deps.machines.job()?.result).toEqual({
ok: true,
- kind: "already-installed",
+ installed: "already-installed",
version: "9.9.9",
});
});
@@ -281,13 +298,27 @@ describe("machines API", () => {
expect(dialects).toEqual([null, "win32"]);
});
+ it("re-running an install keeps the machine id the record already carried", async () => {
+ await boot({
+ install: async () => ({ kind: "already-installed", version: "9.9.9", identity: IDENTITY }),
+ });
+ machinesRepo.patch("ssh:nas", {
+ version: "9.9.9",
+ installedAt: "2026-08-01T00:00:00.000Z",
+ machineId: "kUkIyqU-1GOfXgKD",
+ });
+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ expect(machinesRepo.get("ssh:nas")?.machineId).toBe("kUkIyqU-1GOfXgKD");
+ });
+
it("a throw from the push path still ends the job", async () => {
await boot({
install: () => {
throw new Error("scp vanished");
},
});
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");
await waitFor(() => t.deps.machines.job()?.running === false);
expect(t.deps.machines.job()?.result).toMatchObject({ ok: false, message: "scp vanished" });
});
@@ -296,12 +327,15 @@ describe("machines API", () => {
describe("what stays installed", () => {
/** GET /api/machines, as the page reads it. */
const listed = async () =>
- ((await (await admin.get(`/api/projects/${PROJECT}/machines`)).json()) as MachinesResponse)
- .machines;
+ (
+ (await (
+ await admin.get(`/api/projects/default_project/machines`)
+ ).json()) as MachinesResponse
+ ).machines;
it("a successful install is remembered, and is already visible on the first settled poll", async () => {
await boot();
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await admin.post(`/api/projects/default_project/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
const machines = await listed();
@@ -315,14 +349,14 @@ describe("machines API", () => {
it("survives the process: a fresh service over the same data root reads it back", async () => {
await boot();
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await admin.post(`/api/projects/default_project/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
// A new instance has no job and no memory — only the file. This is the restart case,
// and the hot-push case: the App is rebuilt, the data root is not.
const reborn = new MachinesService(machinesRoot, LOCAL_ID, machinesRepo, effects());
expect(reborn.job()).toBeNull();
- expect(reborn.list(PROJECT).find((m) => m.id === "ssh:nas")?.installed).toEqual({
+ expect(reborn.list("default_project").find((m) => m.id === "ssh:nas")?.installed).toEqual({
version: "9.9.9",
at: "2026-08-24T12:00:00.000Z",
});
@@ -330,7 +364,7 @@ describe("machines API", () => {
it("belongs to the Project that installed it, and to no other", async () => {
await boot();
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await admin.post(`/api/projects/default_project/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
// Another Project sees the same host as installed-but-not-mine: an adoption, not an
@@ -342,11 +376,11 @@ describe("machines API", () => {
it("release drops the membership and leaves the install alone", async () => {
await boot();
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await admin.post(`/api/projects/default_project/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
const body = (await (
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/release`)
+ await admin.post(`/api/projects/default_project/machines/ssh:nas/release`)
).json()) as MachinesResponse;
expect(body.machines.find((m) => m.id === "ssh:nas")?.installed).toBeNull();
// Still installed — the program is on that host whoever uses it.
@@ -360,9 +394,9 @@ describe("machines API", () => {
// The job is one slot, so before the records file existed this is exactly what made an
// installed machine disappear: the second install overwrote the only evidence.
await boot();
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await admin.post(`/api/projects/default_project/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:build-box/install`);
+ await admin.post(`/api/projects/default_project/machines/ssh:build-box/install`);
await waitFor(() => t.deps.machines.job()?.machineId === "ssh:build-box");
await waitFor(() => t.deps.machines.job()?.running === false);
@@ -378,7 +412,7 @@ describe("machines API", () => {
await boot({
install: async () => ({ kind: "already-installed", version: "8.8.8", identity: IDENTITY }),
});
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await admin.post(`/api/projects/default_project/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
expect((await listed()).find((m) => m.id === "ssh:nas")?.installed?.version).toBe("8.8.8");
});
@@ -404,7 +438,7 @@ describe("machines API", () => {
await boot({
install: async () => ({ kind: "failed", step: "connect", detail: "no route to host" }),
});
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await admin.post(`/api/projects/default_project/machines/ssh:nas/install`);
await waitFor(() => t.deps.machines.job()?.running === false);
expect((await listed()).filter((m) => !m.local).every((m) => m.installed === null)).toBe(
true,
@@ -413,77 +447,78 @@ describe("machines API", () => {
});
});
- describe("asking the machines what they are doing", () => {
- /** A machine that answers `penguin server status` with the JSON below. */
- const answering = (o: Record<string, unknown>) =>
- ({
+ describe("server status", () => {
+ const listed = async () =>
+ (
+ (await (
+ await admin.get("/api/projects/default_project/machines")
+ ).json()) as MachinesResponse
+ ).machines;
+ const byId = async (id: string) => (await listed()).find((machine) => machine.id === id);
+
+ it("this machine reports itself running without any probe", async () => {
+ await boot({
+ probe: () => {
+ throw new Error("the local entry must not be probed");
+ },
+ });
+ expect(await byId("local")).toMatchObject({ local: true, status: { state: "running" } });
+ });
+
+ it("is null until probed — listing costs no ssh", async () => {
+ let probes = 0;
+ await boot({
probe: async () => {
- const status = o as { running?: boolean; port?: number; pid?: number };
- return {
- state:
- status.running === true
- ? { kind: "running" as const, port: status.port!, pid: status.pid! }
- : { kind: "stopped" as const },
- machineId: (o.machineId as string | null) ?? null,
- };
+ probes++;
+ return { state: { kind: "running", port: 7364, pid: 1 }, machineId: null };
},
- }) satisfies Partial<MachinesEffects>;
+ });
+ await admin.get("/api/projects/default_project/machines");
+ await admin.get("/api/projects/default_project/machines");
+ expect(probes).toBe(0);
+ expect((await byId("ssh:nas"))?.status).toBeNull();
+ });
- it("probes only the machines this Project installed on, and keeps the answer", async () => {
- await boot(answering({ running: true, port: 7364, pid: 42, machineId: "LNrJdHAZJ91G58i0" }));
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ it("probes only the machines something was installed on", async () => {
+ const probed: string[] = [];
+ await boot({
+ probe: async (target) => {
+ probed.push(target.alias);
+ return { state: { kind: "running", port: 7364, pid: 1 }, machineId: null };
+ },
+ });
+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");
await waitFor(() => t.deps.machines.job()?.running === false);
+ probed.length = 0;
- const body = (await (
- await admin.post(`/api/projects/${PROJECT}/machines/probe`)
- ).json()) as MachinesResponse;
- const nas = body.machines.find((m) => m.id === "ssh:nas");
- expect(nas?.status).toMatchObject({ state: "running", port: 7364 });
- // build-box was never installed on, so nothing was asked of it.
- expect(body.machines.find((m) => m.id === "ssh:build-box")?.status).toBeNull();
+ const res = await admin.post("/api/projects/default_project/machines/probe");
+ expect(res.status).toBe(200);
+ expect(probed).toEqual(["nas"]);
+ expect((await byId("ssh:nas"))?.status).toMatchObject({ state: "running", port: 7364 });
+ expect((await byId("ssh:build-box"))?.status).toBeNull();
});
- it("remembers the id a machine answered, so later reads point at the machine", async () => {
- await boot(answering({ running: true, port: 7364, pid: 42, machineId: "LNrJdHAZJ91G58i0" }));
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ it("a stopped server and an unreachable machine are both answers, not errors", async () => {
+ await boot({ probe: async () => ({ state: { kind: "stopped" }, machineId: null }) });
+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");
await waitFor(() => t.deps.machines.job()?.running === false);
- await admin.post(`/api/projects/${PROJECT}/machines/probe`);
+ await admin.post("/api/projects/default_project/machines/probe");
+ expect((await byId("ssh:nas"))?.status).toMatchObject({ state: "stopped" });
+ expect((await byId("ssh:nas"))?.status?.port).toBeUndefined();
- expect(machinesRepo.get("ssh:nas")?.machineId).toBe("LNrJdHAZJ91G58i0");
- });
-
- it("an alias repointed at another host answers a different id, and the newer one wins", async () => {
- // An id never changes for a machine, so a change of id is a change of machine.
- let answers = "first00000000000";
await boot({
probe: async () => ({
- state: { kind: "running" as const, port: 7364, pid: 42 },
- machineId: answers,
+ state: { kind: "unreachable", detail: "Permission denied (publickey)." },
+ machineId: null,
}),
});
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");
await waitFor(() => t.deps.machines.job()?.running === false);
- await admin.post(`/api/projects/${PROJECT}/machines/probe`);
- expect(machinesRepo.get("ssh:nas")?.machineId).toBe("first00000000000");
- expect(machinesRepo.get("ssh:nas")?.version).not.toBeNull();
-
- answers = "second0000000000";
- await admin.post(`/api/projects/${PROJECT}/machines/probe`);
- const row = machinesRepo.get("ssh:nas");
- expect(row?.machineId).toBe("second0000000000");
- // What the row knew was learned from the machine that is no longer at this address.
- // Kept, the newcomer would read as already installed at a build it has never run —
- // and an "already installed" record is exactly what suppresses the install that would
- // have corrected it.
- expect(row?.version).toBeNull();
- expect(row?.installedAt).toBeNull();
- expect(row?.platform).toBeNull();
- expect(row?.remotePort).toBeNull();
-
- const body = (await (
- await admin.get(`/api/projects/${PROJECT}/machines`)
- ).json()) as MachinesResponse;
- expect(body.machines.find((m) => m.id === "ssh:nas")?.installed).toBeNull();
+ await admin.post("/api/projects/default_project/machines/probe");
+ expect((await byId("ssh:nas"))?.status).toMatchObject({
+ state: "unreachable",
+ detail: "Permission denied (publickey).",
+ });
});
it("two probe requests at once share one round: each machine is asked once", async () => {
@@ -495,31 +530,408 @@ describe("machines API", () => {
return { state: { kind: "stopped" as const }, machineId: null };
},
});
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");
await waitFor(() => t.deps.machines.job()?.running === false);
probes = 0;
// Two tabs, one Project: the second asker joins the round the first started.
await Promise.all([
- admin.post(`/api/projects/${PROJECT}/machines/probe`),
- admin.post(`/api/projects/${PROJECT}/machines/probe`),
+ admin.post("/api/projects/default_project/machines/probe"),
+ admin.post("/api/projects/default_project/machines/probe"),
]);
expect(probes).toBe(1);
// A round that has settled is not reused: the next ask is a fresh one.
- await admin.post(`/api/projects/${PROJECT}/machines/probe`);
+ await admin.post("/api/projects/default_project/machines/probe");
expect(probes).toBe(2);
});
- it("a machine with no server yet has no id, and says stopped rather than guessing", async () => {
- await boot(answering({ running: false, machineId: null }));
- await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ it("refuses to install onto this very machine", async () => {
+ await boot();
+ const res = await admin.post("/api/projects/default_project/machines/local/install");
+ expect(res.status).toBe(409);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("self_install");
+ expect(t.deps.machines.job()).toBeNull();
+ });
+ });
+
+ describe("connecting", () => {
+ /** An install this server did earlier, so the machine is one connect() accepts. */
+ const installed = (version: string) =>
+ machinesRepo.patch("ssh:nas", { version, installedAt: "2026-08-01T00:00:00.000Z" });
+
+ it("a live connection to a dead server is not 'connected': connect asks the machine and starts it", async () => {
+ // The loop this guards: the connection is an ssh process on THIS side and outlives the
+ // far server. Connect used to answer "Already connected" on the connection's word alone,
+ // so the one job that could have started the dead server never did — and every caller
+ // that found the machine silent asked for another connect, forever.
+ const starts: number[] = [];
+ let up = false;
+ await boot({
+ probe: async () =>
+ up
+ ? { state: { kind: "running" as const, port: 7364, pid: 4242 }, machineId: null }
+ : { state: { kind: "stopped" as const }, machineId: null },
+ startServer: async (_t, port) => {
+ starts.push(port);
+ up = true;
+ return { ok: true };
+ },
+ });
+ installed("9.9.9");
+ // A connection that is up, to a server that probes as stopped.
+ connected.add("ssh:nas");
+ machinesRepo.patch("ssh:nas", { remotePort: 7364 });
+ await admin.post("/api/projects/default_project/machines/ssh:nas/connect");
await waitFor(() => t.deps.machines.job()?.running === false);
+ expect(t.deps.machines.job()?.result).toEqual({ ok: true, connected: true });
+ expect(starts).toEqual([7364]);
+ expect(t.deps.machines.job()?.log.join(" ")).toContain("Starting its server");
+ });
- const body = (await (
- await admin.post(`/api/projects/${PROJECT}/machines/probe`)
- ).json()) as MachinesResponse;
- const nas = body.machines.find((m) => m.id === "ssh:nas");
- expect(nas?.status?.state).toBe("stopped");
- expect(nas?.machineId).toBeNull();
+ it("reconnecting over a live connection to an answering server starts nothing new", async () => {
+ // hold() is idempotent in the transport: it promotes the session in place. What must
+ // not happen is a start — the server is up — and the record must name the held session.
+ const starts: number[] = [];
+ let holds = 0;
+ await boot({
+ startServer: async (_t, port) => {
+ starts.push(port);
+ return { ok: true };
+ },
+ hold: async () => {
+ holds++;
+ return { ok: true, session: { pid: process.pid, socksPort: 1 } };
+ },
+ });
+ installed("9.9.9");
+ connected.add("ssh:nas");
+ machinesRepo.patch("ssh:nas", { remotePort: 7364 });
+ await admin.post("/api/projects/default_project/machines/ssh:nas/connect");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ expect(t.deps.machines.job()?.result).toEqual({ ok: true, connected: true });
+ expect(starts).toEqual([]);
+ expect(holds).toBe(1);
+ expect(machinesRepo.get("ssh:nas")?.sessionPid).toBe(process.pid);
+ });
+
+ it("a connect's own probes are the machine's status: it does not read as stopped until the next round", async () => {
+ let up = false;
+ await boot({
+ probe: async () =>
+ up
+ ? {
+ state: { kind: "running" as const, port: 7364, pid: 4242 },
+ machineId: "LNrJdHAZJ91G58i0",
+ }
+ : { state: { kind: "stopped" as const }, machineId: null },
+ startServer: async () => {
+ up = true;
+ return { ok: true };
+ },
+ });
+ installed("9.9.9");
+ await admin.post("/api/projects/default_project/machines/ssh:nas/connect");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ expect(t.deps.machines.job()?.result).toEqual({ ok: true, connected: true });
+ const nas = (
+ (await (await admin.get(`/api/projects/${PROJECT}/machines`)).json()) as MachinesResponse
+ ).machines.find((m) => m.id === "ssh:nas");
+ expect(nas?.status).toMatchObject({ state: "running", port: 7364 });
+ expect(nas?.machineId).toBe("LNrJdHAZJ91G58i0");
+ expect(nas?.connection).not.toBeNull();
+ });
+
+ it("refuses, from what it just heard, an alias that answers this server's own id", async () => {
+ // Never probed before, so the record could not refuse it; the probe inside the job can.
+ let holds = 0;
+ await boot({
+ probe: async () => ({
+ state: { kind: "running" as const, port: 7364, pid: 1 },
+ machineId: LOCAL_ID,
+ }),
+ hold: async () => {
+ holds++;
+ return { ok: true, session: { pid: process.pid, socksPort: 1 } };
+ },
+ });
+ installed("9.9.9");
+ await admin.post("/api/projects/default_project/machines/ssh:nas/connect");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ expect(t.deps.machines.job()?.result).toMatchObject({ ok: false, step: "connect" });
+ expect((t.deps.machines.job()?.result as { message: string }).message).toContain(
+ "this server's own id",
+ );
+ expect(holds).toBe(0);
+ });
+
+ it("409s a Windows machine up front: there is no shell to hold a session on", async () => {
+ await boot();
+ installed("9.9.9");
+ machinesRepo.patch("ssh:nas", { platform: "win32" });
+ const res = await admin.post("/api/projects/default_project/machines/ssh:nas/connect");
+ expect(res.status).toBe(409);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
+ "connect_unsupported",
+ );
+ expect(t.deps.machines.job()).toBeNull();
+ });
+
+ it("start() re-holds what the record says was held, and only that", async () => {
+ const heldNow: string[] = [];
+ await boot({
+ hold: async (target) => {
+ heldNow.push(target.alias);
+ connected.add(`ssh:${target.alias}`);
+ return { ok: true, session: { pid: process.pid, socksPort: 1 } };
+ },
+ });
+ // nas was held by the generation before; build-box was installed on but never asked
+ // for, and a Windows host has nothing to hold.
+ machinesRepo.patch("ssh:nas", {
+ version: "9.9.9",
+ installedAt: "2026-08-01T00:00:00.000Z",
+ sessionPid: 424242,
+ remotePort: 7364,
+ });
+ machinesRepo.patch("ssh:build-box", {
+ version: "9.9.9",
+ installedAt: "2026-08-01T00:00:00.000Z",
+ sessionPid: null,
+ });
+ await t.deps.machines.start();
+ expect(heldNow).toEqual(["nas"]);
+ expect(machinesRepo.get("ssh:nas")?.sessionPid).toBe(process.pid);
+ expect(t.deps.machines.list(PROJECT).find((m) => m.id === "ssh:nas")?.connection).toEqual({
+ pid: process.pid,
+ });
+ });
+
+ it("disconnect clears the record, so a later boot leaves the machine alone", async () => {
+ const heldNow: string[] = [];
+ await boot({
+ hold: async (target) => {
+ heldNow.push(target.alias);
+ connected.add(`ssh:${target.alias}`);
+ return { ok: true, session: { pid: process.pid, socksPort: 1 } };
+ },
+ });
+ installed("9.9.9");
+ await admin.post("/api/projects/default_project/machines/ssh:nas/connect");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ expect(machinesRepo.get("ssh:nas")?.sessionPid).toBe(process.pid);
+
+ await admin.post("/api/projects/default_project/machines/ssh:nas/disconnect");
+ connected.delete("ssh:nas");
+ expect(machinesRepo.get("ssh:nas")?.sessionPid).toBeNull();
+ heldNow.length = 0;
+ await t.deps.machines.start();
+ expect(heldNow).toEqual([]);
+ });
+ });
+
+ describe("browsing a machine's directories", () => {
+ const ID = "LNrJdHAZJ91G58i0";
+ /** A machine this server holds a connection to, whose id a probe has heard. */
+ const connectedMachine = () => {
+ machinesRepo.patch("ssh:nas", {
+ version: "9.9.9",
+ installedAt: "2026-08-01T00:00:00.000Z",
+ machineId: ID,
+ remotePort: 7364,
+ });
+ connected.add("ssh:nas");
+ };
+ const listing = (stdout: string) => async (_t: unknown, command: string) =>
+ command.includes("---penguin-dirs---")
+ ? { code: 0, stdout, stderr: "", timedOut: false }
+ : {
+ code: 0,
+ stdout: "---penguin-auth-token---\nremote-token\n",
+ stderr: "",
+ timedOut: false,
+ };
+
+ it("lists the subdirectories at the path the machine resolved, parent included", async () => {
+ const asked: string[] = [];
+ await boot({
+ runOn: async (_t, command) => {
+ asked.push(command);
+ return listing("/home/deploy/work\n---penguin-dirs---\nsrc\nnotes\n")(_t, command);
+ },
+ });
+ connectedMachine();
+ const res = await admin.get(`/api/projects/${PROJECT}/machines/${ID}/dirs?path=~/work`);
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({
+ path: "/home/deploy/work",
+ parent: "/home/deploy",
+ entries: [
+ { name: "notes", path: "/home/deploy/work/notes" },
+ { name: "src", path: "/home/deploy/work/src" },
+ ],
+ });
+ // The path went to the machine quoted, so a name with a space is one argument there.
+ expect(asked.find((c) => c.includes("---penguin-dirs---"))).toContain("'~/work'");
+ });
+
+ it("404s a directory the machine does not have", async () => {
+ await boot({
+ runOn: async (_t, command) =>
+ command.includes("---penguin-dirs---")
+ ? { code: 3, stdout: "", stderr: "", timedOut: false }
+ : { code: 0, stdout: "", stderr: "", timedOut: false },
+ });
+ connectedMachine();
+ const res = await admin.get(`/api/projects/${PROJECT}/machines/${ID}/dirs?path=/nope`);
+ expect(res.status).toBe(404);
+ });
+
+ it("404s a machine that is not connected, and asks it nothing — a read never opens ssh", async () => {
+ const asked: string[] = [];
+ await boot({
+ runOn: async (_t, command) => {
+ asked.push(command);
+ return { code: 0, stdout: "", stderr: "", timedOut: false };
+ },
+ });
+ connectedMachine();
+ connected.delete("ssh:nas");
+ const res = await admin.get(`/api/projects/${PROJECT}/machines/${ID}/dirs`);
+ expect(res.status).toBe(404);
+ expect(asked).toEqual([]);
+ });
+
+ it("speaks through the alias that holds the session when two aliases share one machine", async () => {
+ const asked: string[] = [];
+ await boot({
+ runOn: async (target, command) => {
+ asked.push(target.alias);
+ return listing("/home/deploy\n---penguin-dirs---\n")(target, command);
+ },
+ });
+ // Both aliases answered the same id; only build-box is connected.
+ machinesRepo.patch("ssh:nas", {
+ machineId: ID,
+ version: "9.9.9",
+ installedAt: "2026-08-02T00:00:00.000Z",
+ });
+ machinesRepo.patch("ssh:build-box", {
+ machineId: ID,
+ version: "9.9.9",
+ installedAt: "2026-08-01T00:00:00.000Z",
+ });
+ connected.add("ssh:build-box");
+ const res = await admin.get(`/api/projects/${PROJECT}/machines/${ID}/dirs`);
+ expect(res.status).toBe(200);
+ expect(asked).toEqual(["build-box"]);
+ });
+ });
+
+ describe("the api sighting", () => {
+ const REMOTE = "kUkIyqU-1GOfXgKD";
+ const nas = async () =>
+ (
+ (await (
+ await admin.get("/api/projects/default_project/machines")
+ ).json()) as MachinesResponse
+ ).machines.find((m) => m.id === "ssh:nas");
+
+ it("is stamped by the proxy's report and served with the list, by machine id", async () => {
+ await boot();
+ machinesRepo.patch("ssh:nas", { machineId: REMOTE });
+ expect((await nas())?.api).toBeNull();
+ t.deps.machines.noteApiSeen(REMOTE, { ok: true });
+ expect((await nas())?.api).toEqual({ answeredAt: "2026-08-24T12:00:00.000Z" });
+ t.deps.machines.noteApiSeen(REMOTE, { ok: false, detail: "connect ECONNREFUSED" });
+ expect((await nas())?.api).toEqual({
+ failedAt: "2026-08-24T12:00:00.000Z",
+ detail: "connect ECONNREFUSED",
+ });
+ });
+
+ it("a sighting of a machine no row names lands nowhere, and does not throw", async () => {
+ await boot();
+ t.deps.machines.noteApiSeen("nobody-knows-this", { ok: true });
+ expect((await nas())?.api).toBeNull();
+ });
+ });
+
+ describe("machine identity", () => {
+ const ID = "LNrJdHAZJ91G58i0";
+ const listed = async () =>
+ (
+ (await (
+ await admin.get("/api/projects/default_project/machines")
+ ).json()) as MachinesResponse
+ ).machines;
+ const byId = async (id: string) => (await listed()).find((machine) => machine.id === id);
+
+ it("mints this machine's id once and keeps answering with it", async () => {
+ await boot();
+ const db = openDatabase(path.join(machinesRoot, "machine-id.db"));
+ try {
+ const minted = new MachinesRepo(db).ownId();
+ expect(minted).toMatch(/^[A-Za-z0-9_-]{16}$/);
+ expect(new MachinesRepo(db).ownId()).toBe(minted);
+ } finally {
+ db.close();
+ }
+ });
+
+ it("reports it as this machine's own, alongside the machines it reaches", async () => {
+ await boot();
+ expect((await byId("local"))?.machineId).toBe(LOCAL_ID);
+ });
+
+ it("a remote's id is null until a probe has heard it", async () => {
+ await boot();
+ expect((await byId("ssh:nas"))?.machineId).toBeNull();
+ });
+
+ it("a probe learns it, and it is remembered without another round trip", async () => {
+ await boot({
+ probe: async () => ({ state: { kind: "running", port: 7364, pid: 1 }, machineId: ID }),
+ });
+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ await admin.post("/api/projects/default_project/machines/probe");
+ expect((await byId("ssh:nas"))?.machineId).toBe(ID);
+
+ const reborn = new MachinesService(machinesRoot, LOCAL_ID, machinesRepo, effects());
+ expect(reborn.list("default_project").find((m) => m.id === "ssh:nas")?.machineId).toBe(ID);
+ });
+
+ it("a machine whose server never started stays without one", async () => {
+ await boot({ probe: async () => ({ state: { kind: "stopped" }, machineId: null }) });
+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ await admin.post("/api/projects/default_project/machines/probe");
+ expect((await byId("ssh:nas"))?.status).toMatchObject({ state: "stopped" });
+ expect((await byId("ssh:nas"))?.machineId).toBeNull();
+ });
+
+ it("an alias repointed at a different machine takes the newer id, and forgets the old one", async () => {
+ let id = ID;
+ await boot({
+ probe: async () => ({ state: { kind: "running", port: 7364, pid: 1 }, machineId: id }),
+ });
+ await admin.post("/api/projects/default_project/machines/ssh:nas/install");
+ await waitFor(() => t.deps.machines.job()?.running === false);
+ await admin.post("/api/projects/default_project/machines/probe");
+ expect((await byId("ssh:nas"))?.machineId).toBe(ID);
+ expect(machinesRepo.get("ssh:nas")?.version).not.toBeNull();
+
+ id = "PO_VCwpQrw1hQLV-";
+ await admin.post("/api/projects/default_project/machines/probe");
+ expect((await byId("ssh:nas"))?.machineId).toBe(id);
+ // What the row held was learned from the machine no longer at this address. Kept, the
+ // newcomer would read as already installed at a build it has never run — and an
+ // "already installed" record is what suppresses the install that would correct it.
+ const row = machinesRepo.get("ssh:nas");
+ expect(row?.version).toBeNull();
+ expect(row?.installedAt).toBeNull();
+ expect(row?.platform).toBeNull();
+ expect(row?.remotePort).toBeNull();
+ expect((await byId("ssh:nas"))?.installed).toBeNull();
});
});
@@ -533,13 +945,6 @@ describe("machines API", () => {
expect(t.deps.machines.job()).toBeNull();
});
- it("409s an install onto the machine this server runs on", async () => {
- await boot();
- const res = await admin.post(`/api/projects/${PROJECT}/machines/local/install`);
- expect(res.status).toBe(409);
- expect(((await res.json()) as { error: { code: string } }).error.code).toBe("self_install");
- });
-
it("409s a second install while one is running", async () => {
let release = () => {};
const held = new Promise<void>((resolve) => {
@@ -551,10 +956,12 @@ describe("machines API", () => {
return { kind: "installed", output: "", identity: IDENTITY };
},
});
- expect((await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`)).status).toBe(
- 202,
+ expect(
+ (await admin.post("/api/projects/default_project/machines/ssh:nas/install")).status,
+ ).toBe(202);
+ const second = await admin.post(
+ "/api/projects/default_project/machines/ssh:build-box/install",
);
- const second = await admin.post(`/api/projects/${PROJECT}/machines/ssh:build-box/install`);
expect(second.status).toBe(409);
expect(((await second.json()) as { error: { code: string } }).error.code).toBe(
"install_running",
@@ -565,7 +972,9 @@ describe("machines API", () => {
it("404s a host this server's config does not declare", async () => {
await boot();
- const res = await admin.post(`/api/projects/${PROJECT}/machines/ssh:not-in-config/install`);
+ const res = await admin.post(
+ "/api/projects/default_project/machines/ssh:not-in-config/install",
+ );
expect(res.status).toBe(404);
expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
"unknown_machine",
@@ -575,7 +984,7 @@ describe("machines API", () => {
it("409s when this server carries no install image", async () => {
await boot({ resolvePlan: () => null });
- const res = await admin.post(`/api/projects/${PROJECT}/machines/ssh:nas/install`);
+ const res = await admin.post("/api/projects/default_project/machines/ssh:nas/install");
expect(res.status).toBe(409);
expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
"no_install_image",
diff --git a/packages/server/test/machines-auth-token.test.ts b/packages/server/test/machines-auth-token.test.ts
new file mode 100644
index 00000000..8461fb9c
--- /dev/null
+++ b/packages/server/test/machines-auth-token.test.ts
@@ -0,0 +1,71 @@
+/**
+ * Asking a MACHINE for a session token, over ssh (machines/remote-token.ts).
+ *
+ * This exists because the path it replaces has a dead end: reading a machine's SEEDED admin
+ * password works only until somebody sets a real one, and then that machine can never be
+ * configured from here again. What authorizes a token instead is the ssh account's access to
+ * the data root — access that already reads every credential on that machine by hand.
+ *
+ * What the token IS — that it authenticates, and only as a password session — is pinned in
+ * auth-token.test.ts. What matters here is the asking: reading it out of a shell's output
+ * without mistaking a login banner for a credential, and telling a machine too OLD to know the
+ * command apart from one that failed. The first is "ask another way" and the caller has one;
+ * the second is not, and confusing them strands every machine carrying an older build.
+ */
+import { describe, expect, it } from "vitest";
+import { authTokenCommand, mintTokenOnRemote, parseToken } from "../src/machines/remote-token.js";
+import type { ExecResult } from "../src/machines/transport/index.js";
+
+const ok = (stdout: string): ExecResult => ({ code: 0, stdout, stderr: "", timedOut: false });
+
+describe("parseToken", () => {
+ it("takes the first line after the marker, not a shell banner before it", () => {
+ // The command runs through a shell whose profile may print anything; a banner is not a
+ // credential, and taking the wrong line would send junk as a cookie.
+ expect(parseToken("Welcome to nas!\nMOTD\n---penguin-auth-token---\nabc123\n")).toBe("abc123");
+ expect(parseToken("---penguin-auth-token---\n\n abc123 \n")).toBe("abc123");
+ expect(parseToken("command not found: penguin")).toBeNull();
+ });
+
+ it("asks for a bounded lifetime, and refuses a nonsensical one", () => {
+ expect(authTokenCommand(60)).toContain("--ttl-seconds 60");
+ // The command the CLI actually has, and `--mark` — without it the token comes back bare
+ // and parseToken has nothing to anchor on.
+ expect(authTokenCommand(60)).toContain("auth token");
+ expect(authTokenCommand(60)).toContain("--mark");
+ expect(authTokenCommand(60)).not.toContain("server auth-token");
+ expect(() => authTokenCommand(0)).toThrow();
+ });
+});
+
+describe("mintTokenOnRemote", () => {
+ it("reads a machine too old to know the command as 'ask another way'", async () => {
+ // Separate from a failure on purpose: the caller still has the seeded-password path, and
+ // treating this as fatal would strand every machine carrying an older build.
+ const outcome = await mintTokenOnRemote({ alias: "nas", user: "me" }, async () =>
+ ok("penguin: unknown command 'auth-token'"),
+ );
+ expect(outcome.kind).toBe("unsupported");
+ });
+
+ it("does not read a timeout as an old build", async () => {
+ const outcome = await mintTokenOnRemote({ alias: "nas", user: "me" }, async () => ({
+ code: 255,
+ stdout: "",
+ stderr: "",
+ timedOut: true,
+ }));
+ expect(outcome.kind).toBe("failed");
+ });
+
+ it("answers when the connection is gone, rather than throwing through its caller", async () => {
+ // The shared ssh connection REJECTS once it is dead. Every other way of not getting a
+ // token is a returned outcome, and signInOn reads outcomes to decide whether to fall back
+ // to the password path — a throw skips that fallback and surfaces as a 500 on a machine
+ // that merely lost its tunnel.
+ const outcome = await mintTokenOnRemote({ alias: "nas", user: "me" }, () => {
+ throw new Error("write after end");
+ });
+ expect(outcome).toEqual({ kind: "failed", detail: "write after end" });
+ });
+});
diff --git a/packages/server/test/machines-proxy.test.ts b/packages/server/test/machines-proxy.test.ts
new file mode 100644
index 00000000..77c37dbd
--- /dev/null
+++ b/packages/server/test/machines-proxy.test.ts
@@ -0,0 +1,146 @@
+/**
+ * The same-origin proxy: which paths it claims, how a remote's redirects are re-rooted, and
+ * what each forwarded request reports having learned. Everything is addressed by the
+ * MACHINE'S own id rather than the ssh alias.
+ */
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ SERVER_PROXY_PREFIX,
+ machinesProxy,
+ parseProxyPath,
+ rewriteLocation,
+} from "../src/machines/proxy.js";
+
+/** A machine, by the id it minted. */
+const A = "QS7J4YVgSovi-Z2c";
+
+describe("parseProxyPath", () => {
+ it("claims /server/<machineId>/api/… and names both halves", () => {
+ expect(parseProxyPath(`${SERVER_PROXY_PREFIX}${A}/api/me`)).toEqual({
+ machineId: A,
+ remotePath: "/api/me",
+ });
+ });
+
+ it("needs no percent-encoding — a machine id is base64url by construction", () => {
+ const path = `${SERVER_PROXY_PREFIX}${A}/api/me`;
+ expect(path).not.toContain("%");
+ expect(parseProxyPath(path)?.machineId).toBe(A);
+ });
+
+ it("forwards ONLY /api — a remote's pages are never proxied", () => {
+ expect(parseProxyPath(`${SERVER_PROXY_PREFIX}${A}/`)).toBeNull();
+ expect(parseProxyPath(`${SERVER_PROXY_PREFIX}${A}/index.html`)).toBeNull();
+ expect(parseProxyPath(`${SERVER_PROXY_PREFIX}${A}/preview/x`)).toBeNull();
+ });
+
+ it("declines anything that is not the proxy prefix", () => {
+ expect(parseProxyPath("/api/me")).toBeNull();
+ expect(parseProxyPath("/server/")).toBeNull();
+ expect(parseProxyPath(`/server/${A}`)).toBeNull();
+ });
+});
+
+describe("rewriteLocation", () => {
+ it("re-roots an absolute redirect under this machine's prefix", () => {
+ expect(rewriteLocation("/api/login", A)).toBe(`${SERVER_PROXY_PREFIX}${A}/api/login`);
+ });
+
+ it("leaves an absolute URL alone — it is not ours to re-root", () => {
+ expect(rewriteLocation("https://example.com/x", A)).toBe("https://example.com/x");
+ });
+});
+
+describe("the report", () => {
+ /** What a forwarded request learned, as noteApiSeen would hear it. */
+ let upstream: http.Server | null = null;
+
+ afterEach(() => {
+ upstream?.close();
+ upstream = null;
+ });
+
+ const listen = (): Promise<number> =>
+ new Promise((resolve) => {
+ upstream = http.createServer((_req, res) => {
+ res.statusCode = 500; // Any HTTP answer is an ANSWER — a refusing server is alive.
+ res.end("{}");
+ });
+ upstream.listen(0, "127.0.0.1", () => {
+ resolve((upstream!.address() as { port: number }).port);
+ });
+ });
+
+ const request = (machineId: string) =>
+ new Request(`http://app.local${SERVER_PROXY_PREFIX}${machineId}/api/me`);
+
+ it("hands the machine its own session and none of this server's credentials", async () => {
+ // The proxy speaks to the machine as ITS admin. A caller's bearer is a credential for
+ // THIS server: sent on, it would both reach another machine and outrank the cookie the
+ // proxy just minted, since the remote's auth reads a bearer before a session.
+ let got: http.IncomingHttpHeaders | null = null;
+ upstream = http.createServer((req, res) => {
+ got = req.headers;
+ res.statusCode = 200;
+ res.end("{}");
+ });
+ const port = await new Promise<number>((resolve) =>
+ upstream!.listen(0, "127.0.0.1", () => resolve((upstream!.address() as AddressInfo).port)),
+ );
+ const proxy = machinesProxy(async () => ({
+ agent: new http.Agent(),
+ port,
+ cookie: "penguin_session=minted",
+ }));
+ await proxy(
+ new Request(`http://app.local${SERVER_PROXY_PREFIX}${A}/api/me`, {
+ headers: { authorization: "Bearer this-server's-token", cookie: "penguin_session=local" },
+ }),
+ );
+
+ expect(got).not.toBeNull();
+ expect(got!.authorization).toBeUndefined();
+ expect(got!.cookie).toBe("penguin_session=minted");
+ });
+
+ it("says the machine answered on any HTTP answer, refusals included", async () => {
+ const port = await listen();
+ const seen: [string, { ok: boolean }][] = [];
+ const proxy = machinesProxy(
+ async () => ({ agent: new http.Agent(), port, cookie: "penguin_session=x" }),
+ (machineId, outcome) => seen.push([machineId, outcome]),
+ );
+ const response = await proxy(request(A));
+ expect(response?.status).toBe(500);
+ expect(seen).toEqual([[A, { ok: true }]]);
+ });
+
+ it("says the forward had nowhere to deliver when the socket fails, with the transport's words", async () => {
+ const port = await listen();
+ upstream!.close();
+ upstream = null;
+ const seen: [string, { ok: boolean; detail?: string }][] = [];
+ const proxy = machinesProxy(
+ async () => ({ agent: new http.Agent(), port, cookie: "penguin_session=x" }),
+ (machineId, outcome) => seen.push([machineId, outcome]),
+ );
+ const response = await proxy(request(A));
+ expect(response?.status).toBe(502);
+ expect(seen).toHaveLength(1);
+ expect(seen[0]![1]).toMatchObject({ ok: false });
+ expect((seen[0]![1] as { detail: string }).detail).not.toBe("");
+ });
+
+ it("reports nothing when there is no forward to try — an unasked machine is unmeasured", async () => {
+ const seen: unknown[] = [];
+ const proxy = machinesProxy(
+ async () => null,
+ (machineId, outcome) => seen.push([machineId, outcome]),
+ );
+ const response = await proxy(request(A));
+ expect(response?.status).toBe(503);
+ expect(seen).toEqual([]);
+ });
+});
diff --git a/packages/server/test/machines-transport-session.test.ts b/packages/server/test/machines-transport-session.test.ts
index e31b7f48..0b47d7f3 100644
--- a/packages/server/test/machines-transport-session.test.ts
+++ b/packages/server/test/machines-transport-session.test.ts
@@ -104,6 +104,49 @@ exit 1
expect(spawns()).toHaveLength(2);
});
+ it("a held session that dies comes back on its own; a closed one stays closed", async () => {
+ const conn = connectionTo({ alias: "nas", user: "deploy" });
+ const held = await conn.hold();
+ expect(held.ok).toBe(true);
+ expect(conn.held()).toBe(true);
+ const first = sessionOf("ssh:nas")!.pid;
+
+ // The link drops — the ssh child is gone, as after keepalives give up on a dead link.
+ process.kill(first);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ expect(sessionOf("ssh:nas")).toBeNull();
+ // Held, so the transport brings it back: the shortest wait is a second.
+ const deadline = Date.now() + 5_000;
+ while (sessionOf("ssh:nas") === null && Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ const second = sessionOf("ssh:nas");
+ expect(second).not.toBeNull();
+ expect(second!.pid).not.toBe(first);
+ expect(spawns()).toHaveLength(2);
+ // And it is a working session, still held.
+ expect(await conn.exec("echo back")).toMatchObject({ code: 0, stdout: "back\n" });
+ expect(conn.held()).toBe(true);
+
+ // An explicit close lets go for good: nothing reopens it.
+ closeConnectionTo("ssh:nas");
+ expect(conn.held()).toBe(false);
+ await new Promise((resolve) => setTimeout(resolve, 1_500));
+ expect(sessionOf("ssh:nas")).toBeNull();
+ expect(spawns()).toHaveLength(2);
+ });
+
+ it("a command that times out on a held session drops the corpse but keeps the hold", async () => {
+ const conn = connectionTo({ alias: "nas", user: "deploy" });
+ await conn.hold();
+ const timedOut = await conn.stream("sleep 5", { input: Buffer.alloc(0), timeoutMs: 150 });
+ expect(timedOut).toMatchObject({ code: 255, stdout: "the machine did not answer in time" });
+ expect(conn.held()).toBe(true);
+ // The next command finds a session — reopened by the command itself or by the hold.
+ expect(await conn.exec("echo after")).toMatchObject({ code: 0, stdout: "after\n" });
+ expect(conn.held()).toBe(true);
+ });
+
it("closing lets go of the session; the next ask opens a new one", async () => {
const conn = connectionTo({ alias: "nas", user: "deploy" });
await conn.exec("true");
diff --git a/packages/server/test/machines.test.ts b/packages/server/test/machines.test.ts
index a485cbbc..1e0b1675 100644
--- a/packages/server/test/machines.test.ts
+++ b/packages/server/test/machines.test.ts
@@ -1,6 +1,6 @@
/**
* The pure half of the machines capability (platform code — see ../src/hmr/README.md):
- * reading ~/.ssh/config and `ssh -G`, reading what the identity probe answered, choosing
+ * reading ~/.ssh/config for its aliases, reading what the identity probe answered, choosing
* the Node runtime to send, the container the image travels in, finding the running
* server's own pushable image, and the exact ssh/scp commands all of that turns into.
* No network, no ssh binary.
@@ -23,9 +23,9 @@ import {
runInstallScriptCommand,
unpackStoreCommand,
scpArgs,
- sessionArgs,
shQuote,
sshArgs,
+ sessionArgs,
} from "../src/machines/commands.js";
import { resolvePushPlan } from "../src/machines/install-server.js";
@@ -78,8 +78,6 @@ describe("parseHostAliases", () => {
describe("machineIdentity", () => {
it("is <user>@<alias>: the Linux account is part of the machine, the alias is the name", () => {
- // Two accounts on one host are two machines — each has its own ~/.penguin, hence its
- // own server and its own user table.
expect(machineIdentity("build-box", "deploy")).toBe("deploy@build-box");
expect(machineIdentity("build-box", "root")).toBe("root@build-box");
expect(machineIdentity("build-box", "")).toBe("build-box");
@@ -88,8 +86,6 @@ describe("machineIdentity", () => {
describe("identity probe", () => {
it("asks in each shell's own dialect — sh cannot read the Windows one and vice versa", () => {
- // POSIX: `;` chains, $VAR expands, `cat` reads. Windows cmd: `&` chains, %VAR% expands,
- // `type` reads. One command cannot do both, which is why there are two.
expect(POSIX_PROBE).toContain("uname -s -m");
expect(POSIX_PROBE).toContain('"$HOME/.penguin/lib/package.json"');
expect(POSIX_PROBE).toContain(".penguin/data/hmr/harness.json");
@@ -164,6 +160,11 @@ describe("ssh / scp invocations", () => {
expect(scpArgs(target, ["/tmp/a"], "/tmp/dir")).toContain("BatchMode=yes");
});
+ it("selects the account on the command line, never by writing the ssh config", () => {
+ expect(sshArgs(target, "true")).toContain("User=deploy");
+ expect(sshArgs({ alias: "build-box", user: "" }, "true").join(" ")).not.toContain("User=");
+ });
+
it("holds ONE session per machine: no tty, a SOCKS listener on loopback, keepalives, sh", () => {
const args = sessionArgs(target, 49152).join(" ");
expect(args).toContain("-T");
@@ -171,6 +172,7 @@ describe("ssh / scp invocations", () => {
expect(args).toContain("ExitOnForwardFailure=yes");
expect(args).toContain("ServerAliveInterval=15");
expect(args).toContain("BatchMode=yes");
+ expect(args).toContain("User=deploy");
expect(args.endsWith("build-box sh")).toBe(true);
// Nothing is forwarded by name: any port on the machine is a channel through -D.
expect(args).not.toContain("-L ");
@@ -181,11 +183,6 @@ describe("ssh / scp invocations", () => {
expect(() => sessionArgs(target, 70000)).toThrow(/bad port/);
});
- it("selects the account on the command line, never by writing the ssh config", () => {
- expect(sshArgs(target, "true")).toContain("User=deploy");
- expect(sshArgs({ alias: "build-box", user: "" }, "true").join(" ")).not.toContain("User=");
- });
-
it("leaves the scp destination unquoted — modern scp transfers over SFTP, taking it literally", () => {
const args = scpArgs(target, ["/local/image.pack"], "/tmp/penguin-abc123");
expect(args.at(-1)).toBe("build-box:/tmp/penguin-abc123");
@@ -194,13 +191,10 @@ describe("ssh / scp invocations", () => {
it("quotes per shell: single quotes for sh, double for cmd.exe", () => {
expect(shQuote("/tmp/it's here")).toBe(`'/tmp/it'\\''s here'`);
expect(cmdQuote("C:\\Users\\First Last\\tmp")).toBe('"C:\\Users\\First Last\\tmp"');
- // cmd.exe has no escape for a quote inside a quoted string: refuse rather than mangle.
expect(() => cmdQuote('C:\\weird"path')).toThrow();
});
it("takes the installer on stdin, so a POSIX install costs ONE ssh handshake", () => {
- // No path anywhere in it: nothing was copied, so nothing has to be placed or cleaned up.
- // scriptOnStdin is the other half — the command alone would run an empty `sh -s`.
expect(runInstallScriptCommand("v0.2.4", { platform: "linux" })).toEqual({
command: "PENGUIN_VERSION='v0.2.4' sh -s",
scriptOnStdin: true,
@@ -208,9 +202,6 @@ describe("ssh / scp invocations", () => {
});
it("runs a Windows remote's copy from a path, and deletes it in the same command", () => {
- // PowerShell cannot take a param()-carrying script on stdin, so the file is real there —
- // but the delete rides the same connection rather than costing another handshake, and the
- // path is required to build the command at all rather than defaulting to an empty one.
expect(
runInstallScriptCommand("v0.2.4", {
platform: "win32",
@@ -224,10 +215,11 @@ describe("ssh / scp invocations", () => {
});
});
- it("unpacks the streamed store into the hmr directory it was tarred from", () => {
- // The members are named relative to the sending side's own hmr directory, so the two
- // `-C` arguments have to name the same layer: one level too high writes a harness.json
- // and a store/ nothing reads, and the machine goes on answering with what it held.
+ it("unpacks the streamed store into the hmr directory, the layer it was tarred from", () => {
+ // install-server.ts tars `-C <root>/hmr harness.json store`, so the members are named
+ // from THERE. Extracting into the data root instead lands them one directory above where
+ // hmr/host.ts reads them: the machine keeps answering with whatever it already had, and
+ // the replication reports success while achieving nothing.
expect(unpackStoreCommand("linux")).toBe(
'mkdir -p "$HOME/.penguin/data/hmr" && tar -xzf - -C "$HOME/.penguin/data/hmr"',
);
@@ -287,7 +279,6 @@ describe("resolvePushPlan", () => {
it("packaged desktop app: its own manifest names the release it shipped under", () => {
const work = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-plan-"));
try {
- // What the app forks: <resources>/app/dist/server.js, one bundled file, asar off.
const appDir = path.join(work, "resources", "app");
fs.mkdirSync(path.join(appDir, "dist"), { recursive: true });
fs.writeFileSync(
diff --git a/packages/web/src/features/machines/machines-view.ts b/packages/web/src/features/machines/machines-view.ts
index 80329e5e..d1f4b1cc 100644
--- a/packages/web/src/features/machines/machines-view.ts
+++ b/packages/web/src/features/machines/machines-view.ts
@@ -12,11 +12,7 @@
* record rather than from the job: the job is one slot, so deriving it from there made an
* installed machine vanish as soon as anything else was installed or the server restarted.
*/
-import type {
- MachineInfo,
- MachineInstallJob,
- MachinesResponse,
-} from "@prismshadow/penguin-server/api";
+import type { MachineInfo, MachineJob, MachinesResponse } from "@prismshadow/penguin-server/api";
/** The finished job's verdict, in the shape the page renders. */
export type MachineVerdict =
@@ -36,10 +32,13 @@ export interface InstallButtonState {
}
/** The verdict of a job that has finished, or null while it is still running. */
-export function verdictOf(job: MachineInstallJob): MachineVerdict | null {
+export function verdictOf(job: MachineJob): MachineVerdict | null {
if (job.result === null) return null;
- if (job.result.ok) return { kind: job.result.kind, version: job.result.version };
- return { kind: "failed", step: job.result.step, message: job.result.message };
+ if (!job.result.ok) return { kind: "failed", step: job.result.step, message: job.result.message };
+ // A connect has no install verdict to report; the controls that start one, and what they
+ // render when it settles, arrive with the page that has them.
+ if (!("installed" in job.result)) return null;
+ return { kind: job.result.installed, version: job.result.version };
}
/**
diff --git a/packages/web/test/machines-view.test.ts b/packages/web/test/machines-view.test.ts
index edadbaa4..df424bdb 100644
--- a/packages/web/test/machines-view.test.ts
+++ b/packages/web/test/machines-view.test.ts
@@ -9,11 +9,7 @@
* stop looking installed as soon as anything else was installed.
*/
import { describe, expect, it } from "vitest";
-import type {
- MachineInfo,
- MachineInstallJob,
- MachinesResponse,
-} from "@prismshadow/penguin-server/api";
+import type { MachineInfo, MachineJob, MachinesResponse } from "@prismshadow/penguin-server/api";
import {
installButtonState,
installedMachines,
@@ -29,6 +25,8 @@ const remote = (alias: string, installed: MachineInfo["installed"]): MachineInfo
machineId: null,
installed,
local: false,
+ connection: null,
+ api: null,
status: null,
});
@@ -36,7 +34,7 @@ const fresh = (alias: string): MachineInfo => remote(alias, null);
const carrying = (alias: string): MachineInfo => remote(alias, INSTALLED);
function response(
- job: MachineInstallJob | null,
+ job: MachineJob | null,
opts: { imageVersion?: string | null; machines?: MachineInfo[] } = {},
): MachinesResponse {
return {
@@ -46,8 +44,9 @@ function response(
};
}
-function job(over: Partial<MachineInstallJob> = {}): MachineInstallJob {
+function job(over: Partial<MachineJob> = {}): MachineJob {
return {
+ kind: "install",
machineId: "ssh:nas",
alias: "nas",
running: true,
@@ -57,7 +56,10 @@ function job(over: Partial<MachineInstallJob> = {}): MachineInstallJob {
};
}
-const done = job({ running: false, result: { ok: true, kind: "installed", version: "9.9.9" } });
+const done = job({
+ running: false,
+ result: { ok: true, installed: "installed", version: "9.9.9" },
+});
describe("verdictOf", () => {
it("is null while the job runs", () => {
@@ -68,7 +70,10 @@ describe("verdictOf", () => {
expect(verdictOf(done)).toEqual({ kind: "installed", version: "9.9.9" });
expect(
verdictOf(
- job({ running: false, result: { ok: true, kind: "already-installed", version: "9.9.9" } }),
+ job({
+ running: false,
+ result: { ok: true, installed: "already-installed", version: "9.9.9" },
+ }),
),
).toEqual({ kind: "already-installed", version: "9.9.9" });
});
@@ -137,7 +142,7 @@ describe("installButtonState", () => {
machineId: "ssh:build-box",
alias: "build-box",
running: false,
- result: { ok: true, kind: "installed", version: "9.9.9" },
+ result: { ok: true, installed: "installed", version: "9.9.9" },
});
expect(installButtonState(carrying("nas"), response(elsewhere), false)).toEqual({
action: "reinstall",
@@ -218,6 +223,8 @@ describe("this machine in the list", () => {
machineId: "LNrJdHAZJ91G58i0",
installed: INSTALLED,
local: true,
+ connection: null,
+ api: null,
status: { state: "running", checkedAt: INSTALLED.at, port: 7364 },
});