@johnhenry/wsh 0.37.0 → 0.38.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
@@ -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
@@ -787,10 +846,17 @@ handshake and the session traffic -- is readable by it unless the two ends seal
787
846
  (per-session `initiateE2E`); it cannot forge the operator's signature or the host's. It can drop, delay or
788
847
  cut a connection, and it sees who dials which id and how much they send.
789
848
 
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`.
849
+ *CLI side (#145).* `wsh --via wss://relay/r/<id> user@host [command...]` dials the operator side
850
+ (`pipeUrl(relay, id)`; the URL must end in `/r/<22-128 base64url characters>`, may sit under a base path, and must not
851
+ be the `?role=host` URL). `user@host` stays the identity: the host key is recorded in `~/.wsh/known_hosts` under
852
+ `host:port` of that target (`--port`, default 4422), the key a direct connection uses, so the same host is the same
853
+ host whichever relay carried it and a different host behind that name is refused (`HOST KEY CHANGED`) before any
854
+ command is sent. A plain URL target (`wsh alice@wss://relay/r/<id> ...`) also dials but is recorded under the URL's
855
+ authority, which is the relay's, so prefer `--via`. `--via` works with `wsh [user@]host`, `connect`, `scp`, `ls`, `sftp`
856
+ and `copy-id`; it is an error elsewhere, and cannot be combined with a URL target. A pipe relay is WebSocket only: no
857
+ fallback, and `--transport` does not apply. The rendezvous id is not written to `last_session.json`. What the Rust
858
+ client does not yet do (host-key proof, channel binding, sealed bridge) is listed under the Security model. The host side
859
+ is any process that can open a WebSocket to `pipeUrl(..., 'host')` and hand it to `accept`.
794
860
 
795
861
  ### Sessions: attach / resume / detach
796
862
 
@@ -1407,7 +1473,7 @@ than left to be found.
1407
1473
  | 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" |
1408
1474
  | 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
1475
  | 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 |
1476
+ | 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
1477
  | 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
1478
  | 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
1479
  | 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 |
@@ -1416,12 +1482,14 @@ than left to be found.
1416
1482
  | 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
1483
  | 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
1484
  | 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) |
1485
+ | 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, and credit (`gateway-credit`) on accepted connections |
1486
+ | 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
1487
  | 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
1488
  | 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
1489
  | 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 |
