@johnhenry/wsh 0.38.0 → 0.39.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
@@ -375,13 +375,30 @@ mistaken for (or smuggled as) a file-system path or an abstract-namespace name,
375
375
  consulted for it; the registered names are an allow-list by construction. `who` is the authenticated
376
376
  `{ username, fingerprint }`, so the embedder can authorise per call (throw to refuse, or `{ open, authorize(who) }`).
377
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`.
378
+ **Rust side.** The Rust `wsh-server` serves the same messages with the same policy (`[gateway]`, off unless
379
+ `enabled = true`; `gateway-unix` is advertised only when a socket is listed):
380
+
381
+ ```toml
382
+ [gateway]
383
+ enabled = true
384
+ unix_connect = ["/var/run/docker.sock", "/run/user/1000/wsh/"] # OpenUnix: exact path, "/dir/" prefix, or "@abstract" (Linux)
385
+ unix_listen = ["/run/user/1000/wsh/"] # ListenUnix: sockets a client may ask the host to create
386
+ unix_replace_stale = false # replace a stale socket file only if the request asks AND this is true
387
+ unix_max_listeners = 4 # per client connection
388
+ max_buffered_bytes = 4194304 # per connection, for a peer without gateway-credit (at least 262144)
389
+ max_client_buffered_bytes = 33554432
390
+ ```
391
+
392
+ The checks are the Node host's: paths judged after `realpath` of the parent, a `..` segment refused, the target must be a
393
+ socket and not a symlink, created sockets are `0600` and unlinked on close, a socket that something still accepts on is
394
+ never replaced, a file that is not a socket is never touched; a bad pattern (`/`, a relative path, `..`) stops the server
395
+ at start-up. `GatewayCredit` is served with 256 KiB per direction when the client lists `gateway-credit`; without it the
396
+ host closes a connection that has more than `max_buffered_bytes` of unconsumed client data (or the client more than
397
+ `max_client_buffered_bytes`). The `gateway_id` and `listener_id` tables are per client connection (before, one table was
398
+ shared by every client). A Rust host does not offer named endpoints.
399
+
400
+ The CLI forwards like OpenSSH (see [Rust implementation](#running-a-command-with-wsh)): `wsh -L /tmp/docker.sock:/var/run/docker.sock user@host`,
401
+ `wsh -N -L 2375:/var/run/docker.sock user@host`, `wsh -N -L /tmp/d.sock:endpoint=docker --via wss://relay/r/<id> user@host`.
385
402
 
386
403
  ### TLS (`wss://`) and host extensions
387
404
 
@@ -763,7 +780,16 @@ set from the operator's login at the relay) and the host's `accept` trusts it:
763
780
  fine for a relay you run, not for a shared one. Two opt-ins close that, and both
764
781
  are negotiated by feature strings so every released peer keeps working
765
782
  (the Rust relay never lists `operator-proof`, so the operator simply does not
766
- offer it there):
783
+ offer it there).
784
+
785
+ **Who is offered proof.** `ReverseConnect.features` is a field a released Rust host (`rust-v0.6` to `v0.8`) cannot decode
786
+ (`deny_unknown_fields`: it drops the connection, which looks like a timeout). So a peer lists `operator-proof` in its
787
+ registered capabilities when it can answer a challenge (JS hosts and, since `rust-v0.9`, Rust hosts with an identity),
788
+ `reverseConnect()` offers proof only to a peer whose record lists it (`proof: 'auto'`, looked up with `listPeers()`;
789
+ `peerCapabilities` skips the lookup, `proof: true` offers regardless, `proof: false` never), and the JS relay strips the
790
+ field for a peer that did not advertise it. `requirePeerProof` and `sealed` against such a peer fail at once with a
791
+ sentence and send nothing. A JS host from npm 0.36-0.38 does not list the capability yet, so proof to it needs an upgrade
792
+ of the host.
767
793
 
768
794
  ```js
769
795
  // host: do not take the operator's identity from the relay.
@@ -809,11 +835,32 @@ many bytes):
809
835
  | tell the host the operator is *absent* when it is present (`ReverseClose`) | yes | yes | yes |
810
836
  | learn the operator's and host's keys, usernames, and the sizes and timing of traffic | yes | yes | yes |
811
837
 
838
+ A Rust host (`wsh reverse`, `wsh agent run`) is in the right-hand column only with `--require-operator-proof`
839
+ and an operator that seals (`wsh reverse-connect --sealed`, or a JS operator with `{ sealed: true }`); with proof alone
840
+ a relay can still inject a plain `Open` stamped with the operator's fingerprint, exactly as the middle column says.
812
841
  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
842
+ sides; a host that does not require proof is exactly as exposed as before), the Rust `wsh-server` relay (it carries these
843
+ messages and seals nothing itself), and a compromised *operator* key (it proves the key, not the
815
844
  person). A relay can still refuse service by dropping the challenge.
816
845
 
846
+ #### A sealed session (#155, host: JS; client: the Rust CLI so far)
847
+
848
+ `createMemoryHost({ hostKey, dataStreams: false, sealSession: 'offer' | 'require' })` (and `createWshServer`, for a connection
849
+ accepted with `dataStreams: false`) seals the WHOLE session end to end. After login the client sends a `KeyExchange` whose
850
+ `session_id` is the connection's, signed with its login key and answered by the host with a signature of its host key (the
851
+ transcripts of the sealed bridge, bound to both identities and both ephemeral keys; hybrid X25519+ML-KEM-768). From then on every
852
+ message but the keepalive -- control messages, `GatewayData` for TCP / unix sockets / named endpoints, `GatewayCredit` -- is an
853
+ authenticated encrypted frame (`EncryptedFrame`, channel 0), so flow-control credit works as before. A plain message is not heard
854
+ once the session is sealed, and a frame that does not open (flipped bit, replay, reorder) closes it. Features: `e2e-session`
855
+ (offered), `e2e-session-required` (the host serves nothing on a session that is not sealed, and no password login). The Rust CLI
856
+ seals with `--sealed` (or on its own when the host says `e2e-session-required`) and refuses a host that does not offer it: no silent
857
+ downgrade. Only `--sealed` is a guarantee: sealing "on its own" rests on a `ServerHello` feature that a relay can strip before
858
+ login, so a client that must never talk in the clear passes `--sealed` (against a host that requires sealing, a stripped client is
859
+ refused, but what it sent before the refusal -- its commands, if any -- was already readable). What it does NOT cover: the handshake before login (the user name, the login public key and the host key proof are
860
+ readable by the relay; the signed key exchange is not secret), the sizes and timing of traffic, a host whose connection has client-opened
861
+ QMux data streams (not offered there), and a denial of service (a relay can always drop or cut). The JS client has no sealed
862
+ session yet, so against a JS client use a host that only `'offer'`s.
863
+
817
864
  #### A pipe relay (`@johnhenry/wsh/pipe-relay`, #118)
818
865
 
819
866
  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
@@ -843,7 +890,10 @@ for nothing, and the rendezvous id is the only thing standing between the host's
843
890
  an impostor that reaches the id first is still a stranger to the operator, who must pin the host key
844
891
  (`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
