@johnhenry/wsh 0.40.0 → 0.42.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
@@ -843,7 +843,7 @@ sides; a host that does not require proof is exactly as exposed as before), the
843
843
  messages and seals nothing itself), and a compromised *operator* key (it proves the key, not the
844
844
  person). A relay can still refuse service by dropping the challenge.
845
845
 
846
- #### A sealed session (#155, host: JS; client: the Rust CLI so far)
846
+ #### A sealed session (#155, host: JS and the Rust `wsh-server`; client: the JS client and the Rust CLI)
847
847
 
848
848
  `createMemoryHost({ hostKey, dataStreams: false, sealSession: 'offer' | 'require' })` (and `createWshServer`, for a connection
849
849
  accepted with `dataStreams: false`) seals the WHOLE session end to end. After login the client sends a `KeyExchange` whose
@@ -858,8 +858,46 @@ downgrade. Only `--sealed` is a guarantee: sealing "on its own" rests on a `Serv
858
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
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
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.
861
+ QMux data streams (not offered there), and a denial of service (a relay can always drop or cut).
862
+
863
+ The JS client is the initiator too: `client.connect(url, { sealSession: false | 'auto' | true })` (also `WshClient.exec`).
864
+ `'auto'`, the default, seals only against a host that says `e2e-session-required` (so a client written before this option keeps
865
+ talking plainly to a host that merely offers it, and a host that requires sealing no longer refuses it); `true` seals or fails --
866
+ a host that does not offer `e2e-session`, one that proved no host key, or a password login is refused BEFORE a credential is
867
+ sent, with a sentence; `false` never seals. `client.sessionSealed` says whether it is. The exchange is bound to the host key the
868
+ host PROVED on this connection: it authenticates that key, not whose it is, so pin the host as well (`expectHostKey` /
869
+ `knownHosts`), or a relay that presents its own host key and terminates the exchange is the host to this client. Once sealed, a
870
+ plain message from the host is dropped, a frame that does not open ends the connection (`onError`, then `onClose`), `openStream()`
871
+ is refused and datagrams are neither sent nor heard (UDP uses the reliable path). `'auto'` is not a guarantee, for the reason above;
872
+ `true` is.
873
+
874
+ The Rust `wsh-server` is a responder too: `[server] seal_session = "off" | "offer" | "require"` (default `off`: no feature is
875
+ advertised and no released client is affected; `offer` and `require` need `host_key`, else the config is refused at start). On a
876
+ WebSocket connection it advertises `e2e-session` (and `e2e-session-required` with `require`), and after a KEY login it answers the
877
+ signed key exchange (it verifies the login key's signature, signs its reply with the host key) with the same `SealGate` the CLI uses;
878
+ from then on every control message but ping/pong is an `EncryptedFrame` both ways, gateway data included, and a frame that does not open
879
+ closes the connection. `offer` serves a client that never asks as before. `require` serves nothing in the clear: a plain message before
880
+ the key exists is answered with an error and the connection is closed, a password login is refused, and WebTransport connections and
881
+ WISP tunnels are refused (they cannot be sealed; connect over WebSocket). **Typed rpc channels (`wsh-fs`, ...) are not offered while
882
+ `seal_session` is on** (they ride client-opened data streams, which are not frames; the server says so at start). WebTransport on an
883
+ `offer` server is served as before and does not list `e2e-session`, so a client that must seal (`sealSession: true`, `--sealed`) is
884
+ refused there before a credential is sent. The same limits apply as for the JS host: the handshake before login, sizes and timing,
885
+ and a denial of service are not covered, and sealing "on its own" (`'auto'`, the CLI without `--sealed`) against an `offer` server is
886
+ not a guarantee. Pin the server's host key on the client (`expectHostKey`, `known_hosts`): the exchange authenticates the key the server proved.
887
+
888
+ #### Knowing who a host turned away: `onRefused` (#163)
889
+
890
+ `createMemoryHost`, `createWshServer` and `createReverseHost` take `onRefused({ reason, who, detail })`, called once per
891
+ connection the host turned away, so an embedder can tell the user why a terminal was refused without parsing `onLog`. `reason`
892
+ is a stable code, the list is exported as `REFUSAL_REASONS` from `@johnhenry/wsh/host`: `not-sealed` (a plain client on a
893
+ host that requires a sealed session, or a password login there), `unauthorized` (a key the host does not allow, a wrong
894
+ password, or an operator a reverse host's `accept` turned down), `binding-required`, `bad-signature`, `method-disabled`,
895
+ `rate-limited`, `bad-request`, `seal-failed` (a sealed session's key exchange failed or a frame did not open), and for a reverse
896
+ host `busy`, `proof-required`, `proof-failed`. `who` holds what is known: `username`, `fingerprint` (a key login), `address` (when
897
+ the transport gives one); a refusal before the login names no one. `detail` is human text and not stable. New codes may be added;
898
+ none is renamed. It reports only what this host decided: it does not say what a relay in the middle dropped, a client
899
+ that never reached the host, or a frame the host silently ignored on an already-sealed session (a plain message after sealing
900
+ is dropped, as before, without a report).
863
901
 
864
902
  #### A pipe relay (`@johnhenry/wsh/pipe-relay`, #118)
865
903
 
@@ -893,7 +931,7 @@ handshake and the session traffic -- is readable by it unless the two ends seal
893
931
  (per-session `initiateE2E`, or the **sealed session** below); it cannot forge the operator's signature or the host's.
894
932
  **Until you seal the session, treat a pipe relay as trusted for secrecy AND integrity**: it can read every control message and
895
933
  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
934
+ (#155; the JS client's `sealSession: true` and the CLI's `--sealed` seal it against a JS host that offers it). Pin the host key, require channel binding, use `wss://` to a relay you trust, or seal the session. It can drop, delay or
897
935
  cut a connection, and it sees who dials which id and how much they send.
898
936
 
