@johnhenry/wsh 0.36.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
@@ -66,7 +66,7 @@ Or via CDN:
66
66
  - **MCP bridge** -- discover and invoke remote MCP tools through the control channel
67
67
  - **Session recording** -- own JSON schema (asciicast-v2-shaped, not a playable asciicast file -- see note below) recording and playback with seek/pause/resume
68
68
  - **Key management** -- IndexedDB storage with OPFS encrypted backup (PBKDF2 + AES-256-GCM)
69
- - **99 message types** -- handshake, channel, gateway, guest sharing, compression negotiation, copilot, policy, authorized-key management, and more
69
+ - **105 message types** -- handshake, channel, gateway, guest sharing, compression negotiation, copilot, policy, authorized-key management, and more
70
70
 
71
71
  > **Session recording is asciicast-v2-shaped, but not an asciicast file.**
72
72
  > The JS `SessionRecorder.toJSON()` export borrows asciicast v2's vocabulary --
@@ -229,12 +229,159 @@ restricted host with no shell. `fs.root` confines every path: `..`, absolute
229
229
  paths and symlinks pointing out of it are refused -- for `write` and `rename`
230
230
  (both paths) exactly as for `read`.
231
231
 
232
+ **Client environment (`clientEnv`).** A client may ask for environment
233
+ variables with `openSession({ env })`. Since 0.36 the host accepts only
234
+ `TERM`, `COLORTERM`, `LANG`, `LANGUAGE` and `LC_*` by default (the shape of
235
+ sshd's `AcceptEnv`); `PATH`, `LD_PRELOAD`, `BASH_ENV` and the like are dropped,
236
+ because they change what a shell or a restricted runner executes. Set
237
+ `exec: { clientEnv: true }` to accept everything (the old behaviour),
238
+ `false` for nothing, a list (`['TERM', 'LC_*', 'MY_APP_TOKEN']`, replacing the
239
+ default list) or a predicate `(name, value) => boolean`; `pty: { clientEnv }`
240
+ takes the same. At most 64 variables of at most 4096 bytes with plain names
241
+ are looked at. **This is a breaking default** for a host that relied on clients
242
+ setting arbitrary variables.
243
+
244
+ **Connection lifetime (`connectionTtlMs`).** `AuthOk` carries a `token` and a
245
+ `ttl`. The token is an opaque per-connection value that nothing accepts back
246
+ (session resume uses its own per-session token); it stays on the wire because
247
+ released clients require the field. `ttl` is now true: `connectionTtlMs: n`
248
+ ends every authenticated connection `n` ms after login and advertises it
249
+ (`client.authTtl`, whole seconds, rounded up); without it the host promises no
250
+ limit and sends `ttl: 0`. Before 0.36 it sent an unenforced 3600. The Rust
251
+ `wsh-server` still sends its `session_ttl` setting unenforced.
252
+
232
253
  ### Gateway (TCP and DNS egress from the host)
233
254
 
234
- `gateway: { allow: ['broker.lan:1883'], socks: '127.0.0.1:9050' }` makes the Node server answer the gateway opcodes, so a
235
- client (a browser tab via netway's `GatewayBackend`) can open TCP connections and resolve names from the host. Default
236
- deny; `allow` takes `"*"`, `"host"` or `"host:port"`. `socks` routes every dial through a SOCKS5 proxy (Tor) with the name
237
- unresolved. UDP and reverse tunnels are refused.
255
+ `gateway: { allow: ['broker.lan:1883'], allowPrivate: ['10.0.0.0/8'], socks: '127.0.0.1:9050' }` makes the Node server
256
+ answer the gateway opcodes, so a client (a browser tab via netway's `GatewayBackend`, or `client.openTcp()`) can open TCP
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. `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`.
322
+
323
+ **The address is checked, not just the name.** The host resolves a name once, refuses every resolved address that is not
324
+ globally routable (loopback, private, link-local, CGNAT, ULA, multicast, reserved, and IPv4 addresses wrapped as
325
+ IPv4-mapped, NAT64 or 6to4 IPv6), and connects to the address it checked, so a name that resolves to something else a
326
+ moment later cannot redirect the connection. Reaching private space is an explicit rule: `allowPrivate` (CIDR blocks or
327
+ addresses) for names and `"*"`, or an `allow` entry that is itself an IP literal (`"127.0.0.1:1883"`), which permits
328
+ exactly that address. `ResolveDns` answers are filtered with the same rule. Through `socks` the proxy resolves the name,
329
+ so only IP literals can be checked there. See the Security model below and the CHANGELOG (this is a behaviour change).
330
+
331
+ **Flow control.** Gateway data is metered in both directions when both ends offer the `gateway-credit` feature: each
332
+ direction of each connection starts with 256 KiB of credit that the receiver tops up (`GatewayCredit`) as its
333
+ application consumes data, so a slow reader stops its peer (the origin socket is paused, `write()` results and `drain`
334
+ are honoured) instead of making the host buffer. Against a peer without the feature the host still holds the origin back
335
+ by the transport's own backpressure and bounds what a client can make it hold with `maxBufferedBytes` (default 4 MiB per
336
+ connection) and `maxClientBufferedBytes` (default 32 MiB per client), closing a connection that exceeds them.
337
+
338
+ #### Unix-domain sockets (streamlocal) and named endpoints
339
+
340
+ Modelled on OpenSSH's streamlocal forwarding. Off unless configured:
341
+
342
+ ```js
343
+ createWshServer({ auth, gateway: {
344
+ allow: [],
345
+ unix: {
346
+ connect: ['/var/run/docker.sock'], // OpenUnix: a client may connect to these (exact path, or "/dir/" prefix, or "@abstract")
347
+ listen: ['/run/user/1000/wsh/'], // ListenUnix: a client may ask the host to create sockets under here
348
+ replaceStale: false, // a client may replace a STALE socket file only if it asks AND this is true
349
+ },
350
+ endpoints: { ping: async (duplex, who) => { /* ... */ } }, // named virtual endpoints, below
351
+ } });
352
+ ```
353
+
354
+ Paths are checked after `realpath` of the parent directory (so `/var/run` and `/private/var/run` agree and a symlinked
355
+ directory cannot lead out of an allowed one), a `..` segment is refused, and the file must be a socket and not a symlink.
356
+ The abstract namespace (`@name`) is refused unless listed. Sockets the host creates are mode `0600` (the umask is
357
+ tightened while binding) and are unlinked when the listener closes or the connection ends; an existing socket file is
358
+ replaced only when the request says `replace` AND `replaceStale` is on AND nothing accepts connections on it, and a file
359
+ that is not a socket is never touched. Allow only directories no other local user can write to: the check cannot close
360
+ the instant between it and the connect.
361
+
362
+ ```js
363
+ const duplex = await client.openUnix('/var/run/docker.sock'); // web streams with backpressure
364
+ await duplex.writable.getWriter().write(new TextEncoder().encode('GET /containers/json HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n'));
365
+ // Node: ssh -L / -R shapes, unix and TCP ends mixed
366
+ await client.forwardUnix({ local: '127.0.0.1:2375', remote: '/var/run/docker.sock' }); // -L 127.0.0.1:2375:/var/run/docker.sock
367
+ await client.forwardUnix({ local: '/tmp/docker.sock', remote: '/var/run/docker.sock' });
368
+ await client.forwardUnix({ reverse: true, remote: '/run/user/1000/wsh/app.sock', local: '127.0.0.1:8080' }); // -R
369
+ ```
370
+
371
+ **Named virtual endpoints** are for a host with no file system (the memory host, a browser tab):
372
+ `endpoints: { docker: (duplex, who) => ... }` registers handlers and a client reaches one with `client.openEndpoint('docker')`.
373
+ It is its own message (`OpenEndpoint { name }`) rather than a reserved `OpenUnix` path so that a name can never be
374
+ mistaken for (or smuggled as) a file-system path or an abstract-namespace name, and so a host's file-system policy is not
375
+ consulted for it; the registered names are an allow-list by construction. `who` is the authenticated
376
+ `{ username, fingerprint }`, so the embedder can authorise per call (throw to refuse, or `{ open, authorize(who) }`).
377
+
378
+ **Rust side: JS only for now.** `wsh-server` does not advertise `gateway-unix`, `gateway-endpoints` or `gateway-credit`,
379
+ and `wsh` has no `-L` / `-R` with unix sockets yet. What it must implement: `OpenUnix { gateway_id, path }` and
380
+ `ListenUnix { listener_id, path, replace? }` (answer with the existing `GatewayOk`/`GatewayFail` and `ListenOk` with
381
+ `actual_port: 0`/`ListenFail`; accepted connections announced with `InboundOpen` and answered by `InboundAccept`'s
382
+ `gateway_id`), the same path policy and `0600`/unlink rules, `GatewayCredit` (256 KiB initial credit per direction when
383
+ the client's `Hello.features` lists `gateway-credit`), and in the CLI `-L [bind:]port:/remote.sock`,
384
+ `-L /local.sock:/remote.sock`, `-R /remote.sock:host:port` and `-R /remote.sock:/local.sock`.
238
385
 
239
386
  ### TLS (`wss://`) and host extensions
240
387
 
@@ -280,7 +427,9 @@ session.onData = (d) => console.log(new TextDecoder().decode(d)); // "ran hi"
280
427
  It is the real connection handler speaking QMux over an in-memory socket pair, so the client code you test is the code
281
428
  you ship. `host.createClient()` / `host.WebSocket` / `host.accept(socket)` / `createSocketPair()` are the lower-level pieces.
282
429
  Supported: `auth`, `exec` (a function; there is no shell), `pty`, `fs` and `hostKey` (injected, below), `mcp`,
283
- `extensions`, `rpc` and `sessions` (below). Not available in memory: `gateway`, `relay`, WebTransport, `exec: true` and
430
+ `extensions`, `rpc`, `sessions` (below) and `endpoints` ([named virtual endpoints](#unix-domain-sockets-streamlocal-and-named-endpoints):
431
+ `endpoints: { api: (duplex, who) => ... }`, reached with `client.openEndpoint('api')`, with flow control). Not available
432
+ in memory: the TCP, DNS, UDP and unix-socket parts of `gateway`, `relay`, WebTransport, `exec: true` and
284
433
  `fs: { root }` (they need Node) and the `wsh-host` / `wsh-fs` rpc built-ins (use `@johnhenry/wsh/server`).
285
434
 
286
435
  **Injected backends**, shaped like the Node host's, so a page can be a real host (#114):
@@ -607,6 +756,108 @@ const s = await client.openSession({ type: 'exec', command: 'echo hello' });
607
756
  there): against such a relay or operator, set `reportFeatures: false` on the
608
757
  host (and use `ReverseAccept` without the field in your own peers).
609
758
 
759
+ #### Operator proof and sealed bridges (#117)
760
+
761
+ Out of the box the relay tells the host who the operator is (`from_fingerprint`,
762
+ set from the operator's login at the relay) and the host's `accept` trusts it:
763
+ fine for a relay you run, not for a shared one. Two opt-ins close that, and both
764
+ are negotiated by feature strings so every released peer keeps working
765
+ (the Rust relay never lists `operator-proof`, so the operator simply does not
766
+ offer it there):
767
+
768
+ ```js
769
+ // host: do not take the operator's identity from the relay.
770
+ createReverseHost({ url, username, keyPair, exec: true,
771
+ requireOperatorProof: true,
772
+ accept: ({ fingerprint, username, proven, publicKey }) => fingerprint === aliceFingerprint });
773
+ // operator: prove yourself, and seal the bridge (nothing naming a command is sent before the key exists).
774
+ await client.reverseConnect(hostFingerprint, 10_000, { sealed: true, requirePeerProof: true });
775
+ ```
776
+
777
+ 1. **Operator proof.** After `ReverseConnect` the host sends a signed
778
+ `ReverseChallenge` (its key, the operator fingerprint it saw, a nonce it chose and a
779
+ session id); the operator checks the host's signature, that the key is the host it asked for and that
780
+ the host saw the operator's *own* fingerprint (so a relay that rewrote `from_fingerprint` shows
781
+ up here), and answers with a `ReverseProof`: an Ed25519 signature over the host's key, its own key, the
782
+ username it claims, and the host's nonce and session id. The host verifies it **before `accept` runs**, takes
783
+ the identity from the proof and refuses when it differs from what the relay asserted. `accept` receives
784
+ `{ fingerprint, username, proven, publicKey }`; by default the proof is requested whenever the relay
785
+ and operator can do it and merely *reported* (`proven`).
786
+ 2. **Sealed bridge.** A proof is a point in time, and a relay can stamp any
787
+ `from_fingerprint` on a plain message afterwards (an injected `Open`), so a host with
788
+ `requireOperatorProof` also requires the bridge to be sealed: the operator opens it with a
789
+ `KeyExchange` that **both** sides sign (the operator's half covers the session id, algorithm, its
790
+ ephemeral key and the host's identity; the host's reply covers both ephemeral keys), hybrid
791
+ X25519+ML-KEM-768 by default, and from then on every message that would cross the relay (`Open`, `OpenOk`,
792
+ `SessionData`, `FileOp`, `McpCall` ...) travels as an `EncryptedFrame` on channel 0 with a strict counter.
793
+ The host acts on nothing else. The only plaintext before the key exists is the key exchange itself (ephemeral
794
+ public keys, signatures); before this change `Open` -- the command, the environment, the working size --
795
+ and `OpenOk` with its resume token crossed the relay in the clear until a per-session `initiateE2E`.
796
+
797
+ What a relay can and cannot do, with and without these (a relay always sees who connects to whom, when, and how
798
+ many bytes):
799
+
800
+ | The relay can ... | Plain bridge (default) | + operator proof | + `requireOperatorProof` (sealed) |
801
+ |---|---|---|---|
802
+ | read commands, output, files, MCP calls | yes, until a per-session `initiateE2E` | yes | **no** (ciphertext; metadata and sizes only) |
803
+ | make the host think an operator it chose is connecting | yes (it stamps `from_fingerprint`) | **no**: the host verifies the operator's own signature before `accept` | no |
804
+ | replay an old operator's login to the host | n/a | **no**: the nonce is the host's, single use, signed over the host's key and the session | no |
805
+ | swap the operator's key or the host's ephemeral key | n/a | no (signature does not verify) | no (both halves are signed) |
806
+ | inject an `Open` / `SessionData` stamped as the operator | **yes** | **yes** (a proof is a point in time) | **no** (plain messages are dropped) |
807
+ | replay or reorder a sealed frame | n/a | n/a | **no** (strict counter and role tag) |
808
+ | drop, delay or truncate traffic, or end the bridge | yes | yes | yes (a denial of service is always open to a relay) |
809
+ | tell the host the operator is *absent* when it is present (`ReverseClose`) | yes | yes | yes |
810
+ | learn the operator's and host's keys, usernames, and the sizes and timing of traffic | yes | yes | yes |
811
+
812
+ Not covered: an operator or host that skips the checks (the options are opt-in on both
813
+ sides; a host that does not require proof is exactly as exposed as before), the Rust `wsh-server` relay and
814
+ `wsh` client (they neither carry nor send these messages), and a compromised *operator* key (it proves the key, not the
815
+ person). A relay can still refuse service by dropping the challenge.
816
+
817
+ #### A pipe relay (`@johnhenry/wsh/pipe-relay`, #118)
818
+
819
+ When you do not want the relay to be a party at all, use a pipe: the host dials the relay, the operator dials the
820
+ relay, the relay matches them by an unguessable rendezvous id and copies bytes. **There is no relay-asserted identity**:
821
+ the host runs the ordinary handshake and verifies the operator's own signature (`authorize`, `authorizedKeys`,
822
+ channel binding, ...) exactly as on a direct connection, and the operator can pin the host key.
823
+
824
+ ```js
825
+ import { createPipeRelay, newRendezvousId, pipeUrl } from '@johnhenry/wsh/pipe-relay';
826
+ const relay = createPipeRelay({ idleTimeoutMs: 300_000, maxWaiting: 1024 });
827
+ const { port } = await relay.listen({ port: 8443 }); // or relay.accept(socket, { id, role }) from your own HTTP server
828
+
829
+ const id = newRendezvousId(); // 128 bits; hand it to both sides out of band
830
+ // host (behind NAT): dial out, wait for the socket to open, serve it like any accepted connection
831
+ const ws = new WebSocket(pipeUrl('wss://relay.example', id, 'host'));
832
+ await new Promise((r) => ws.addEventListener('open', r, { once: true }));
833
+ await server.accept(ws); // createWshServer / createMemoryHost
834
+ // operator: the stock client, any URL form
835
+ await client.connect(pipeUrl('wss://relay.example', id), { username, keyPair, expectHostKey });
836
+ ```
837
+
838
+ The module imports nothing that can execute code or read files (a test walks its module graph); it does not parse wsh.
839
+ Bounds, all with defaults: `maxWaiting`, `rendezvousTimeoutMs`, `idleTimeoutMs`, `maxLifetimeMs`, `maxBytes`,
840
+ `maxMessageBytes`, `earlyBytes`, `highWaterBytes` (a receiver that is not draining pauses the sender; a socket that
841
+ cannot pause is closed). **Trust difference:** relay mode has the relay vouch for the operator; a pipe relay vouches
842
+ for nothing, and the rendezvous id is the only thing standing between the host's socket and whoever dials first --
843
+ an impostor that reaches the id first is still a stranger to the operator, who must pin the host key
844
+ (`expectHostKey`) to notice; and the host still authenticates every operator. A pipe relay terminates the TLS of each leg, so what it copies -- the wsh
845
+ handshake and the session traffic -- is readable by it unless the two ends seal it themselves
846
+ (per-session `initiateE2E`); it cannot forge the operator's signature or the host's. It can drop, delay or
847
+ cut a connection, and it sees who dials which id and how much they send.
848
+
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`.
860
+
610
861
  ### Sessions: attach / resume / detach
611
862
 
612
863
  By default a pty/exec session dies with the connection that opened it. Pass
@@ -800,6 +1051,41 @@ client.onHostKey = (hk) => confirm(`Trust ${hk.fingerprint}?`); // or per call
800
1051
  ServerHello and then read or alter the rest. Pinning keeps you from talking
801
1052
  to the wrong host; confidentiality still needs `wss://` or a link you trust.
802
1053
 
1054
+ ### Channel binding (tie the login to the connection)
1055
+
1056
+ A host key proves who the host is; it does not stop an intermediary from
1057
+ passing a genuine challenge through to the host and getting your login
1058
+ signature back. With binding, the signature also covers what the two ends of
1059
+ *this* connection share, so a relayed signature is worthless to the host:
1060
+
1061
+ ```js
1062
+ // host: accept a key login only when it is bound (requires hostKey for `host`; wss served by this process for `tls-exporter`)
1063
+ createWshServer({ auth, hostKey: { file }, requireChannelBinding: true }); // or ['host', 'tls-exporter']
1064
+ // client: refuse to sign a login that cannot be bound
1065
+ await client.connect(url, { username, keyPair, requireChannelBinding: true });
1066
+ client.channelBinding; // ['host'] -- which kinds this login's signature covered
1067
+ ```
1068
+
1069
+ | Kind | Bound to | Who can supply it |
1070
+ |---|---|---|
1071
+ | `host` | the Ed25519 host key that proved possession in `ServerHello` | a host with `hostKey`; any client that checked the proof (so a relay presenting its own key binds to *its* key) |
1072
+ | `cert-hash` | the SHA-256 of the pinned WebTransport certificate | a `selfSigned` WebTransport host; a client with exactly one `serverCertificateHashes` entry |
1073
+ | `tls-exporter` | 32 bytes of TLS keying material (RFC 5705/8446, label `EXPORTER-wsh-channel-binding`) | Node on both ends over `wss://` served by the process itself (the client must use the `ws` package, e.g. `new WebSocketTransport({ WebSocket })`; Node's global `WebSocket` and every browser expose no exporter) |
1074
+
1075
+ It is negotiated with feature strings (`channel-binding:<kind>`,
1076
+ `channel-binding-required`), so released clients and hosts keep working: a
1077
+ host that does not require binding still accepts an unbound login, and a
1078
+ client binds whatever the host offers. A host that requires it refuses an
1079
+ unbound signature with a reason. **What it does not do:** it protects only
1080
+ what you require. An intermediary that strips the host's offer gets an unbound
1081
+ signature from a client that did not set `requireChannelBinding`, and a host
1082
+ that does not require binding accepts it -- set the option on whichever side
1083
+ you control (a host protects every client; a client protects itself).
1084
+ `tls-exporter` fails behind a TLS-terminating proxy by design. Password logins
1085
+ are not bound (nothing is signed). The Rust `wsh-server` and `wsh` CLI do not
1086
+ offer or compute a binding yet, so against them a client with
1087
+ `requireChannelBinding` refuses to log in.
1088
+
803
1089
  ### Password auth
804
1090
 
805
1091
  ```js
@@ -1122,7 +1408,7 @@ so options the platform gains later need no change here.
1122
1408
 
1123
1409
  | Export | Description |
1124
1410
  |--------|-------------|
1125
- | `MSG` | 99 message type constants (hex opcodes) |
1411
+ | `MSG` | 105 message type constants (hex opcodes) |
1126
1412
  | `CHANNEL_KIND` | Channel types: `pty`, `exec`, `meta`, `file`, `tcp`, `udp`, `job` |
1127
1413
  | `AUTH_METHOD` | Auth methods: `pubkey`, `password` |
1128
1414
  | `cborEncode` / `cborDecode` | CBOR codec (maps, arrays, strings, ints, bytes, bools, null, floats) |
@@ -1146,7 +1432,7 @@ instead of dragging its own toolchain and CI job into an unrelated
1146
1432
  browser-app repo. It was previously deleted from clawser by accident
1147
1433
  (2026-03-14) and restored (2026-07-05) before this move.
1148
1434
 
1149
- Four crates, workspace-versioned (currently `0.5.0`):
1435
+ Four crates, workspace-versioned (currently `0.7.0`):
1150
1436
 
1151
1437
  | Crate | Kind | Description |
1152
1438
  |-------|------|--------------|
@@ -1155,6 +1441,22 @@ Four crates, workspace-versioned (currently `0.5.0`):
1155
1441
  | `wsh-cli` | binary (`wsh`) | SSH-like CLI: connect, exec, scp-style copy, reverse tunnels, key management |
1156
1442
  | `wsh-server` | binary (`wsh-server`) | Server: WebTransport/WebSocket listener, real PTY sessions (`portable-pty`), relay/reverse-connect, WISP bridging |
1157
1443
 
1444
+ ### Running a command with `wsh`
1445
+
1446
+ ```sh
1447
+ wsh alice@host ls -l # dials https://host:4422, then wss://host:4422
1448
+ wsh -t ws -p 8443 alice@host ls -l # wss:// only, on port 8443
1449
+ wsh wss://host:8443/rendezvous/ab12 ls -l # a full URL, dialled exactly as written (path and query kept)
1450
+ printf 'a\nb\n' | wsh alice@host sort # stdin is forwarded; its end reaches the command as EOF
1451
+ wsh --tty alice@host top # a terminal for the command: raw keys, resizes forwarded
1452
+ ```
1453
+
1454
+ stdout and stderr stay separate where the host offers `exec-pipes`; the exit status is the command's.
1455
+ SIGINT, SIGTERM and SIGHUP sent to `wsh` are forwarded to the command, and the same signal twice
1456
+ disconnects. `wsh connect` ends when the remote session does. Diagnostics go to stderr (`-v` for more),
1457
+ 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
1458
+ `ws://` URL is accepted only for a loopback host.
1459
+
1158
1460
  ### Capability matrix: JS SDK vs Rust CLI/client
1159
1461
 
1160
1462
  Two implementations of one protocol will always have *some* asymmetry --
@@ -1170,12 +1472,24 @@ than left to be found.
1170
1472
  | 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 |
1171
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" |
1172
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 |
1173
- | Exec stdin + EOF, separate stderr | `exec({ stdin })`, `session.closeStdin()`, `session.onStderr` | none yet in `wsh-client` | **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 |
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 |
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 |
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 |
1174
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) |
1175
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 |
1176
1480
  | 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) |
1177
1481
  | 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 |
1178
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 |
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) |
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 |
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) |
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 |
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 |
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 |
1179
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 |
1180
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 |
1181
1495
 
