@johnhenry/wsh 0.42.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -66,7 +66,7 @@ Or via CDN:
66
66
  - **MCP bridge** -- discover and invoke remote MCP tools through the control channel
67
67
  - **Session recording** -- own JSON schema (asciicast-v2-shaped, not a playable asciicast file -- see note below) recording and playback with seek/pause/resume
68
68
  - **Key management** -- IndexedDB storage with OPFS encrypted backup (PBKDF2 + AES-256-GCM)
69
- - **108 message types** -- handshake, channel, gateway, guest sharing, compression negotiation, copilot, policy, authorized-key management, and more
69
+ - **110 message types** -- handshake, channel, gateway, guest sharing, compression negotiation, copilot, policy, authorized-key management, and more
70
70
 
71
71
  > **Session recording is asciicast-v2-shaped, but not an asciicast file.**
72
72
  > The JS `SessionRecorder.toJSON()` export borrows asciicast v2's vocabulary --
@@ -250,6 +250,102 @@ ends every authenticated connection `n` ms after login and advertises it
250
250
  limit and sends `ttl: 0`. Before 0.36 it sent an unenforced 3600. The Rust
251
251
  `wsh-server` still sends its `session_ttl` setting unenforced.
252
252
 
253
+ ### Authorized-key options (#122)
254
+
255
+ `auth.authorizedKeys` takes `authorized_keys` lines with options, and reads them the way the Rust `wsh-server` does: **the same
256
+ key file gives the same answer on both hosts.** The two parsers share one set of test vectors
257
+ (`spec/key-options.vectors.json`: a key line gives these permissions, a request is allowed or refused with this code), run by the
258
+ JS suite and by a Rust test, so they cannot drift.
259
+
260
+ ```
261
+ restrict,permit-exec,max-sessions=2 ssh-ed25519 AAAA... ci@build
262
+ command="/usr/bin/uptime" ssh-ed25519 AAAA... monitor
263
+ no-pty ssh-ed25519 AAAA... alice
264
+ ```
265
+
266
+ A line is `[options] ssh-ed25519 <base64> [comment]`. The options are one token (spaces only inside double quotes) of
267
+ comma-separated items, each `name` or `name=value`; a value is `"..."` (`\"` is a quote, any other backslash is literal) or, for
268
+ values without spaces, a bare word. Single quotes are not quotes. Names are case-sensitive.
269
+
270
+ | Option | Meaning | Node host (`@johnhenry/wsh/server`) | Rust `wsh-server` |
271
+ |---|---|---|---|
272
+ | *(none)* | full access: everything the host is configured to offer | as before | as before |
273
+ | `restrict` | grant nothing; add back with `permit-*` | all entries below | all entries below |
274
+ | `permit-pty` | a pty shell, and commands (a shell can run them) | `Open` kind `pty`, `exec` | `Open` kind `pty`, `exec` |
275
+ | `permit-exec` | `exec` channels | `Open` kind `exec` | `Open` kind `exec` |
276
+ | `permit-file-transfer` | file channels, `FileOp`, `wsh-fs` | `Open` kind `file` (upload, download), `FileOp`, rpc `wsh-fs` | the same |
277
+ | `permit-mcp` | MCP discovery and calls | `McpDiscover` (an empty list otherwise), `McpCall`, rpc `mcp` | `McpDiscover`, `McpCall` (no rpc `mcp`) |
278
+ | `permit-relay` | relay registration, listing and connecting | `ReverseRegister`, `ReverseList`, `ReverseConnect` (`relay`) | the same (`--enable-relay`) |
279
+ | *(any restriction)* | a key that is not wholly unrestricted may not install another key | no `AuthorizedKeyAdd` handler | `AuthorizedKeyAdd` (the installed line has no options, so it would otherwise mint an unrestricted key) |
280
+ | `no-pty` | no pty, even when otherwise permitted | `Open` kind `pty` | `Open` kind `pty` |
281
+ | `command="..."` | the only command the key may run; it replaces what the client asks for, and the key gets no pty, files, MCP, relay or rpc | `Open` (exec only), `FileOp`, rpc | the same |
282
+ | `max-sessions=N` (N >= 1) | at most N live pty/exec sessions for the key, over all its connections | counted on this host (detached hosted sessions too) | counted by the session manager |
283
+ | `no-agent-forwarding`, `no-port-forwarding`, `no-X11-forwarding`, `no-user-rc` | accepted, **no effect** (see below) | ignored | ignored |
284
+
285
+ Without `restrict`, the `permit-*` options change nothing. Another rpc protocol (one the embedder added) is open only to a key
286
+ that is not restricted at all; `wsh-host` is open to every key but a forced-command one.
287
+
288
+ **An option this host does not understand refuses the key**: it is not on the allowlist, and the reason is logged (the Node
289
+ host's `onLog`, the Rust server's log: `key refused ... code=unknown-option`). It is never skipped and then granted. The same
290
+ for a malformed value: `max-sessions=0` (it used to mean "no limit" on the Rust server), an empty `command=""`, an option given
291
+ twice, a stray comma. Refusal codes: `unknown-option`, `bad-syntax`, `bad-value`, `duplicate-option`. A line whose options
292
+ cannot be separated from the key (an unterminated quote) or whose key is not `ssh-ed25519` is skipped. If a key appears on
293
+ several lines the first decides.
294
+
295
+ `parseAuthorizedKeys(text)` still returns bare keys, and now only for lines **without** options (it never hands out a key with
296
+ its restrictions dropped); `parseAuthorizedKeyEntries(text)` returns `{ entries, refused }` with each key's permissions.
297
+
298
+ Not covered by `restrict` and the `permit-*` options (see [Security model](#security-model)): the **gateway** (TCP, DNS, unix,
299
+ endpoints, reverse listeners) and the **targets**, so `restrict` and `no-port-forwarding` do not stop a key from using a gateway
300
+ the host has turned on; scope them with `capabilities` below. `no-port-forwarding` is accepted for ssh compatibility and does nothing.
301
+
302
+ #### Capabilities and expiry (#122, step two)
303
+
304
+ Two more options give a key a finer, **default-deny** licence. Nothing changes for a key line that has neither.
305
+
306
+ ```
307
+ capabilities="exec,fs:read,gateway:tcp:db.internal:5432,mcp:search" ssh-ed25519 AAAA... ci@build
308
+ expires="2030-01-01T00:00:00Z" ssh-ed25519 AAAA... contractor
309
+ ```
310
+
311
+ `capabilities="a,b,c"` (comma-separated, no spaces) lists what the key may do; **once the option is present the key may do only
312
+ that**, on top of what its other options allow (the two are ANDed: `restrict,permit-exec,capabilities="exec,pty"` still has no
313
+ pty). `capabilities=""` is a key that may do nothing. `expires="<RFC 3339>"` (`2030-01-01T00:00:00Z` or with an offset; whole
314
+ seconds; upper-case `T`/`Z`) refuses the key from that second: at login, and for every request after it. An unknown capability, a
315
+ malformed argument or a bad timestamp refuses the key (logged with the code `unknown-capability`, `bad-capability` or
316
+ `bad-value`), as unknown options do.
317
+
318
+ | Capability | What it allows | Entry points (Node host / Rust `wsh-server`) |
319
+ |---|---|---|
320
+ | `exec` | `exec` channels | `Open` kind `exec` / the same |
321
+ | `pty` | a pty shell (does **not** imply `exec`) | `Open` kind `pty` / the same |
322
+ | `fs:read` | stat, list, read, download | `FileOp` `stat` `list` `read`, `Open` kind `file` download / the same |
323
+ | `fs:write` | write, mkdir, remove, rename, upload (does not read) | `FileOp` `write` `mkdir` `remove` `rename` (an op nobody knows is a write), `Open` kind `file` upload / the same |
324
+ | `gateway:tcp:<host>:<port>` | `OpenTcp` to that destination; also `ResolveDns` for a host that matches | the Node gateway / the Rust gateway |
325
+ | `gateway:udp:<host>:<port>` | `OpenUdp` to that destination | the same |
326
+ | `gateway:listen:tcp:<port>` | a reverse TCP listener (`ListenRequest`) on that port | `gateway.reverse` / `enable_reverse_tunnels` |
327
+ | `unix:<path>` , `unix:listen:<path>` | connect to, or listen on, that unix socket | `OpenUnix` / `ListenUnix` |
328
+ | `endpoint:<name>` | a named endpoint | Node host only: the Rust server has none and refuses every `OpenEndpoint`, whatever a key holds |
329
+ | `mcp:<tool>` | list and call that tool (`mcp:*`: every tool, and the `mcp` rpc channel) | `McpDiscover` lists only these, `McpCall` / the same |
330
+ | `target:<name>` | name that target in `Open`, `FileOp`, `OpenEndpoint`; `ListTargets` shows only these | Node host only: the Rust server has no targets and refuses a request that names one |
331
+ | `rpc:<protocol>` | open that rpc protocol (`wsh-host`, or an embedder's own) | `Open` kind `rpc` / the same |
332
+ | `relay` | register, list and connect through the relay | `ReverseRegister` `ReverseList` `ReverseConnect` / the same |
333
+
334
+ `<host>` is a name, an IP literal (IPv6 in brackets), `*`, or `*.suffix` (any subdomain, not the apex; the name is compared
335
+ case-insensitively as the client sent it, so resolution is the gateway's `allow` policy's business). `<port>` is a number or `*`.
336
+ `<path>` is absolute with no `.` or `..`, exact or ending in `/*` (anything below that directory). `<name>`/`<tool>` are exact or `*`.
337
+ The `wsh-fs` rpc channel puts read and write methods on one channel, so it needs **both** `fs:read` and `fs:write`; a client without
338
+ both falls back to `FileOp` and the file channels, which are checked per operation. A request with no target runs on the host's own
339
+ backends and needs no `target:` capability (use `requireTarget` to confine keys to targets). Installing a key (`AuthorizedKeyAdd`) is never
340
+ allowed for a key with a capability list. A custom `authorize` on `createWshServer` / `createMemoryHost` may return `{ capabilities,
341
+ expires }` instead of `true`: the same grammar, narrowing the key's own options (it never widens them).
342
+
343
+ Refusals name the missing capability (`missing capability fs:write`, `missing capability gateway:tcp:db.internal:22`) in the answer
344
+ the client already gets (`OpenFail`, a failed `FileResult`, `GatewayFail`, `ListenFail`, an MCP result, a relay `Error` /
345
+ `ReverseReject`, `AuthFail` for an expired key), and the Node host reports each one to `onRefused` with the stable reason
346
+ `not-permitted` (`detail`: `capability-missing: missing capability exec (open exec)`), or `key-expired`. The Rust server logs them.
347
+ `capabilities` and `expires` apply to **key logins**: a password login has no key and is not narrowed by them.
348
+
253
349
  ### Gateway (TCP and DNS egress from the host)
254
350
 
255
351
  `gateway: { allow: ['broker.lan:1883'], allowPrivate: ['10.0.0.0/8'], socks: '127.0.0.1:9050' }` makes the Node server
@@ -713,10 +809,20 @@ const s = await client.openSession({ type: 'exec', command: 'echo hello' });
713
809
  `ReverseConnect` at a time (a concurrent one is told `busy: ... retry in a
714
810
  moment`), since a `ReverseAccept` does not name its operator; and at the cap
715
811
  the reason is `busy: this peer already has its maximum of n operators`
716
- (`busyPeerFull(n)`). The **Rust relay is still one operator per peer**: it
717
- never sends `ReverseClose` and rejects the second operator; the new spec
718
- fields are regenerated into the Rust types and ignored there. Tracked for the
719
- Rust relay in #93.
812
+ (`busyPeerFull(n)`). The **Rust relay and the Rust peer do this too** (#93): `wsh-server --enable-relay`
813
+ with `[relay] max_operators_per_peer = n` in its config (default `1`, 1 to 64; above 1 it advertises
814
+ `relay-multi-operator`), and `wsh --max-operators n reverse ...` / `wsh --max-operators n agent run ...` on the
815
+ peer (default `1`; the peer states the feature only to a relay that advertises it, and serves one operator at a
816
+ time on any other). The Rust relay rejects a busy peer's next operator with a `ReverseReject` carrying the same
817
+ `busy:` reasons. Differences from the JS relay, kept so nothing existing changes: when an operator leaves a peer
818
+ that serves one, the Rust relay leaves the peer connected (it may take the operator back), where the JS relay
819
+ closes it; and a peer that goes away leaves its operators connected. A Rust peer serving several operators keeps
820
+ each operator's sessions, processes and files apart (when one leaves, only its work is killed), takes each
821
+ operator's `--allow-operator` decision and operator proof on its own, and **does not seal bridges** (a
822
+ connection holds one seal): `--max-operators` above 1 is refused together with `--require-operator-proof`, and
823
+ an operator that insists on `--sealed` is refused by such a peer. The Rust relay also carries
824
+ `KeyExchange.signature` and advertises `e2e-sign`, so a JS reverse host signs its half of an end-to-end
825
+ exchange through it.
720
826
  - **On the peer**, the bridged operator is served by the same connection code as
721
827
  a direct client, over an in-memory message pipe instead of a socket. Nothing a
722
828
  client opens can cross the relay but control messages, so exec sessions are
@@ -1096,6 +1202,40 @@ const server = createWshServer({
1096
1202
  - Without `mcp`, `McpDiscover` answers an empty list and `McpCall` an
1097
1203
  `{ success: false, error: 'mcp is not enabled on this server' }` result.
1098
1204
 
1205
+ ### `wsh-mcp`: a stdio bridge for MCP clients (#127)
1206
+
1207
+ An MCP client (Claude Desktop, Cursor, an SDK `StdioClientTransport`, ...) launches a command and speaks MCP over its stdio. The package
1208
+ ships one, `wsh-mcp`, that connects to a wsh host, opens its `mcp` [rpc channel](#rpc-channels-object-mode) and passes the messages
1209
+ both ways, verbatim (ids, notifications, progress, cancellation). The host serves it with
1210
+ `createWshServer({ rpc: { mcp: mcpServerAdapter(server) } })` or, in a page, `createMemoryHost({ rpc: { mcp } })` (reach a memory host
1211
+ through whatever carries its WebSocket or a [pipe relay](#a-pipe-relay-johnhenrywshpipe-relay-118)); give each channel its own server with a factory
1212
+ (`mcpServerAdapter(() => makeServer())`) so a reconnect is served.
1213
+
1214
+ ```
1215
+ npx -p @johnhenry/wsh wsh-mcp [options] [user@]<url> # or install the package and run `wsh-mcp`
1216
+
1217
+ -l, --user NAME login name (default: the user@ in the URL, $WSH_USER, $USER, the OS user)
1218
+ -i, --identity FILE Ed25519 private key (default ~/.wsh/keys/default.pem, what `wsh keygen` writes; a PKCS#8 PEM works too)
1219
+ --channel NAME the rpc channel to open (default mcp)
1220
+ --host-key KEY pin the host (hex fingerprint or ssh-ed25519 line); unpinned, it warns on stderr
1221
+ --no-reconnect, --reconnect-attempts N, --timeout MS
1222
+ ```
1223
+
1224
+ An MCP client configuration:
1225
+
1226
+ ```json
1227
+ { "mcpServers": { "remote": { "command": "wsh-mcp", "args": ["--identity", "/home/me/.wsh/keys/default.pem", "--host-key", "<fingerprint>", "wss://host.example:4422"] } } }
1228
+ ```
1229
+
1230
+ stdout carries MCP messages only (one JSON-RPC message per line); every diagnostic goes to stderr. Exit status: `0` the client closed
1231
+ its side, `1` the host was lost for good, `2` it could not start -- no connection, a refused login or host key, or **a host that offers
1232
+ no such channel** (the error lists the channels it does offer and how to serve one). After a dropped connection it reconnects (5
1233
+ attempts from 500 ms, doubling), re-sends the client's `initialize` to the new channel without telling the client, answers a request
1234
+ that was in flight with a JSON-RPC error (`-32603`, the client may retry) and delivers what the client sent meanwhile (at most 200
1235
+ messages). `--target` is not offered: rpc channels are not per target on any host (#121). The same bridge is a function,
1236
+ `runMcpStdioBridge()` from `@johnhenry/wsh/mcp-stdio`. **Rust: not built** -- the `wsh` CLI has no `wsh mcp`, because `wsh-client` has no
1237
+ rpc channel yet; `wsh-mcp` needs Node.
1238
+
1099
1239
  ### Host key (fingerprint / TOFU)
1100
1240
 
1101
1241
  Give the server an identity and the stock client can pin it:
@@ -1223,6 +1363,47 @@ The host advertises `file-write` / `file-rename` in `ServerHello`; the client
1223
1363
  throws instead of sending to a host without them (the Rust `wsh-server`
1224
1364
  refuses these ops).
1225
1365
 
1366
+ ### Execution targets (#121)
1367
+
1368
+ A host that fronts several places to run things (containers, VMs, workers, sandboxes) names them, instead of overloading `username` or
1369
+ prefixing the command. Off unless you give `targets` (to `createWshServer`, `createMemoryHost`, or `createConnectionFactory` through
1370
+ `resolveBackends`); then the host advertises `targets` in `ServerHello.features`.
1371
+
1372
+ ```js
1373
+ createWshServer({
1374
+ auth: { authorizedKeys },
1375
+ targets: {
1376
+ web: { description: 'the web container', exec: true },
1377
+ db: { description: 'the database VM', exec: (command, io) => runInVm(io.target, command, io), fs: dbFiles,
1378
+ authorize: (who, { target, kind }) => who.fingerprint === DBA_KEY }, // kind: exec | pty | file | endpoint | list
1379
+ },
1380
+ // requireTarget: true, // an Open, FileOp or OpenEndpoint that names no target is refused: nothing runs on the host itself
1381
+ });
1382
+ const targets = await client.listTargets(); // [{ name, description?, capabilities }] -- only what THIS key may use
1383
+ await client.openSession({ type: 'exec', command: 'psql -c ...', target: 'db' }); // also exec(url, cmd, { target })
1384
+ await client.fileOperation('list', '/var/lib', { target: 'db' }); // FileOp.target
1385
+ await client.openEndpoint('metrics', { target: 'web' }); // OpenEndpoint.target
1386
+ ```
1387
+
1388
+ Each target has its own `exec`, `pty`, `fs` and `endpoints` (the same forms as the host's own, `exec: true` and `fs: { root }` included on
1389
+ Node); the host's own are used only by a request that names no target. A target without a backend for the request refuses it (`exec is
1390
+ not enabled for this target`): a request is never run somewhere else. `io.target` (exec), `{ target }` in the pty `spawn` options, in every
1391
+ file backend call and on an endpoint's `duplex.target` tell a shared function which target it serves. `authorize(who, { target, kind })` is
1392
+ asked for every request that names the target and for `listTargets()`; only `true` lets the caller on, and a refused target and one that
1393
+ does not exist get the same answer (`no such target`), so the reply does not say which targets exist. A target without `authorize` is open
1394
+ to every key the host authenticated, as the host's own `exec` is. A `target` the client sends to a host that does not advertise `targets` is
1395
+ not sent (the client throws); a raw one is refused (`this host has no targets`). `createReverseHost` takes no `targets`.
1396
+
1397
+ What it does **not** do: `requireTarget` covers `Open` (exec, pty, file, rpc), `FileOp` and `OpenEndpoint`, not the gateway (`OpenTcp`,
1398
+ `OpenUnix`, `ListenRequest`, ...), MCP, the `rpc` channels (`wsh-fs`, ... are the host's own and are refused when a target is named), or
1399
+ `Attach` to a session that already exists (it was opened on its target, and its owner may attach as before). A target is an authorization
1400
+ boundary only as far as your `authorize` and your backends make it one: the library routes and refuses, it does not isolate anything.
1401
+
1402
+ The Rust CLI names one with `wsh --target NAME [user@]host [command...]` (or `wsh --target NAME connect [user@]host`) and lists them with
1403
+ `wsh targets [user@]host [--json]`; `--target` is refused (exit 2) by file transfer, forwarding, `--share`, `-N` and every other subcommand,
1404
+ and sent only to a host that advertises `targets`. The Rust `wsh-server` has no targets (it states no feature and refuses any request that
1405
+ names one).
1406
+
1226
1407
  ### Compatibility: announce vs. primer
1227
1408
 
1228
1409
  An exec session's output flows on a second, client-opened stream, and a QMux
@@ -1297,7 +1478,7 @@ closes the channel when received.
1297
1478
  | Protocol | Methods |
1298
1479
  |---|---|
1299
1480
  | `wsh-host` | `host.info` -> `{ version, protocol, features (this connection's ServerHello), hostFingerprint, user, rpc }`; `host.ping` -> `{ time }` |
1300
- | `wsh-fs` | `stat`, `list`, `mkdir`, `remove`, `rename { path, newPath }`, `write { path, data, offset? }`, `upload { path, data, offset? }` (offset omitted/0 creates or truncates, later offsets continue in place: chunk big files), `read { path, offset?, length? }` and `download { path }` (the bytes arrive as `$/progress` chunks of at most 64 KiB; the result is `{ size, offset, length, eof }`). Same confinement as `fs`: no traversal or symlink escapes, `readOnly`, `maxFileBytes`; policy refusals are `-32003`. |
1481
+ | `wsh-fs` | `stat`, `list` (entries sorted by name in UTF-16 code-unit order on every platform and on both hosts: upper case before lower case, whatever the filesystem's case rules), `mkdir`, `remove`, `rename { path, newPath }`, `write { path, data, offset? }`, `upload { path, data, offset? }` (offset omitted/0 creates or truncates, later offsets continue in place: chunk big files), `read { path, offset?, length? }` and `download { path }` (the bytes arrive as `$/progress` chunks of at most 64 KiB; the result is `{ size, offset, length, eof }`). Same confinement as `fs`: no traversal or symlink escapes, `readOnly`, `maxFileBytes`; policy refusals are `-32003`. |
1301
1482
  | `mcp` | The MCP JSON-RPC surface verbatim; see below |
1302
1483
 
1303
1484
  When a host advertises `rpc-protocol:wsh-fs`, `fileStat` / `fileList` / `fileRead` /
@@ -1498,7 +1679,7 @@ so options the platform gains later need no change here.
1498
1679
 
1499
1680
  | Export | Description |
1500
1681
  |--------|-------------|
1501
- | `MSG` | 108 message type constants (hex opcodes) |
1682
+ | `MSG` | 110 message type constants (hex opcodes) |
1502
1683
  | `CHANNEL_KIND` | Channel types: `pty`, `exec`, `meta`, `file`, `tcp`, `udp`, `job` |
1503
1684
  | `AUTH_METHOD` | Auth methods: `pubkey`, `password` |
1504
1685
  | `cborEncode` / `cborDecode` | CBOR codec (maps, arrays, strings, ints, bytes, bools, null, floats) |
@@ -1522,7 +1703,7 @@ instead of dragging its own toolchain and CI job into an unrelated
1522
1703
  browser-app repo. It was previously deleted from clawser by accident
1523
1704
  (2026-03-14) and restored (2026-07-05) before this move.
1524
1705
 
1525
- Four crates, workspace-versioned (currently `0.13.0`):
1706
+ Four crates, workspace-versioned (currently `0.15.0`):
1526
1707
 
1527
1708
  | Crate | Kind | Description |
1528
1709
  |-------|------|--------------|
@@ -1547,6 +1728,9 @@ disconnects. `wsh connect` ends when the remote session does. Diagnostics go to
1547
1728
  never into the command's stdout. TLS uses the platform trust store, and `SSL_CERT_FILE` points it at another certificate (how a self-signed host is trusted); a plain
1548
1729
  `ws://` URL is accepted only for a loopback host.
1549
1730
 
1731
+ `wsh --target NAME [user@]host [command...]` runs on one of the host's execution targets and `wsh targets [user@]host` lists the ones this key may
1732
+ use (see [Execution targets](#execution-targets-121)); it is sent only to a host that advertises `targets`.
1733
+
1550
1734
  ### Forwarding with `wsh -L` / `-R` / `-N`
1551
1735
 
1552
1736
  Modelled on OpenSSH. The forwards live as long as the connection does (`wsh -L ... user@host` also runs the command or
@@ -1669,13 +1853,14 @@ than left to be found.
1669
1853
  | Install an authorized key | `WshClient.addAuthorizedKey()` | `wsh_client::WshClient::add_authorized_key()`, `wsh copy-id` | **Wire-unified** (wsh #59): `AuthorizedKeyAdd`/`AuthorizedKeyResult`, replacing a Rust-CLI-only shell command with a message every implementation can send |
1670
1854
  | Host identity / TOFU | `WshKnownHosts` (localStorage-backed) | `KnownHosts`/`HostStatus` (`~/.wsh/known_hosts`-backed); the client sends `host-key-nonce`, verifies `host-key`/`host-key-sig`, pins only a proven key, and a first use needs `--accept-new-host-key` or a yes at a terminal (`--require-host-key` refuses a host with no proof); `wsh-server` has an opt-in host key (`[server] host_key`) | **Unified** (wsh #59, #145): both pin a PROVEN `ServerHello.host_fingerprint`. A Rust server with no `host_key` configured (the default, so released clients keep working) proves nothing |
1671
1855
  | Typed RPC channels (`openRpc`, `rpc` sessions; `wsh-host`, `wsh-fs`, `mcp`) | `WshClient.openRpc()`, `RpcChannel` | Rust `wsh-server` (`rust-v0.4.0`+): `wsh-host`, and `wsh-fs` when `[rpc] fs_root` is set; no client yet in `wsh-client` | **No wire change**: `Open { kind: 'rpc', command: <protocol> }` plus `rpc*` `ServerHello` features, negotiated so it fails fast elsewhere; the Rust server serves it on WebSocket/QMux only |
1856
+ | MCP over stdio for MCP clients that launch a command (#127) | `wsh-mcp` (the package's `bin`) and `runMcpStdioBridge()` from `@johnhenry/wsh/mcp-stdio`: opens the host's `mcp` rpc channel, reconnects, a clear error when the host offers none | **not built**: no `wsh mcp`, because `wsh-client` has no rpc channel; the Rust `wsh-server` also serves no `mcp` rpc channel (it answers `McpDiscover`/`McpCall`, which `WshMcpBridge` uses) | **JS-only for now** -- no wire change (the channel is #85's) |
1672
1857
  | Exec stdin + EOF, separate stderr | `exec({ stdin })`, `session.closeStdin()`, `session.onStderr` | `SessionOpts { stdio: Some("pipes") }`, `WshSession::read_stderr()` / `close_stdin()`; `wsh host command` uses them whenever its stdin is a pipe or a file and the host offers `exec-pipes` | **Wire-unified, negotiated** (#105): `Open.stdio = "pipes"` + `OpenOk.stderr_channel_id` + zero-length `SessionData` as EOF, offered by the `exec-pipes` `ServerHello` feature. `@johnhenry/wsh/server` needs none of it (stream-mode EOF); the Rust `wsh-server` (`rust-v0.5.0`+) runs such an exec on pipes, everything else on the PTY. Against a host without `exec-pipes` the CLI still forwards stdin, but cannot tell the command it ended |
1673
1858
  | Signals and resize for a one-off command | `session.signal()`, `session.resize()` | `wsh host command` forwards SIGINT/SIGTERM/SIGHUP (the same signal twice disconnects); `wsh --tty host command` also forwards terminal resizes | **Wire-unified** (`Signal`, `Resize`). The Rust `wsh-server` delivers `Signal` (#145) to a pty session's foreground process group (what ^C reaches) and to an exec-on-pipes command's own process group, for `HUP INT QUIT TERM KILL USR1 USR2 WINCH CONT STOP TSTP ALRM` (with or without `SIG`); another name is ignored, and only the control attachment of the connection that owns the channel can send one. Not delivered on Windows |
1674
1859
  | Dial target | a URL | `wsh [user@]host` (dials `https://` then `wss://` on `--port`), or a full URL: `wsh wss://host:8443/rendezvous/ab12 command`, `ws://127.0.0.1:PORT/` | **CLI-only convenience**: a URL is dialled exactly as given (no transport fallback; `--port` and `--transport` do not apply). Plain `ws://` is accepted only to a loopback host |
1675
1860
  | Host that runs in a browser page (`createMemoryHost`, `@johnhenry/wsh/reverse`) | yes, with injected `pty` / `fs` / `hostKey` | no (a Rust host is a process) | **JS-only**. A Rust *client* can operate such a host only with `dataStreams: false` (#132): the released Rust client over WebSocket cannot open QMux data streams, and says nothing in `Hello` that a host could use to decide. `wsh scp` works against such a host with the Rust client of the next `rust-v` release (it speaks `FileChunk`, #140); a released `rust-v0.11.0` or older `wsh scp` hangs against it (`wsh ls` and exec work) |
1676
1861
  | Interactive shell UI | none -- this SDK is a protocol client, not a terminal emulator; pair with xterm.js/ghostty-web | `wsh connect`, `wsh sftp` (line-oriented REPL) | **Deliberately not unified** -- a browser embeds a terminal widget the host page owns; a CLI process owns its own TTY |
1677
1862
  | Attach / resume | `attachSession()`, `resumeSession()`, `WshSession.seq` | `attach_session()`, `resume_session()` | **Wire-unified** (`Attach`/`Resume`/`Presence`); `seq` = cumulative output bytes. `@johnhenry/wsh/server` honours `last_seq` (bounded ring, gap errors) and answers Presence with `channel_id`/`seq`; the Rust `wsh-server` does the same (`rust-v0.2.0`+; fixed 256 KiB ring) |
1678
- | Reverse-connect / relay peer | `connectReverse()`, `trustRelayPeer()`; `@johnhenry/wsh/server`: `relay` option and `createReverseHost()` | `wsh reverse`, `wsh agent` (persistent, with startup-unit install) | **Wire-unified** (registration, discovery, signed peer records); **daemonization is CLI-only** -- a browser tab cannot be a background OS service. The Node relay is default-deny and bridges one operator per peer unless `maxOperatorsPerPeer` is raised (`busy:` reasons say so); E2E and bridged feature gates need `rust-v0.3.0`+ on the Rust side; several operators per peer and the signed `KeyExchange` are JS-relay only for now |
1863
+ | Reverse-connect / relay peer | `connectReverse()`, `trustRelayPeer()`; `@johnhenry/wsh/server`: `relay` option and `createReverseHost()` | `wsh reverse`, `wsh agent` (persistent, with startup-unit install) | **Wire-unified** (registration, discovery, signed peer records); **daemonization is CLI-only** -- a browser tab cannot be a background OS service. The Node relay is default-deny and bridges one operator per peer unless `maxOperatorsPerPeer` is raised (`busy:` reasons say so); E2E and bridged feature gates need `rust-v0.3.0`+ on the Rust side. **Several operators per peer (#93): both relays** (`maxOperatorsPerPeer`; `[relay] max_operators_per_peer`, default 1) **and both peers** (`createReverseHost({ maxOperators })`; `wsh --max-operators n reverse` / `agent run`, default 1), negotiated by `relay-multi-operator`; a Rust peer serving several operators does not seal bridges (see the reverse-mode notes), and the Rust relay leaves a peer connected when its operator leaves. The signed `KeyExchange` (`e2e-sign`) is carried by the Rust relay too |
1679
1864
  | Post-quantum E2E (experimental) | `initiateE2E()` (WebCrypto ML-KEM-768 or `@noble/post-quantum` fallback) | `E2eKeyExchange` (`ml-kem` crate) | **Wire-unified** algorithm and transcript; key material backends differ by platform necessity |
1680
1865
  | Unix-domain socket forwarding, both directions; named endpoints (#120) | `client.openUnix()`, `listenUnix()`, `forwardUnix()` (Node: `-L`/`-R` shapes with unix and TCP ends mixed), `openEndpoint()`; host: `gateway: { unix, endpoints }`, `createMemoryHost({ endpoints })` | `wsh-server` serves `OpenUnix`/`ListenUnix` (`[gateway] unix_connect`, `unix_listen`, `unix_replace_stale`, `unix_max_listeners`; same policy as the Node host); `wsh-client` has `open_tcp`/`open_unix`/`open_endpoint`/`listen_unix`/`listen_tcp`; CLI `wsh -L` / `-R` / `-N` with TCP, unix and `endpoint=NAME` ends, also through `--via` | **Wire-unified, both directions** (#145). A Rust host does not offer named endpoints (an in-page host does); the CLI reaches them. See [Forwarding with `wsh -L`](#forwarding-with-wsh--l---r---n) |
1681
1866
  | Gateway flow control (#123) | credit per connection (`GatewayCredit`, feature `gateway-credit`); host caps for peers without it | `wsh-server` and `wsh-client`: 256 KiB per direction when both list `gateway-credit`; without it, per-connection and per-client byte caps (`max_buffered_bytes` 4 MiB, `max_client_buffered_bytes` 32 MiB) close the connection that exceeds them | **Wire-unified, negotiated**; an older peer on either side keeps working under the caps. `OpenUdp` flows are metered too (a datagram without credit is dropped) |
@@ -1685,11 +1870,14 @@ than left to be found.
1685
1870
  | Operator proof to the peer, sealed bridge, signed initiator half (#117) | `reverseConnect(.., { sealed, requirePeerProof })`; host `createReverseHost({ requireOperatorProof })`; relay lists `operator-proof` | **Operator proof: yes.** The Rust relay lists `operator-proof` and carries `ReverseChallenge`/`ReverseProof`/`ReverseConnect.features`; `wsh reverse-connect` answers a challenge (`--operator-proof` / `--no-operator-proof`; by default only for a peer that registered the `operator-proof` capability, because a released Rust host cannot decode the field); `wsh reverse` / `wsh agent run` challenge, verify BEFORE accepting, and take `--require-operator-proof` and `--allow-operator`. **Sealed bridge and both signed `KeyExchange` halves: yes** (`wsh reverse-connect --sealed`; a host with an identity states `e2e` / `e2e-sign` / `e2e-sealed` in its `ReverseAccept` once it has proven the operator). The exchange is byte-identical to JS (transcripts compared against vectors printed by the JS code), hybrid X25519+ML-KEM-768 negotiated exactly as JS does, X25519 when the peer lists no ML-KEM key. A host started with `--require-operator-proof` REQUIRES the sealed bridge (the JS rule): until the key exists it hears and sends nothing but the key exchange, and drops a bridge that has not sealed in 10 s; an operator that does not seal gets no answer to its plain messages. Every message that would cross the relay travels as an `EncryptedFrame` on channel 0; a plain message (wrapped or not) is dropped; **a frame that does not open (tampered, replayed, reordered) closes the bridge** (stricter than the JS host, which drops the frame and ignores the rest). Not covered: a direct or pipe-relayed connection, and `GatewayData` outside a reverse bridge (#155) | **Wire-unified, negotiated** (`ReverseConnect.features`, `operator-proof`, `e2e-sealed`); both implementations seal a reverse bridge |
1686
1871
  | Channel binding of the login signature (#119) | `requireChannelBinding` (client and server); kinds `host`, `cert-hash`, `tls-exporter` | Kind `host`: the client binds to the proven host key (`--require-channel-binding`, and it honours `channel-binding-required`), and `wsh-server` offers it and can require it (`[server] require_channel_binding`, needs `host_key`). `cert-hash` and `tls-exporter`: not in Rust (the Rust WebTransport client has no certificate-hash pinning; `ConnectConfig.cert_hash` binds it if a caller supplies one) | **Wire-unified, negotiated** (`channel-binding:<kind>` features); verified against the spec's test vectors |
1687
1872
  | Pipe relay (#118) | `@johnhenry/wsh/pipe-relay` | operator side only (#145): `wsh --via wss://relay/r/<id> user@host command...` (also `connect`, `scp`, `ls`, `sftp`, `copy-id`), or the URL as the target. The host side of a pipe is not implemented in Rust. As on a direct connection the Rust client verifies the host-key proof (`host-key` / `host-key-sig` over its own nonce) before sending a credential, pins only a proven key, and binds the login to it (channel binding `host`; `test/rust/wsh-cli-identity.test.mjs`); the pipe-relayed session itself is not sealed (see Security model). `wsh -N -L` exits non-zero when the host drops the session (#156), and the error lines show the relay and a shortened id, never the whole rendezvous id | **Deliberately a relay without wsh parsing** -- nothing to unify on the wire. `--via` keeps `user@host` as the identity: its key is recorded in `known_hosts` under `host:port` (what a direct connection uses), never under the relay's address; a URL target is recorded under the URL's own authority, i.e. the relay's. The URL is not saved to `last_session.json` (the id is a capability) |
1873
+ | Execution targets (#121): `Open.target`, `FileOp.target`, `OpenEndpoint.target`, `ListTargets` / `TargetList` | host: `targets` on `createWshServer` / `createMemoryHost` (own backends and `authorize(who, { target, kind })` per target, `requireTarget`); client: `openSession({ target })`, `exec(.., { target })`, `fileOperation(.., { target })`, `openEndpoint(.., { target })`, `listTargets()` | CLI: `wsh --target NAME [user@]host [command...]` and `wsh connect` (exec and shells only; every other subcommand, `-L`/`-R`/`-N` and `--share` refuse `--target`), `wsh targets [user@]host [--json]`; the client's `open_session(SessionOpts { target })` and `list_targets()` (file and endpoint calls send no target). **A Rust host with targets: not built**: `wsh-server` states no `targets`, refuses a request that names one and answers `ListTargets` with an error | **Wire-unified, negotiated** (`targets` feature; every new field optional, never sent to a host that did not advertise it) |
1688
1874
  | Operator-side shared folders (`--share`, #159) | host side: `onShare(name, fs, who)` on `createMemoryHost` / `createWshServer` / `createReverseHost` (the host *uses* the operator's directories; `fs` is an object of async file operations, also shaped like an `fs` backend; `fs.root` is the operator's advisory, unverified path for the share, #164). The JS client does not offer shares | CLI side: `wsh --share NAME=/abs/dir[:ro\|:rw]` offers them, with each directory's path unless `--share-hide-path` (`wsh_client::share`, `wsh-cli`'s `sharefs`: descriptor-relative, never follows a link, see [Sharing a directory](#sharing-a-directory-with-the-host-wsh---share-159)); unix only. **A Rust host that uses shares: not built** (`wsh-server` does not state `shares`) | **Wire-unified, negotiated**: the host states the feature `shares`; the client sends one `ShareOffer` after login (opcodes `0xa8` `ShareOffer`, `0xa9` `ShareRequest`, host to client, `0xaa` `ShareReply`). No change notification, no sharing over `reverse-connect` |
1689
1875
  | Sealed session: any authenticated connection incl. gateway/endpoint data (#155) | host `sealSession: 'offer' \| 'require'` (stage b); client `connect(url, { sealSession: false \| 'auto' \| true })` (stage c) | `wsh --sealed ...` (or automatic against `e2e-session-required`) seals a direct or pipe-relayed session; `wsh-server` offers or requires it on WebSocket (`[server] seal_session = "off" \| "offer" \| "require"`, needs `host_key`; `require` refuses WebTransport, WISP tunnels and password logins; no typed rpc channels while it is on) | **Wire-unified, negotiated** (`e2e-session`, `e2e-session-required`, `KeyExchange` for the connection's session id, `EncryptedFrame` channel 0) |
1690
1876
  | Refusal event with stable reason codes (`onRefused`, #163) | `onRefused({ reason, who, detail })` on `createMemoryHost` / `createWshServer` / `createReverseHost`; `REFUSAL_REASONS` from `@johnhenry/wsh/host` | none: `wsh-server` and `wsh reverse` log a refusal, they have no callback (an embedding process has none) | **JS-only** -- a host-side callback of the embedding API, no wire change |
1691
1877
  | `AuthOk.ttl` enforced, `token` opaque (#125) | `connectionTtlMs`; `client.authTtl` | `wsh-server` sends `ttl: 0` (no lifetime promised; `session_ttl` is the lifetime of a *detached* session) and an HMAC token that nothing accepts back | **Wire-compatible**: both fields are still sent (released peers require them). **Changed in the Rust server after `rust-v0.6.0`**: it used to send `session_ttl` (86400), which nothing enforced. The Rust client ignores `ttl` |
1692
1878
  | `clientEnv` allow-list (#126) | default `TERM`, `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*` | `wsh-server`: the same default; `[server] client_env = true` (everything, the old behaviour), `false` (nothing) or a list of names / `PREFIX*` (replaces the default) | **Both hosts**; wire unchanged. **Breaking default in the Rust server**, see the CHANGELOG |
1879
+ | `authorized_keys` options (#122): `restrict`, `permit-*`, `no-pty`, `command=`, `max-sessions=` | `auth.authorizedKeys` lines with options on `createWshServer` / `createMemoryHost`; `parseAuthorizedKeyEntries()` | `wsh-server` reads `~/.wsh/authorized_keys` (then `~/.ssh/authorized_keys`) | **Same rules and the same vectors on both hosts** (`spec/key-options.vectors.json`, run by the JS suite and a Rust test); an option that is not understood keeps the key out, on both. See [Authorized-key options](#authorized-key-options-122) for the per-host column |
1880
+ | Per-key capabilities and expiry (#122): `capabilities="..."`, `expires="..."`; `authorize()` may return a set | every entry the host has: `Open` kinds, `FileOp` read vs write, gateway TCP/UDP/unix/endpoint open and listen, MCP discovery and calls, targets, rpc channels, relay; refusals through `onRefused` (`not-permitted`, `key-expired`) | the same, except **no endpoints and no targets** (`endpoint:` / `target:` parse and grant nothing; such requests are refused); refusals are logged, there is no callback; no `authorize` | **Same grammar, same vectors, same refusal codes on both hosts**; default-deny only for a key whose line has `capabilities`. Neither covers sessions already open, see [Security model](#security-model) |
1693
1881
  | Session recording/replay | `SessionRecorder`/`SessionPlayer` (asciicast-v2-shaped JSON) | none | **JS-only** -- no current Rust consumer needs playback; the vocabulary is asciicast v2's, so a Rust port could share it |
1694
1882
  | Self-signed cert pinning | `serverCertificateHashes` (WebTransport option) | N/A -- Rust dials a cert its own TLS stack already trusts, or `--generate-cert`'s self-signed cert out of band | **Deliberately not unified** -- this is a browser-specific WebTransport API shape, not a wire-protocol concept |
1695
1883
 
@@ -1746,7 +1934,7 @@ plus one `SHA256SUMS` file covering every archive in the release. These
1746
1934
  names are a stable contract other repos (clawser) pin and download by --
1747
1935
  do not change them without coordinating downstream.
1748
1936
 
1749
- `wsh --version` and `wsh-server --version` print the workspace version the binary was built from (`wsh 0.13.0`), which is the
1937
+ `wsh --version` and `wsh-server --version` print the workspace version the binary was built from (`wsh 0.15.0`), which is the
1750
1938
  number in the `rust-vX.Y.Z` tag. Binaries of `rust-v0.9.0` to `rust-v0.10.0` printed a fixed `0.1.0`, so against one of those the
1751
1939
  version cannot be read from the binary (look for a flag in `wsh --help` instead).
1752
1940
 
@@ -1797,6 +1985,44 @@ out explicitly below rather than left to be discovered.
1797
1985
  entry client-side and reports a `verified` boolean, independent of
1798
1986
  trusting the relay.
1799
1987
 
1988
+ - **Execution targets: a name the client sends and the host decides on (#121).** Off unless `targets` is given. The host runs
1989
+ `authorize(who, { target, kind })` for every request that names a target (and `listTargets()`), and a refused target looks like an
1990
+ unknown one. It does NOT isolate targets from each other: a key allowed on two can use both, the library only routes and refuses, so the
1991
+ isolation a target gives is your backends'. `requireTarget` does not cover the gateway, MCP or `Attach`; without it a request with no
1992
+ target runs on the host's own backends, which any authenticated key can use, so a deployment that confines a key to one target must set
1993
+ `requireTarget` (or leave the host with no backends of its own). The Rust `wsh-server` has no targets and refuses any request that names one.
1994
+ - **A key's `authorized_keys` options mean the same on both hosts, and a line that is not understood never grants anything (#122).**
1995
+ `restrict`, `permit-*`, `no-pty`, `command=` and `max-sessions=` are enforced at every entry the table in
1996
+ [Authorized-key options](#authorized-key-options-122) lists (`Open`, `FileOp`, the rpc channels, MCP, the relay entry
1997
+ points, installing a key), with the shared vectors run by both test suites. An option that is not understood -- or a value
1998
+ that is malformed, such as `max-sessions=0` -- keeps the key out altogether and is logged. They do NOT scope the gateway
1999
+ (TCP, DNS, unix, endpoints, reverse listeners) or the targets: a key that may not run commands can still use a gateway the host
2000
+ turned on, and `no-port-forwarding` is accepted and ignored. A key's permissions are read when the host starts (the Rust
2001
+ server) or when `createWshServer` is built (the Node host): editing the file does not change a running host. They limit what a
2002
+ key can ask for, not what a command it may run can do: `permit-exec` runs any command the client names (use `command=` to fix
2003
+ it), as the host's user.
2004
+ - **Per-key capabilities and expiry narrow what a key may ask for; they are not a sandbox (#122).** `capabilities="..."` (and what
2005
+ `authorize` returns) is default-deny at the entry points in the [capability table](#capabilities-and-expiry-122-step-two), on both
2006
+ hosts, with the same vectors. What they do NOT protect against: (1) **what a granted capability can reach.** `exec` runs any
2007
+ command as the host's user, `fs:write` writes anywhere the `fs` root allows, `gateway:tcp:*:*` is an open proxy -- a capability is
2008
+ as strong as the backend behind it; the gateway's own policy (`allow`, resolved-address checks, unix paths) and the `fs` root still
2009
+ apply on top, and the capability only narrows. (2) **Things already open.** `expires` is checked at login and at every request; it
2010
+ does not close a connection, a running command, a forwarded stream or a reverse listener that was open when the key expired
2011
+ (use `connectionTtlMs` for that), and an `Attach` / `Resume` / `Signal` / `Resize` of a session the key already owns, session
2012
+ sharing, recordings and `Detach` are not gated by capabilities. (3) **Host names are compared as the client wrote them**:
2013
+ `gateway:tcp:db.internal:5432` constrains the name a client sends, not where a granted name resolves (the gateway's address
2014
+ policy does that). (4) **Password logins** are not narrowed (no key). (5) **Clock:** `expires` trusts the host's clock. (6) A key
2015
+ file is read when the host starts (Rust) or is built (Node): editing it does not change a running host. (7) The Rust server has no
2016
+ endpoints or targets: `endpoint:` and `target:` are accepted in a key line (so one file serves both hosts) and grant nothing there.
2017
+ - **Several operators per peer share one peer, and the relay decides who is who (#93).** Off unless both the relay
2018
+ (`maxOperatorsPerPeer`, `[relay] max_operators_per_peer`) and the peer (`maxOperators`, `--max-operators`) are
2019
+ set above 1. The relay stamps each message with its own record of the sender's authenticated key and removes
2020
+ `to_fingerprint`; it checks the inner of a forward a peer wrote (size, decodes, a forwardable type) and drops what it
2021
+ cannot address. It does NOT protect operators from each other beyond that: they run as the same OS user as the
2022
+ peer, so a command one operator starts can read or kill another's files and processes. A Rust peer serving several
2023
+ operators cannot seal bridges (one seal per connection), so its bridges are as private as the relay is honest;
2024
+ use one operator per peer where that matters (`--require-operator-proof` needs it and is refused otherwise).
2025
+
1800
2026
  - **The Node gateway checks where a connection goes, not only what it was called.** `gateway.allow` matches the name a
1801
2027
  client sent, and then the address it resolves to must be globally routable (or permitted by `allowPrivate` or an
1802
2028
  IP-literal rule); the connection is made to that checked address, and `ResolveDns` answers are filtered the same way.
@@ -1818,6 +2044,13 @@ out explicitly below rather than left to be discovered.
1818
2044
 
1819
2045
  **What is still yours:**
1820
2046
 
2047
+ - **`wsh-mcp` runs as a client with your key (#127).** It reads a private key file you point it at (no passphrase support: protect the
2048
+ file, `0600`), logs in as you and hands the MCP client everything the host's `mcp` channel serves; whatever the MCP client (or the
2049
+ model behind it) asks of those tools is done as you. It does not pin the host unless you pass `--host-key` (it warns once on stderr),
2050
+ so a first connection to an unpinned host trusts whoever answers. After a reconnect it re-sends the client's `initialize` to a new
2051
+ server-side session: server state from the old session (subscriptions, per-session data) is not carried over. It does not filter
2052
+ or inspect MCP messages; a tool's own authorization is the host's (`mcp.authorize`).
2053
+
1821
2054
  - **What a reverse listener exposes.** Whoever can reach the bound port can talk to whatever the client behind it serves,
1822
2055
  as the client, with no authentication of their own: wsh authenticates the operator that asks for the listener, not the
1823
2056
  peers that connect to it. `bindAddr: '0.0.0.0'` (or an `allowBindAddrs` entry that does the same) puts that on every
@@ -0,0 +1,92 @@
1
+ #!/usr/bin/env node
2
+ // wsh-mcp (wsh #127): a stdio bridge so an MCP client can reach an MCP server behind a wsh host. See src/mcp-stdio.mjs and the README.
3
+
4
+ import { parseArgs } from 'node:util';
5
+ import { createRequire } from 'node:module';
6
+ import { userInfo } from 'node:os';
7
+ import { runMcpStdioBridge, loadIdentity, defaultIdentityPath, McpBridgeError } from '../src/mcp-stdio.mjs';
8
+
9
+ const { version } = createRequire(import.meta.url)('../package.json');
10
+
11
+ const HELP = `wsh-mcp ${version} -- reach an MCP server behind a wsh host from an MCP client that launches a command
12
+
13
+ Usage: wsh-mcp [options] [user@]<url>
14
+
15
+ <url> ws://, wss:// or https:// URL of the wsh host (a host serving an rpc channel "mcp")
16
+ -l, --user NAME login name (default: the user@ part of the URL, else $WSH_USER, $USER, or the OS user)
17
+ -i, --identity FILE Ed25519 private key (default: ~/.wsh/keys/default.pem, the key \`wsh keygen\` makes)
18
+ --channel NAME the rpc channel to open (default: mcp)
19
+ --host-key KEY pin the host: a hex fingerprint, or an ssh-ed25519 line (default: not pinned, with a warning)
20
+ --no-reconnect exit when the connection is lost instead of reconnecting
21
+ --reconnect-attempts N attempts before giving up (default: 5, from 500 ms, doubling)
22
+ --timeout MS to log in and to open the channel (default: 15000)
23
+ -h, --help this text
24
+ -V, --version
25
+
26
+ stdout carries MCP messages only (one JSON-RPC message per line); everything else goes to stderr.
27
+ Exit status: 0 the client closed the connection, 1 the host was lost for good, 2 it could not start.
28
+
29
+ An MCP client configuration (Claude Desktop, Cursor, ...):
30
+
31
+ { "mcpServers": { "remote": { "command": "wsh-mcp", "args": ["--identity", "/home/me/.wsh/keys/default.pem", "wss://host.example:4422"] } } }
32
+ `;
33
+
34
+ function usage(message) {
35
+ process.stderr.write(`wsh-mcp: ${message}\nTry \`wsh-mcp --help\`.\n`);
36
+ process.exit(2);
37
+ }
38
+
39
+ let parsed;
40
+ try {
41
+ parsed = parseArgs({
42
+ allowPositionals: true,
43
+ options: {
44
+ user: { type: 'string', short: 'l' },
45
+ identity: { type: 'string', short: 'i' },
46
+ channel: { type: 'string' },
47
+ 'host-key': { type: 'string' },
48
+ 'no-reconnect': { type: 'boolean' },
49
+ 'reconnect-attempts': { type: 'string' },
50
+ timeout: { type: 'string' },
51
+ target: { type: 'string' },
52
+ help: { type: 'boolean', short: 'h' },
53
+ version: { type: 'boolean', short: 'V' },
54
+ },
55
+ });
56
+ } catch (e) { usage(e.message); }
57
+ const { values, positionals } = parsed;
58
+ if (values.help) { process.stdout.write(HELP); process.exit(0); }
59
+ if (values.version) { process.stdout.write(`${version}\n`); process.exit(0); }
60
+ if (values.target !== undefined) usage('--target: rpc channels are not per target (#121), so there is nothing to select; the host serves one "mcp" channel');
61
+ if (positionals.length !== 1) usage('exactly one host URL is required');
62
+
63
+ let url = positionals[0];
64
+ let userFromUrl;
65
+ const at = url.indexOf('@');
66
+ if (at > 0 && !url.slice(0, at).includes('/') && !url.slice(0, at).includes(':')) { userFromUrl = url.slice(0, at); url = url.slice(at + 1); }
67
+ if (!/^(wss?|https?):\/\//.test(url)) usage(`${url}: expected a ws://, wss:// or https:// URL`);
68
+ const number = (name, v, min) => {
69
+ if (v === undefined) return undefined;
70
+ const n = Number(v);
71
+ if (!Number.isInteger(n) || n < min) usage(`--${name} must be a whole number of at least ${min}`);
72
+ return n;
73
+ };
74
+ const attempts = number('reconnect-attempts', values['reconnect-attempts'], 0);
75
+ const timeoutMs = number('timeout', values.timeout, 1);
76
+ const username = values.user ?? userFromUrl ?? process.env.WSH_USER ?? process.env.USER ?? userInfo().username;
77
+
78
+ const handle = { close: null };
79
+ let exitCode;
80
+ try {
81
+ const signer = await loadIdentity(values.identity ?? defaultIdentityPath());
82
+ for (const sig of ['SIGINT', 'SIGTERM']) process.once(sig, () => { void handle.close?.(); });
83
+ exitCode = await runMcpStdioBridge({
84
+ url, username, signer, channel: values.channel, expectHostKey: values['host-key'], timeoutMs,
85
+ reconnect: values['no-reconnect'] ? false : (attempts === undefined ? undefined : { attempts }),
86
+ signalHandle: handle,
87
+ });
88
+ } catch (e) {
89
+ process.stderr.write(`wsh-mcp: ${e?.message ?? e}\n`);
90
+ exitCode = e instanceof McpBridgeError ? e.exitCode : 2;
91
+ }
92
+ process.exit(exitCode);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.42.0",
3
+ "version": "0.44.0",
4
4
  "description": "Web Shell \u2014 browser-native remote command execution over WebTransport and WebSocket with Ed25519 authentication",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -28,12 +28,20 @@
28
28
  "./reverse": {
29
29
  "types": "./src/reverse-host.d.ts",
30
30
  "import": "./src/reverse-host.mjs"
31
+ },
32
+ "./mcp-stdio": {
33
+ "types": "./src/mcp-stdio.d.ts",
34
+ "import": "./src/mcp-stdio.mjs"
31
35
  }
32
36
  },
37
+ "bin": {
38
+ "wsh-mcp": "./bin/wsh-mcp.mjs"
39
+ },
33
40
  "sideEffects": false,
34
41
  "types": "./src/index.d.ts",
35
42
  "files": [
36
43
  "src",
44
+ "bin",
37
45
  "LICENSE",
38
46
  "README.md"
39
47
  ],