899
937
  *CLI side (#145).* `wsh --via wss://relay/r/<id> user@host [command...]` dials the operator side
@@ -1484,7 +1522,7 @@ instead of dragging its own toolchain and CI job into an unrelated
1484
1522
  browser-app repo. It was previously deleted from clawser by accident
1485
1523
  (2026-03-14) and restored (2026-07-05) before this move.
1486
1524
 
1487
- Four crates, workspace-versioned (currently `0.11.0`):
1525
+ Four crates, workspace-versioned (currently `0.13.0`):
1488
1526
 
1489
1527
  | Crate | Kind | Description |
1490
1528
  |-------|------|--------------|
@@ -1556,6 +1594,12 @@ stderr, what it shares and how (`wsh: sharing "src" = /home/me/project (read-onl
1556
1594
  command, applies to `wsh [user@]host [command...]` and `wsh connect` only (`scp`, `ls`, `sftp`, `copy-id` refuse it), and fails
1557
1595
  with a sentence when the host does not say it can use shares: a share that silently does not exist is worse than none. Unix only.
1558
1596
 
1597
+ **The path is sent too (#164).** The offer carries each share's root as an absolute path, as you typed it (made tidy: `//`, `.`
1598
+ and a trailing `/` removed; `..` is left as typed), so a host that was asked for `-v /home/me/project:/in` can recognise the share
1599
+ it belongs to (`fs.root`) instead of a hash in the share name. It is advisory (see [Security model](#security-model)): the host
1600
+ cannot verify it. To keep your directory layout to yourself add `--share-hide-path`: the offer then has no path (exactly what
1601
+ 0.40.0 / `rust-v0.11.0` clients sent), `fs.root` is `undefined` on the host, and everything else works.
1602
+
1559
1603
  **What the host can do.** Stat and lstat, readdir (every entry WITH its attributes, in pages), readlink, open and read (ranges; a
1560
1604
  small file's content rides the open, so reading it is one message), write, create, mkdir, rename, unlink, rmdir, setattr (mode,
1561
1605
  times, truncate) and close, each a bounded `ShareRequest` the host sends and the CLI answers with an errno-like code. At most 16
@@ -1588,10 +1632,18 @@ const host = createMemoryHost({
1588
1632
  const entries = await fs.readdir('/'); // [{ name, type, size, mode, mtimeMs, ... }] -- attributes included
1589
1633
  const pkg = JSON.parse(new TextDecoder().decode(await fs.readFile('/package.json')));
1590
1634
  if (fs.writable) await fs.writeFile('/out/built.txt', new TextEncoder().encode('done'));
1635
+ if (fs.root === '/home/me/project') { /* a request for `-v /home/me/project:/in` is this share */ }
1591
1636
  },
1592
1637
  });
1593
1638
  ```
1594
1639
 
1640
+ `fs.root` (a string or `undefined`) is the directory's path on the operator's machine, as the operator typed it (#164). **It is
1641
+ advisory and unverified**: the operator's client sends it, the host cannot check it, and the CLI still enforces the real
1642
+ boundary (it serves only the directory it opened, whatever the path says). It is `undefined` when the client is older, sent
1643
+ `--share-hide-path`, or sent something the host does not accept: the host keeps a path only if it is an absolute string of at
1644
+ most 4096 bytes without a NUL and `paths` has exactly one entry per share; anything else is ignored, never an error. Use it to
1645
+ recognise a share, not to decide what is safe.
1646
+
1595
1647
  `createMemoryHost`, `createWshServer` and `createReverseHost` take `onShare`; listing it makes the host state the feature
1596
1648
  `shares`, and a host without it never hears an offer. `fs` is an object of async operations (`stat`, `lstat`, `readlink`,
1597
1649
  `readdir`, `open` / `create` returning a file with `read(offset, length)` / `write` / `setattr` / `close`, `readFile`,
@@ -1612,7 +1664,7 @@ than left to be found.
1612
1664
  | Capability | JS SDK (browser) | Rust CLI/client | Unified via |
1613
1665
  |---|---|---|---|
1614
1666
  | Directory listing (`list`) | `WshFileTransfer.list()` | `wsh_client::file_transfer::list()`, `wsh ls`, `wsh sftp` | **Wire-unified**: `FileOp`/`FileResult` with the generated `FileEntry` type (wsh #59) -- both languages decode the same shape, including symlink targets |
1615
- | Upload/download | `WshClient.upload()`/`.download()` | `file_transfer::upload()`/`download()`, `wsh scp` | **Wire-unified**: `FileChunk` over a `'file'`-kind channel (wsh #13) |
1667
+ | Upload/download | `WshClient.upload()`/`.download()` | `file_transfer::upload()`/`download()`, `wsh scp` | **Wire-unified**: `FileChunk` over a `'file'`-kind channel (wsh #13). Before the Rust client of the next `rust-v` release (#140) it read a raw stream (an 8-byte size, then the data) that no host sends, so `wsh scp` hung against every host (JS and `wsh-server`); the CLI is now tested against a Node host through a pipe relay and against `wsh-server` (`test/rust/wsh-cli-scp.test.mjs`), uploads and downloads of 0 B to 300 KiB |
1616
1668
  | 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 |
1617
1669
  | 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 |
1618
1670
  | 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 |
@@ -1620,7 +1672,7 @@ than left to be found.
1620
1672
  | 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 |
1621
1673
  | 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 |
1622
1674
  | 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 |
1623
- | 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) |
1675
+ | Host that runs in a browser page (`createMemoryHost`, `@johnhenry/wsh/reverse`) | yes, with injected `pty` / `fs` / `hostKey` | no (a Rust host is a process) | **JS-only**. A Rust *client* can operate such a host only with `dataStreams: false` (#132): the released Rust client over WebSocket cannot open QMux data streams, and says nothing in `Hello` that a host could use to decide. `wsh scp` works against such a host with the Rust client of the next `rust-v` release (it speaks `FileChunk`, #140); a released `rust-v0.11.0` or older `wsh scp` hangs against it (`wsh ls` and exec work) |
1624
1676
  | 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 |
1625
1677
  | 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) |
1626
1678
  | Reverse-connect / relay peer | `connectReverse()`, `trustRelayPeer()`; `@johnhenry/wsh/server`: `relay` option and `createReverseHost()` | `wsh reverse`, `wsh agent` (persistent, with startup-unit install) | **Wire-unified** (registration, discovery, signed peer records); **daemonization is CLI-only** -- a browser tab cannot be a background OS service. The Node relay is default-deny and bridges one operator per peer unless `maxOperatorsPerPeer` is raised (`busy:` reasons say so); E2E and bridged feature gates need `rust-v0.3.0`+ on the Rust side; several operators per peer and the signed `KeyExchange` are JS-relay only for now |
@@ -1633,8 +1685,9 @@ than left to be found.
1633
1685
  | 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 |
1634
1686
  | 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 |
1635
1687
  | Pipe relay (#118) | `@johnhenry/wsh/pipe-relay` | operator side only (#145): `wsh --via wss://relay/r/<id> user@host command...` (also `connect`, `scp`, `ls`, `sftp`, `copy-id`), or the URL as the target. The host side of a pipe is not implemented in Rust. As on a direct connection the Rust client verifies the host-key proof (`host-key` / `host-key-sig` over its own nonce) before sending a credential, pins only a proven key, and binds the login to it (channel binding `host`; `test/rust/wsh-cli-identity.test.mjs`); the pipe-relayed session itself is not sealed (see Security model). `wsh -N -L` exits non-zero when the host drops the session (#156), and the error lines show the relay and a shortened id, never the whole rendezvous id | **Deliberately a relay without wsh parsing** -- nothing to unify on the wire. `--via` keeps `user@host` as the identity: its key is recorded in `known_hosts` under `host:port` (what a direct connection uses), never under the relay's address; a URL target is recorded under the URL's own authority, i.e. the relay's. The URL is not saved to `last_session.json` (the id is a capability) |
1636
- | Operator-side shared folders (`--share`, #159) | host side: `onShare(name, fs, who)` on `createMemoryHost` / `createWshServer` / `createReverseHost` (the host *uses* the operator's directories; `fs` is an object of async file operations, also shaped like an `fs` backend). The JS client does not offer shares | CLI side: `wsh --share NAME=/abs/dir[:ro\|:rw]` offers them (`wsh_client::share`, `wsh-cli`'s `sharefs`: descriptor-relative, never follows a link, see [Sharing a directory](#sharing-a-directory-with-the-host-wsh---share-159)); unix only. **A Rust host that uses shares: not built** (`wsh-server` does not state `shares`) | **Wire-unified, negotiated**: the host states the feature `shares`; the client sends one `ShareOffer` after login (opcodes `0xa8` `ShareOffer`, `0xa9` `ShareRequest`, host to client, `0xaa` `ShareReply`). No change notification, no sharing over `reverse-connect` |
1637
- | 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) |
1688
+ | Operator-side shared folders (`--share`, #159) | host side: `onShare(name, fs, who)` on `createMemoryHost` / `createWshServer` / `createReverseHost` (the host *uses* the operator's directories; `fs` is an object of async file operations, also shaped like an `fs` backend; `fs.root` is the operator's advisory, unverified path for the share, #164). The JS client does not offer shares | CLI side: `wsh --share NAME=/abs/dir[:ro\|:rw]` offers them, with each directory's path unless `--share-hide-path` (`wsh_client::share`, `wsh-cli`'s `sharefs`: descriptor-relative, never follows a link, see [Sharing a directory](#sharing-a-directory-with-the-host-wsh---share-159)); unix only. **A Rust host that uses shares: not built** (`wsh-server` does not state `shares`) | **Wire-unified, negotiated**: the host states the feature `shares`; the client sends one `ShareOffer` after login (opcodes `0xa8` `ShareOffer`, `0xa9` `ShareRequest`, host to client, `0xaa` `ShareReply`). No change notification, no sharing over `reverse-connect` |
1689
+ | Sealed session: any authenticated connection incl. gateway/endpoint data (#155) | host `sealSession: 'offer' \| 'require'` (stage b); client `connect(url, { sealSession: false \| 'auto' \| true })` (stage c) | `wsh --sealed ...` (or automatic against `e2e-session-required`) seals a direct or pipe-relayed session; `wsh-server` offers or requires it on WebSocket (`[server] seal_session = "off" \| "offer" \| "require"`, needs `host_key`; `require` refuses WebTransport, WISP tunnels and password logins; no typed rpc channels while it is on) | **Wire-unified, negotiated** (`e2e-session`, `e2e-session-required`, `KeyExchange` for the connection's session id, `EncryptedFrame` channel 0) |
1690
+ | Refusal event with stable reason codes (`onRefused`, #163) | `onRefused({ reason, who, detail })` on `createMemoryHost` / `createWshServer` / `createReverseHost`; `REFUSAL_REASONS` from `@johnhenry/wsh/host` | none: `wsh-server` and `wsh reverse` log a refusal, they have no callback (an embedding process has none) | **JS-only** -- a host-side callback of the embedding API, no wire change |
1638
1691
  | `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` |
1639
1692
  | `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 |
1640
1693
  | 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 |
@@ -1693,6 +1746,10 @@ plus one `SHA256SUMS` file covering every archive in the release. These
1693
1746
  names are a stable contract other repos (clawser) pin and download by --
1694
1747
  do not change them without coordinating downstream.
1695
1748
 
1749
+ `wsh --version` and `wsh-server --version` print the workspace version the binary was built from (`wsh 0.13.0`), which is the
1750
+ number in the `rust-vX.Y.Z` tag. Binaries of `rust-v0.9.0` to `rust-v0.10.0` printed a fixed `0.1.0`, so against one of those the
1751
+ version cannot be read from the binary (look for a flag in `wsh --help` instead).
1752
+
1696
1753
  ## Security model
1697
1754
 
1698
1755
  wsh's protocol draws its line at authentication and message integrity: what
@@ -1920,19 +1977,25 @@ What this does **not** protect against:
1920
1977
  is sealed, #155); a host that is itself malicious software on a page can read what the page's other code can ask for. The
1921
1978
  JS side treats the CLI as untrusted too (window, size, shape and deadline of every reply are checked), but an embedder
1922
1979
  that mounts `fs` is responsible for what it does with the files.
1980
+ **The root path (`ShareOffer.paths`, `fs.root`, #164) is a claim, not evidence.** By default the CLI tells the host where each
1981
+ shared directory is on your machine (so it can map a bind-mount source onto a share); the host cannot verify it, a modified
1982
+ client can send any string, and the CLI serves only the directory it opened whatever the path says. A host must use it to
1983
+ recognise a share, never to decide what is safe to mount or run. It reveals your directory layout (a user name, a project
1984
+ name) to the host and to a relay that is not sealed; `--share-hide-path` leaves it out.
1923
1985
  - **Rust `wsh-server`'s `AuthOk.ttl` is 0 and its `token` is opaque** (as the
1924
1986
  JS host's, above): nothing is promised or enforced at connection level; do not
1925
1987
  treat the token as a credential.
1926
1988
  - **`wsh --via` (pipe relay from the Rust CLI) is the operator side only, and
1927
- still not sealed** (the sealed bridge of `wsh reverse-connect --sealed` covers
1928
- reverse bridges only; #155 tracks sealing a direct or pipe-relayed connection and
1929
- its gateway data). The Rust client now verifies the host-key proof
1989
+ not sealed unless you ask** (`wsh --sealed` seals a direct or pipe-relayed session, gateway
1990
+ data included, against a host that offers `e2e-session`: the JS host with `sealSession`, or
1991
+ `wsh-server` with `seal_session`; #155. Without `--sealed` the session is plain, and a relay reads
1992
+ it). The Rust client now verifies the host-key proof
1930
1993
  (`host-key` / `host-key-sig` over its own `host-key-nonce`) before sending
1931
1994
  any credential, records only a PROVEN key in `known_hosts`, binds the login
1932
1995
  signature to that key (channel binding `host`), and refuses a changed key
1933
1996
  always. A replayed `ServerHello` or an impostor's key is refused as the JS
1934
- client refuses it. What is still unprotected: the bridge is not sealed
1935
- end to end (a pipe-relayed session has no sealing layer yet, #155), so the relay sees
1997
+ client refuses it. What is still unprotected without `--sealed`: the session is not sealed
1998
+ end to end, so the relay sees
1936
1999
  session traffic in the clear unless the legs are TLS and it is trusted not
1937
2000
  to read them (it terminates each leg's TLS), and it can stamp an identity on
1938
2001
  a plain message after the handshake. A host with no host key proves nothing:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.40.0",
3
+ "version": "0.42.0",
4
4
  "description": "Web Shell \u2014 browser-native remote command execution over WebTransport and WebSocket with Ed25519 authentication",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/client.mjs CHANGED
@@ -8,7 +8,7 @@
8
8
  * reverse mode (client registers as a peer for incoming connections).
9
9
  */
10
10
 
11
- import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE } from './features.mjs';
11
+ import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE, SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE } from './features.mjs';
12
12
  import { WebTransportTransport, normalizeWebTransportOptions } from './transport.mjs';
13
13
  import { clientChannelBinding, offeredKinds, TLS_EXPORTER_LABEL, TLS_EXPORTER_LENGTH } from './channel-binding.mjs';
14
14
  import { WebSocketTransport } from './transport-ws.mjs';
@@ -183,6 +183,10 @@ function assertStdinSource(stdin) {
183
183
  throw new TypeError('exec: stdin must be a string, Uint8Array, ReadableStream or (async) iterable of those');
184
184
  }
185
185
 
186
+ function assertSealSession(v) {
187
+ if (v !== false && v !== 'auto' && v !== true) throw new TypeError("connect: sealSession must be false, 'auto' or true");
188
+ }
189
+
186
190
  /** Write `stdin` to `session` in bounded chunks, then close the write side (EOF). */
187
191
  async function pumpStdin(session, stdin) {
188
192
  const send = async (chunk) => {
@@ -274,6 +278,13 @@ export class WshClient {
274
278
  */
275
279
  #sealState = null;
276
280
 
281
+ /**
282
+ * Set from the moment this client starts sealing its whole session (#155) until the connection ends: `{ sessionId,
283
+ * bridge }`, `bridge` null until the key exists. A message that arrives from the host itself is then heard only
284
+ * as the key exchange (while pending), a frame of the session, or the keepalive.
285
+ */
286
+ #sessionSeal = null;
287
+
277
288
  /** The binding kinds the last login's signature covered (#119); empty when it was unbound. */
278
289
  #channelBindingKinds = [];
279
290
 
@@ -558,6 +569,14 @@ export class WshClient {
558
569
  return this.#hostKey;
559
570
  }
560
571
 
572
+ /**
573
+ * Is this whole session sealed end to end (#155, `connect(url, { sealSession })`)? Every message but the keepalive,
574
+ * gateway and endpoint data included, then travels as an authenticated encrypted frame a relay cannot read or alter.
575
+ */
576
+ get sessionSealed() {
577
+ return !!this.#sessionSeal?.bridge;
578
+ }
579
+
561
580
  // ── Connection ──────────────────────────────────────────────────────
562
581
 
563
582
  /**
@@ -595,15 +614,25 @@ export class WshClient {
595
614
  * to this connection (#119): `true` needs at least one binding kind (`host`, `cert-hash`, `tls-exporter`) that
596
615
  * both the host offers and this client can supply; an array names kinds that must all be bound. Not for
597
616
  * password auth (nothing is signed). Stops an intermediary from relaying a genuine challenge to the host.
617
+ * @param {false | 'auto' | true} [opts.sealSession='auto'] - Seal the WHOLE session end to end (#155): after login a
618
+ * signed key exchange with the host (bound to its proven host key and this login key), then every message but the
619
+ * keepalive -- gateway and endpoint data included -- is an authenticated encrypted frame, so a relay that copies
620
+ * bytes can neither read nor alter it, and a frame that does not open closes the connection. `'auto'` seals only
621
+ * against a host that says `e2e-session-required` (a host that merely offers it is spoken to as before); `true`
622
+ * seals or fails -- a host that does not offer `e2e-session`, one that proved no host key, or a password login is
623
+ * refused BEFORE a credential is sent; `false` never seals (a host that requires it then serves nothing). Only
624
+ * `true` is a guarantee: `'auto'` rests on a ServerHello feature that a relay can strip before login. Pin the host
625
+ * (`expectHostKey` / `knownHosts`) too: the exchange authenticates the key the host proved, not whose it is.
598
626
  * @returns {Promise<string>} The server-assigned session ID
599
627
  */
600
- async connect(url, { username, keyPair, signer, password, transport: transportHint, webTransport, timeout = DEFAULT_AUTH_TIMEOUT, requireChannelBinding = false, ...hostKeyOpts } = {}) {
628
+ async connect(url, { username, keyPair, signer, password, transport: transportHint, webTransport, timeout = DEFAULT_AUTH_TIMEOUT, requireChannelBinding = false, sealSession = 'auto', ...hostKeyOpts } = {}) {
601
629
  if (this.#state !== STATE_DISCONNECTED && this.#state !== STATE_CLOSED) {
602
630
  throw new Error(`Client already ${this.#state}`);
603
631
  }
604
632
  if (!username) {
605
633
  throw new Error('username is required');
606
634
  }
635
+ assertSealSession(sealSession);
607
636
  const cred = await resolveSigner({ keyPair, signer });
608
637
  this.#signer = cred;
609
638
  this.#loginUsername = username;
@@ -616,6 +645,7 @@ export class WshClient {
616
645
  this.#channelBindingKinds = [];
617
646
  this.#certHash = null;
618
647
  this.#sealState = null;
648
+ this.#sessionSeal = null;
619
649
  this.#peerProof = null;
620
650
  this.#sessions.clear();
621
651
  this.#channelCounter = 0;
@@ -651,6 +681,9 @@ export class WshClient {
651
681
  }
652
682
 
653
683
  let tempSessionId = null;
684
+ // Whether this session is to be sealed (#155): decided from the ServerHello and the proven host key, BEFORE a
685
+ // credential is sent, so a host that cannot seal is refused while nothing has been signed.
686
+ let seal = false;
654
687
 
655
688
  if (firstResponse.type === MSG.SERVER_HELLO) {
656
689
  // Server may proceed directly to auth if it accepted the hello.
@@ -665,6 +698,7 @@ export class WshClient {
665
698
  : null;
666
699
  challengeWait?.catch(() => {});
667
700
  await this.#verifyHostKey(firstResponse, hostCtx);
701
+ seal = this.#planSealing(sealSession, this.#serverFeatures, !!cred);
668
702
 
669
703
  if (authMethod === AUTH_METHOD.PUBKEY) {
670
704
  const challengeMsg = await challengeWait;
@@ -675,6 +709,7 @@ export class WshClient {
675
709
  this.#authToken = challengeMsg.token || null;
676
710
  this.#authTtl = Number(challengeMsg.ttl) || 0;
677
711
  this.#state = STATE_AUTHENTICATED;
712
+ if (seal) await this.#sealSession(timeout);
678
713
  this.#startPing();
679
714
  return this.#sessionId;
680
715
  }
@@ -708,6 +743,7 @@ export class WshClient {
708
743
  } else if (firstResponse.type === MSG.CHALLENGE) {
709
744
  // Some servers skip SERVER_HELLO and go straight to CHALLENGE.
710
745
  await this.#verifyHostKey(null, hostCtx);
746
+ seal = this.#planSealing(sealSession, [], !!cred);
711
747
  if (authMethod !== AUTH_METHOD.PUBKEY || !cred) {
712
748
  throw new Error('Server sent CHALLENGE but no key pair was provided');
713
749
  }
@@ -751,6 +787,7 @@ export class WshClient {
751
787
  this.#authToken = authResult.token || null;
752
788
  this.#authTtl = Number(authResult.ttl) || 0;
753
789
  this.#state = STATE_AUTHENTICATED;
790
+ if (seal) await this.#sealSession(timeout);
754
791
  this.#startPing();
755
792
 
756
793
  return this.#sessionId;
@@ -1562,7 +1599,7 @@ export class WshClient {
1562
1599
  // Datagrams for UDP flows: only on a transport that has them AND a host that listed "gateway-datagram".
1563
1600
  datagrams: () => {
1564
1601
  const t = this.#transport;
1565
- return t?.supportsDatagrams && this.hasFeature(GATEWAY_DATAGRAM_FEATURE) ? { send: (b) => t.sendDatagram(b), maxSize: () => t.maxDatagramSize } : null;
1602
+ return !this.#sessionSeal && t?.supportsDatagrams && this.hasFeature(GATEWAY_DATAGRAM_FEATURE) ? { send: (b) => t.sendDatagram(b), maxSize: () => t.maxDatagramSize } : null;
1566
1603
  },
1567
1604
  }));
1568
1605
  }
@@ -1650,6 +1687,7 @@ export class WshClient {
1650
1687
  */
1651
1688
  async openStream() {
1652
1689
  this.#assertAuthenticated('openStream');
1690
+ if (this.#sessionSeal) throw new Error('openStream: a sealed session carries no client-opened data streams (their bytes are not frames)');
1653
1691
  return this.#transport.openStream();
1654
1692
  }
1655
1693
 
@@ -2689,10 +2727,11 @@ export class WshClient {
2689
2727
  * @private
2690
2728
  */
2691
2729
  #attachTransportHandlers(transport) {
2692
- transport.onControl = (msg) => this.#handleControl(msg);
2730
+ transport.onControl = (msg) => this.#onTransportControl(msg);
2693
2731
  transport.onClose = () => this.#handleTransportClose();
2694
2732
  transport.onError = (err) => this.#handleTransportError(err);
2695
- transport.onDatagram = (bytes) => this.#gateway?.handleDatagram(bytes);
2733
+ // A datagram is not a frame: on a sealed session a relay could inject one, so none is heard (UDP uses the reliable path).
2734
+ transport.onDatagram = (bytes) => { if (!this.#sessionSeal) this.#gateway?.handleDatagram(bytes); };
2696
2735
  }
2697
2736
 
2698
2737
  /**
@@ -2853,6 +2892,90 @@ export class WshClient {
2853
2892
  }
2854
2893
  }
2855
2894
 
2895
+ // ── Internal: a sealed session (#155) ───────────────────────────────
2896
+
2897
+ /**
2898
+ * Whether this connection is to be sealed, decided from the ServerHello's features and the proven host key BEFORE
2899
+ * a credential is sent. `true` and a host that requires sealing (`'auto'`) fail here, with a sentence, when sealing
2900
+ * is not possible -- never by talking in the clear.
2901
+ * @param {false | 'auto' | true} mode
2902
+ * @param {string[]} features - the host's ServerHello features (`[]` when it sent none)
2903
+ * @param {boolean} haveKey - this login signs (a key login)
2904
+ * @returns {boolean}
2905
+ */
2906
+ #planSealing(mode, features, haveKey) {
2907
+ if (mode === false) return false;
2908
+ if (mode === 'auto' && !features.includes(SESSION_SEAL_REQUIRED_FEATURE)) return false;
2909
+ const why = !features.includes(SESSION_SEAL_FEATURE)
2910
+ ? `the host does not offer "${SESSION_SEAL_FEATURE}" (it needs a host key and a connection without client-opened data streams)`
2911
+ : !this.#hostKey?.publicKey
2912
+ ? 'the host proved no host key to authenticate the exchange against'
2913
+ : !haveKey
2914
+ ? 'a sealed session needs a key login (a password login has nothing to sign with)'
2915
+ : null;
2916
+ if (why) throw new Error(`sealed session: ${why} -- nothing was sent`);
2917
+ return true;
2918
+ }
2919
+
2920
+ /**
2921
+ * Seal this whole connection: a signed `KeyExchange` for the connection's session id (the login key signs this half,
2922
+ * the host's proven key the other), then every message but the keepalive leaves as an `EncryptedFrame` on channel 0,
2923
+ * in order. Until the key exists nothing but the key exchange may be sent, and nothing plain is heard.
2924
+ * @param {number} timeout
2925
+ */
2926
+ async #sealSession(timeout) {
2927
+ const sessionId = this.#sessionId;
2928
+ const hostKey = this.#hostKey?.publicKey;
2929
+ if (!sessionId || !hostKey || !this.#signer) throw new Error('sealed session: no session id, host key or login key -- nothing was sent');
2930
+ const transport = this.#transport;
2931
+ const plainSend = transport.sendControl.bind(transport);
2932
+ let bridge = null;
2933
+ this.#sessionSeal = { sessionId, bridge: null };
2934
+ transport.sendControl = async (msg) => {
2935
+ if (msg.type === MSG.PING || msg.type === MSG.PONG) return plainSend(msg);
2936
+ if (bridge) return plainSend(await bridge.seal(msg));
2937
+ if (msg.type === MSG.KEY_EXCHANGE && msg.session_id === sessionId) return plainSend(msg);
2938
+ throw new Error('sealed session: nothing is sent before the key exists');
2939
+ };
2940
+ const { sharedSecret } = await this.initiateE2E(sessionId, 'X25519+ML-KEM-768', timeout, {
2941
+ verifyPeer: hostKey, signAs: this.#signer, responderIdentity: hostKey,
2942
+ });
2943
+ bridge = new SealedBridge({ key: sharedSecret, sessionId, role: 'initiator', scope: 'session' });
2944
+ this.#sessionSeal = { sessionId, bridge };
2945
+ }
2946
+
2947
+ /**
2948
+ * Every message that arrives from the host itself passes here. On a sealed session only the key exchange (while the
2949
+ * key does not exist yet), the keepalive and frames of the session are heard: a relay in the middle can write any
2950
+ * plain message, so a plain one is dropped; a frame that does not open (flipped bit, replay, reorder, forged) is the
2951
+ * relay at work, and ends the connection.
2952
+ * @param {object} msg
2953
+ */
2954
+ #onTransportControl(msg) {
2955
+ const seal = this.#sessionSeal;
2956
+ if (!seal || msg.type === MSG.PING || msg.type === MSG.PONG) { this.#handleControl(msg); return; }
2957
+ if (seal.bridge) {
2958
+ if (!seal.bridge.isFrame(msg)) {
2959
+ console.warn(`[wsh:client] dropping a plaintext message (type ${msg.type}) on a sealed session`);
2960
+ return;
2961
+ }
2962
+ seal.bridge.open(msg).then(
2963
+ (inner) => { if (this.#sessionSeal === seal) this.#handleControl(inner); },
2964
+ (err) => this.#sealedFrameFailed(seal, err),
2965
+ );
2966
+ return;
2967
+ }
2968
+ if (msg.type === MSG.KEY_EXCHANGE && msg.session_id === seal.sessionId) { this.#handleControl(msg); return; }
2969
+ console.warn(`[wsh:client] dropping a plaintext message (type ${msg.type}) before the session is sealed`);
2970
+ }
2971
+
2972
+ #sealedFrameFailed(seal, err) {
2973
+ if (this.#sessionSeal !== seal || this.#state === STATE_CLOSED) return;
2974
+ this.#sessionSeal = { ...seal, failed: true };
2975
+ this.#emitError(new Error(`wsh: a sealed frame did not open (${err.message}); the session is closed`));
2976
+ this.#transport?.close().catch(() => {});
2977
+ }
2978
+
2856
2979
  // ── Internal: auth handshake ────────────────────────────────────────
2857
2980
 
2858
2981
  /**
@@ -2868,8 +2991,10 @@ export class WshClient {
2868
2991
  * @returns {Promise<string>} Session ID
2869
2992
  * @private
2870
2993
  */
2871
- async #performAuth({ username, keyPair, signer, password, timeout = DEFAULT_AUTH_TIMEOUT, url, requireChannelBinding = false, ...hostKeyOpts } = {}) {
2994
+ async #performAuth({ username, keyPair, signer, password, timeout = DEFAULT_AUTH_TIMEOUT, url, requireChannelBinding = false, sealSession = 'auto', ...hostKeyOpts } = {}) {
2872
2995
  if (!username) throw new Error('username is required');
2996
+ assertSealSession(sealSession);
2997
+ this.#sessionSeal = null;
2873
2998
  const cred = await resolveSigner({ keyPair, signer });
2874
2999
  this.#signer = cred;
2875
3000
  this.#loginUsername = username;
@@ -2895,6 +3020,7 @@ export class WshClient {
2895
3020
  }
2896
3021
 
2897
3022
  let tempSessionId = null;
3023
+ let seal = false; // see connect()
2898
3024
 
2899
3025
  if (firstResponse.type === MSG.SERVER_HELLO) {
2900
3026
  tempSessionId = firstResponse.session_id;
@@ -2905,6 +3031,7 @@ export class WshClient {
2905
3031
  : null;
2906
3032
  challengeWait?.catch(() => {});
2907
3033
  await this.#verifyHostKey(firstResponse, hostCtx);
3034
+ seal = this.#planSealing(sealSession, this.#serverFeatures, !!cred);
2908
3035
 
2909
3036
  if (authMethod === AUTH_METHOD.PUBKEY) {
2910
3037
  const challengeMsg = await challengeWait;
@@ -2914,6 +3041,7 @@ export class WshClient {
2914
3041
  this.#authToken = challengeMsg.token || null;
2915
3042
  this.#authTtl = Number(challengeMsg.ttl) || 0;
2916
3043
  this.#state = STATE_AUTHENTICATED;
3044
+ if (seal) await this.#sealSession(timeout);
2917
3045
  this.#startPing();
2918
3046
  return this.#sessionId;
2919
3047
  }
@@ -2934,6 +3062,7 @@ export class WshClient {
2934
3062
  } else if (firstResponse.type === MSG.CHALLENGE) {
2935
3063
  if (!cred) throw new Error('Server sent CHALLENGE but no key pair provided');
2936
3064
  await this.#verifyHostKey(null, hostCtx);
3065
+ seal = this.#planSealing(sealSession, [], true);
2937
3066
 
2938
3067
  // Challenge carries session_id directly — see connect()'s
2939
3068
  // CHALLENGE branch for why. Keep tempSessionId as a fallback for
@@ -2964,6 +3093,7 @@ export class WshClient {
2964
3093
  this.#authToken = authResult.token || null;
2965
3094
  this.#authTtl = Number(authResult.ttl) || 0;
2966
3095
  this.#state = STATE_AUTHENTICATED;
3096
+ if (seal) await this.#sealSession(timeout);
2967
3097
  this.#startPing();
2968
3098
 
2969
3099
  return this.#sessionId;
@@ -3053,6 +3183,10 @@ export class WshClient {
3053
3183
  const serverChannelId = msg.channel_id ?? pending.requestedChannelId;
3054
3184
  const streamIds = msg.stream_ids ?? {};
3055
3185
  const dataMode = msg.data_mode === 'virtual' ? 'virtual' : 'stream';
3186
+ if (this.#sessionSeal && dataMode !== 'virtual') {
3187
+ pending.reject(new Error('Failed to open session: the host answered with a data stream, and a sealed session carries none'));
3188
+ return;
3189
+ }
3056
3190
  const capabilities = Array.isArray(msg.capabilities) ? msg.capabilities : [];
3057
3191
 
3058
3192
  const session = new WshSession(
package/src/features.mjs CHANGED
@@ -26,3 +26,11 @@ export const MCP_CANCEL_FEATURE = 'mcp-cancel';
26
26
  */
27
27
  export const STREAM_ANNOUNCE_FEATURE = 'stream-announce';
28
28
  export const EXEC_PIPES_FEATURE = 'exec-pipes';
29
+
30
+ /**
31
+ * Host feature (#155): this host seals the whole session end to end when asked (a signed `KeyExchange` for the
32
+ * connection's session id, then every message but the keepalive as an `EncryptedFrame` on channel 0).
33
+ */
34
+ export const SESSION_SEAL_FEATURE = 'e2e-session';
35
+ /** Host feature (#155): this host serves nothing on a session that is not sealed. */
36
+ export const SESSION_SEAL_REQUIRED_FEATURE = 'e2e-session-required';
@@ -91,8 +91,10 @@ export class GatewayConnections {
91
91
  onRemoteClose: datagram ? () => channel.destroy() : undefined,
92
92
  onData,
93
93
  sendData: (data) => this.#send(gatewayDataMsg({ gatewayId: id, data })),
94
- sendCredit: (n) => this.#send(gatewayCreditMsg({ gatewayId: id, bytes: n })),
95
- sendClose: (reason) => this.#send(gatewayCloseMsg({ gatewayId: id, reason })),
94
+ sendCredit: (n) => Promise.resolve(this.#send(gatewayCreditMsg({ gatewayId: id, bytes: n }))).catch(() => {}),
95
+ // Best effort and not awaited by the channel: on a sealed session (#155) the send finishes after the frame is
96
+ // sealed, so a connection that closed meanwhile must not surface as an unhandled rejection.
97
+ sendClose: (reason) => Promise.resolve(this.#send(gatewayCloseMsg({ gatewayId: id, reason }))).catch(() => {}),
96
98
  onClose: () => { this.#channels.delete(id); this.#udp.delete(id); },
97
99
  });
98
100
  this.#channels.set(id, channel);
package/src/host.d.ts CHANGED
@@ -84,6 +84,8 @@ export interface WshConnectionConfig extends Partial<WshResolvedBackends> {
84
84
  bindTimeoutMs?: number;
85
85
  /** Folders the operator offers (`wsh --share`, #159): called once per share; listing it makes the host state `shares`. */
86
86
  onShare?: WshOnShare;
87
+ /** Told once per connection this host turned away, with a stable reason code (#163). */
88
+ onRefused?: WshOnRefused;
87
89
  log?: (line: string) => void;
88
90
  [key: string]: unknown;
89
91
  }
@@ -193,6 +195,14 @@ export interface WshShareFs extends WshFileBackend {
193
195
  readonly name: string;
194
196
  /** Whether the operator offered writes (`:rw`). A change on a read-only share fails with `EROFS`. */
195
197
  readonly writable: boolean;
198
+ /**
199
+ * The folder's absolute path on the operator's machine, as the operator typed it (made absolute and tidied), or
200
+ * `undefined` when the operator's client did not send it (an older client, or `wsh --share-hide-path`) or sent
201
+ * something invalid (not absolute, a NUL, over 4096 bytes, the wrong count). ADVISORY: the host cannot verify it, so use
202
+ * it only to recognise a share (a bind-mount source, say), never to decide what is safe. The operator's client still
203
+ * serves only the folder it opened, whatever this says.
204
+ */
205
+ readonly root: string | undefined;
196
206
  /** Aborted when the connection to the operator ends; every later call fails with `EIO`. */
197
207
  readonly signal: AbortSignal;
198
208
  /** Requests, replies, errors, bytes each way and timeouts on this connection so far. */
@@ -219,3 +229,15 @@ export interface WshShareFs extends WshFileBackend {
219
229
 
220
230
  /** Called once per share the operator offers (#159). Mount `fs` where you like; `who` is the authenticated operator. */
221
231
  export type WshOnShare = (name: string, fs: WshShareFs, who: { username: string | null; fingerprint: string | null }) => void | Promise<void>;
232
+
233
+ /** The stable reason codes of `onRefused` (#163). New ones may be added; none is renamed. */
234
+ export const REFUSAL_REASONS: readonly WshRefusalReason[];
235
+ export type WshRefusalReason =
236
+ | 'not-sealed' | 'unauthorized' | 'binding-required' | 'bad-signature' | 'method-disabled' | 'rate-limited' | 'bad-request'
237
+ | 'seal-failed' | 'busy' | 'proof-required' | 'proof-failed';
238
+ /**
239
+ * Called once per connection a host turned away (#163): `reason` is a stable code, `who` what is known of the peer (a
240
+ * refusal before the login names no one), `detail` human text that is not stable. Not for parsing `onLog`.
241
+ * Reverse hosts also use `busy`, `proof-required`, `proof-failed`; a sealed session that fails mid-way reports `seal-failed`.
242
+ */
243
+ export type WshOnRefused = (refusal: { reason: WshRefusalReason; who: { username?: string; fingerprint?: string; address?: string }; detail: string }) => void;
package/src/host.mjs CHANGED
@@ -29,3 +29,4 @@ export { bindSocket } from './server/socket.mjs';
29
29
  export { resolveBackends, resolveHostKey, normalizeFileBackend } from './host-backends.mjs';
30
30
  export { buildAuthorizer, authMethods } from './server/auth.mjs';
31
31
  export { ShareError, SHARES_FEATURE } from './shares.mjs';
32
+ export { REFUSAL_REASONS } from './refusal.mjs';
package/src/index.d.ts CHANGED
@@ -1839,6 +1839,16 @@ export interface WshHostKeyOptions {
1839
1839
  * kinds that must all be bound. Nothing is signed otherwise. Key logins only.
1840
1840
  */
1841
1841
  requireChannelBinding?: boolean | WshChannelBindingKind[];
1842
+ /**
1843
+ * Seal the WHOLE session end to end (#155): after login a signed key exchange with the host (bound to its proven host
1844
+ * key and this login key), then every message but the keepalive -- gateway and endpoint data included -- is an
1845
+ * authenticated encrypted frame a relay that copies bytes can neither read nor alter; a frame that does not open
1846
+ * closes the connection. Default `'auto'`: seal only against a host that says `e2e-session-required`. `true` seals or
1847
+ * fails, BEFORE a credential is sent (a host that does not offer `e2e-session`, one that proved no host key, a password
1848
+ * login). `false` never seals. Only `true` is a guarantee (a relay can strip the ServerHello feature `'auto'` rests
1849
+ * on); pin the host (`expectHostKey` / `knownHosts`) as well, since the exchange authenticates the key the host proved.
1850
+ */
1851
+ sealSession?: false | 'auto' | true;
1842
1852
  }
1843
1853
 
1844
1854
  /** What a login signature can be bound to (wsh #119). */
@@ -2235,6 +2245,9 @@ export class WshClient {
2235
2245
  */
2236
2246
  readonly hostKey: WshHostKey | null;
2237
2247
 
2248
+ /** Is this whole session sealed end to end (`connect(url, { sealSession })`, #155)? */
2249
+ readonly sessionSealed: boolean;
2250
+
2238
2251
  /** Default `onHostKey` for `connect()` (a per-call option wins). */
2239
2252
  onHostKey: ((hostKey: WshHostKey) => boolean | void | Promise<boolean | void>) | null;
2240
2253
 
@@ -1,6 +1,6 @@
1
1
  import type { WshClient, RpcChannel } from './index.js';
2
2
  import type { WshSigner } from './index.js';
3
- import type { WshFileBackend, WshHostKeyOption, WshOnShare } from './host.js';
3
+ import type { WshFileBackend, WshHostKeyOption, WshOnShare, WshOnRefused } from './host.js';
4
4
  import type {
5
5
  WshServerAuthOptions, WshServerPrincipal, WshServerMcpOptions, WshExecRunner, WshServerOptions, WshServerPtyOptions, WshClientEnv,
6
6
  WshAcceptableSocket, WshAcceptOptions, WshGatewayEndpointHandler as WshMemoryEndpointHandler,
@@ -84,6 +84,8 @@ export interface WshMemoryHostOptions {
84
84
  onShare?: WshOnShare;
85
85
  /** #155: seal the whole session end to end (needs `hostKey`; offered where `dataStreams` is false). `'require'` serves nothing unsealed. */
86
86
  sealSession?: false | 'offer' | 'require';
87
+ /** #163: told once per connection this host turned away (a key it does not allow, a plain client on a host that requires a sealed session, ...), with a stable reason code. */
88
+ onRefused?: WshOnRefused;
87
89
  onLog?: (line: string) => void;
88
90
  }
89
91
 
@@ -39,6 +39,7 @@ import { CHANNEL_BINDING_KINDS } from './channel-binding.mjs';
39
39
  import { RPC_PROTOCOL_NAME_RE, RPC_DEFAULT_MAX_MESSAGE } from './rpc.mjs';
40
40
  import { SessionRegistry, DEFAULT_RING_BYTES, DEFAULT_DETACH_TTL_MS, DEFAULT_MAX_DETACHED } from './session-registry.mjs';
41
41
  import { validateOnShare } from './shares.mjs';
42
+ import { validateOnRefused } from './refusal.mjs';
42
43
 
43
44
  const CONNECTING = 0;
44
45
  const OPEN = 1;
@@ -182,11 +183,16 @@ function createRegistry(sessions, log) {
182
183
  * this is called once per share with an object of async file operations (`stat`, `readdir` with attributes, `readFile`,
183
184
  * `open`, `writeFile`, `mkdir`, `rename`, `unlink`, ... and the `operate` / `readWhole` / `writeWhole` / `writeAt` shape of
184
185
  * an `fs` backend) that the embedder can mount. Listing it makes the host state the `shares` feature. See `shares.mjs`.
186
+ * @param {(refusal: { reason: string, who: { username?: string, fingerprint?: string, address?: string }, detail: string }) => void} [options.onRefused]
187
+ * #163: called once per connection that this host turned away (a key it does not allow, a plain client on a host that
188
+ * requires a sealed session, a login that is not bound, ...) with a stable `reason` code (`REFUSAL_REASONS`, exported
189
+ * from `@johnhenry/wsh/host`), what is known of `who`, and a human `detail` (not stable). Not for parsing `onLog`.
185
190
  * @param {(line: string) => void} [options.onLog]
186
191
  */
187
192
  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 = () => {},
188
- onShare } = {}) {
193
+ onShare, onRefused } = {}) {
189
194
  validateOnShare(onShare, 'createMemoryHost');
195
+ validateOnRefused(onRefused, 'createMemoryHost');
190
196
  if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createMemoryHost: connectionTtlMs must be a non-negative number');
191
197
  if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
192
198
  throw new TypeError(`createMemoryHost: requireChannelBinding must be true, false or an array of kinds (${CHANNEL_BINDING_KINDS.join(', ')})`);
@@ -218,7 +224,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
218
224
 
219
225
  const ready = Promise.all([buildAuthorizer(auth), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
220
226
  authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
221
- methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare,
227
+ methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare, onRefused,
222
228
  gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
223
229
  }));
224
230
  ready.catch(() => {});
@@ -991,14 +991,10 @@ export function authorizedKeyResult({ success, added = false, errorMessage } = {
991
991
  return msg;
992
992
  }
993
993
 
994
- export function shareOffer({ shares, writable = [], maxInflight, maxBytes } = {}) {
995
- return {
996
- type: MSG.SHARE_OFFER,
997
- shares,
998
- writable,
999
- max_inflight: maxInflight,
1000
- max_bytes: maxBytes,
1001
- };
994
+ export function shareOffer({ shares, writable = [], maxInflight, maxBytes, paths } = {}) {
995
+ const msg = { type: MSG.SHARE_OFFER, shares, writable, max_inflight: maxInflight, max_bytes: maxBytes };
996
+ if (paths !== undefined) msg.paths = paths;
997
+ return msg;
1002
998
  }
1003
999
 
1004
1000
  export function shareRequest({ requestId, share, op, path, to, handle, offset, length, mode, flags = [], cursor, attr = {}, data } = {}) {
@@ -0,0 +1,42 @@
1
+ /**
2
+ * `onRefused` (#163): a host tells its embedder that it turned a client (or, on a reverse host, an operator) away, with a
3
+ * stable reason code instead of a log line to parse. Browser-safe; shared by every host.
4
+ *
5
+ * The codes are part of the API (new ones may be added, none is renamed):
6
+ * - `not-sealed` the host requires a sealed session (`sealSession: 'require'`, `requireOperatorProof`) and the peer sent
7
+ * something that is not sealed, or logged in in a way that cannot seal
8
+ * - `unauthorized` a key the host does not allow, a wrong password, or an operator the host's `accept` turned down
9
+ * - `binding-required` the host requires the login to be bound to the connection (`requireChannelBinding`) and it was not
10
+ * - `bad-signature` the login signature does not verify
11
+ * - `method-disabled` the login method is not on (password on a key-only host, or the reverse)
12
+ * - `rate-limited` too many failed password attempts from that caller
13
+ * - `bad-request` a malformed login (bad username, malformed key, the wrong message)
14
+ * - `seal-failed` a sealed session's key exchange failed, or one of its frames did not open
15
+ * - `busy` (reverse host) it already serves its operators
16
+ * - `proof-required` (reverse host) it requires the operator to prove its identity and the operator offered none
17
+ * - `proof-failed` (reverse host) the operator's proof did not arrive, did not verify or names someone else
18
+ */
19
+ export const REFUSAL_REASONS = Object.freeze([
20
+ 'not-sealed', 'unauthorized', 'binding-required', 'bad-signature', 'method-disabled', 'rate-limited', 'bad-request',
21
+ 'seal-failed', 'busy', 'proof-required', 'proof-failed',
22
+ ]);
23
+
24
+ /** @throws {TypeError} when `onRefused` is given and is not a function */
25
+ export function validateOnRefused(onRefused, where) {
26
+ if (onRefused !== undefined && onRefused !== null && typeof onRefused !== 'function') throw new TypeError(`${where}: onRefused must be a function`);
27
+ }
28
+
29
+ /**
30
+ * A function `(reason, who, detail)` that calls `onRefused({ reason, who, detail })`, dropping the undefined parts of `who`. A
31
+ * callback that throws is logged and does not change what the host does. Returns a no-op when there is no callback.
32
+ * @param {Function | undefined | null} onRefused
33
+ * @param {(line: string) => void} [log]
34
+ */
35
+ export function refusalNotifier(onRefused, log = () => {}) {
36
+ if (typeof onRefused !== 'function') return () => {};
37
+ return (reason, who = {}, detail = '') => {
38
+ const clean = {};
39
+ for (const [k, v] of Object.entries(who)) if (v !== undefined && v !== null && v !== '') clean[k] = v;
40
+ try { onRefused({ reason, who: clean, detail: String(detail) }); } catch (e) { log(`onRefused threw: ${e?.message ?? e}`); }
41
+ };
42
+ }
@@ -24,6 +24,7 @@ import { SealedBridge } from './bridge-seal.mjs';
24
24
  import { resolveBackends } from './host-backends.mjs';
25
25
  import { createConnectionFactory, hostFeatures } from './server/connection.mjs';
26
26
  import { validateOnShare } from './shares.mjs';
27
+ import { refusalNotifier, validateOnRefused } from './refusal.mjs';
27
28
 
28
29
  const BACKOFF_START_MS = 500;
29
30
  const BACKOFF_MAX_MS = 30_000;
@@ -71,6 +72,9 @@ const BACKOFF_MAX_MS = 30_000;
71
72
  * @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => void | Promise<void>} [options.onShare]
72
73
  * Folders an operator offers (`ShareOffer`, #159), once per share, as an object of async file operations. The Rust CLI
73
74
  * offers shares on a direct or pipe-relayed session (`wsh --share`), not over `wsh reverse-connect` yet.
75
+ * @param {(refusal: { reason: string, who: { username?: string, fingerprint?: string, address?: string }, detail: string }) => void} [options.onRefused]
76
+ * #163: called when this host turns an operator away (`unauthorized` when `accept` says no, `busy`, `proof-required`,
77
+ * `proof-failed`, `not-sealed`, `seal-failed`; see `REFUSAL_REASONS`), with what is known of `who` and a human `detail`.
74
78
  * @param {(line: string) => void} [options.onLog]
75
79
  */
76
80
  export function createReverseHost(options = {}) {
@@ -85,9 +89,11 @@ export function createReverseHost(options = {}) {
85
89
  */
86
90
  export function createReverseHostWith({
87
91
  url, username, keyPair, accept, reconnect = true, connect = {}, peerType = 'host', reportFeatures = true, maxOperators = 1, e2e = {},
88
- requireOperatorProof = false, proofTimeoutMs = 5000, onLog = () => {}, onShare,
92
+ requireOperatorProof = false, proofTimeoutMs = 5000, onLog = () => {}, onShare, onRefused,
89
93
  } = {}, backends) {
90
94
  validateOnShare(onShare, 'createReverseHost');
95
+ validateOnRefused(onRefused, 'createReverseHost');
96
+ const notifyRefused = refusalNotifier(onRefused, onLog);
91
97
  if (typeof requireOperatorProof !== 'boolean') throw new TypeError('createReverseHost: requireOperatorProof must be a boolean');
92
98
  if (requireOperatorProof && e2e === false) throw new TypeError('createReverseHost: requireOperatorProof seals the bridge, which needs e2e (do not set e2e: false)');
93
99
  if (requireOperatorProof && !reportFeatures) throw new TypeError('createReverseHost: requireOperatorProof needs reportFeatures (the operator learns "e2e-sealed" from ReverseAccept.features)');
@@ -163,8 +169,11 @@ export function createReverseHostWith({
163
169
  c.onReverseConnect = async (req) => {
164
170
  const from = req.from_fingerprint;
165
171
  const answer = (m) => c.sendRelayControl(m).catch(() => {});
166
- const refuse = (reason) => answer(reverseReject({ targetFingerprint: myFingerprint, username, reason }));
167
- if (typeof from !== 'string' || !from) { await refuse('busy: this host is already serving an operator'); return; }
172
+ const refuse = (reason, code = 'busy') => {
173
+ notifyRefused(code, { fingerprint: typeof from === 'string' ? from : undefined, username: req.username }, reason);
174
+ return answer(reverseReject({ targetFingerprint: myFingerprint, username, reason }));
175
+ };
176
+ if (typeof from !== 'string' || !from) { await refuse('busy: this host is already serving an operator', 'bad-request'); return; }
168
177
  if (bridges.has(from) || reserved.has(from)) { await refuse('busy: you already have a bridge with this host'); return; }
169
178
  if (bridges.size + reserved.size >= operatorLimit()) {
170
179
  await refuse(manyOperators() ? `busy: this host is already serving its maximum of ${maxOperators} operators` : 'busy: this host is already serving an operator');
@@ -175,20 +184,21 @@ export function createReverseHostWith({
175
184
  try {
176
185
  // Who is this operator? The relay says (`from`); with proof the operator says so itself (#117).
177
186
  const canProve = c.hasFeature(OPERATOR_PROOF_FEATURE) && Array.isArray(req.features) && req.features.includes(OPERATOR_PROOF_FEATURE);
178
- if (requireOperatorProof && !canProve) { await refuse('operator proof required'); return; }
187
+ if (requireOperatorProof && !canProve) { await refuse('operator proof required', 'proof-required'); return; }
179
188
  let proven = null;
180
189
  let challenge = null;
181
190
  if (canProve) {
182
191
  const outcome = await challengeOperator(c, from);
183
- if (outcome.error) { await refuse(outcome.error); return; }
192
+ if (outcome.error) { await refuse(outcome.error, 'proof-failed'); return; }
184
193
  ({ proven, challenge } = outcome);
185
194
  // The relay's claim and the operator's own must agree: a relay that rewrote from_fingerprint is caught here.
186
- if (proven.fingerprint !== from) { onLog(`[reverse] proof is by ${proven.fingerprint.slice(0, 12)}, the relay said ${from.slice(0, 12)}`); await refuse('operator proof does not match the identity the relay asserted'); return; }
187
- if (proven.username !== String(req.username ?? '')) { await refuse('operator proof names another username than the relay asserted'); return; }
195
+ if (proven.fingerprint !== from) { onLog(`[reverse] proof is by ${proven.fingerprint.slice(0, 12)}, the relay said ${from.slice(0, 12)}`); await refuse('operator proof does not match the identity the relay asserted', 'proof-failed'); return; }
196
+ if (proven.username !== String(req.username ?? '')) { await refuse('operator proof names another username than the relay asserted', 'proof-failed'); return; }
188
197
  }
189
198
  const who = { fingerprint: from, username: String(req.username ?? ''), proven: !!proven, ...(proven ? { publicKey: proven.publicKey } : {}) };
190
199
  try { ok = (await accept?.(who)) === true; } catch (e) { onLog(`[reverse] accept threw: ${e.message}`); }
191
- if (!ok || bridges.size >= operatorLimit()) { await refuse('not accepted'); return; }
200
+ if (!ok) { await refuse('not accepted', 'unauthorized'); return; }
201
+ if (bridges.size >= operatorLimit()) { await refuse('not accepted'); return; }
192
202
  c.trustRelayPeer(from);
193
203
  const bridge = makeBridge(c, from, String(req.username ?? 'operator'), proven, challenge);
194
204
  bridges.set(from, bridge);
@@ -253,7 +263,9 @@ export function createReverseHostWith({
253
263
  });
254
264
  let chain = Promise.resolve();
255
265
  let giveUp = null;
256
- const fail = (why) => { onLog(`[reverse] sealed bridge with ${from.slice(0, 12)} failed: ${why}`); endBridge(from); };
266
+ const who = { fingerprint: from, username: operatorName };
267
+ let unsealedReported = false;
268
+ const fail = (why) => { onLog(`[reverse] sealed bridge with ${from.slice(0, 12)} failed: ${why}`); notifyRefused('seal-failed', who, why); endBridge(from); };
257
269
  if (mustSeal) {
258
270
  giveUp = setTimeout(() => { if (!sealed) fail('no key exchange in time'); }, proofTimeoutMs * 2);
259
271
  giveUp.unref?.();
@@ -276,7 +288,11 @@ export function createReverseHostWith({
276
288
  }).catch((e) => fail(e.message));
277
289
  return;
278
290
  }
279
- if (mustSeal) { onLog(`[reverse] dropped a message that is not sealed (type ${msg.type}) on a bridge that must be`); return; }
291
+ if (mustSeal) {
292
+ onLog(`[reverse] dropped a message that is not sealed (type ${msg.type}) on a bridge that must be`);
293
+ if (!unsealedReported) { unsealedReported = true; notifyRefused('not-sealed', who, `a message that is not sealed (type ${msg.type}) on a bridge that must be`); }
294
+ return;
295
+ }
280
296
  base.receiveMessage(msg);
281
297
  },
282
298
  bindStream: (s) => base.bindStream?.(s),
@@ -24,7 +24,7 @@ import {
24
24
  generateNonce, verifyChallenge, fingerprint, importPublicKeyRaw,
25
25
  } from '../auth.mjs';
26
26
  import { FILE_CHUNK_BYTES, MAX_ATTACHMENTS } from './constants.mjs';
27
- import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE } from '../features.mjs';
27
+ import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE } from '../features.mjs';
28
28
  import { RpcChannel, RPC_FEATURE, RPC_MAX_MESSAGE_PREFIX, rpcProtocolFeature } from '../rpc.mjs';
29
29
  import { sealFrame, openFrame, ROLE_TAGS } from '../e2e-frame.mjs';
30
30
  import { E2EResponder, E2E_FEATURE, E2E_SIGN_FEATURE } from '../e2e-exchange.mjs';
@@ -35,14 +35,12 @@ 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
37
  import { SealedBridge } from '../bridge-seal.mjs';
38
+ import { refusalNotifier, validateOnRefused } from '../refusal.mjs';
38
39
  import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMessage, toHex } from '../host-key.mjs';
39
40
  import { SHARES_FEATURE, createShareSession } from '../shares.mjs';
40
41
 
41
42
  export const STREAM_ANNOUNCE = 'stream-announce';
42
- /** Host feature (#155): this host seals the whole session end to end when asked (a signed `KeyExchange` for the connection's session id). */
43
- export const SESSION_SEAL_FEATURE = 'e2e-session';
44
- /** Host feature: this host serves nothing on a session that is not sealed. */
45
- export const SESSION_SEAL_REQUIRED_FEATURE = 'e2e-session-required';
43
+ export { SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE };
46
44
 
47
45
  /**
48
46
  * The features a host built from `cfg` advertises (`ServerHello.features`, minus the host-key proof).
@@ -124,6 +122,8 @@ export function createConnectionFactory(cfg) {
124
122
  bindTimeoutMs: cfg.bindTimeoutMs ?? 3000,
125
123
  log: cfg.log ?? (() => {}),
126
124
  };
125
+ validateOnRefused(cfg.onRefused, 'createConnectionFactory');
126
+ const notifyRefused = refusalNotifier(cfg.onRefused, cfg.log);
127
127
  let counter = 0;
128
128
  // What a client may put in `Open.env` (#126): an allow-list unless the host says otherwise.
129
129
  const execEnv = clientEnvFilter(cfg.execOptions?.clientEnv);
@@ -381,8 +381,17 @@ export function createConnectionFactory(cfg) {
381
381
  await send(authOk({ sessionId: state.sessionId, token: randomBytes(16), ttl: Math.ceil(ttlMs / 1000) }));
382
382
  }
383
383
 
384
- async function refuse(reason) {
384
+ /** Tell the embedder (`onRefused`, #163) once per connection that this peer was turned away. */
385
+ let refusalReported = false;
386
+ function reportRefused(code, detail, extra = {}) {
387
+ if (refusalReported) return;
388
+ refusalReported = true;
389
+ notifyRefused(code, { username: state.username, fingerprint: state.fingerprint, address: remote.address, ...extra }, detail);
390
+ }
391
+
392
+ async function refuse(reason, code = 'bad-request', who) {
385
393
  log(`AUTH_FAIL: ${reason}`);
394
+ reportRefused(code, reason, who);
386
395
  await send(authFail({ reason }));
387
396
  setTimeout(() => shutdown('auth failed'), 50);
388
397
  }
@@ -393,13 +402,13 @@ export function createConnectionFactory(cfg) {
393
402
  if (!USERNAME_RE.test(user)) return refuse(`bad username ${JSON.stringify(user)}`);
394
403
  const method = m.auth_method || 'pubkey';
395
404
  if (method === 'password') {
396
- if (!cfg.methods.password) return refuse('password auth is not enabled on this host');
405
+ if (!cfg.methods.password) return refuse('password auth is not enabled on this host', 'method-disabled', { username: user });
397
406
  } else if (method === 'pubkey') {
398
- if (!cfg.methods.pubkey) return refuse('pubkey auth is not enabled on this host');
407
+ if (!cfg.methods.pubkey) return refuse('pubkey auth is not enabled on this host', 'method-disabled', { username: user });
399
408
  } else {
400
- return refuse(`unsupported auth method ${JSON.stringify(method)}`);
409
+ return refuse(`unsupported auth method ${JSON.stringify(method)}`, 'bad-request', { username: user });
401
410
  }
402
- if (cfg.sealSession === 'require' && cfg.hostKey && !dataStreams && method !== 'pubkey') return refuse('this host requires a sealed session, which needs a key login');
411
+ if (cfg.sealSession === 'require' && cfg.hostKey && !dataStreams && method !== 'pubkey') return refuse('this host requires a sealed session, which needs a key login', 'not-sealed', { username: user });
403
412
  state.username = user;
404
413
  state.method = method;
405
414
  gateway?.setPeerFeatures(m.features);
@@ -445,6 +454,7 @@ export function createConnectionFactory(cfg) {
445
454
  fp = await fingerprint(m.public_key);
446
455
  key = await importPublicKeyRaw(m.public_key);
447
456
  } catch { return refuse('malformed public key'); }
457
+ const claimed = { fingerprint: fp };
448
458
  // Verify the signature first: nothing about who is on the allowlist
449
459
  // is revealed to a caller who cannot even prove they hold a key.
450
460
  // The signature may be over the empty binding (a client that knows nothing of #119, or a browser that can
@@ -463,16 +473,16 @@ export function createConnectionFactory(cfg) {
463
473
  if (required) {
464
474
  let unbound = false;
465
475
  try { unbound = await verifyChallenge(key, m.signature, state.sessionId, state.nonce, { username: state.username }); } catch { /* not that either */ }
466
- if (unbound) return refuse('channel binding required: the signature is not bound to this connection');
476
+ if (unbound) return refuse('channel binding required: the signature is not bound to this connection', 'binding-required', claimed);
467
477
  }
468
- return refuse('signature does not verify over the transcript');
478
+ return refuse('signature does not verify over the transcript', 'bad-signature', claimed);
469
479
  }
470
480
  state.channelBinding = boundKinds;
471
481
  let allowed = false;
472
482
  try {
473
483
  allowed = await cfg.authorize({ username: state.username, fingerprint: fp, publicKey: m.public_key });
474
484
  } catch (e) { log(`authorize threw: ${e.message}`); }
475
- if (!allowed) return refuse('key not authorized');
485
+ if (!allowed) return refuse('key not authorized', 'unauthorized', claimed);
476
486
  state.authed = true;
477
487
  state.fingerprint = fp;
478
488
  state.publicKey = m.public_key;
@@ -493,12 +503,13 @@ export function createConnectionFactory(cfg) {
493
503
  if (!sealed.bridge.isFrame(m)) { log(`dropped a plaintext message (type ${m.type}) on a sealed session`); return undefined; }
494
504
  try { return await sealed.bridge.open(m); } catch (e) {
495
505
  log(`a sealed frame did not open (${e.message}): closing the session`);
506
+ reportRefused('seal-failed', `a sealed frame did not open: ${e.message}`);
496
507
  shutdown('sealed frame did not open');
497
508
  return undefined;
498
509
  }
499
510
  }
500
511
  if (m.type === MSG.KEY_EXCHANGE && m.session_id === state.sessionId) {
501
- if (!state.publicKey) { log('sealed session refused: no login key to authenticate the initiator with'); shutdown('sealed session needs a key login'); return undefined; }
512
+ if (!state.publicKey) { log('sealed session refused: no login key to authenticate the initiator with'); reportRefused('seal-failed', 'no login key to authenticate the initiator with'); shutdown('sealed session needs a key login'); return undefined; }
502
513
  sealed.responder ??= new E2EResponder({
503
514
  signKey: cfg.hostKey, hybrid: true, identity: cfg.hostKey.publicKey,
504
515
  initiator: { publicKey: state.publicKey, require: true },
@@ -509,12 +520,13 @@ export function createConnectionFactory(cfg) {
509
520
  sealed.bridge = new SealedBridge({ key: result.key, sessionId: state.sessionId, role: 'responder', scope: 'session' });
510
521
  log(`session sealed${result.hybrid ? ' (hybrid)' : ''}`);
511
522
  }
512
- } catch (e) { log(`sealed session refused: ${e.message}`); shutdown('sealed session key exchange failed'); }
523
+ } catch (e) { log(`sealed session refused: ${e.message}`); reportRefused('seal-failed', `key exchange failed: ${e.message}`); shutdown('sealed session key exchange failed'); }
513
524
  return undefined;
514
525
  }
515
526
  if (m.type === MSG.PING) return m;
516
527
  if (sealRequired) {
517
528
  log(`refused a plaintext message (type ${m.type}): this host requires a sealed session`);
529
+ reportRefused('not-sealed', `a plaintext message (type ${m.type}) on a host that requires a sealed session`);
518
530
  await deliverRaw(errorMsg({ code: 1, message: 'this host requires a sealed session (e2e-session-required)' }));
519
531
  setTimeout(() => shutdown('sealed session required'), 50);
520
532
  return undefined;
@@ -524,20 +536,20 @@ export function createConnectionFactory(cfg) {
524
536
 
525
537
  async function handlePasswordAuth(m) {
526
538
  state.awaitingPassword = false; // one guess per connection
527
- if (m.method !== 'password' || typeof m.password !== 'string') return refuse('expected a password AUTH');
539
+ if (m.method !== 'password' || typeof m.password !== 'string') return refuse('expected a password AUTH', 'bad-request');
528
540
  const rl = cfg.rateLimit;
529
541
  const key = rl.key({ address: remote.address, headers: remote.headers, username: state.username });
530
542
  const locked = rl.limiter.lockedFor(key);
531
543
  if (locked > 0) {
532
544
  // Not even evaluated: a locked-out caller learns nothing and costs nothing.
533
- return refuse(`too many failed attempts; try again in ${Math.ceil(locked / 1000)}s`);
545
+ return refuse(`too many failed attempts; try again in ${Math.ceil(locked / 1000)}s`, 'rate-limited');
534
546
  }
535
547
  let ok = false;
536
548
  try { ok = (await cfg.methods.password(state.username, m.password)) === true; } catch (e) { log(`password check threw: ${e.message}`); }
537
549
  if (!ok) {
538
550
  rl.limiter.fail(key);
539
551
  if (rl.failureDelayMs > 0) await new Promise((r) => setTimeout(r, rl.failureDelayMs));
540
- return refuse('authentication failed');
552
+ return refuse('authentication failed', 'unauthorized');
541
553
  }
542
554
  rl.limiter.succeed(key);
543
555
  state.authed = true;
@@ -485,6 +485,8 @@ export interface WshServerOptions {
485
485
  * async file operations to mount. Listing it makes the host state the `shares` feature.
486
486
  */
487
487
  onShare?: import('../host.js').WshOnShare;
488
+ /** #163: told once per connection this host turned away (an operator, on a reverse host), with a stable reason code (`REFUSAL_REASONS`, from `@johnhenry/wsh/host`). */
489
+ onRefused?: import('../host.js').WshOnRefused;
488
490
  onLog?: (line: string) => void;
489
491
  }
490
492
 
@@ -635,6 +637,8 @@ export interface WshReverseHostOptions {
635
637
  proofTimeoutMs?: number;
636
638
  /** Folders an operator offers over a bridge (#159), once per share, as an object of async file operations. */
637
639
  onShare?: import('../host.js').WshOnShare;
640
+ /** #163: told once per connection this host turned away (an operator, on a reverse host), with a stable reason code (`REFUSAL_REASONS`, from `@johnhenry/wsh/host`). */
641
+ onRefused?: import('../host.js').WshOnRefused;
638
642
  onLog?: (line: string) => void;
639
643
  }
640
644
 
@@ -16,6 +16,7 @@ import { RelayHub } from './relay.mjs';
16
16
  import { startWebTransport } from './webtransport.mjs';
17
17
  import { createConnectionFactory, STREAM_ANNOUNCE } from './connection.mjs';
18
18
  import { validateOnShare } from '../shares.mjs';
19
+ import { validateOnRefused } from '../refusal.mjs';
19
20
  import { normalizeGateway, createGatewaySession } from './gateway.mjs';
20
21
  import { createRpcHost, mcpServerAdapter } from './rpc.mjs';
21
22
  import { bindSocket } from './socket.mjs';
@@ -97,14 +98,18 @@ function tlsChannelBinding(socket) {
97
98
  * @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => void | Promise<void>} [options.onShare]
98
99
  * Folders of the operator's machine (`wsh --share`, #159), once per share, as an object of async file operations to mount;
99
100
  * listing it makes the host state the `shares` feature. As for `createMemoryHost`.
101
+ * @param {(refusal: { reason: string, who: { username?: string, fingerprint?: string, address?: string }, detail: string }) => void} [options.onRefused]
102
+ * Called once per connection this host turned away, with a stable `reason` code (`REFUSAL_REASONS`, from
103
+ * `@johnhenry/wsh/host`), what is known of `who` and a human `detail`. As for `createMemoryHost`.
100
104
  * @param {(line: string) => void} [options.onLog]
101
105
  * @returns {{ listen(): Promise<{address: string, port: number}>, accept(socket: object, options?: object): Promise<{ close(): void }>, close(): Promise<void>, address(): ({address: string, port: number} | null) }}
102
106
  */
103
107
  export function createWshServer({
104
108
  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 = () => {},
105
- onShare,
109
+ onShare, onRefused,
106
110
  } = {}) {
107
111
  validateOnShare(onShare, 'createWshServer');
112
+ validateOnRefused(onRefused, 'createWshServer');
108
113
  if (sealSession !== false && sealSession !== 'offer' && sealSession !== 'require') throw new TypeError("createWshServer: sealSession must be false, 'offer' or 'require'");
109
114
  if (sealSession && !hostKey) throw new TypeError('createWshServer: sealSession needs a hostKey (the host signs its half of the key exchange with it)');
110
115
  if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
@@ -158,7 +163,7 @@ export function createWshServer({
158
163
  return createConnectionFactory({
159
164
  authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
160
165
  methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, createGatewaySession, sessions: registry, relay: hub,
161
- onShare,
166
+ onShare, onRefused,
162
167
  });
163
168
  })();
164
169
  ready.catch(() => { ready = null; });
package/src/shares.mjs CHANGED
@@ -25,6 +25,18 @@ const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
25
25
  const ERRNOS = new Set(['ENOENT', 'EEXIST', 'ENOTDIR', 'EISDIR', 'ENOTEMPTY', 'EACCES', 'EPERM', 'EROFS', 'EINVAL', 'EBADF', 'ELOOP',
26
26
  'ENAMETOOLONG', 'ENOSPC', 'EMFILE', 'EBUSY', 'EAGAIN', 'EXDEV', 'EFBIG', 'ENOTSUP', 'ESTALE', 'EIO']);
27
27
  const MAX_SHARES = 16;
28
+ const MAX_ROOT_BYTES = 4096;
29
+
30
+ /**
31
+ * The advisory root path of each share from `ShareOffer.paths` (#164): an array exactly as long as `shares`, each entry an
32
+ * absolute string of at most 4096 bytes without NUL. Anything else is `undefined` (never an error): the host cannot verify it.
33
+ * @returns {Array<string | undefined>}
34
+ */
35
+ function offeredRoots(paths, count) {
36
+ const none = new Array(count).fill(undefined);
37
+ if (!Array.isArray(paths) || paths.length !== count) return none;
38
+ return paths.map((p) => (typeof p === 'string' && p.startsWith('/') && !p.includes('\0') && new TextEncoder().encode(p).length <= MAX_ROOT_BYTES ? p : undefined));
39
+ }
28
40
  const MAX_INFLIGHT = 64;
29
41
  const MIN_BYTES = 4096;
30
42
  const MAX_BYTES = 4 * 1024 * 1024;
@@ -231,7 +243,7 @@ function wireAttr(c = {}) {
231
243
  * ("/"-separated; a leading "/" means the root); `..` is refused by the operator's client. Errors are `ShareError`s
232
244
  * with `.code` an errno-like string (`ENOENT`, `EROFS`, ...).
233
245
  */
234
- function createShareFs(core, name, writable, signal) {
246
+ function createShareFs(core, name, writable, signal, root) {
235
247
  const call = (op, fields) => core.call(name, op, fields);
236
248
  const norm = (p) => { if (typeof p !== 'string') throw new ShareError('EINVAL', 'a path must be a string'); return p; };
237
249
  const maxFileBytes = DEFAULT_MAX_FILE_BYTES;
@@ -240,6 +252,8 @@ function createShareFs(core, name, writable, signal) {
240
252
  name,
241
253
  /** Whether the operator offered writes. */
242
254
  writable,
255
+ /** The share's root path on the operator's machine, as the operator typed it, or undefined. ADVISORY and unverified (#164). */
256
+ get root() { return root; },
243
257
  maxFileBytes,
244
258
  /** Aborted when the connection to the operator ends. */
245
259
  signal,
@@ -392,8 +406,9 @@ export function createShareSession({ send, onShare, who, log = () => {}, timeout
392
406
  }
393
407
  const writable = new Set(Array.isArray(m.writable) ? m.writable.filter((n) => names.includes(n)) : []);
394
408
  core.configure({ maxInflight: clampInt(m.max_inflight, 1, MAX_INFLIGHT), maxBytes: clampInt(m.max_bytes, MIN_BYTES, MAX_BYTES) });
395
- for (const name of names) {
396
- const fs = createShareFs(core, name, writable.has(name), abort.signal);
409
+ const roots = offeredRoots(m.paths, names.length);
410
+ for (const [i, name] of names.entries()) {
411
+ const fs = createShareFs(core, name, writable.has(name), abort.signal, roots[i]);
397
412
  shares.set(name, fs);
398
413
  Promise.resolve()
399
414
  .then(() => onShare(name, fs, who()))