@@ -1245,7 +1559,28 @@ out explicitly below rather than left to be discovered.
1245
1559
  - **Auth transcript binding.** Challenge signatures cover
1246
1560
  `SHA-256("wsh-v1\0" || lp(username) || lp(session_id) || nonce || channel_binding)`,
1247
1561
  so a signature can't be replayed against a different session or relabeled
1248
- to a different username.
1562
+ to a different username. `channel_binding` is empty unless both ends agree
1563
+ on one (wsh #119): then it also names the connection (host key, pinned
1564
+ certificate, TLS exporter), so a relaying intermediary cannot reuse a
1565
+ signature -- but only against a host that requires it or a client that
1566
+ does; see [Channel binding](#channel-binding-tie-the-login-to-the-connection).
1567
+ - **A relay need not be believed about who the operator is (opt-in).** With
1568
+ `requireOperatorProof` on the host and `sealed` on the operator, the host
1569
+ verifies the operator's own signature before `accept`, and acts only on
1570
+ sealed traffic, so a relay cannot stamp an identity, replay a login or inject
1571
+ an `Open`; see the table under
1572
+ [Operator proof and sealed bridges](#operator-proof-and-sealed-bridges-117).
1573
+ Not default, not available through the Rust relay, and no defence against a
1574
+ relay that drops traffic.
1575
+ - **A pipe relay vouches for nothing.** With `createPipeRelay` the host
1576
+ authenticates the operator itself (see [A pipe relay](#a-pipe-relay-johnhenrywshpipe-relay-118)).
1577
+ - **`AuthOk.ttl` and `token`.** The token is an opaque per-connection value
1578
+ with no authority; `ttl` is enforced when `connectionTtlMs` is set (else 0:
1579
+ no limit) -- do not read either as a session credential.
1580
+ - **Client environment is an allow-list** (`clientEnv`, default `TERM`,
1581
+ `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*`): a client cannot set `PATH`,
1582
+ `LD_PRELOAD` or `BASH_ENV` for a command your host runs through a shell
1583
+ unless you say so.
1249
1584
  - **E2E through a relay is opt-in.** The relay carries `KeyExchange` /
1250
1585
  `EncryptedFrame` between a bridged operator and peer without being able to
1251
1586
  read the sealed frames. `KeyExchange` is unauthenticated unless the peer signs
@@ -1258,8 +1593,52 @@ out explicitly below rather than left to be discovered.
1258
1593
  entry client-side and reports a `verified` boolean, independent of
1259
1594
  trusting the relay.
1260
1595
 
1596
+ - **The Node gateway checks where a connection goes, not only what it was called.** `gateway.allow` matches the name a
1597
+ client sent, and then the address it resolves to must be globally routable (or permitted by `allowPrivate` or an
1598
+ IP-literal rule); the connection is made to that checked address, and `ResolveDns` answers are filtered the same way.
1599
+ Unix-domain sockets (`gateway.unix`) and named endpoints (`gateway.endpoints`) are off unless configured, are listed
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()`).
1614
+
1261
1615
  **What is still yours:**
1262
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
+
1631
+ - **What the gateway does NOT protect against.** A name that resolves to a *public* address is dialled as the client
1632
+ asked, so `allow: ['*']` is an open proxy to the internet for every authorized client. Through `socks` the proxy
1633
+ resolves the name, so the host cannot check the address (only IP literals are checked) and the proxy's own network
1634
+ is the egress. The path check for unix sockets is made just before the connect: a local user who can write to an
1635
+ allowed directory can still swap a path between the two, so list only directories that are not writable by others.
1636
+ A client may open any listed socket as the host's user; a socket that speaks a powerful API (the Docker socket is
1637
+ root on the host) is exactly as powerful for every authorized client, so list it only for clients you would give that
1638
+ access. Named endpoints run embedder code with the caller's identity (`who`) but the handler decides what that
1639
+ identity may do. A `wsh-server` built before the Rust release that followed `rust-v0.6.0` only matches the name, not the
1640
+ resolved address (see the Rust defaults above): do not expose such a binary with a `"*"` allow list.
1641
+
1263
1642
  - **Hybrid post-quantum E2E is experimental and not fully wired (in
1264
1643
  progress).** `initiateE2E(sessionId, 'X25519+ML-KEM-768')` combines
1265
1644
  X25519 ECDH with ML-KEM-768 via HKDF-SHA256, preferring native WebCrypto
@@ -1305,7 +1684,85 @@ out explicitly below rather than left to be discovered.
1305
1684
  above), but nothing in this protocol or client stops a non-browser
1306
1685
  caller (Node, the Rust CLI) from dialing `ws://` directly. Prefer pubkey
1307
1686
  auth, or make sure the transport is actually encrypted, before sending a
1308
- password.
1687
+ password. (The Rust `wsh` CLI refuses a plain `ws://` URL unless the host is
1688
+ loopback.)
1689
+
1690
+ ### Rust `wsh-server`: what is off until you turn it on
1691
+
1692
+ An authorized key is a login, not a licence to use the machine as a network
1693
+ position. From the Rust release after `rust-v0.6.0` the server's defaults are:
1694
+
1695
+ - **The gateway is off** (`[gateway] enabled = false`), and `gateway` is not
1696
+ advertised. Turning it on allows **no destination** until `allowed_destinations`
1697
+ lists some. `"*"` means any *public* destination: an address that is loopback,
1698
+ link-local (including `169.254.169.254`), private (RFC 1918), unique-local
1699
+ (`fc00::/7`), carrier-grade NAT (`100.64.0.0/10`), unspecified or multicast is
1700
+ refused **after the name is resolved**, whichever rule matched the name, unless
1701
+ a rule names that host (`"db.internal:5432"`) or address/range
1702
+ (`"10.1.0.0/16:5432"`, `"127.0.0.1:8080"`). The server connects to the address it
1703
+ checked, so a name cannot pass the check as one address and connect as another.
1704
+ `ResolveDns` follows the same rule and does not return internal answers.
1705
+ - **Reverse listeners are off** (`enable_reverse_tunnels = false`) and, when on,
1706
+ bind to `reverse_bind_addr` (default `127.0.0.1`). The client's own `bind_addr`
1707
+ in `ListenRequest` (its wire default is `0.0.0.0`) is ignored.
1708
+ - **Password login is off** (`[auth] allow_password = false`). Stored hashes are
1709
+ Argon2id PHC strings with a per-user salt (`printf '%s' "$PW" | wsh-server
1710
+ --hash-password`), compared in constant time; an unknown user and a wrong password
1711
+ cost the same and fail with the same message. Old unsalted `sha256:` entries are
1712
+ **refused** (logged at start-up, naming the user) unless `allow_legacy_sha256 = true`,
1713
+ which accepts them with a warning at every start-up. Refusing, not warning, is the
1714
+ default because a warning nobody reads leaves the weak hash live on every
1715
+ deployment that is not watched; the edit that turns password login back on is the
1716
+ natural moment to rehash.
1717
+
1718
+ What this does **not** protect against:
1719
+
1720
+ - **A rule you write is trusted.** A hostname rule (`"db.internal"`) allows that name
1721
+ to resolve to anything, including a restricted address; only the wildcard is
1722
+ held to public addresses. An address range or literal address rule allows
1723
+ exactly what it says.
1724
+ - **It is not per-key.** Every authorized key gets the same gateway. A key that
1725
+ should not have it should not be in `authorized_keys`.
1726
+ - **There is no bandwidth or request-rate limit** beyond `max_connections`
1727
+ (default 100 concurrent connections and listeners together), and a listener's
1728
+ port is chosen by the client within what the server's user may bind.
1729
+ - **Hashing protects the stored file, not the wire.** The password still travels
1730
+ inside the auth message (see above); only use password login over `wss://` or
1731
+ WebTransport. The per-address auth rate limit bounds how fast one address can
1732
+ make the server run Argon2id (19 MiB each); it is not a defence against many
1733
+ addresses.
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.
1309
1766
 
1310
1767
  - **A host that lives in a page (`createMemoryHost`, `@johnhenry/wsh/reverse`) is only as trustworthy as the page.** A
1311
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.36.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",
@@ -13,6 +13,10 @@
13
13
  "types": "./src/server/index.d.ts",
14
14
  "import": "./src/server/index.mjs"
15
15
  },
16
+ "./pipe-relay": {
17
+ "types": "./src/pipe-relay.d.ts",
18
+ "import": "./src/pipe-relay.mjs"
19
+ },
16
20
  "./memory": {
17
21
  "types": "./src/memory-host.d.ts",
18
22
  "import": "./src/memory-host.mjs"