892
  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
893
+ (per-session `initiateE2E`, or the **sealed session** below); it cannot forge the operator's signature or the host's.
894
+ **Until you seal the session, treat a pipe relay as trusted for secrecy AND integrity**: it can read every control message and
895
+ all gateway and endpoint data (`GatewayData`: TCP, unix sockets, named endpoints) and alter forwarded bytes after the handshake
896
+ (#155). Pin the host key, require channel binding, use `wss://` to a relay you trust, or seal the session. It can drop, delay or
847
897
  cut a connection, and it sees who dials which id and how much they send.
848
898
 
849
899
  *CLI side (#145).* `wsh --via wss://relay/r/<id> user@host [command...]` dials the operator side
@@ -1272,7 +1322,7 @@ fs_max_file_bytes = 67108864
1272
1322
  Key options apply as they do to other channels: a key restricted to a forced
1273
1323
  command opens no rpc channel, and `wsh-fs` needs the `file-transfer` scope
1274
1324
  (`permit-file-transfer` under `restrict`). `host.info` reports the crate version
1275
- and `hostFingerprint: null` (the Rust server has no host key). The JS client
1325
+ and `hostFingerprint: null` unless `[server] host_key` is configured. The JS client
1276
1326
  needs nothing new: it reads `rpc` from `ServerHello`, and its file helpers prefer
1277
1327
  `wsh-fs` automatically once the server offers it.
1278
1328
 
@@ -1432,7 +1482,7 @@ instead of dragging its own toolchain and CI job into an unrelated
1432
1482
  browser-app repo. It was previously deleted from clawser by accident
1433
1483
  (2026-03-14) and restored (2026-07-05) before this move.
1434
1484
 
1435
- Four crates, workspace-versioned (currently `0.7.0`):
1485
+ Four crates, workspace-versioned (currently `0.10.0`):
1436
1486
 
1437
1487
  | Crate | Kind | Description |
1438
1488
  |-------|------|--------------|
@@ -1457,6 +1507,36 @@ disconnects. `wsh connect` ends when the remote session does. Diagnostics go to
1457
1507
  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
1508
  `ws://` URL is accepted only for a loopback host.
1459
1509
 
1510
+ ### Forwarding with `wsh -L` / `-R` / `-N`
1511
+
1512
+ Modelled on OpenSSH. The forwards live as long as the connection does (`wsh -L ... user@host` also runs the command or
1513
+ shell; `-N` only forwards, until Ctrl-C), work with `--via` (the pipe relay carries them like anything else), and may be
1514
+ repeated:
1515
+
1516
+ ```sh
1517
+ wsh -L 8080:db.internal:5432 alice@host # [bind_addr:]port:host:hostport (the HOST connects to db.internal)
1518
+ wsh -N -L /tmp/docker.sock:/var/run/docker.sock alice@host # local unix socket -> a unix socket on the host
1519
+ wsh -N -L 127.0.0.1:2375:/var/run/docker.sock alice@host # local TCP port -> a unix socket on the host
1520
+ wsh -N -L /tmp/db.sock:db.internal:5432 alice@host # local unix socket -> TCP the host reaches
1521
+ wsh -N -L /tmp/docker.sock:endpoint=docker --via wss://relay/r/<id> alice@tab.example # a NAMED ENDPOINT of an in-page host
1522
+ wsh -N -R /run/user/1000/wsh/app.sock:127.0.0.1:3000 alice@host # the HOST listens on a unix socket; connections come here
1523
+ wsh -N -R 9000:localhost:3000 alice@host # the host listens on a TCP port (loopback by default)
1524
+ ```
1525
+
1526
+ A named endpoint is written `endpoint=NAME` as the remote end of `-L` (`NAME`: letters, digits, `.`, `_`, `-`; at most 64).
1527
+ The `=` cannot occur in a host name, a port or a path, so it can never be mistaken for a host called "endpoint" (that is
1528
+ `endpoint:80`), and `@NAME` is already the Linux abstract-namespace socket (`-L 8080:@name`). A host with no file system
1529
+ (an in-page host) offers endpoints instead of unix sockets; `wsh -L ...:endpoint=docker` plus `DOCKER_HOST=unix:///tmp/docker.sock`
1530
+ is the shape of reaching a daemon behind one. `-R` cannot name an endpoint (a host offers those, it does not listen on them).
1531
+
1532
+ Local TCP listeners bind `127.0.0.1` unless `bind_addr` says otherwise (`*` or `0.0.0.0` listens on every interface, and `wsh`
1533
+ warns). Local unix sockets are created `0600`, removed on exit (a killed `wsh` leaves its file), and an existing file at the
1534
+ path is **refused** unless `--replace-socket` is given, which replaces only a stale socket: never a live one, never a file that
1535
+ is not a socket. With `-R`, `--replace-socket` asks the host to replace its own stale socket (its policy decides). A host that
1536
+ cannot do what a forward needs says so (`this host does not offer unix-socket forwarding`, `no such endpoint`, `not allowed by
1537
+ the gateway policy`); a malformed spec exits with status 2 before anything is dialled. Up to 128 forwarded connections are
1538
+ open at once. `-L`/`-R`/`-N` apply to `wsh [user@]host [command...]` and `wsh connect` only.
1539
+
1460
1540
  ### Capability matrix: JS SDK vs Rust CLI/client
1461
1541
 
1462
1542
  Two implementations of one protocol will always have *some* asymmetry --
@@ -1470,7 +1550,7 @@ than left to be found.
1470
1550
  | Upload/download | `WshClient.upload()`/`.download()` | `file_transfer::upload()`/`download()`, `wsh scp` | **Wire-unified**: `FileChunk` over a `'file'`-kind channel (wsh #13) |
1471
1551
  | Remove a remote file | `WshClient.fileRemove()` | `file_transfer::remove()`, `wsh sftp`'s `rm` | **Wire-unified**: `FileOp`/`FileResult` (`op: "remove"`) -- refused today by every `wsh-server` release ("not yet implemented"), the same refusal on both sides |
1472
1552
  | 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 |
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" |
1553
+ | Host identity / TOFU | `WshKnownHosts` (localStorage-backed) | `KnownHosts`/`HostStatus` (`~/.wsh/known_hosts`-backed); the client sends `host-key-nonce`, verifies `host-key`/`host-key-sig`, pins only a proven key, and a first use needs `--accept-new-host-key` or a yes at a terminal (`--require-host-key` refuses a host with no proof); `wsh-server` has an opt-in host key (`[server] host_key`) | **Unified** (wsh #59, #145): both pin a PROVEN `ServerHello.host_fingerprint`. A Rust server with no `host_key` configured (the default, so released clients keep working) proves nothing |
1474
1554
  | 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 |
1475
1555
  | 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
1556
  | 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 |
@@ -1480,13 +1560,14 @@ than left to be found.
1480
1560
  | 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) |
1481
1561
  | 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 |
1482
1562
  | 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 |
1563
+ | Unix-domain socket forwarding, both directions; named endpoints (#120) | `client.openUnix()`, `listenUnix()`, `forwardUnix()` (Node: `-L`/`-R` shapes with unix and TCP ends mixed), `openEndpoint()`; host: `gateway: { unix, endpoints }`, `createMemoryHost({ endpoints })` | `wsh-server` serves `OpenUnix`/`ListenUnix` (`[gateway] unix_connect`, `unix_listen`, `unix_replace_stale`, `unix_max_listeners`; same policy as the Node host); `wsh-client` has `open_tcp`/`open_unix`/`open_endpoint`/`listen_unix`/`listen_tcp`; CLI `wsh -L` / `-R` / `-N` with TCP, unix and `endpoint=NAME` ends, also through `--via` | **Wire-unified, both directions** (#145). A Rust host does not offer named endpoints (an in-page host does); the CLI reaches them. See [Forwarding with `wsh -L`](#forwarding-with-wsh--l---r---n) |
1564
+ | Gateway flow control (#123) | credit per connection (`GatewayCredit`, feature `gateway-credit`); host caps for peers without it | `wsh-server` and `wsh-client`: 256 KiB per direction when both list `gateway-credit`; without it, per-connection and per-client byte caps (`max_buffered_bytes` 4 MiB, `max_client_buffered_bytes` 32 MiB) close the connection that exceeds them | **Wire-unified, negotiated**; an older peer on either side keeps working under the caps. `OpenUdp` flows are metered too (a datagram without credit is dropped) |
1565
+ | TCP reverse tunnels (`ListenRequest`, #98) | `@johnhenry/wsh/server` `gateway.reverse` (off by default; loopback unless the operator lists addresses; port allow-list, nothing below 1024 unless named; bounded listeners/connections/backlog/idle); client `listenTcp(port, { onConnection })` | `wsh-server` `[gateway] enable_reverse_tunnels` + `reverse_bind_addr` (off by default, loopback, client `bind_addr` ignored); no port allow-list; no per-listener connection, backlog or idle bounds beyond `max_connections` | **Wire-unified** (`ListenRequest`/`ListenOk`/`ListenFail`/`InboundOpen`/`InboundAccept`; the JS host sends the real `peer_addr`/`peer_port`). **Rust still needs**: a port allow-list and per-client listener / per-listener connection / idle bounds to match the JS host. Accepted connections are metered by `gateway-credit` now |
1486
1566
  | 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
1567
  | 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 |
1568
+ | Operator proof to the peer, sealed bridge, signed initiator half (#117) | `reverseConnect(.., { sealed, requirePeerProof })`; host `createReverseHost({ requireOperatorProof })`; relay lists `operator-proof` | **Operator proof: yes.** The Rust relay lists `operator-proof` and carries `ReverseChallenge`/`ReverseProof`/`ReverseConnect.features`; `wsh reverse-connect` answers a challenge (`--operator-proof` / `--no-operator-proof`; by default only for a peer that registered the `operator-proof` capability, because a released Rust host cannot decode the field); `wsh reverse` / `wsh agent run` challenge, verify BEFORE accepting, and take `--require-operator-proof` and `--allow-operator`. **Sealed bridge and both signed `KeyExchange` halves: yes** (`wsh reverse-connect --sealed`; a host with an identity states `e2e` / `e2e-sign` / `e2e-sealed` in its `ReverseAccept` once it has proven the operator). The exchange is byte-identical to JS (transcripts compared against vectors printed by the JS code), hybrid X25519+ML-KEM-768 negotiated exactly as JS does, X25519 when the peer lists no ML-KEM key. A host started with `--require-operator-proof` REQUIRES the sealed bridge (the JS rule): until the key exists it hears and sends nothing but the key exchange, and drops a bridge that has not sealed in 10 s; an operator that does not seal gets no answer to its plain messages. Every message that would cross the relay travels as an `EncryptedFrame` on channel 0; a plain message (wrapped or not) is dropped; **a frame that does not open (tampered, replayed, reordered) closes the bridge** (stricter than the JS host, which drops the frame and ignores the rest). Not covered: a direct or pipe-relayed connection, and `GatewayData` outside a reverse bridge (#155) | **Wire-unified, negotiated** (`ReverseConnect.features`, `operator-proof`, `e2e-sealed`); both implementations seal a reverse bridge |
1569
+ | Channel binding of the login signature (#119) | `requireChannelBinding` (client and server); kinds `host`, `cert-hash`, `tls-exporter` | Kind `host`: the client binds to the proven host key (`--require-channel-binding`, and it honours `channel-binding-required`), and `wsh-server` offers it and can require it (`[server] require_channel_binding`, needs `host_key`). `cert-hash` and `tls-exporter`: not in Rust (the Rust WebTransport client has no certificate-hash pinning; `ConnectConfig.cert_hash` binds it if a caller supplies one) | **Wire-unified, negotiated** (`channel-binding:<kind>` features); verified against the spec's test vectors |
1570
+ | Sealed session: any authenticated connection incl. gateway/endpoint data (#155) | host `sealSession: 'offer' \| 'require'` (stage b); the JS client does not seal yet | `wsh --sealed ...` (or automatic against `e2e-session-required`) seals a direct or pipe-relayed session; `wsh-server` does not offer it yet | **Wire-unified, negotiated** (`e2e-session`, `e2e-session-required`, `KeyExchange` for the connection's session id, `EncryptedFrame` channel 0) |
1490
1571
  | 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
1572
  | `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
1573
  | `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 |
@@ -1649,6 +1730,11 @@ out explicitly below rather than left to be discovered.
1649
1730
  treat `initiateE2E` as key agreement, not confidentiality, unless you've
1650
1731
  separately confirmed the session has sealing enabled.
1651
1732
  - **Host identity (TOFU) has a known, named gap (wsh #59).**
1733
+ **Update (#145): the Rust `wsh-server` now has an opt-in host key
1734
+ (`[server] host_key = "<path>"`, created 0600 on first start; see the
1735
+ capability matrix) and the Rust client verifies the proof; the paragraph
1736
+ below describes the state before that and still applies to a Rust server
1737
+ with no `host_key` configured, which proves nothing.**
1652
1738
  `ServerHello.host_fingerprint` is the spec's formal host-identity slot:
1653
1739
  the SHA-256 fingerprint of a server's persistent Ed25519 host key, meant
1654
1740
  to be pinned across connections the way SSH pins a host key. **As of 0.19
@@ -1746,23 +1832,32 @@ What this does **not** protect against:
1746
1832
  `Signal` goes only to the process group of a channel the sending connection
1747
1833
  controls. This does not make a command safe to run: an authorized key still
1748
1834
  runs commands as the server's user.
1835
+ - **Forwarding (`wsh -L`/`-R`, `OpenUnix`, `ListenUnix`) lends the host's reach, not a sandbox.** Listing a socket in
1836
+ `unix_connect` gives every authorized key everything that socket's service can do: Docker's socket is root on the
1837
+ machine. The policy checks the path, not the peer, and cannot close the instant between the check and the connect
1838
+ (allow only directories no other local user can write to). It is not per key and has no rate limit beyond
1839
+ `max_connections`. `wsh -L` publishes a local port or socket to whoever can reach it: loopback by default, but an explicit
1840
+ `bind_addr` of `0.0.0.0` (the CLI warns) hands the forward to the network, and a local unix socket is `0600` only against
1841
+ other users, not against your own processes. A forwarded connection is as private as the wsh connection under it (a pipe
1842
+ relay sees it unless the legs are TLS). The Rust host binds a created socket inside a private `0700` directory and links it into place, so it is never visible with a looser mode and the process umask is not touched.
1749
1843
  - **Rust `wsh-server`'s `AuthOk.ttl` is 0 and its `token` is opaque** (as the
1750
1844
  JS host's, above): nothing is promised or enforced at connection level; do not
1751
1845
  treat the token as a credential.
1752
1846
  - **`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.
1847
+ still not sealed** (the sealed bridge of `wsh reverse-connect --sealed` covers
1848
+ reverse bridges only; #155 tracks sealing a direct or pipe-relayed connection and
1849
+ its gateway data). The Rust client now verifies the host-key proof
1850
+ (`host-key` / `host-key-sig` over its own `host-key-nonce`) before sending
1851
+ any credential, records only a PROVEN key in `known_hosts`, binds the login
1852
+ signature to that key (channel binding `host`), and refuses a changed key
1853
+ always. A replayed `ServerHello` or an impostor's key is refused as the JS
1854
+ client refuses it. What is still unprotected: the bridge is not sealed
1855
+ end to end (a pipe-relayed session has no sealing layer yet, #155), so the relay sees
1856
+ session traffic in the clear unless the legs are TLS and it is trusted not
1857
+ to read them (it terminates each leg's TLS), and it can stamp an identity on
1858
+ a plain message after the handshake. A host with no host key proves nothing:
1859
+ the CLI connects to it (as every release did) unless `--require-host-key`
1860
+ says otherwise.
1766
1861
 
1767
1862
  - **A host that lives in a page (`createMemoryHost`, `@johnhenry/wsh/reverse`) is only as trustworthy as the page.** A
1768
1863
  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.38.0",
3
+ "version": "0.39.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",
@@ -72,7 +72,7 @@
72
72
  },
73
73
  "scripts": {
74
74
  "test": "node --test test/*.test.mjs",
75
- "test:rust": "node --test test/rust/*.test.mjs",
75
+ "test:rust": "node --test --test-timeout=180000 test/rust/*.test.mjs",
76
76
  "test:browser": "playwright test --config test/browser/playwright.config.mjs",
77
77
  "size": "node scripts/bundle-size.mjs",
78
78
  "typecheck": "tsc --noEmit -p tsconfig.json",
@@ -21,6 +21,7 @@ export const BRIDGE_CHANNEL_ID = 0;
21
21
 
22
22
  export class SealedBridge {
23
23
  #key;
24
+ #scope;
24
25
  #sessionId;
25
26
  #sendTag;
26
27
  #recvTag;
@@ -30,9 +31,13 @@ export class SealedBridge {
30
31
  #inChain = Promise.resolve();
31
32
 
32
33
  /**
33
- * @param {{ key: CryptoKey, sessionId: string, role: 'initiator' | 'responder' }} p - `initiator` is the operator
34
+ * @param {{ key: CryptoKey, sessionId: string, role: 'initiator' | 'responder', scope?: 'bridge' | 'session' }} p -
35
+ * `initiator` is the operator. `scope: 'session'` (#155) seals a whole direct or pipe-relayed connection, so any
36
+ * message may be inside a frame; the default, a bridge, accepts only what a relay may forward.
34
37
  */
35
- constructor({ key, sessionId, role }) {
38
+ constructor({ key, sessionId, role, scope = 'bridge' }) {
39
+ if (scope !== 'bridge' && scope !== 'session') throw new TypeError("SealedBridge: scope must be 'bridge' or 'session'");
40
+ this.#scope = scope;
36
41
  if (role !== 'initiator' && role !== 'responder') throw new TypeError("SealedBridge: role must be 'initiator' or 'responder'");
37
42
  this.#key = key;
38
43
  this.#sessionId = sessionId;
@@ -68,7 +73,7 @@ export class SealedBridge {
68
73
  const plain = await openFrame(this.#key, this.#sessionId, this.#recvCounter, { nonce: frame.nonce, ciphertext: frame.ciphertext, expectedRoleTag: this.#recvTag });
69
74
  this.#recvCounter += 1;
70
75
  const inner = cborDecode(plain);
71
- if (!inner || typeof inner.type !== 'number' || inner.type === MSG.RELAY_FORWARD || !isRelayForwardable(inner.type)) throw new Error('sealed message of a type that may not cross a bridge');
76
+ if (!inner || typeof inner.type !== 'number' || inner.type === MSG.RELAY_FORWARD || (this.#scope === 'bridge' && !isRelayForwardable(inner.type))) throw new Error('sealed message of a type that may not cross a bridge');
72
77
  return inner;
73
78
  });
74
79
  this.#inChain = run.catch(() => {});
package/src/client.mjs CHANGED
@@ -1234,6 +1234,8 @@ export class WshClient {
1234
1234
  * @param {object} [opts.expose] - Capabilities to expose { shell, exec, fs, tools }
1235
1235
  * @param {string} [opts.peerType]
1236
1236
  * @param {string} [opts.shellBackend]
1237
+ * @param {boolean} [opts.operatorProof=true] list `operator-proof` in the registered capabilities (a key login only): this
1238
+ * peer can answer an operator's challenge. A hand-written handler that never challenges passes `false`.
1237
1239
  * @param {boolean} [opts.supportsAttach]
1238
1240
  * @param {boolean} [opts.supportsReplay]
1239
1241
  * @param {boolean} [opts.supportsEcho]
@@ -1253,6 +1255,7 @@ export class WshClient {
1253
1255
  supportsReplay,
1254
1256
  supportsEcho,
1255
1257
  supportsTermSync,
1258
+ operatorProof = true,
1256
1259
  ...hostKeyOpts
1257
1260
  } = {}) {
1258
1261
  // Authenticate normally first.
@@ -1267,6 +1270,9 @@ export class WshClient {
1267
1270
 
1268
1271
  // Export public key for peer identification.
1269
1272
  const cred = await resolveSigner({ keyPair, signer });
1273
+ // A peer that can answer an operator's challenge says so in its signed record: a released peer cannot decode
1274
+ // `ReverseConnect.features`, so an operator (and the relay) states the field only to a peer that lists this.
1275
+ if (cred && operatorProof) capabilities.push(OPERATOR_PROOF_FEATURE);
1270
1276
  this.#signer = cred;
1271
1277
  this.#loginUsername = username;
1272
1278
  let publicKey = null;
@@ -1359,12 +1365,21 @@ export class WshClient {
1359
1365
  /**
1360
1366
  * Initiate a reverse connection and wait for accept/reject.
1361
1367
  *
1368
+ * Offering proof (`ReverseConnect.features: ['operator-proof']`) needs a key login, a relay that carries it, and a peer
1369
+ * whose registered record lists `operator-proof`: a released Rust host (v0.6 to v0.8) rejects the field outright. Options:
1370
+ * - `proof`: `'auto'` (default; offer to a peer that advertises it, looked up with `listPeers()`), `true` (offer anyway;
1371
+ * the relay still strips it for a peer that did not advertise), `false` (never offer).
1372
+ * - `requirePeerProof` / `sealed`: fail at once, with a sentence, when the peer does not advertise it.
1373
+ * - `peerCapabilities`: the peer's capability list, when the caller already has it (skips the lookup).
1374
+ *
1362
1375
  * @param {string} targetFingerprint
1363
1376
  * @param {number} [timeout=10000]
1377
+ * @param {{ proof?: 'auto'|boolean, requirePeerProof?: boolean, sealed?: boolean|object, peerCapabilities?: string[] }} [opts]
1364
1378
  * @returns {Promise<object>}
1365
1379
  */
1366
- async reverseConnect(targetFingerprint, timeout = DEFAULT_OPEN_TIMEOUT, { proof = 'auto', requirePeerProof = false, sealed = false } = {}) {
1380
+ async reverseConnect(targetFingerprint, timeout = DEFAULT_OPEN_TIMEOUT, { proof = 'auto', requirePeerProof = false, sealed = false, peerCapabilities } = {}) {
1367
1381
  this.#assertAuthenticated('reverseConnect');
1382
+ if (proof !== 'auto' && typeof proof !== 'boolean') throw new TypeError("reverseConnect: proof must be 'auto', true or false");
1368
1383
 
1369
1384
  // Proving this operator's identity to the PEER (wsh #117) needs a relay that carries the challenge and a key to sign with.
1370
1385
  const relayCarriesProof = this.#serverFeatures.includes(OPERATOR_PROOF_FEATURE);
@@ -1373,7 +1388,6 @@ export class WshClient {
1373
1388
  throw new Error(`reverseConnect: this relay does not carry operator proof (no "${OPERATOR_PROOF_FEATURE}" in its features), so ${sealOpts ? 'a sealed bridge' : 'proof'} is not available -- nothing was sent`);
1374
1389
  }
1375
1390
  if ((sealOpts || requirePeerProof || proof === true) && !this.#signer) throw new Error('reverseConnect: proof needs a key login (a password login has nothing to sign with)');
1376
- const offerProof = proof !== false && relayCarriesProof && !!this.#signer;
1377
1391
 
1378
1392
  // A sealed bridge sends nothing that names a command, a path or a session before the key exists: from here on a
1379
1393
  // message the relay may forward is refused locally until the bridge key is in place.
@@ -1395,6 +1409,24 @@ export class WshClient {
1395
1409
  let response = null;
1396
1410
  let challenge = null;
1397
1411
  try {
1412
+ // A released peer (rust-v0.6 to v0.8) drops the connection on a ReverseConnect with a field it does not know, so the
1413
+ // offer is made only to a peer whose registered record lists `operator-proof` ('auto'), or when the caller insists
1414
+ // (`proof: true`). The relay checks the same on its side and strips the field for a peer that did not advertise it.
1415
+ let peerCanProve = proof === true;
1416
+ if (!peerCanProve && proof === 'auto' && relayCarriesProof && this.#signer) {
1417
+ let caps = peerCapabilities;
1418
+ if (!Array.isArray(caps)) {
1419
+ const peers = await this.listPeers(timeout).catch(() => []);
1420
+ const hits = peers.filter((p) => p.fingerprint === targetFingerprint || (targetFingerprint.length >= 8 && String(p.fingerprint ?? '').startsWith(targetFingerprint)));
1421
+ caps = hits.length === 1 ? hits[0].capabilities : [];
1422
+ }
1423
+ peerCanProve = caps.includes(OPERATOR_PROOF_FEATURE);
1424
+ if ((sealOpts || requirePeerProof) && !peerCanProve) {
1425
+ throw new Error(`reverseConnect: the peer does not advertise "${OPERATOR_PROOF_FEATURE}" in its registered record (a host older than operator proof, or one that cannot answer a challenge), so ${sealOpts ? 'a sealed bridge' : 'proof'} is not available -- nothing was sent`);
1426
+ }
1427
+ }
1428
+ const offerProof = proof !== false && relayCarriesProof && !!this.#signer && peerCanProve;
1429
+
1398
1430
  const ownFingerprint = this.#signer ? await computeFingerprint(this.#signer.publicKeyRaw) : null;
1399
1431
  // Register before sending: the answer can follow the request closely.
1400
1432
  const first = this.#waitForMessage(
@@ -1425,7 +1457,7 @@ export class WshClient {
1425
1457
  }
1426
1458
 
1427
1459
  if (response.type === MSG.REVERSE_ACCEPT) {
1428
- if (requirePeerProof && !challenge) throw new Error('reverseConnect: the peer did not prove its identity (requirePeerProof) -- nothing was sent over the bridge');
1460
+ if (requirePeerProof && !challenge) throw new Error(`reverseConnect: the peer did not prove its identity (requirePeerProof)${proof === true ? `; the relay does not pass the offer to a peer that does not advertise "${OPERATOR_PROOF_FEATURE}"` : ''} -- nothing was sent over the bridge`);
1429
1461
  if (challenge && response.target_fingerprint !== challenge.peerFingerprint) throw new Error('reverseConnect: the relay named a different peer than the one that signed the challenge');
1430
1462
  if (sealOpts) {
1431
1463
  if (!challenge) throw new Error('reverseConnect: a sealed bridge needs the peer to answer with a challenge (does it require operator proof support?)');
@@ -151,7 +151,7 @@ export class E2EResponder {
151
151
 
152
152
  /**
153
153
  * @param {object} [opts]
154
- * @param {CryptoKey | null} [opts.signKey] - long-term Ed25519 private key; given, the reply is signed
154
+ * @param {CryptoKey | { sign: (data: Uint8Array) => Promise<Uint8Array> } | null} [opts.signKey] - long-term Ed25519 private key (or a signer); given, the reply is signed
155
155
  * @param {boolean} [opts.hybrid=true] - offer X25519+ML-KEM-768 when the initiator asks for it
156
156
  * @param {Uint8Array | null} [opts.identity] - this responder's raw 32-byte identity key (what an initiator signs as `responderIdentity`)
157
157
  * @param {{ publicKey: Uint8Array, require?: boolean } | null} [opts.initiator] - the operator's identity key, already
@@ -234,7 +234,9 @@ export class E2EResponder {
234
234
  kemPublicKey: localKem?.publicKey,
235
235
  };
236
236
  if (this.#sign) {
237
- reply.signature = await signBytes(this.#sign, keyExchangeTranscript({ sessionId, algorithm, initiatorKey: peerPub, responderKey: localPub }));
237
+ const transcript = keyExchangeTranscript({ sessionId, algorithm, initiatorKey: peerPub, responderKey: localPub });
238
+ // a CryptoKey, or a signer ({ sign }) such as a host key that is not extractable or lives elsewhere
239
+ reply.signature = typeof this.#sign.sign === 'function' ? await this.#sign.sign(transcript) : await signBytes(this.#sign, transcript);
238
240
  }
239
241
  await out(keyExchange(reply));
240
242
 
package/src/index.d.ts CHANGED
@@ -1946,6 +1946,8 @@ export interface WshConnectReverseOptions {
1946
1946
  fs?: boolean;
1947
1947
  tools?: boolean;
1948
1948
  };
1949
+ /** List `operator-proof` in the registered capabilities (key logins only; default true): this peer can answer an operator's challenge. */
1950
+ operatorProof?: boolean;
1949
1951
  peerType?: string;
1950
1952
  shellBackend?: string;
1951
1953
  supportsAttach?: boolean;
@@ -2416,8 +2418,10 @@ export class WshClient {
2416
2418
  targetFingerprint: string,
2417
2419
  timeout?: number,
2418
2420
  opts?: {
2419
- /** `'auto'` (default): prove when the relay carries it and the peer asks; `false`: never; `true`: refuse if the relay cannot carry it. */
2421
+ /** `'auto'` (default): offer proof when the relay carries it and the peer's registered record lists `operator-proof`; `false`: never; `true`: offer regardless of the record (the relay still strips it for a peer that did not advertise it) and refuse if the relay cannot carry it. */
2420
2422
  proof?: 'auto' | boolean;
2423
+ /** The peer's capability list, when the caller already holds it (skips the `listPeers()` lookup `'auto'` makes). */
2424
+ peerCapabilities?: string[];
2421
2425
  /** Refuse the bridge unless the peer signed its challenge (so it proved its key to this operator). */
2422
2426
  requirePeerProof?: boolean;
2423
2427
  /**
@@ -75,6 +75,8 @@ export interface WshMemoryHostOptions {
75
75
  * Needs `hostKey`; a client older than 0.36 cannot satisfy it.
76
76
  */
77
77
  requireChannelBinding?: boolean | Array<'host'>;
78
+ /** #155: seal the whole session end to end (needs `hostKey`; offered where `dataStreams` is false). `'require'` serves nothing unsealed. */
79
+ sealSession?: false | 'offer' | 'require';
78
80
  onLog?: (line: string) => void;
79
81
  }
80
82
 
@@ -140,6 +140,12 @@ function createRegistry(sessions, log) {
140
140
  * @param {{ operate: Function, readWhole: Function, writeWhole: Function, writeAt: Function, openRange?: Function, maxFileBytes?: number }} [options.fs]
141
141
  * File operations, as `createFileAccess` in `@johnhenry/wsh/server` returns them (see `normalizeFileBackend` in
142
142
  * `host-backends.mjs`). Not a root path: confining paths is the backend's job.
143
+ * @param {false | 'offer' | 'require'} [options.sealSession=false] - #155: seal the whole session end to end (needs `hostKey` and
144
+ * `dataStreams: false`, which is how a page host is served). A client that asks (a signed `KeyExchange` for the connection's
145
+ * session id, features `e2e-session`) gets every message after login -- gateway and endpoint data included -- as an
146
+ * authenticated encrypted frame, so a relay that only copies bytes (a pipe relay) can neither read nor alter it; a frame that
147
+ * does not open closes the session. `'offer'` serves a client that does not ask in the clear; `'require'` (advertised as
148
+ * `e2e-session-required`) serves nobody who has not sealed, and no password login. The keepalive stays plain.
143
149
  * @param {true | CryptoKeyPair | { publicKey: Uint8Array | CryptoKey, sign: Function }} [options.hostKey]
144
150
  * This host's own identity, so clients can pin it (TOFU): a `CryptoKeyPair` (non-extractable is fine), a signer
145
151
  * `{ publicKey, sign(data) }`, or `true` for a fresh non-extractable key.
@@ -172,13 +178,15 @@ function createRegistry(sessions, log) {
172
178
  * `true` or `['host']`.
173
179
  * @param {(line: string) => void} [options.onLog]
174
180
  */
175
- export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, endpoints, dataStreams = true, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, onLog = () => {} } = {}) {
181
+ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, endpoints, dataStreams = true, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, sealSession = false, onLog = () => {} } = {}) {
176
182
  if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createMemoryHost: connectionTtlMs must be a non-negative number');
177
183
  if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
178
184
  throw new TypeError(`createMemoryHost: requireChannelBinding must be true, false or an array of kinds (${CHANNEL_BINDING_KINDS.join(', ')})`);
179
185
  }
180
186
  if (Array.isArray(requireChannelBinding) && requireChannelBinding.some((k) => k !== 'host')) throw new TypeError('createMemoryHost: requireChannelBinding can name only "host" (a memory host has no TLS connection or certificate to bind)');
181
187
  if (requireChannelBinding && !hostKey) throw new TypeError('createMemoryHost: requireChannelBinding needs a hostKey (the only thing a memory host can bind a login to)');
188
+ if (sealSession !== false && sealSession !== 'offer' && sealSession !== 'require') throw new TypeError("createMemoryHost: sealSession must be false, 'offer' or 'require'");
189
+ if (sealSession && !hostKey) throw new TypeError('createMemoryHost: sealSession needs a hostKey (the host signs its half of the key exchange with it)');
182
190
  if (exec === true) throw new TypeError('createMemoryHost: exec must be a function (run(command, io)); there is no shell to run `true` with');
183
191
  if (exec !== undefined && typeof exec !== 'function' && typeof exec?.run !== 'function') {
184
192
  throw new TypeError('createMemoryHost: exec must be a function or { run }');
@@ -201,7 +209,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
201
209
  const gatewayCfg = endpoints === undefined || endpoints === null ? null : normalizeEndpointGateway({ endpoints });
202
210
 
203
211
  const ready = Promise.all([buildAuthorizer(auth), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
204
- authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, log: onLog,
212
+ authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
205
213
  methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost,
206
214
  gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
207
215
  }));
@@ -34,9 +34,14 @@ import { GATEWAY_DATAGRAM_FEATURE } from '../gateway-datagram.mjs';
34
34
  import { OPERATOR_PROOF_FEATURE } from '../operator-proof.mjs';
35
35
  import { clientEnvFilter } from './client-env.mjs';
36
36
  import { acceptableBindings, bindingFeatures } from '../channel-binding.mjs';
37
+ import { SealedBridge } from '../bridge-seal.mjs';
37
38
  import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMessage, toHex } from '../host-key.mjs';
38
39
 
39
40
  export const STREAM_ANNOUNCE = 'stream-announce';
41
+ /** Host feature (#155): this host seals the whole session end to end when asked (a signed `KeyExchange` for the connection's session id). */
42
+ export const SESSION_SEAL_FEATURE = 'e2e-session';
43
+ /** Host feature: this host serves nothing on a session that is not sealed. */
44
+ export const SESSION_SEAL_REQUIRED_FEATURE = 'e2e-session-required';
40
45
 
41
46
  /**
42
47
  * The features a host built from `cfg` advertises (`ServerHello.features`, minus the host-key proof).
@@ -58,6 +63,8 @@ export function hostFeatures(cfg, { dataStreams = true } = {}) {
58
63
  if (cfg.relay.maxOperatorsPerPeer > 1) features.push(MULTI_OPERATOR_FEATURE);
59
64
  }
60
65
  if (cfg.e2e && !dataStreams) features.push(E2E_FEATURE, ...(cfg.e2e.signKey ? [E2E_SIGN_FEATURE] : []));
66
+ // A sealed session (#155) needs the host's identity to sign its half, and no client-opened streams (their bytes are not frames).
67
+ if (cfg.sealSession && cfg.hostKey && !dataStreams) features.push(SESSION_SEAL_FEATURE, ...(cfg.sealSession === 'require' ? [SESSION_SEAL_REQUIRED_FEATURE] : []));
61
68
  if (cfg.rpc && dataStreams && cfg.rpc.protocols.size) {
62
69
  features.push(RPC_FEATURE, ...[...cfg.rpc.protocols.keys()].map(rpcProtocolFeature), RPC_MAX_MESSAGE_PREFIX + cfg.rpc.maxMessageBytes);
63
70
  }
@@ -155,6 +162,13 @@ export function createConnectionFactory(cfg) {
155
162
  /** Ends the connection at `connectionTtlMs` after authentication (#125). */
156
163
  let ttlTimer = null;
157
164
 
165
+ // A sealed session (#155): after login, a signed KeyExchange for this connection's session id seals everything
166
+ // that follows (control messages, gateway and endpoint data included) as EncryptedFrames on channel 0.
167
+ const sealOn = !!cfg.sealSession && !!cfg.hostKey && !dataStreams;
168
+ const sealRequired = sealOn && cfg.sealSession === 'require';
169
+ /** @type {{ bridge: SealedBridge | null, responder: E2EResponder | null }} */
170
+ const sealed = { bridge: null, responder: null };
171
+
158
172
  // The gateway needs Node sockets, so `gateway.mjs` is not imported here (a browser host must not pull it in):
159
173
  // the embedder that has them (`createWshServer`) passes `cfg.createGatewaySession` along with `cfg.gateway`; a
160
174
  // host in a page passes the endpoints-only session of `gateway-core.mjs` (`createMemoryHost({ endpoints })`).
@@ -198,6 +212,14 @@ export function createConnectionFactory(cfg) {
198
212
  };
199
213
 
200
214
  const deliver = (msg) => {
215
+ // Sealed: everything but the keepalive leaves as a frame, in the order it was sent (the bridge seals in call order).
216
+ if (sealed.bridge && msg.type !== MSG.PING && msg.type !== MSG.PONG) {
217
+ return sealed.bridge.seal(msg).then((frame) => deliverRaw(frame), (e) => { log(`could not seal: ${e.message}`); });
218
+ }
219
+ return deliverRaw(msg);
220
+ };
221
+
222
+ const deliverRaw = (msg) => {
201
223
  if (state.closed) return Promise.resolve();
202
224
  if (sendMessage) {
203
225
  try { return Promise.resolve(sendMessage(msg)).catch(() => {}); } catch { return Promise.resolve(); }
@@ -266,6 +288,11 @@ export function createConnectionFactory(cfg) {
266
288
  async function handle(m) {
267
289
  if (state.closed) return;
268
290
  if (!state.authed) return handleAuth(m);
291
+ if (sealOn) {
292
+ const inner = await sealedInput(m);
293
+ if (inner === undefined) return;
294
+ m = inner;
295
+ }
269
296
  if (await handleRelay(m)) return;
270
297
  if (gateway && await gateway.handle(m)) return;
271
298
  switch (m.type) {
@@ -363,6 +390,7 @@ export function createConnectionFactory(cfg) {
363
390
  } else {
364
391
  return refuse(`unsupported auth method ${JSON.stringify(method)}`);
365
392
  }
393
+ if (cfg.sealSession === 'require' && cfg.hostKey && !dataStreams && method !== 'pubkey') return refuse('this host requires a sealed session, which needs a key login');
366
394
  state.username = user;
367
395
  state.method = method;
368
396
  gateway?.setPeerFeatures(m.features);
@@ -438,12 +466,53 @@ export function createConnectionFactory(cfg) {
438
466
  if (!allowed) return refuse('key not authorized');
439
467
  state.authed = true;
440
468
  state.fingerprint = fp;
469
+ state.publicKey = m.public_key;
441
470
  state.nonce = null;
442
471
  await grantAuth();
443
472
  log(`authenticated ${state.username} (${fp.slice(0, 12)}...)`);
444
473
  }
445
474
  }
446
475
 
476
+ /**
477
+ * The sealed-session gate (#155) for a message from an authenticated peer: the message to handle, or undefined
478
+ * when it was consumed (the key exchange) or refused. A plain message is not heard once the session is sealed
479
+ * (a relay in the middle can inject any), and with `sealSession: 'require'` not before either.
480
+ */
481
+ async function sealedInput(m) {
482
+ if (sealed.bridge) {
483
+ if (m.type === MSG.PING) return m;
484
+ if (!sealed.bridge.isFrame(m)) { log(`dropped a plaintext message (type ${m.type}) on a sealed session`); return undefined; }
485
+ try { return await sealed.bridge.open(m); } catch (e) {
486
+ log(`a sealed frame did not open (${e.message}): closing the session`);
487
+ shutdown('sealed frame did not open');
488
+ return undefined;
489
+ }
490
+ }
491
+ if (m.type === MSG.KEY_EXCHANGE && m.session_id === state.sessionId) {
492
+ if (!state.publicKey) { log('sealed session refused: no login key to authenticate the initiator with'); shutdown('sealed session needs a key login'); return undefined; }
493
+ sealed.responder ??= new E2EResponder({
494
+ signKey: cfg.hostKey, hybrid: true, identity: cfg.hostKey.publicKey,
495
+ initiator: { publicKey: state.publicKey, require: true },
496
+ });
497
+ try {
498
+ const result = await sealed.responder.respond(m, (reply) => deliverRaw(reply));
499
+ if (result.key) {
500
+ sealed.bridge = new SealedBridge({ key: result.key, sessionId: state.sessionId, role: 'responder', scope: 'session' });
501
+ log(`session sealed${result.hybrid ? ' (hybrid)' : ''}`);
502
+ }
503
+ } catch (e) { log(`sealed session refused: ${e.message}`); shutdown('sealed session key exchange failed'); }
504
+ return undefined;
505
+ }
506
+ if (m.type === MSG.PING) return m;
507
+ if (sealRequired) {
508
+ log(`refused a plaintext message (type ${m.type}): this host requires a sealed session`);
509
+ await deliverRaw(errorMsg({ code: 1, message: 'this host requires a sealed session (e2e-session-required)' }));
510
+ setTimeout(() => shutdown('sealed session required'), 50);
511
+ return undefined;
512
+ }
513
+ return m;
514
+ }
515
+
447
516
  async function handlePasswordAuth(m) {
448
517
  state.awaitingPassword = false; // one guess per connection
449
518
  if (m.method !== 'password' || typeof m.password !== 'string') return refuse('expected a password AUTH');
@@ -86,6 +86,9 @@ function tlsChannelBinding(socket) {
86
86
  * @param {number} [options.bindTimeoutMs=3000]
87
87
  * @param {number} [options.connectionTtlMs=0] - End every authenticated connection this long after login (0 = never).
88
88
  * Advertised as `AuthOk.ttl` in whole seconds, rounded up; the client reads it as `client.authTtl`.
89
+ * @param {false | 'offer' | 'require'} [options.sealSession=false] - #155: seal a session end to end when the client asks (`e2e-session`); see
90
+ * `createMemoryHost`. Offered on connections accepted with `dataStreams: false` (a socket handed to `server.accept`); a
91
+ * byte-stream connection with QMux data streams is not sealed.
89
92
  * @param {boolean | string[]} [options.requireChannelBinding=false] - Accept a key login only when its signature is bound to
90
93
  * this connection (#119): `true` needs any binding kind, an array names kinds that must all be bound (`host` needs
91
94
  * `hostKey`; `tls-exporter` needs `wss://` served by this process, not a TLS-terminating proxy; `cert-hash` needs
@@ -94,8 +97,10 @@ function tlsChannelBinding(socket) {
94
97
  * @returns {{ listen(): Promise<{address: string, port: number}>, accept(socket: object, options?: object): Promise<{ close(): void }>, close(): Promise<void>, address(): ({address: string, port: number} | null) }}
95
98
  */
96
99
  export function createWshServer({
97
- host = '127.0.0.1', port = 0, tls, auth, exec, pty, fs, hostKey, mcp, rpc, rpcMaxMessageBytes, rpcMaxInflight, sessions, sessionSecret, relay, extensions, gateway, webTransport, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, onLog = () => {},
100
+ host = '127.0.0.1', port = 0, tls, auth, exec, pty, fs, hostKey, mcp, rpc, rpcMaxMessageBytes, rpcMaxInflight, sessions, sessionSecret, relay, extensions, gateway, webTransport, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, sealSession = false, onLog = () => {},
98
101
  } = {}) {
102
+ if (sealSession !== false && sealSession !== 'offer' && sealSession !== 'require') throw new TypeError("createWshServer: sealSession must be false, 'offer' or 'require'");
103
+ if (sealSession && !hostKey) throw new TypeError('createWshServer: sealSession needs a hostKey (the host signs its half of the key exchange with it)');
99
104
  if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
100
105
  throw new TypeError(`createWshServer: requireChannelBinding must be true, false or an array of kinds (${CHANNEL_BINDING_KINDS.join(', ')})`);
101
106
  }
@@ -145,7 +150,7 @@ export function createWshServer({
145
150
  if (relay) hub = new RelayHub({ ...relay, log: onLog });
146
151
  if (extensions !== undefined && (extensions === null || typeof extensions !== 'object')) throw new TypeError('createWshServer: extensions must be an object of handlers');
147
152
  return createConnectionFactory({
148
- authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, log: onLog,
153
+ authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
149
154
  methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, createGatewaySession, sessions: registry, relay: hub,
150
155
  });
151
156
  })();
@@ -28,6 +28,7 @@
28
28
  import { cborEncode, cborDecode } from '../cbor.mjs';
29
29
  import { fingerprint as fingerprintOf, importPublicKeyRaw, verifyPeerRecord } from '../auth.mjs';
30
30
  import { MSG, isRelayForwardable, relayForward, reversePeers, reverseReject, reverseClose } from '../messages.gen.mjs';
31
+ import { OPERATOR_PROOF_FEATURE } from '../operator-proof.mjs';
31
32
 
32
33
  export const DEFAULT_MAX_PEERS = 1024;
33
34
  export const DEFAULT_CONNECT_TIMEOUT_MS = 8000;
@@ -253,7 +254,11 @@ export class RelayHub {
253
254
  from_fingerprint: operator.fingerprint,
254
255
  };
255
256
  // What the operator says it can do (#117), bounded; it is the operator's own claim and decides nothing here.
256
- if (Array.isArray(msg.features) && msg.features.length <= MAX_OPERATOR_FEATURES && msg.features.every((f) => isStr(f, MAX_FEATURE_LENGTH))) forwarded.features = [...msg.features];
257
+ // Only to a peer that advertised `operator-proof` in its registered record: a released peer (rust-v0.6 to v0.8) rejects
258
+ // the field outright (its generated types deny unknown fields), which the operator would see as a timeout. Stripped,
259
+ // that peer answers as it always did, without a challenge; an operator that insists on proof then fails at once.
260
+ const peerCanProve = (target.meta.capabilities ?? []).includes(OPERATOR_PROOF_FEATURE);
261
+ if (peerCanProve && Array.isArray(msg.features) && msg.features.length <= MAX_OPERATOR_FEATURES && msg.features.every((f) => isStr(f, MAX_FEATURE_LENGTH))) forwarded.features = [...msg.features];
257
262
  target.handle.send(forwarded);
258
263
  this.log(`relay: ${operator.fingerprint.slice(0, 12)} -> ${target.meta.fingerprint.slice(0, 12)} requested`);
259
264
  }