1490
+ | 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) |
1491
+ | `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` |
1492
+ | `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
1493
  | 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
1494
  | 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
1495
 
@@ -1530,9 +1598,36 @@ out explicitly below rather than left to be discovered.
1530
1598
  IP-literal rule); the connection is made to that checked address, and `ResolveDns` answers are filtered the same way.
1531
1599
  Unix-domain sockets (`gateway.unix`) and named endpoints (`gateway.endpoints`) are off unless configured, are listed
1532
1600
  paths or names only, and sockets the host creates are `0600`.
1601
+ - **TCP reverse tunnels (`gateway.reverse`) are off unless configured, bind where the operator says, and cap what they open.**
1602
+ A reverse listener is a port of the HOST that other machines can connect to, with the authenticated client on the other
1603
+ end of every connection. The host binds `reverse.bindAddr` (default `127.0.0.1`) and ignores the address the client
1604
+ asks for unless the operator listed it; ports come from an allow-list (default 0 and 1024-65535; privileged ports only
1605
+ if named); listeners per client, connections per listener, the listen backlog and idle time are bounded, and listeners
1606
+ die with the client's connection.
1607
+ - **UDP flows are one destination, rate-limited in both directions.** An `OpenUdp` flow has the same destination and
1608
+ resolved-address policy as TCP, is `connect()`ed to the one address it passed (so no other source reaches the client
1609
+ through it), and is bounded by flows per client, packets per second per flow and per client, bytes per second per client
1610
+ and an idle timeout. The byte limit is the amplification bound: a small query to an open resolver or a UDP service
1611
+ that answers big (DNS, NTP, memcached-style services) can return no more than `bytesPerSecondPerClient` (4 MiB/s by
1612
+ default) to the client, and the same budget caps what the client can make the host send. Datagrams over a limit are
1613
+ dropped and counted (`server.gatewayStats()`).
1533
1614
 
1534
1615
  **What is still yours:**
1535
1616
 
1617
+ - **What a reverse listener exposes.** Whoever can reach the bound port can talk to whatever the client behind it serves,
1618
+ as the client, with no authentication of their own: wsh authenticates the operator that asks for the listener, not the
1619
+ peers that connect to it. `bindAddr: '0.0.0.0'` (or an `allowBindAddrs` entry that does the same) puts that on every
1620
+ interface of the host, so firewall it and keep `ports` narrow. The client sees each peer's address (`InboundOpen`) and
1621
+ can reject it, but behind a NAT or proxy that address is not the real source. The Rust server's defaults are the
1622
+ same (loopback, off) but it has no port allow-list.
1623
+ - **UDP is not authenticated or private beyond the tunnel.** `allow: ['*']` with a public resolver lets every authorized
1624
+ client send UDP to the internet from the host's address (a DNS-sized query, or a spoofed-looking flood limited only by
1625
+ the packet rates above); the bounds make that slow, not impossible, and an origin that answers many large datagrams
1626
+ to one small one is bounded by `bytesPerSecondPerClient`, not eliminated. WebTransport datagrams can be dropped,
1627
+ reordered and duplicated by the network, and are only as private as the QUIC connection that carries them (a
1628
+ datagram flow is not covered by E2E sealing, which is for sessions). A payload that did not fit a datagram travels on the
1629
+ reliable stream by default (see the README section above).
1630
+
1536
1631
  - **What the gateway does NOT protect against.** A name that resolves to a *public* address is dialled as the client
1537
1632
  asked, so `allow: ['*']` is an open proxy to the internet for every authorized client. Through `socks` the proxy
1538
1633
  resolves the name, so the host cannot check the address (only IP literals are checked) and the proxy's own network
@@ -1636,10 +1731,38 @@ What this does **not** protect against:
1636
1731
  WebTransport. The per-address auth rate limit bounds how fast one address can
1637
1732
  make the server run Argon2id (19 MiB each); it is not a defence against many
1638
1733
  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.
1734
+ - **The dev certificate from `--generate-cert` is a self-signed leaf** (not
1735
+ flagged as a CA, since #145), so a TLS client can trust it as a server
1736
+ certificate by being given the file (`SSL_CERT_FILE=~/.wsh/cert.pem`); it is
1737
+ still self-signed, so nothing vouches for it but that file. Before, it was
1738
+ flagged as a CA, TLS clients rejected it, and the only way in was
1739
+ `WSH_INSECURE_LOOPBACK_TLS=1`, which disables verification (loopback testing
1740
+ only).
1741
+ - **Rust `wsh-server`: the client's environment is an allow-list, and `Signal`
1742
+ is delivered.** Only `TERM`, `COLORTERM`, `LANG`, `LANGUAGE` and `LC_*` of
1743
+ `Open.env` reach the command (at most 64 variables, bounded sizes);
1744
+ `[server] client_env = true` re-opens everything (a client can then set `PATH`
1745
+ or `LD_PRELOAD` for what the server runs, and the server warns at start-up).
1746
+ `Signal` goes only to the process group of a channel the sending connection
1747
+ controls. This does not make a command safe to run: an authorized key still
1748
+ runs commands as the server's user.
1749
+ - **Rust `wsh-server`'s `AuthOk.ttl` is 0 and its `token` is opaque** (as the
1750
+ JS host's, above): nothing is promised or enforced at connection level; do not
1751
+ treat the token as a credential.
1752
+ - **`wsh --via` (pipe relay from the Rust CLI) is the operator side only, and
1753
+ weaker than the JS client's pinning.** The Rust client records
1754
+ `ServerHello.host_fingerprint` in `known_hosts` (trust on first use) but does
1755
+ not verify the proof of possession (`host-key-sig`) the JS client checks
1756
+ before sending credentials, does not bind the login signature to the host key
1757
+ (no channel binding), and cannot seal the bridge end to end. Over a pipe relay
1758
+ that means: a relay or impostor that replays a genuine host's `ServerHello`
1759
+ is not detected by the Rust CLI the way it is by a JS client with
1760
+ `expectHostKey`; the host still authenticates the operator's own signature,
1761
+ and a host whose key differs from the recorded one is refused. The relay
1762
+ sees the handshake and session traffic in the clear unless the legs are TLS
1763
+ and it is trusted not to read them (it terminates each leg's TLS). Use a JS
1764
+ client with `expectHostKey` where that matters. Proof, binding and sealing
1765
+ are the next part of #145.
1643
1766
 
1644
1767
  - **A host that lives in a page (`createMemoryHost`, `@johnhenry/wsh/reverse`) is only as trustworthy as the page.** A
1645
1768
  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.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",
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
 
@@ -1523,7 +1524,15 @@ export class WshClient {
1523
1524
 
1524
1525
  #gw() {
1525
1526
  this.#assertAuthenticated('gateway');
1526
- return (this.#gateway ??= new GatewayConnections({ send: (m) => this.sendControl(m), hasFeature: (f) => this.hasFeature(f) }));
1527
+ return (this.#gateway ??= new GatewayConnections({
1528
+ send: (m) => this.sendControl(m),
1529
+ hasFeature: (f) => this.hasFeature(f),
1530
+ // Datagrams for UDP flows: only on a transport that has them AND a host that listed "gateway-datagram".
1531
+ datagrams: () => {
1532
+ const t = this.#transport;
1533
+ return t?.supportsDatagrams && this.hasFeature(GATEWAY_DATAGRAM_FEATURE) ? { send: (b) => t.sendDatagram(b), maxSize: () => t.maxDatagramSize } : null;
1534
+ },
1535
+ }));
1527
1536
  }
1528
1537
 
1529
1538
  /**
@@ -1549,14 +1558,30 @@ export class WshClient {
1549
1558
  async openTcp(host, port, opts) { return this.#gw().openTcp(host, port, opts); }
1550
1559
 
1551
1560
  /**
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.
1561
+ * A UDP flow to ONE destination, host:port, FROM THE HOST (same destination policy as TCP). Each payload is one
1562
+ * datagram, which MAY BE DROPPED: over WebTransport, when the host lists "gateway-datagram", payloads travel as WebTransport
1563
+ * datagrams (unordered, not retransmitted, no head-of-line blocking against other flows); over WebSocket, or against a
1564
+ * host without the feature, they ride the reliable control stream (ordered, retransmitted, and the host still drops
1565
+ * what you cannot take fast enough). The result has `send(bytes) => Promise<boolean>`, `readable`, `writable`, `close()`,
1566
+ * `transport` ('datagram' | 'stream'), `maxDatagramSize` and `stats`; see `UdpFlow`.
1555
1567
  * @param {string} host @param {number} port
1556
- * @param {{ signal?: AbortSignal, timeoutMs?: number }} [opts]
1568
+ * @param {{ signal?: AbortSignal, timeoutMs?: number, oversize?: 'reliable' | 'drop' }} [opts]
1569
+ * `oversize`: what to do with a payload that does not fit one datagram: 'reliable' (default) sends it on the control
1570
+ * stream, 'drop' makes `send()` reject with a RangeError.
1571
+ * @returns {Promise<import('./gateway-datagram.mjs').UdpFlow>}
1557
1572
  */
1558
1573
  async openUdp(host, port, opts) { return this.#gw().openUdp(host, port, opts); }
1559
1574
 
1575
+ /**
1576
+ * Ask the HOST to listen on a TCP port (a reverse tunnel, OpenSSH `-R`) and hand each connection to `onConnection(duplex, { peer, peerPort })`.
1577
+ * Off unless the host's `gateway.reverse` is set; the host chooses the address it binds (loopback by default) and which ports are allowed.
1578
+ * @param {number} port 0 = any port the host's policy allows
1579
+ * @param {{ bindAddr?: string, onConnection: (duplex: import('./gateway-client.mjs').GatewayDuplex, info: { peer: string, peerPort: number }) => void, timeoutMs?: number }} opts
1580
+ * `bindAddr` is a request: the host ignores it unless its operator listed that address.
1581
+ * @returns {Promise<{ port: number, close: () => Promise<void> }>} `port` is the port the host bound
1582
+ */
1583
+ async listenTcp(port, opts) { return this.#gw().listenTcp(port, opts); }
1584
+
1560
1585
  /**
1561
1586
  * Ask the host to listen on a unix-domain socket (OpenSSH `-R /remote.sock:...`) and hand each connection to
1562
1587
  * `onConnection(duplex)`. The host creates the socket 0600 and removes it when the listener or the connection closes.
@@ -2635,6 +2660,7 @@ export class WshClient {
2635
2660
  transport.onControl = (msg) => this.#handleControl(msg);
2636
2661
  transport.onClose = () => this.#handleTransportClose();
2637
2662
  transport.onError = (err) => this.#handleTransportError(err);
2663
+ transport.onDatagram = (bytes) => this.#gateway?.handleDatagram(bytes);
2638
2664
  }
2639
2665
 
2640
2666
  /**
@@ -2823,7 +2849,7 @@ export class WshClient {
2823
2849
  try {
2824
2850
  const authMethod = cred ? AUTH_METHOD.PUBKEY : AUTH_METHOD.PASSWORD;
2825
2851
  const hostKeyNonce = newHostKeyNonce();
2826
- await this.#transport.sendControl(hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce, GATEWAY_CREDIT_FEATURE] }));
2852
+ await this.#transport.sendControl(hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce, GATEWAY_CREDIT_FEATURE, ...(this.#transport.supportsDatagrams ? [GATEWAY_DATAGRAM_FEATURE] : [])] }));
2827
2853
  const hostCtx = { ...hostKeyOpts, url, username, nonce: hostKeyNonce };
2828
2854
 
2829
2855
  const firstResponse = await this.#waitForMessage(
@@ -9,11 +9,12 @@
9
9
  */
10
10
 
11
11
  import {
12
- MSG, openTcp as openTcpMsg, openUdp as openUdpMsg, openUnix as openUnixMsg, openEndpoint as openEndpointMsg, listenUnix as listenUnixMsg,
12
+ MSG, openTcp as openTcpMsg, openUdp as openUdpMsg, listenRequest as listenRequestMsg, openUnix as openUnixMsg, openEndpoint as openEndpointMsg, listenUnix as listenUnixMsg,
13
13
  listenClose as listenCloseMsg, inboundAccept as inboundAcceptMsg, inboundReject as inboundRejectMsg,
14
14
  gatewayData as gatewayDataMsg, gatewayCredit as gatewayCreditMsg, gatewayClose as gatewayCloseMsg,
15
15
  } from './messages.mjs';
16
16
  import { GatewayChannel, GATEWAY_CREDIT_FEATURE } from './gateway-channel.mjs';
17
+ import { UdpFlow, decodeDatagram } from './gateway-datagram.mjs';
17
18
 
18
19
  const ID_BASE = 0x40000000;
19
20
  const ID_LIMIT = 0xffffffff;
@@ -54,9 +55,20 @@ export class GatewayConnections {
54
55
  * @param {(msg: object) => Promise<void>} o.send
55
56
  * @param {(feature: string) => boolean} o.hasFeature
56
57
  */
57
- constructor({ send, hasFeature }) {
58
+ constructor({ send, hasFeature, datagrams = () => null }) {
58
59
  this.#send = send;
59
60
  this.#hasFeature = hasFeature;
61
+ this.#datagrams = datagrams;
62
+ }
63
+
64
+ #datagrams;
65
+ /** @type {Map<number, UdpFlow>} */
66
+ #udp = new Map();
67
+
68
+ /** A WebTransport datagram arrived: [gateway_id][payload]. A flow we do not have is dropped, as a stray datagram is. */
69
+ handleDatagram(bytes) {
70
+ const d = decodeDatagram(bytes);
71
+ if (d) this.#udp.get(d.id)?.deliverDatagram(d.payload);
60
72
  }
61
73
 
62
74
  #id() {
@@ -68,8 +80,8 @@ export class GatewayConnections {
68
80
  if (!this.#hasFeature(feature)) throw new GatewayError(`this host does not support ${what} (it did not advertise "${feature}")`, 0);
69
81
  }
70
82
 
71
- /** @param {{ datagram?: boolean }} [kind] a datagram flow has no half-close: the peer's close ends it */
72
- #makeChannel(id, { datagram = false } = {}) {
83
+ /** @param {{ datagram?: boolean, onData?: (bytes: Uint8Array) => void }} [kind] a datagram flow has no half-close: the peer's close ends it */
84
+ #makeChannel(id, { datagram = false, onData } = {}) {
73
85
  const channel = new GatewayChannel({
74
86
  id,
75
87
  credit: this.#hasFeature(GATEWAY_CREDIT_FEATURE),
@@ -77,16 +89,19 @@ export class GatewayConnections {
77
89
  // our side closes too, so a connection nobody closes does not stay in the table forever.
78
90
  graceMs: CLIENT_GRACE_MS,
79
91
  onRemoteClose: datagram ? () => channel.destroy() : undefined,
92
+ onData,
80
93
  sendData: (data) => this.#send(gatewayDataMsg({ gatewayId: id, data })),
81
94
  sendCredit: (n) => this.#send(gatewayCreditMsg({ gatewayId: id, bytes: n })),
82
95
  sendClose: (reason) => this.#send(gatewayCloseMsg({ gatewayId: id, reason })),
83
- onClose: () => { this.#channels.delete(id); },
96
+ onClose: () => { this.#channels.delete(id); this.#udp.delete(id); },
84
97
  });
85
98
  this.#channels.set(id, channel);
86
99
  return channel;
87
100
  }
88
101
 
89
102
  #duplex(channel) {
103
+ const flow = this.#udp.get(channel.id);
104
+ if (flow) return flow;
90
105
  const { readable, writable } = channel.streams();
91
106
  return { readable, writable, close: (r) => channel.end(r), destroy: (r) => channel.destroy(r), closed: channel.closedPromise };
92
107
  }
@@ -94,7 +109,9 @@ export class GatewayConnections {
94
109
  async #open(build, { timeoutMs = DEFAULT_TIMEOUT_MS, signal } = {}, kind) {
95
110
  if (signal?.aborted) throw signal.reason ?? new DOMException('aborted', 'AbortError');
96
111
  const id = this.#id();
97
- const channel = this.#makeChannel(id, kind);
112
+ let flow;
113
+ const channel = this.#makeChannel(id, { ...kind, onData: kind?.udp ? (b) => flow.deliverReliable(b) : undefined });
114
+ if (kind?.udp) { flow = new UdpFlow({ id, channel, ...kind.udp }); this.#udp.set(id, flow); }
98
115
  const done = new Promise((resolve, reject) => {
99
116
  const timer = setTimeout(() => { this.#opening.delete(id); channel.abandon(); reject(new GatewayError('the host did not answer the open request in time', 5)); }, timeoutMs);
100
117
  timer.unref?.();
@@ -148,7 +165,45 @@ export class GatewayConnections {
148
165
  async openUdp(host, port, opts) {
149
166
  this.#need('gateway', 'UDP egress');
150
167
  if (typeof host !== 'string' || !host || !Number.isInteger(port)) throw new TypeError('openUdp: host and port are required');
151
- return this.#open((id) => openUdpMsg({ gatewayId: id, host, port }), opts, { datagram: true });
168
+ if (opts?.oversize !== undefined && opts.oversize !== 'reliable' && opts.oversize !== 'drop') throw new TypeError('openUdp: oversize must be "reliable" or "drop"');
169
+ // Whether this flow uses datagrams is fixed at open: both ends negotiated it for the connection.
170
+ const datagrams = this.#datagrams();
171
+ return this.#open((id) => openUdpMsg({ gatewayId: id, host, port }), opts, {
172
+ datagram: true,
173
+ udp: { datagrams, oversize: opts?.oversize },
174
+ });
175
+ }
176
+
177
+ /**
178
+ * Ask the host to listen on a TCP port (a reverse tunnel) and hand each inbound connection to `onConnection(duplex, { peer, peerPort })`.
179
+ * @param {number} port @param {{ bindAddr?: string, onConnection: Function, timeoutMs?: number }} opts
180
+ * @returns {Promise<{ port: number, close: () => Promise<void> }>}
181
+ */
182
+ async listenTcp(port, { bindAddr, onConnection, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
183
+ this.#need('gateway', 'reverse tunnels (ListenRequest)');
184
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new TypeError('listenTcp: port must be an integer 0-65535');
185
+ if (typeof onConnection !== 'function') throw new TypeError('listenTcp: onConnection is required');
186
+ const id = this.#id();
187
+ const entry = { onConnection, path: '', closed: false, actualPort: 0 };
188
+ const answered = new Promise((resolve, reject) => {
189
+ entry.resolve = resolve; entry.reject = reject;
190
+ entry.timer = setTimeout(() => { this.#listeners.delete(id); reject(new GatewayError('the host did not answer the listen request in time', 5)); }, timeoutMs);
191
+ entry.timer.unref?.();
192
+ });
193
+ this.#listeners.set(id, entry);
194
+ try {
195
+ await this.#send(listenRequestMsg({ listenerId: id, port, ...(bindAddr === undefined ? {} : { bindAddr }) }));
196
+ await answered;
197
+ } catch (e) { this.#listeners.delete(id); throw e; }
198
+ return {
199
+ port: entry.actualPort,
200
+ close: async () => {
201
+ if (entry.closed) return;
202
+ entry.closed = true;
203
+ this.#listeners.delete(id);
204
+ await this.#send(listenCloseMsg({ listenerId: id })).catch(() => {});
205
+ },
206
+ };
152
207
  }
153
208
 
154
209
  /**
@@ -214,7 +269,7 @@ export class GatewayConnections {
214
269
  c.remoteClosed(m.reason);
215
270
  return true;
216
271
  }
217
- case MSG.LISTEN_OK: { const l = this.#listeners.get(m.listener_id); if (!l?.resolve) return false; clearTimeout(l.timer); l.resolve(); l.resolve = undefined; return true; }
272
+ case MSG.LISTEN_OK: { const l = this.#listeners.get(m.listener_id); if (!l?.resolve) return false; clearTimeout(l.timer); l.actualPort = m.actual_port; l.resolve(); l.resolve = undefined; return true; }
218
273
  case MSG.LISTEN_FAIL: {
219
274
  const l = this.#listeners.get(m.listener_id);
220
275
  if (!l?.reject) return false;
@@ -232,7 +287,7 @@ export class GatewayConnections {
232
287
  const channel = this.#makeChannel(id);
233
288
  const duplex = this.#duplex(channel);
234
289
  void this.#send(inboundAcceptMsg({ channelId: m.channel_id, gatewayId: id })).then(() => {
235
- try { l.onConnection(duplex, { peer: m.peer_addr }); } catch { channel.destroy('handler error'); }
290
+ try { l.onConnection(duplex, { peer: m.peer_addr, peerPort: m.peer_port }); } catch { channel.destroy('handler error'); }
236
291
  }, () => channel.abandon());
237
292
  return true;
238
293
  }