@johnhenry/wsh 0.37.0 → 0.38.1

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
@@ -255,11 +255,70 @@ limit and sends `ttl: 0`. Before 0.36 it sent an unenforced 3600. The Rust
255
255
  `gateway: { allow: ['broker.lan:1883'], allowPrivate: ['10.0.0.0/8'], socks: '127.0.0.1:9050' }` makes the Node server
256
256
  answer the gateway opcodes, so a client (a browser tab via netway's `GatewayBackend`, or `client.openTcp()`) can open TCP
257
257
  connections and resolve names from the host. Default deny; `allow` takes `"*"`, `"host"` or `"host:port"`. `socks` routes
258
- every dial through a SOCKS5 proxy (Tor) with the name unresolved. TCP reverse tunnels are refused. `OpenUdp` is served
259
- (`client.openUdp(host, port)`: one chunk is one datagram, same destination policy, idle flows closed after `udpIdleMs`,
260
- default 60 s, not available through `socks`), but over the reliable control stream: it is ordered and retransmitted, and a
261
- datagram the client cannot take fast enough is dropped by the host. **WebTransport datagrams (the real UDP semantics) are
262
- not implemented yet (#124).**
258
+ every dial through a SOCKS5 proxy (Tor) with the name unresolved. `OpenUdp` and TCP reverse tunnels are served too, each
259
+ with its own bounds; both are described below.
260
+
261
+ #### UDP (`client.openUdp`), and WebTransport datagrams (#98, #124)
262
+
263
+ `client.openUdp(host, port)` opens a UDP flow to ONE destination, fixed when it is opened. The destination goes through the
264
+ same name rule and resolved-address policy as TCP (a loopback or private address needs `allowPrivate` or an IP-literal
265
+ `allow` entry, and `allow: []` is still default deny), the host's socket is `connect()`ed to the resolved address so the
266
+ kernel delivers nothing to it from any other address or port, and `socks` refuses UDP. The result has `send(bytes) =>
267
+ Promise<boolean>`, `readable`, `writable`, `close()`, `transport`, `maxDatagramSize` and `stats`. **Datagram semantics:** a
268
+ payload may be dropped (a rate limit, transport back-pressure, a receive queue that is full) and nothing says which; a
269
+ slow reader loses the newest datagrams past 128 queued, it does not make anyone buffer.
270
+
271
+ - **Over WebTransport, when both ends list `gateway-datagram`**, payloads are WebTransport datagrams: a 4-byte big-endian
272
+ flow id (the `gateway_id` of the `OpenUdp`) and the payload, nothing else. They are not ordered and not retransmitted, so
273
+ loss on one flow does not delay another, and `GatewayCredit` does not apply to them. `OpenUdp`, `GatewayOk`/`GatewayFail`
274
+ and `GatewayClose` stay on the control stream. The client lists `gateway-datagram` in `Hello.features` when its transport
275
+ has datagrams (WebTransport: browsers and `@fails-components/webtransport`); the host lists it in `ServerHello.features`
276
+ when it is on WebTransport, its gateway serves UDP and `udp.datagrams` is not `false`.
277
+ - **The size limit is read, not assumed.** `maxDatagramSize` comes from the transport (`WebTransport.datagrams.maxDatagramSize`,
278
+ which the platform defines as the largest datagram you may write; the host side uses the same property of the session, and
279
+ senders use `createWritable()` where present and the deprecated `writable` otherwise). It is about 1.2 KB on a QUIC path
280
+ (1207 payload bytes on a loopback test connection) and can change, so it is read again for every payload. A payload bigger than
281
+ `maxDatagramSize - 4` is **sent on the reliable control stream by default**, in both directions, rather than lost: real
282
+ UDP semantics would drop it (or IP would fragment it), but a tunnel that cannot carry a 1252-byte QUIC Initial or an
283
+ unfragmented big DNS answer is not useful, and the cost (that one payload is ordered and retransmitted) is stated, counted
284
+ (`oversizeReliable`) and bounded by the same rate limits. For strict semantics set `udp: { oversize: 'drop' }` on the host
285
+ (an oversize reply is dropped and counted in `oversizeDropped`) and `openUdp(h, p, { oversize: 'drop' })` on the client
286
+ (`send()` rejects with a `RangeError`, the sender's error). A payload over 65507 bytes is always a `RangeError`.
287
+ - **Over WebSocket, or against a host without the feature (every released host), or with `udp.datagrams: false`**, one
288
+ `GatewayData` is one datagram on the reliable control stream as before: ordered, retransmitted, credit-metered. `flow.transport` says
289
+ which path a flow uses.
290
+ - **Bounds** (`gateway.udp`, all with defaults): `maxFlows` 16 per client; `packetsPerSecondPerFlow` 500 and
291
+ `packetsPerSecondPerClient` 2000, as token buckets over both directions; `bytesPerSecondPerClient` 4 MiB/s over both
292
+ directions; a flow idle for `udpIdleMs` (default 60 s) is closed. A datagram over a limit is dropped and counted, never
293
+ queued. `server.gatewayStats().udp` has the counters (`datagramsFromClient`, `datagramsToClient`, `rateDropped`,
294
+ `oversizeReliable`, `oversizeDropped`, `unknownFlow`, ...).
295
+
296
+ #### TCP reverse tunnels (`client.listenTcp`, #98)
297
+
298
+ `gateway: { allow: [], reverse: { ... } }` lets a client ask the HOST to listen on a TCP port and be handed every connection
299
+ made to it (OpenSSH `-R`). This puts a port of the host on a network, so it is **off unless `reverse` is given** (a
300
+ separate switch from outbound use: `allow` has no say in it) and bounded:
301
+
302
+ ```js
303
+ createWshServer({ auth, gateway: { allow: [], reverse: {
304
+ bindAddr: '127.0.0.1', // what the host binds, default loopback; the client's bind_addr is IGNORED unless listed in...
305
+ allowBindAddrs: [], // ...the addresses a client may pick (IP literals only). The default ListenRequest bind_addr, "0.0.0.0", is never honoured unless you list it.
306
+ ports: [0, '1024-65535'], // what a client may ask for (the default shown). A list you give REPLACES it: a port below 1024 only if you name it.
307
+ maxListeners: 4, maxConnectionsPerListener: 16, backlog: 8, idleMs: 300000,
308
+ } } });
309
+ const l = await client.listenTcp(0, { onConnection: (duplex, { peer, peerPort }) => { /* web streams with backpressure */ } });
310
+ console.log(l.port); // the port the host bound (the actual port for 0)
311
+ await l.close();
312
+ ```
313
+
314
+ Each inbound connection is announced with `InboundOpen` (the real peer address and port), the client answers
315
+ `InboundAccept { gateway_id }` (or `InboundReject`), and data then flows exactly like any gateway connection, with the same
316
+ credit rules. Every refusal says why in the `ListenFail` text (`reverse tunnels are not enabled on this gateway`, `port 80
317
+ is not allowed by the reverse-tunnel policy (ports below 1024 must be listed ...)`, `too many reverse listeners (limit 4)`,
318
+ `address in use`). A connection over `maxConnectionsPerListener`, or over the client's `maxConnections`, is closed without
319
+ being announced; accepted connections idle for `idleMs` are closed; a connection nobody accepts within 30 s is dropped;
320
+ listeners and their connections close when the client goes away. The host advertises `gateway` (it lists no separate
321
+ feature for reverse tunnels, matching the Rust server), so against a host that has them off the answer is the `ListenFail`.
263
322
 
264
323
  **The address is checked, not just the name.** The host resolves a name once, refuses every resolved address that is not
265
324
  globally routable (loopback, private, link-local, CGNAT, ULA, multicast, reserved, and IPv4 addresses wrapped as
@@ -316,13 +375,30 @@ mistaken for (or smuggled as) a file-system path or an abstract-namespace name,
316
375
  consulted for it; the registered names are an allow-list by construction. `who` is the authenticated
317
376
  `{ username, fingerprint }`, so the embedder can authorise per call (throw to refuse, or `{ open, authorize(who) }`).
318
377
 
319
- **Rust side: JS only for now.** `wsh-server` does not advertise `gateway-unix`, `gateway-endpoints` or `gateway-credit`,
320
- and `wsh` has no `-L` / `-R` with unix sockets yet. What it must implement: `OpenUnix { gateway_id, path }` and
321
- `ListenUnix { listener_id, path, replace? }` (answer with the existing `GatewayOk`/`GatewayFail` and `ListenOk` with
322
- `actual_port: 0`/`ListenFail`; accepted connections announced with `InboundOpen` and answered by `InboundAccept`'s
323
- `gateway_id`), the same path policy and `0600`/unlink rules, `GatewayCredit` (256 KiB initial credit per direction when
324
- the client's `Hello.features` lists `gateway-credit`), and in the CLI `-L [bind:]port:/remote.sock`,
325
- `-L /local.sock:/remote.sock`, `-R /remote.sock:host:port` and `-R /remote.sock:/local.sock`.
378
+ **Rust side.** The Rust `wsh-server` serves the same messages with the same policy (`[gateway]`, off unless
379
+ `enabled = true`; `gateway-unix` is advertised only when a socket is listed):
380
+
381
+ ```toml
382
+ [gateway]
383
+ enabled = true
384
+ unix_connect = ["/var/run/docker.sock", "/run/user/1000/wsh/"] # OpenUnix: exact path, "/dir/" prefix, or "@abstract" (Linux)
385
+ unix_listen = ["/run/user/1000/wsh/"] # ListenUnix: sockets a client may ask the host to create
386
+ unix_replace_stale = false # replace a stale socket file only if the request asks AND this is true
387
+ unix_max_listeners = 4 # per client connection
388
+ max_buffered_bytes = 4194304 # per connection, for a peer without gateway-credit (at least 262144)
389
+ max_client_buffered_bytes = 33554432
390
+ ```
391
+
392
+ The checks are the Node host's: paths judged after `realpath` of the parent, a `..` segment refused, the target must be a
393
+ socket and not a symlink, created sockets are `0600` and unlinked on close, a socket that something still accepts on is
394
+ never replaced, a file that is not a socket is never touched; a bad pattern (`/`, a relative path, `..`) stops the server
395
+ at start-up. `GatewayCredit` is served with 256 KiB per direction when the client lists `gateway-credit`; without it the
396
+ host closes a connection that has more than `max_buffered_bytes` of unconsumed client data (or the client more than
397
+ `max_client_buffered_bytes`). The `gateway_id` and `listener_id` tables are per client connection (before, one table was
398
+ shared by every client). A Rust host does not offer named endpoints.
399
+
400
+ The CLI forwards like OpenSSH (see [Rust implementation](#running-a-command-with-wsh)): `wsh -L /tmp/docker.sock:/var/run/docker.sock user@host`,
401
+ `wsh -N -L 2375:/var/run/docker.sock user@host`, `wsh -N -L /tmp/d.sock:endpoint=docker --via wss://relay/r/<id> user@host`.
326
402
 
327
403
  ### TLS (`wss://`) and host extensions
328
404
 
@@ -704,7 +780,16 @@ set from the operator's login at the relay) and the host's `accept` trusts it:
704
780
  fine for a relay you run, not for a shared one. Two opt-ins close that, and both
705
781
  are negotiated by feature strings so every released peer keeps working
706
782
  (the Rust relay never lists `operator-proof`, so the operator simply does not
707
- offer it there):
783
+ offer it there).
784
+
785
+ **Who is offered proof.** `ReverseConnect.features` is a field a released Rust host (`rust-v0.6` to `v0.8`) cannot decode
786
+ (`deny_unknown_fields`: it drops the connection, which looks like a timeout). So a peer lists `operator-proof` in its
787
+ registered capabilities when it can answer a challenge (JS hosts and, since `rust-v0.9`, Rust hosts with an identity),
788
+ `reverseConnect()` offers proof only to a peer whose record lists it (`proof: 'auto'`, looked up with `listPeers()`;
789
+ `peerCapabilities` skips the lookup, `proof: true` offers regardless, `proof: false` never), and the JS relay strips the
790
+ field for a peer that did not advertise it. `requirePeerProof` and `sealed` against such a peer fail at once with a
791
+ sentence and send nothing. A JS host from npm 0.36-0.38 does not list the capability yet, so proof to it needs an upgrade
792
+ of the host.
708
793
 
709
794
  ```js
710
795
  // host: do not take the operator's identity from the relay.
@@ -787,10 +872,17 @@ handshake and the session traffic -- is readable by it unless the two ends seal
787
872
  (per-session `initiateE2E`); it cannot forge the operator's signature or the host's. It can drop, delay or
788
873
  cut a connection, and it sees who dials which id and how much they send.
789
874
 
790
- *CLI side (not built here).* The Rust `wsh` client always dials `wss://<host>/` (#136), so it cannot dial
791
- `/r/<id>` yet. It needs either `wsh --via wss://relay/r/<id> user@host`, or to keep the URL path and query it is
792
- given; the JS client already does. The host side is any process that can open a WebSocket to `pipeUrl(..., 'host')`
793
- and hand it to `accept`.
875
+ *CLI side (#145).* `wsh --via wss://relay/r/<id> user@host [command...]` dials the operator side
876
+ (`pipeUrl(relay, id)`; the URL must end in `/r/<22-128 base64url characters>`, may sit under a base path, and must not
877
+ be the `?role=host` URL). `user@host` stays the identity: the host key is recorded in `~/.wsh/known_hosts` under
878
+ `host:port` of that target (`--port`, default 4422), the key a direct connection uses, so the same host is the same
879
+ host whichever relay carried it and a different host behind that name is refused (`HOST KEY CHANGED`) before any
880
+ command is sent. A plain URL target (`wsh alice@wss://relay/r/<id> ...`) also dials but is recorded under the URL's
881
+ authority, which is the relay's, so prefer `--via`. `--via` works with `wsh [user@]host`, `connect`, `scp`, `ls`, `sftp`
882
+ and `copy-id`; it is an error elsewhere, and cannot be combined with a URL target. A pipe relay is WebSocket only: no
883
+ fallback, and `--transport` does not apply. The rendezvous id is not written to `last_session.json`. What the Rust
884
+ client does not yet do (host-key proof, channel binding, sealed bridge) is listed under the Security model. The host side
885
+ is any process that can open a WebSocket to `pipeUrl(..., 'host')` and hand it to `accept`.
794
886
 
795
887
  ### Sessions: attach / resume / detach
796
888
 
@@ -1206,7 +1298,7 @@ fs_max_file_bytes = 67108864
1206
1298
  Key options apply as they do to other channels: a key restricted to a forced
1207
1299
  command opens no rpc channel, and `wsh-fs` needs the `file-transfer` scope
1208
1300
  (`permit-file-transfer` under `restrict`). `host.info` reports the crate version
1209
- and `hostFingerprint: null` (the Rust server has no host key). The JS client
1301
+ and `hostFingerprint: null` unless `[server] host_key` is configured. The JS client
1210
1302
  needs nothing new: it reads `rpc` from `ServerHello`, and its file helpers prefer
1211
1303
  `wsh-fs` automatically once the server offers it.
1212
1304
 
@@ -1366,7 +1458,7 @@ instead of dragging its own toolchain and CI job into an unrelated
1366
1458
  browser-app repo. It was previously deleted from clawser by accident
1367
1459
  (2026-03-14) and restored (2026-07-05) before this move.
1368
1460
 
1369
- Four crates, workspace-versioned (currently `0.7.0`):
1461
+ Four crates, workspace-versioned (currently `0.9.0`):
1370
1462
 
1371
1463
  | Crate | Kind | Description |
1372
1464
  |-------|------|--------------|
@@ -1391,6 +1483,36 @@ disconnects. `wsh connect` ends when the remote session does. Diagnostics go to
1391
1483
  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
1392
1484
  `ws://` URL is accepted only for a loopback host.
1393
1485
 
1486
+ ### Forwarding with `wsh -L` / `-R` / `-N`
1487
+
1488
+ Modelled on OpenSSH. The forwards live as long as the connection does (`wsh -L ... user@host` also runs the command or
1489
+ shell; `-N` only forwards, until Ctrl-C), work with `--via` (the pipe relay carries them like anything else), and may be
1490
+ repeated:
1491
+
1492
+ ```sh
1493
+ wsh -L 8080:db.internal:5432 alice@host # [bind_addr:]port:host:hostport (the HOST connects to db.internal)
1494
+ wsh -N -L /tmp/docker.sock:/var/run/docker.sock alice@host # local unix socket -> a unix socket on the host
1495
+ wsh -N -L 127.0.0.1:2375:/var/run/docker.sock alice@host # local TCP port -> a unix socket on the host
1496
+ wsh -N -L /tmp/db.sock:db.internal:5432 alice@host # local unix socket -> TCP the host reaches
1497
+ wsh -N -L /tmp/docker.sock:endpoint=docker --via wss://relay/r/<id> alice@tab.example # a NAMED ENDPOINT of an in-page host
1498
+ wsh -N -R /run/user/1000/wsh/app.sock:127.0.0.1:3000 alice@host # the HOST listens on a unix socket; connections come here
1499
+ wsh -N -R 9000:localhost:3000 alice@host # the host listens on a TCP port (loopback by default)
1500
+ ```
1501
+
1502
+ A named endpoint is written `endpoint=NAME` as the remote end of `-L` (`NAME`: letters, digits, `.`, `_`, `-`; at most 64).
1503
+ The `=` cannot occur in a host name, a port or a path, so it can never be mistaken for a host called "endpoint" (that is
1504
+ `endpoint:80`), and `@NAME` is already the Linux abstract-namespace socket (`-L 8080:@name`). A host with no file system
1505
+ (an in-page host) offers endpoints instead of unix sockets; `wsh -L ...:endpoint=docker` plus `DOCKER_HOST=unix:///tmp/docker.sock`
1506
+ is the shape of reaching a daemon behind one. `-R` cannot name an endpoint (a host offers those, it does not listen on them).
1507
+
1508
+ Local TCP listeners bind `127.0.0.1` unless `bind_addr` says otherwise (`*` or `0.0.0.0` listens on every interface, and `wsh`
1509
+ warns). Local unix sockets are created `0600`, removed on exit (a killed `wsh` leaves its file), and an existing file at the
1510
+ path is **refused** unless `--replace-socket` is given, which replaces only a stale socket: never a live one, never a file that
1511
+ is not a socket. With `-R`, `--replace-socket` asks the host to replace its own stale socket (its policy decides). A host that
1512
+ cannot do what a forward needs says so (`this host does not offer unix-socket forwarding`, `no such endpoint`, `not allowed by
1513
+ the gateway policy`); a malformed spec exits with status 2 before anything is dialled. Up to 128 forwarded connections are
1514
+ open at once. `-L`/`-R`/`-N` apply to `wsh [user@]host [command...]` and `wsh connect` only.
1515
+
1394
1516
  ### Capability matrix: JS SDK vs Rust CLI/client
1395
1517
 
1396
1518
  Two implementations of one protocol will always have *some* asymmetry --
@@ -1404,24 +1526,26 @@ than left to be found.
1404
1526
  | Upload/download | `WshClient.upload()`/`.download()` | `file_transfer::upload()`/`download()`, `wsh scp` | **Wire-unified**: `FileChunk` over a `'file'`-kind channel (wsh #13) |
1405
1527
  | Remove a remote file | `WshClient.fileRemove()` | `file_transfer::remove()`, `wsh sftp`'s `rm` | **Wire-unified**: `FileOp`/`FileResult` (`op: "remove"`) -- refused today by every `wsh-server` release ("not yet implemented"), the same refusal on both sides |
1406
1528
  | 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 |
1407
- | Host identity / TOFU | `WshKnownHosts` (localStorage-backed) | `KnownHosts`/`HostStatus` (`~/.wsh/known_hosts`-backed) | **Record unified, policy is not** (wsh #59): both pin `ServerHello.host_fingerprint`, which `@johnhenry/wsh/server` populates (with a proof of possession, [Host key](#host-key-fingerprint--tofu)) but no Rust `wsh-server` release does yet (see [Security](#security-model)). *When* to trust, prompt, or persist is deliberately left per-implementation -- a browser and a CLI have different UX for "first time seeing this host" |
1529
+ | 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 |
1408
1530
  | 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 |
1409
1531
  | 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 |
1410
- | 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`). **Not everywhere honoured**: the Rust `wsh-server` currently only logs `Signal`, so a forwarded signal does not stop the command there |
1532
+ | 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 |
1411
1533
  | 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 |
1412
1534
  | 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. Its `scp` download also reads a raw stream, not the `FileChunk` messages this host sends, so `wsh scp` from such a host does not work (`wsh ls` and exec do) |
1413
1535
  | 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 |
1414
1536
  | 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) |
1415
1537
  | 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 |
1416
1538
  | 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 |
1417
- | 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 })` | none yet (`wsh -L` / `-R` with sockets are not implemented) | **JS only for now.** Wire: `OpenUnix`, `OpenEndpoint`, `ListenUnix` behind the `gateway-unix` / `gateway-endpoints` host features; the Rust server and CLI must implement them (message handling, the path policy, `-L`/`-R` flags) as described under [Gateway](#unix-domain-sockets-streamlocal-and-named-endpoints) |
1418
- | Gateway flow control (#123) | credit per connection (`GatewayCredit`, feature `gateway-credit`); host caps for peers without it | none: the Rust forwarder has bounded in-process queues but no per-connection credit and no per-client byte cap | **JS only for now** (negotiated, so a Rust peer on either side keeps today's unmetered behaviour) |
1539
+ | 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) |
1540
+ | 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) |
1541
+ | TCP reverse tunnels (`ListenRequest`, #98) | `@johnhenry/wsh/server` `gateway.reverse` (off by default; loopback unless the operator lists addresses; port allow-list, nothing below 1024 unless named; bounded listeners/connections/backlog/idle); client `listenTcp(port, { onConnection })` | `wsh-server` `[gateway] enable_reverse_tunnels` + `reverse_bind_addr` (off by default, loopback, client `bind_addr` ignored); no port allow-list; no per-listener connection, backlog or idle bounds beyond `max_connections` | **Wire-unified** (`ListenRequest`/`ListenOk`/`ListenFail`/`InboundOpen`/`InboundAccept`; the JS host sends the real `peer_addr`/`peer_port`). **Rust still needs**: a port allow-list and per-client listener / per-listener connection / idle bounds to match the JS host. Accepted connections are metered by `gateway-credit` now |
1542
+ | UDP (`OpenUdp`) as WebTransport datagrams (#124) | `client.openUdp()` over WebTransport when both ends list `gateway-datagram`: payloads are datagrams (4-byte flow id + payload), read from `maxDatagramSize`; oversize goes on the control stream (or drops); bounds: flows, packet and byte rates, idle; policy as TCP. Host: `gateway.udp`; Playwright test from Chromium | `wsh-server` serves `OpenUdp` over the reliable control stream only (one `GatewayData` per datagram); no datagrams, no rate bounds | **JS only for now** (negotiated by `gateway-datagram`, so a Rust peer keeps the reliable path). **Rust must implement**: list `gateway-datagram` in `ServerHello.features` on a WebTransport connection, accept/send datagrams `[gateway_id u32 BE][payload]` for `OpenUdp` flows when the client listed it (ignore the id of an unknown flow), read `maxDatagramSize` and send a bigger payload as `GatewayData` (or drop, by config), `connect()` the UDP socket to the checked address, and the same rate/flow bounds |
1419
1543
  | Gateway destination policy by resolved address | `@johnhenry/wsh/server` `gateway`: resolved address checked, `allowPrivate` | fixed in the Rust release after `rust-v0.6.0`: a loopback/private/link-local/ULA/CGNAT/unspecified/multicast address is refused after resolution unless a rule names it, and the server connects to the address it checked | **Same rule on both sides** (a Rust server released before that still has the name-only check) |
1420
- | Operator proof to the peer, sealed bridge, signed initiator half (#117) | `reverseConnect(.., { sealed, requirePeerProof })`; host `createReverseHost({ requireOperatorProof })`; relay lists `operator-proof` | none: the Rust relay neither carries `ReverseChallenge`/`ReverseProof` nor lists the feature, and the Rust agent/client send and answer neither | **Wire-unified, negotiated** (`ReverseConnect.features`, `operator-proof`, `e2e-sealed`); the Rust types are regenerated (and `ReverseConnect.features` is `None` there) but no Rust peer implements it yet |
1421
- | Channel binding of the login signature (#119) | `requireChannelBinding` (client and server); kinds `host`, `cert-hash`, `tls-exporter` | none: no Rust host offers one and the Rust client signs with an empty binding | **Wire-unified, negotiated** (`channel-binding:<kind>` features); a Rust client logging in to a JS host that requires it is refused |
1422
- | Pipe relay (#118) | `@johnhenry/wsh/pipe-relay` | none; the `wsh` CLI always dials `wss://<host>/` (#136), so it cannot reach `/r/<id>` -- it needs `--via` or to keep the URL path | **Deliberately a relay without wsh parsing** -- nothing to unify on the wire |
1423
- | `AuthOk.ttl` enforced, `token` opaque (#125) | `connectionTtlMs`; `client.authTtl` | `wsh-server` sends `session_ttl` (default 86400) and an HMAC token, neither enforced or checked | **Wire-compatible**: both fields are still sent (released peers require them); the JS host sends `ttl: 0` unless a limit is set |
1424
- | `clientEnv` allow-list (#126) | default `TERM`, `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*` | the Rust server applies whatever environment the client sends | **JS host only**; wire unchanged |
1544
+ | 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 signed `KeyExchange` halves: not yet** (no Rust E2E responder), so `--require-operator-proof` proves who connected but does not stop a relay stamping an identity on later plain messages | **Wire-unified, negotiated** (`ReverseConnect.features`, `operator-proof`, `e2e-sealed`); sealing is JS-only |
1545
+ | 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 |
1546
+ | 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, and the Rust client does not yet verify the host-key proof or bind the login to the host (see Security model) | **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) |
1547
+ | `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` |
1548
+ | `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 |
1425
1549
  | 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 |
1426
1550
  | 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 |
1427
1551
 
@@ -1530,9 +1654,36 @@ out explicitly below rather than left to be discovered.
1530
1654
  IP-literal rule); the connection is made to that checked address, and `ResolveDns` answers are filtered the same way.
1531
1655
  Unix-domain sockets (`gateway.unix`) and named endpoints (`gateway.endpoints`) are off unless configured, are listed
1532
1656
  paths or names only, and sockets the host creates are `0600`.
1657
+ - **TCP reverse tunnels (`gateway.reverse`) are off unless configured, bind where the operator says, and cap what they open.**
1658
+ A reverse listener is a port of the HOST that other machines can connect to, with the authenticated client on the other
1659
+ end of every connection. The host binds `reverse.bindAddr` (default `127.0.0.1`) and ignores the address the client
1660
+ asks for unless the operator listed it; ports come from an allow-list (default 0 and 1024-65535; privileged ports only
1661
+ if named); listeners per client, connections per listener, the listen backlog and idle time are bounded, and listeners
1662
+ die with the client's connection.
1663
+ - **UDP flows are one destination, rate-limited in both directions.** An `OpenUdp` flow has the same destination and
1664
+ resolved-address policy as TCP, is `connect()`ed to the one address it passed (so no other source reaches the client
1665
+ through it), and is bounded by flows per client, packets per second per flow and per client, bytes per second per client
1666
+ and an idle timeout. The byte limit is the amplification bound: a small query to an open resolver or a UDP service
1667
+ that answers big (DNS, NTP, memcached-style services) can return no more than `bytesPerSecondPerClient` (4 MiB/s by
1668
+ default) to the client, and the same budget caps what the client can make the host send. Datagrams over a limit are
1669
+ dropped and counted (`server.gatewayStats()`).
1533
1670
 
1534
1671
  **What is still yours:**
1535
1672
 
1673
+ - **What a reverse listener exposes.** Whoever can reach the bound port can talk to whatever the client behind it serves,
1674
+ as the client, with no authentication of their own: wsh authenticates the operator that asks for the listener, not the
1675
+ peers that connect to it. `bindAddr: '0.0.0.0'` (or an `allowBindAddrs` entry that does the same) puts that on every
1676
+ interface of the host, so firewall it and keep `ports` narrow. The client sees each peer's address (`InboundOpen`) and
1677
+ can reject it, but behind a NAT or proxy that address is not the real source. The Rust server's defaults are the
1678
+ same (loopback, off) but it has no port allow-list.
1679
+ - **UDP is not authenticated or private beyond the tunnel.** `allow: ['*']` with a public resolver lets every authorized
1680
+ client send UDP to the internet from the host's address (a DNS-sized query, or a spoofed-looking flood limited only by
1681
+ the packet rates above); the bounds make that slow, not impossible, and an origin that answers many large datagrams
1682
+ to one small one is bounded by `bytesPerSecondPerClient`, not eliminated. WebTransport datagrams can be dropped,
1683
+ reordered and duplicated by the network, and are only as private as the QUIC connection that carries them (a
1684
+ datagram flow is not covered by E2E sealing, which is for sessions). A payload that did not fit a datagram travels on the
1685
+ reliable stream by default (see the README section above).
1686
+
1536
1687
  - **What the gateway does NOT protect against.** A name that resolves to a *public* address is dialled as the client
1537
1688
  asked, so `allow: ['*']` is an open proxy to the internet for every authorized client. Through `socks` the proxy
1538
1689
  resolves the name, so the host cannot check the address (only IP literals are checked) and the proxy's own network
@@ -1554,6 +1705,11 @@ out explicitly below rather than left to be discovered.
1554
1705
  treat `initiateE2E` as key agreement, not confidentiality, unless you've
1555
1706
  separately confirmed the session has sealing enabled.
1556
1707
  - **Host identity (TOFU) has a known, named gap (wsh #59).**
1708
+ **Update (#145): the Rust `wsh-server` now has an opt-in host key
1709
+ (`[server] host_key = "<path>"`, created 0600 on first start; see the
1710
+ capability matrix) and the Rust client verifies the proof; the paragraph
1711
+ below describes the state before that and still applies to a Rust server
1712
+ with no `host_key` configured, which proves nothing.**
1557
1713
  `ServerHello.host_fingerprint` is the spec's formal host-identity slot:
1558
1714
  the SHA-256 fingerprint of a server's persistent Ed25519 host key, meant
1559
1715
  to be pinned across connections the way SSH pins a host key. **As of 0.19
@@ -1636,10 +1792,45 @@ What this does **not** protect against:
1636
1792
  WebTransport. The per-address auth rate limit bounds how fast one address can
1637
1793
  make the server run Argon2id (19 MiB each); it is not a defence against many
1638
1794
  addresses.
1639
- - **The dev certificate from `--generate-cert` is not a certificate a TLS client
1640
- can verify** (it is flagged as a CA); clients dial it with
1641
- `WSH_INSECURE_LOOPBACK_TLS=1`, which disables verification and is for loopback
1642
- testing only.
1795
+ - **The dev certificate from `--generate-cert` is a self-signed leaf** (not
1796
+ flagged as a CA, since #145), so a TLS client can trust it as a server
1797
+ certificate by being given the file (`SSL_CERT_FILE=~/.wsh/cert.pem`); it is
1798
+ still self-signed, so nothing vouches for it but that file. Before, it was
1799
+ flagged as a CA, TLS clients rejected it, and the only way in was
1800
+ `WSH_INSECURE_LOOPBACK_TLS=1`, which disables verification (loopback testing
1801
+ only).
1802
+ - **Rust `wsh-server`: the client's environment is an allow-list, and `Signal`
1803
+ is delivered.** Only `TERM`, `COLORTERM`, `LANG`, `LANGUAGE` and `LC_*` of
1804
+ `Open.env` reach the command (at most 64 variables, bounded sizes);
1805
+ `[server] client_env = true` re-opens everything (a client can then set `PATH`
1806
+ or `LD_PRELOAD` for what the server runs, and the server warns at start-up).
1807
+ `Signal` goes only to the process group of a channel the sending connection
1808
+ controls. This does not make a command safe to run: an authorized key still
1809
+ runs commands as the server's user.
1810
+ - **Forwarding (`wsh -L`/`-R`, `OpenUnix`, `ListenUnix`) lends the host's reach, not a sandbox.** Listing a socket in
1811
+ `unix_connect` gives every authorized key everything that socket's service can do: Docker's socket is root on the
1812
+ machine. The policy checks the path, not the peer, and cannot close the instant between the check and the connect
1813
+ (allow only directories no other local user can write to). It is not per key and has no rate limit beyond
1814
+ `max_connections`. `wsh -L` publishes a local port or socket to whoever can reach it: loopback by default, but an explicit
1815
+ `bind_addr` of `0.0.0.0` (the CLI warns) hands the forward to the network, and a local unix socket is `0600` only against
1816
+ other users, not against your own processes. A forwarded connection is as private as the wsh connection under it (a pipe
1817
+ relay sees it unless the legs are TLS). The Rust host binds a created socket inside a private `0700` directory and links it into place, so it is never visible with a looser mode and the process umask is not touched.
1818
+ - **Rust `wsh-server`'s `AuthOk.ttl` is 0 and its `token` is opaque** (as the
1819
+ JS host's, above): nothing is promised or enforced at connection level; do not
1820
+ treat the token as a credential.
1821
+ - **`wsh --via` (pipe relay from the Rust CLI) is the operator side only, and
1822
+ still not sealed.** The Rust client now verifies the host-key proof
1823
+ (`host-key` / `host-key-sig` over its own `host-key-nonce`) before sending
1824
+ any credential, records only a PROVEN key in `known_hosts`, binds the login
1825
+ signature to that key (channel binding `host`), and refuses a changed key
1826
+ always. A replayed `ServerHello` or an impostor's key is refused as the JS
1827
+ client refuses it. What is still unprotected: the bridge is not sealed
1828
+ end to end (the Rust side has no sealed bridge yet), so the relay sees
1829
+ session traffic in the clear unless the legs are TLS and it is trusted not
1830
+ to read them (it terminates each leg's TLS), and it can stamp an identity on
1831
+ a plain message after the handshake. A host with no host key proves nothing:
1832
+ the CLI connects to it (as every release did) unless `--require-host-key`
1833
+ says otherwise.
1643
1834
 
1644
1835
  - **A host that lives in a page (`createMemoryHost`, `@johnhenry/wsh/reverse`) is only as trustworthy as the page.** A
1645
1836
  non-extractable host key or client key keeps the private key from being *read*, not from being *used*: any script that
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.37.0",
3
+ "version": "0.38.1",
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",
@@ -72,7 +72,7 @@
72
72
  },
73
73
  "scripts": {
74
74
  "test": "node --test test/*.test.mjs",
75
- "test:rust": "node --test test/rust/*.test.mjs",
75
+ "test:rust": "node --test --test-timeout=180000 test/rust/*.test.mjs",
76
76
  "test:browser": "playwright test --config test/browser/playwright.config.mjs",
77
77
  "size": "node scripts/bundle-size.mjs",
78
78
  "typecheck": "tsc --noEmit -p tsconfig.json",
package/src/client.mjs CHANGED
@@ -47,6 +47,7 @@ import { SealedBridge } from './bridge-seal.mjs';
47
47
  import { WshSession } from './session.mjs';
48
48
  import { GatewayConnections } from './gateway-client.mjs';
49
49
  import { GATEWAY_CREDIT_FEATURE } from './gateway-channel.mjs';
50
+ import { GATEWAY_DATAGRAM_FEATURE } from './gateway-datagram.mjs';
50
51
  import { cborDecode, cborEncode } from './cbor.mjs';
51
52
  import {
52
53
  RpcChannel, RpcError, RPC_ERROR, RPC_FEATURE, RPC_PROTOCOL_NAME_RE, RPC_DEFAULT_MAX_MESSAGE,
@@ -634,7 +635,7 @@ export class WshClient {
634
635
  const authMethod = cred ? AUTH_METHOD.PUBKEY : AUTH_METHOD.PASSWORD;
635
636
  const hostKeyNonce = newHostKeyNonce();
636
637
  await transport.sendControl(
637
- hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce, GATEWAY_CREDIT_FEATURE] })
638
+ hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce, GATEWAY_CREDIT_FEATURE, ...(transport.supportsDatagrams ? [GATEWAY_DATAGRAM_FEATURE] : [])] })
638
639
  );
639
640
  const hostCtx = { ...hostKeyOpts, url, username, nonce: hostKeyNonce };
640
641
 
@@ -1233,6 +1234,8 @@ export class WshClient {
1233
1234
  * @param {object} [opts.expose] - Capabilities to expose { shell, exec, fs, tools }
1234
1235
  * @param {string} [opts.peerType]
1235
1236
  * @param {string} [opts.shellBackend]
1237
+ * @param {boolean} [opts.operatorProof=true] list `operator-proof` in the registered capabilities (a key login only): this
1238
+ * peer can answer an operator's challenge. A hand-written handler that never challenges passes `false`.
1236
1239
  * @param {boolean} [opts.supportsAttach]
1237
1240
  * @param {boolean} [opts.supportsReplay]
1238
1241
  * @param {boolean} [opts.supportsEcho]
@@ -1252,6 +1255,7 @@ export class WshClient {
1252
1255
  supportsReplay,
1253
1256
  supportsEcho,
1254
1257
  supportsTermSync,
1258
+ operatorProof = true,
1255
1259
  ...hostKeyOpts
1256
1260
  } = {}) {
1257
1261
  // Authenticate normally first.
@@ -1266,6 +1270,9 @@ export class WshClient {
1266
1270
 
1267
1271
  // Export public key for peer identification.
1268
1272
  const cred = await resolveSigner({ keyPair, signer });
1273
+ // A peer that can answer an operator's challenge says so in its signed record: a released peer cannot decode
1274
+ // `ReverseConnect.features`, so an operator (and the relay) states the field only to a peer that lists this.
1275
+ if (cred && operatorProof) capabilities.push(OPERATOR_PROOF_FEATURE);
1269
1276
  this.#signer = cred;
1270
1277
  this.#loginUsername = username;
1271
1278
  let publicKey = null;
@@ -1358,12 +1365,21 @@ export class WshClient {
1358
1365
  /**
1359
1366
  * Initiate a reverse connection and wait for accept/reject.
1360
1367
  *
1368
+ * Offering proof (`ReverseConnect.features: ['operator-proof']`) needs a key login, a relay that carries it, and a peer
1369
+ * whose registered record lists `operator-proof`: a released Rust host (v0.6 to v0.8) rejects the field outright. Options:
1370
+ * - `proof`: `'auto'` (default; offer to a peer that advertises it, looked up with `listPeers()`), `true` (offer anyway;
1371
+ * the relay still strips it for a peer that did not advertise), `false` (never offer).
1372
+ * - `requirePeerProof` / `sealed`: fail at once, with a sentence, when the peer does not advertise it.
1373
+ * - `peerCapabilities`: the peer's capability list, when the caller already has it (skips the lookup).
1374
+ *
1361
1375
  * @param {string} targetFingerprint
1362
1376
  * @param {number} [timeout=10000]
1377
+ * @param {{ proof?: 'auto'|boolean, requirePeerProof?: boolean, sealed?: boolean|object, peerCapabilities?: string[] }} [opts]
1363
1378
  * @returns {Promise<object>}
1364
1379
  */
1365
- async reverseConnect(targetFingerprint, timeout = DEFAULT_OPEN_TIMEOUT, { proof = 'auto', requirePeerProof = false, sealed = false } = {}) {
1380
+ async reverseConnect(targetFingerprint, timeout = DEFAULT_OPEN_TIMEOUT, { proof = 'auto', requirePeerProof = false, sealed = false, peerCapabilities } = {}) {
1366
1381
  this.#assertAuthenticated('reverseConnect');
1382
+ if (proof !== 'auto' && typeof proof !== 'boolean') throw new TypeError("reverseConnect: proof must be 'auto', true or false");
1367
1383
 
1368
1384
  // Proving this operator's identity to the PEER (wsh #117) needs a relay that carries the challenge and a key to sign with.
1369
1385
  const relayCarriesProof = this.#serverFeatures.includes(OPERATOR_PROOF_FEATURE);
@@ -1372,7 +1388,6 @@ export class WshClient {
1372
1388
  throw new Error(`reverseConnect: this relay does not carry operator proof (no "${OPERATOR_PROOF_FEATURE}" in its features), so ${sealOpts ? 'a sealed bridge' : 'proof'} is not available -- nothing was sent`);
1373
1389
  }
1374
1390
  if ((sealOpts || requirePeerProof || proof === true) && !this.#signer) throw new Error('reverseConnect: proof needs a key login (a password login has nothing to sign with)');
1375
- const offerProof = proof !== false && relayCarriesProof && !!this.#signer;
1376
1391
 
1377
1392
  // A sealed bridge sends nothing that names a command, a path or a session before the key exists: from here on a
1378
1393
  // message the relay may forward is refused locally until the bridge key is in place.
@@ -1394,6 +1409,24 @@ export class WshClient {
1394
1409
  let response = null;
1395
1410
  let challenge = null;
1396
1411
  try {
1412
+ // A released peer (rust-v0.6 to v0.8) drops the connection on a ReverseConnect with a field it does not know, so the
1413
+ // offer is made only to a peer whose registered record lists `operator-proof` ('auto'), or when the caller insists
1414
+ // (`proof: true`). The relay checks the same on its side and strips the field for a peer that did not advertise it.
1415
+ let peerCanProve = proof === true;
1416
+ if (!peerCanProve && proof === 'auto' && relayCarriesProof && this.#signer) {
1417
+ let caps = peerCapabilities;
1418
+ if (!Array.isArray(caps)) {
1419
+ const peers = await this.listPeers(timeout).catch(() => []);
1420
+ const hits = peers.filter((p) => p.fingerprint === targetFingerprint || (targetFingerprint.length >= 8 && String(p.fingerprint ?? '').startsWith(targetFingerprint)));
1421
+ caps = hits.length === 1 ? hits[0].capabilities : [];
1422
+ }
1423
+ peerCanProve = caps.includes(OPERATOR_PROOF_FEATURE);
1424
+ if ((sealOpts || requirePeerProof) && !peerCanProve) {
1425
+ throw new Error(`reverseConnect: the peer does not advertise "${OPERATOR_PROOF_FEATURE}" in its registered record (a host older than operator proof, or one that cannot answer a challenge), so ${sealOpts ? 'a sealed bridge' : 'proof'} is not available -- nothing was sent`);
1426
+ }
1427
+ }
1428
+ const offerProof = proof !== false && relayCarriesProof && !!this.#signer && peerCanProve;
1429
+
1397
1430
  const ownFingerprint = this.#signer ? await computeFingerprint(this.#signer.publicKeyRaw) : null;
1398
1431
  // Register before sending: the answer can follow the request closely.
1399
1432
  const first = this.#waitForMessage(
@@ -1424,7 +1457,7 @@ export class WshClient {
1424
1457
  }
1425
1458
 
1426
1459
  if (response.type === MSG.REVERSE_ACCEPT) {
1427
- if (requirePeerProof && !challenge) throw new Error('reverseConnect: the peer did not prove its identity (requirePeerProof) -- nothing was sent over the bridge');
1460
+ if (requirePeerProof && !challenge) throw new Error(`reverseConnect: the peer did not prove its identity (requirePeerProof)${proof === true ? `; the relay does not pass the offer to a peer that does not advertise "${OPERATOR_PROOF_FEATURE}"` : ''} -- nothing was sent over the bridge`);
1428
1461
  if (challenge && response.target_fingerprint !== challenge.peerFingerprint) throw new Error('reverseConnect: the relay named a different peer than the one that signed the challenge');
1429
1462
  if (sealOpts) {
1430
1463
  if (!challenge) throw new Error('reverseConnect: a sealed bridge needs the peer to answer with a challenge (does it require operator proof support?)');
@@ -1523,7 +1556,15 @@ export class WshClient {
1523
1556
 
1524
1557
  #gw() {
1525
1558
  this.#assertAuthenticated('gateway');
1526
- return (this.#gateway ??= new GatewayConnections({ send: (m) => this.sendControl(m), hasFeature: (f) => this.hasFeature(f) }));
1559
+ return (this.#gateway ??= new GatewayConnections({
1560
+ send: (m) => this.sendControl(m),
1561
+ hasFeature: (f) => this.hasFeature(f),
1562
+ // Datagrams for UDP flows: only on a transport that has them AND a host that listed "gateway-datagram".
1563
+ datagrams: () => {
1564
+ const t = this.#transport;
1565
+ return t?.supportsDatagrams && this.hasFeature(GATEWAY_DATAGRAM_FEATURE) ? { send: (b) => t.sendDatagram(b), maxSize: () => t.maxDatagramSize } : null;
1566
+ },
1567
+ }));
1527
1568
  }
1528
1569
 
1529
1570
  /**
@@ -1549,14 +1590,30 @@ export class WshClient {
1549
1590
  async openTcp(host, port, opts) { return this.#gw().openTcp(host, port, opts); }
1550
1591
 
1551
1592
  /**
1552
- * A UDP flow to host:port FROM THE HOST over the reliable control stream: each chunk written or read is one datagram
1553
- * (at most 65507 bytes), so it is ordered and retransmitted (WebTransport datagrams are not used yet), and datagrams the
1554
- * receiver cannot keep up with are dropped by the host. Same destination policy as TCP.
1593
+ * A UDP flow to ONE destination, host:port, FROM THE HOST (same destination policy as TCP). Each payload is one
1594
+ * datagram, which MAY BE DROPPED: over WebTransport, when the host lists "gateway-datagram", payloads travel as WebTransport
1595
+ * datagrams (unordered, not retransmitted, no head-of-line blocking against other flows); over WebSocket, or against a
1596
+ * host without the feature, they ride the reliable control stream (ordered, retransmitted, and the host still drops
1597
+ * what you cannot take fast enough). The result has `send(bytes) => Promise<boolean>`, `readable`, `writable`, `close()`,
1598
+ * `transport` ('datagram' | 'stream'), `maxDatagramSize` and `stats`; see `UdpFlow`.
1555
1599
  * @param {string} host @param {number} port
1556
- * @param {{ signal?: AbortSignal, timeoutMs?: number }} [opts]
1600
+ * @param {{ signal?: AbortSignal, timeoutMs?: number, oversize?: 'reliable' | 'drop' }} [opts]
1601
+ * `oversize`: what to do with a payload that does not fit one datagram: 'reliable' (default) sends it on the control
1602
+ * stream, 'drop' makes `send()` reject with a RangeError.
1603
+ * @returns {Promise<import('./gateway-datagram.mjs').UdpFlow>}
1557
1604
  */
1558
1605
  async openUdp(host, port, opts) { return this.#gw().openUdp(host, port, opts); }
1559
1606
 
1607
+ /**
1608
+ * Ask the HOST to listen on a TCP port (a reverse tunnel, OpenSSH `-R`) and hand each connection to `onConnection(duplex, { peer, peerPort })`.
1609
+ * Off unless the host's `gateway.reverse` is set; the host chooses the address it binds (loopback by default) and which ports are allowed.
1610
+ * @param {number} port 0 = any port the host's policy allows
1611
+ * @param {{ bindAddr?: string, onConnection: (duplex: import('./gateway-client.mjs').GatewayDuplex, info: { peer: string, peerPort: number }) => void, timeoutMs?: number }} opts
1612
+ * `bindAddr` is a request: the host ignores it unless its operator listed that address.
1613
+ * @returns {Promise<{ port: number, close: () => Promise<void> }>} `port` is the port the host bound
1614
+ */
1615
+ async listenTcp(port, opts) { return this.#gw().listenTcp(port, opts); }
1616
+
1560
1617
  /**
1561
1618
  * Ask the host to listen on a unix-domain socket (OpenSSH `-R /remote.sock:...`) and hand each connection to
1562
1619
  * `onConnection(duplex)`. The host creates the socket 0600 and removes it when the listener or the connection closes.
@@ -2635,6 +2692,7 @@ export class WshClient {
2635
2692
  transport.onControl = (msg) => this.#handleControl(msg);
2636
2693
  transport.onClose = () => this.#handleTransportClose();
2637
2694
  transport.onError = (err) => this.#handleTransportError(err);
2695
+ transport.onDatagram = (bytes) => this.#gateway?.handleDatagram(bytes);
2638
2696
  }
2639
2697
 
2640
2698
  /**
@@ -2823,7 +2881,7 @@ export class WshClient {
2823
2881
  try {
2824
2882
  const authMethod = cred ? AUTH_METHOD.PUBKEY : AUTH_METHOD.PASSWORD;
2825
2883
  const hostKeyNonce = newHostKeyNonce();
2826
- await this.#transport.sendControl(hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce, GATEWAY_CREDIT_FEATURE] }));
2884
+ await this.#transport.sendControl(hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce, GATEWAY_CREDIT_FEATURE, ...(this.#transport.supportsDatagrams ? [GATEWAY_DATAGRAM_FEATURE] : [])] }));
2827
2885
  const hostCtx = { ...hostKeyOpts, url, username, nonce: hostKeyNonce };
2828
2886
 
2829
2887
  const firstResponse = await this.#waitForMessage(