@johnhenry/wsh 0.40.0 → 0.41.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
@@ -861,6 +861,20 @@ readable by the relay; the signed key exchange is not secret), the sizes and tim
861
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
862
  session yet, so against a JS client use a host that only `'offer'`s.
863
863
 
864
+ #### Knowing who a host turned away: `onRefused` (#163)
865
+
866
+ `createMemoryHost`, `createWshServer` and `createReverseHost` take `onRefused({ reason, who, detail })`, called once per
867
+ connection the host turned away, so an embedder can tell the user why a terminal was refused without parsing `onLog`. `reason`
868
+ is a stable code, the list is exported as `REFUSAL_REASONS` from `@johnhenry/wsh/host`: `not-sealed` (a plain client on a
869
+ host that requires a sealed session, or a password login there), `unauthorized` (a key the host does not allow, a wrong
870
+ password, or an operator a reverse host's `accept` turned down), `binding-required`, `bad-signature`, `method-disabled`,
871
+ `rate-limited`, `bad-request`, `seal-failed` (a sealed session's key exchange failed or a frame did not open), and for a reverse
872
+ host `busy`, `proof-required`, `proof-failed`. `who` holds what is known: `username`, `fingerprint` (a key login), `address` (when
873
+ the transport gives one); a refusal before the login names no one. `detail` is human text and not stable. New codes may be added;
874
+ none is renamed. It reports only what this host decided: it does not say what a relay in the middle dropped, a client
875
+ that never reached the host, or a frame the host silently ignored on an already-sealed session (a plain message after sealing
876
+ is dropped, as before, without a report).
877
+
864
878
  #### A pipe relay (`@johnhenry/wsh/pipe-relay`, #118)
865
879
 
866
880
  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
@@ -1484,7 +1498,7 @@ instead of dragging its own toolchain and CI job into an unrelated
1484
1498
  browser-app repo. It was previously deleted from clawser by accident
1485
1499
  (2026-03-14) and restored (2026-07-05) before this move.
1486
1500
 
1487
- Four crates, workspace-versioned (currently `0.11.0`):
1501
+ Four crates, workspace-versioned (currently `0.12.0`):
1488
1502
 
1489
1503
  | Crate | Kind | Description |
1490
1504
  |-------|------|--------------|
@@ -1556,6 +1570,12 @@ stderr, what it shares and how (`wsh: sharing "src" = /home/me/project (read-onl
1556
1570
  command, applies to `wsh [user@]host [command...]` and `wsh connect` only (`scp`, `ls`, `sftp`, `copy-id` refuse it), and fails
1557
1571
  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
1572
 
1573
+ **The path is sent too (#164).** The offer carries each share's root as an absolute path, as you typed it (made tidy: `//`, `.`
1574
+ and a trailing `/` removed; `..` is left as typed), so a host that was asked for `-v /home/me/project:/in` can recognise the share
1575
+ it belongs to (`fs.root`) instead of a hash in the share name. It is advisory (see [Security model](#security-model)): the host
1576
+ cannot verify it. To keep your directory layout to yourself add `--share-hide-path`: the offer then has no path (exactly what
1577
+ 0.40.0 / `rust-v0.11.0` clients sent), `fs.root` is `undefined` on the host, and everything else works.
1578
+
1559
1579
  **What the host can do.** Stat and lstat, readdir (every entry WITH its attributes, in pages), readlink, open and read (ranges; a
1560
1580
  small file's content rides the open, so reading it is one message), write, create, mkdir, rename, unlink, rmdir, setattr (mode,
1561
1581
  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 +1608,18 @@ const host = createMemoryHost({
1588
1608
  const entries = await fs.readdir('/'); // [{ name, type, size, mode, mtimeMs, ... }] -- attributes included
1589
1609
  const pkg = JSON.parse(new TextDecoder().decode(await fs.readFile('/package.json')));
1590
1610
  if (fs.writable) await fs.writeFile('/out/built.txt', new TextEncoder().encode('done'));
1611
+ if (fs.root === '/home/me/project') { /* a request for `-v /home/me/project:/in` is this share */ }
1591
1612
  },
1592
1613
  });
1593
1614
  ```
1594
1615
 
1616
+ `fs.root` (a string or `undefined`) is the directory's path on the operator's machine, as the operator typed it (#164). **It is
1617
+ advisory and unverified**: the operator's client sends it, the host cannot check it, and the CLI still enforces the real
1618
+ boundary (it serves only the directory it opened, whatever the path says). It is `undefined` when the client is older, sent
1619
+ `--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
1620
+ most 4096 bytes without a NUL and `paths` has exactly one entry per share; anything else is ignored, never an error. Use it to
1621
+ recognise a share, not to decide what is safe.
1622
+
1595
1623
  `createMemoryHost`, `createWshServer` and `createReverseHost` take `onShare`; listing it makes the host state the feature
1596
1624
  `shares`, and a host without it never hears an offer. `fs` is an object of async operations (`stat`, `lstat`, `readlink`,
1597
1625
  `readdir`, `open` / `create` returning a file with `read(offset, length)` / `write` / `setattr` / `close`, `readFile`,
@@ -1612,7 +1640,7 @@ than left to be found.
1612
1640
  | Capability | JS SDK (browser) | Rust CLI/client | Unified via |
1613
1641
  |---|---|---|---|
1614
1642
  | 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) |
1643
+ | 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
1644
  | 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
1645
  | 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
1646
  | 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 +1648,7 @@ than left to be found.
1620
1648
  | 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
1649
  | 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
1650
  | 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) |
1651
+ | 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
1652
  | 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
1653
  | 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
1654
  | 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 +1661,9 @@ than left to be found.
1633
1661
  | 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
1662
  | 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
1663
  | 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` |
1664
+ | 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` |
1637
1665
  | 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) |
1666
+ | 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
1667
  | `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
1668
  | `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
1669
  | 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 +1722,10 @@ plus one `SHA256SUMS` file covering every archive in the release. These
1693
1722
  names are a stable contract other repos (clawser) pin and download by --
1694
1723
  do not change them without coordinating downstream.
1695
1724
 
1725
+ `wsh --version` and `wsh-server --version` print the workspace version the binary was built from (`wsh 0.12.0`), which is the
1726
+ 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
1727
+ version cannot be read from the binary (look for a flag in `wsh --help` instead).
1728
+
1696
1729
  ## Security model
1697
1730
 
1698
1731
  wsh's protocol draws its line at authentication and message integrity: what
@@ -1920,6 +1953,11 @@ What this does **not** protect against:
1920
1953
  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
1954
  JS side treats the CLI as untrusted too (window, size, shape and deadline of every reply are checked), but an embedder
1922
1955
  that mounts `fs` is responsible for what it does with the files.
1956
+ **The root path (`ShareOffer.paths`, `fs.root`, #164) is a claim, not evidence.** By default the CLI tells the host where each
1957
+ shared directory is on your machine (so it can map a bind-mount source onto a share); the host cannot verify it, a modified
1958
+ client can send any string, and the CLI serves only the directory it opened whatever the path says. A host must use it to
1959
+ recognise a share, never to decide what is safe to mount or run. It reveals your directory layout (a user name, a project
1960
+ name) to the host and to a relay that is not sealed; `--share-hide-path` leaves it out.
1923
1961
  - **Rust `wsh-server`'s `AuthOk.ttl` is 0 and its `token` is opaque** (as the
1924
1962
  JS host's, above): nothing is promised or enforced at connection level; do not
1925
1963
  treat the token as a credential.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.40.0",
3
+ "version": "0.41.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/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';
@@ -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),
@@ -35,6 +35,7 @@ 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
 
@@ -124,6 +125,8 @@ export function createConnectionFactory(cfg) {
124
125
  bindTimeoutMs: cfg.bindTimeoutMs ?? 3000,
125
126
  log: cfg.log ?? (() => {}),
126
127
  };
128
+ validateOnRefused(cfg.onRefused, 'createConnectionFactory');
129
+ const notifyRefused = refusalNotifier(cfg.onRefused, cfg.log);
127
130
  let counter = 0;
128
131
  // What a client may put in `Open.env` (#126): an allow-list unless the host says otherwise.
129
132
  const execEnv = clientEnvFilter(cfg.execOptions?.clientEnv);
@@ -381,8 +384,17 @@ export function createConnectionFactory(cfg) {
381
384
  await send(authOk({ sessionId: state.sessionId, token: randomBytes(16), ttl: Math.ceil(ttlMs / 1000) }));
382
385
  }
383
386
 
384
- async function refuse(reason) {
387
+ /** Tell the embedder (`onRefused`, #163) once per connection that this peer was turned away. */
388
+ let refusalReported = false;
389
+ function reportRefused(code, detail, extra = {}) {
390
+ if (refusalReported) return;
391
+ refusalReported = true;
392
+ notifyRefused(code, { username: state.username, fingerprint: state.fingerprint, address: remote.address, ...extra }, detail);
393
+ }
394
+
395
+ async function refuse(reason, code = 'bad-request', who) {
385
396
  log(`AUTH_FAIL: ${reason}`);
397
+ reportRefused(code, reason, who);
386
398
  await send(authFail({ reason }));
387
399
  setTimeout(() => shutdown('auth failed'), 50);
388
400
  }
@@ -393,13 +405,13 @@ export function createConnectionFactory(cfg) {
393
405
  if (!USERNAME_RE.test(user)) return refuse(`bad username ${JSON.stringify(user)}`);
394
406
  const method = m.auth_method || 'pubkey';
395
407
  if (method === 'password') {
396
- if (!cfg.methods.password) return refuse('password auth is not enabled on this host');
408
+ if (!cfg.methods.password) return refuse('password auth is not enabled on this host', 'method-disabled', { username: user });
397
409
  } else if (method === 'pubkey') {
398
- if (!cfg.methods.pubkey) return refuse('pubkey auth is not enabled on this host');
410
+ if (!cfg.methods.pubkey) return refuse('pubkey auth is not enabled on this host', 'method-disabled', { username: user });
399
411
  } else {
400
- return refuse(`unsupported auth method ${JSON.stringify(method)}`);
412
+ return refuse(`unsupported auth method ${JSON.stringify(method)}`, 'bad-request', { username: user });
401
413
  }
402
- if (cfg.sealSession === 'require' && cfg.hostKey && !dataStreams && method !== 'pubkey') return refuse('this host requires a sealed session, which needs a key login');
414
+ 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
415
  state.username = user;
404
416
  state.method = method;
405
417
  gateway?.setPeerFeatures(m.features);
@@ -445,6 +457,7 @@ export function createConnectionFactory(cfg) {
445
457
  fp = await fingerprint(m.public_key);
446
458
  key = await importPublicKeyRaw(m.public_key);
447
459
  } catch { return refuse('malformed public key'); }
460
+ const claimed = { fingerprint: fp };
448
461
  // Verify the signature first: nothing about who is on the allowlist
449
462
  // is revealed to a caller who cannot even prove they hold a key.
450
463
  // The signature may be over the empty binding (a client that knows nothing of #119, or a browser that can
@@ -463,16 +476,16 @@ export function createConnectionFactory(cfg) {
463
476
  if (required) {
464
477
  let unbound = false;
465
478
  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');
479
+ if (unbound) return refuse('channel binding required: the signature is not bound to this connection', 'binding-required', claimed);
467
480
  }
468
- return refuse('signature does not verify over the transcript');
481
+ return refuse('signature does not verify over the transcript', 'bad-signature', claimed);
469
482
  }
470
483
  state.channelBinding = boundKinds;
471
484
  let allowed = false;
472
485
  try {
473
486
  allowed = await cfg.authorize({ username: state.username, fingerprint: fp, publicKey: m.public_key });
474
487
  } catch (e) { log(`authorize threw: ${e.message}`); }
475
- if (!allowed) return refuse('key not authorized');
488
+ if (!allowed) return refuse('key not authorized', 'unauthorized', claimed);
476
489
  state.authed = true;
477
490
  state.fingerprint = fp;
478
491
  state.publicKey = m.public_key;
@@ -493,12 +506,13 @@ export function createConnectionFactory(cfg) {
493
506
  if (!sealed.bridge.isFrame(m)) { log(`dropped a plaintext message (type ${m.type}) on a sealed session`); return undefined; }
494
507
  try { return await sealed.bridge.open(m); } catch (e) {
495
508
  log(`a sealed frame did not open (${e.message}): closing the session`);
509
+ reportRefused('seal-failed', `a sealed frame did not open: ${e.message}`);
496
510
  shutdown('sealed frame did not open');
497
511
  return undefined;
498
512
  }
499
513
  }
500
514
  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; }
515
+ 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
516
  sealed.responder ??= new E2EResponder({
503
517
  signKey: cfg.hostKey, hybrid: true, identity: cfg.hostKey.publicKey,
504
518
  initiator: { publicKey: state.publicKey, require: true },
@@ -509,12 +523,13 @@ export function createConnectionFactory(cfg) {
509
523
  sealed.bridge = new SealedBridge({ key: result.key, sessionId: state.sessionId, role: 'responder', scope: 'session' });
510
524
  log(`session sealed${result.hybrid ? ' (hybrid)' : ''}`);
511
525
  }
512
- } catch (e) { log(`sealed session refused: ${e.message}`); shutdown('sealed session key exchange failed'); }
526
+ } catch (e) { log(`sealed session refused: ${e.message}`); reportRefused('seal-failed', `key exchange failed: ${e.message}`); shutdown('sealed session key exchange failed'); }
513
527
  return undefined;
514
528
  }
515
529
  if (m.type === MSG.PING) return m;
516
530
  if (sealRequired) {
517
531
  log(`refused a plaintext message (type ${m.type}): this host requires a sealed session`);
532
+ reportRefused('not-sealed', `a plaintext message (type ${m.type}) on a host that requires a sealed session`);
518
533
  await deliverRaw(errorMsg({ code: 1, message: 'this host requires a sealed session (e2e-session-required)' }));
519
534
  setTimeout(() => shutdown('sealed session required'), 50);
520
535
  return undefined;
@@ -524,20 +539,20 @@ export function createConnectionFactory(cfg) {
524
539
 
525
540
  async function handlePasswordAuth(m) {
526
541
  state.awaitingPassword = false; // one guess per connection
527
- if (m.method !== 'password' || typeof m.password !== 'string') return refuse('expected a password AUTH');
542
+ if (m.method !== 'password' || typeof m.password !== 'string') return refuse('expected a password AUTH', 'bad-request');
528
543
  const rl = cfg.rateLimit;
529
544
  const key = rl.key({ address: remote.address, headers: remote.headers, username: state.username });
530
545
  const locked = rl.limiter.lockedFor(key);
531
546
  if (locked > 0) {
532
547
  // 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`);
548
+ return refuse(`too many failed attempts; try again in ${Math.ceil(locked / 1000)}s`, 'rate-limited');
534
549
  }
535
550
  let ok = false;
536
551
  try { ok = (await cfg.methods.password(state.username, m.password)) === true; } catch (e) { log(`password check threw: ${e.message}`); }
537
552
  if (!ok) {
538
553
  rl.limiter.fail(key);
539
554
  if (rl.failureDelayMs > 0) await new Promise((r) => setTimeout(r, rl.failureDelayMs));
540
- return refuse('authentication failed');
555
+ return refuse('authentication failed', 'unauthorized');
541
556
  }
542
557
  rl.limiter.succeed(key);
543
558
  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()))