@johnhenry/wsh 0.39.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
@@ -66,7 +66,7 @@ Or via CDN:
66
66
  - **MCP bridge** -- discover and invoke remote MCP tools through the control channel
67
67
  - **Session recording** -- own JSON schema (asciicast-v2-shaped, not a playable asciicast file -- see note below) recording and playback with seek/pause/resume
68
68
  - **Key management** -- IndexedDB storage with OPFS encrypted backup (PBKDF2 + AES-256-GCM)
69
- - **105 message types** -- handshake, channel, gateway, guest sharing, compression negotiation, copilot, policy, authorized-key management, and more
69
+ - **108 message types** -- handshake, channel, gateway, guest sharing, compression negotiation, copilot, policy, authorized-key management, and more
70
70
 
71
71
  > **Session recording is asciicast-v2-shaped, but not an asciicast file.**
72
72
  > The JS `SessionRecorder.toJSON()` export borrows asciicast v2's vocabulary --
@@ -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
@@ -904,8 +918,10 @@ host whichever relay carried it and a different host behind that name is refused
904
918
  command is sent. A plain URL target (`wsh alice@wss://relay/r/<id> ...`) also dials but is recorded under the URL's
905
919
  authority, which is the relay's, so prefer `--via`. `--via` works with `wsh [user@]host`, `connect`, `scp`, `ls`, `sftp`
906
920
  and `copy-id`; it is an error elsewhere, and cannot be combined with a URL target. A pipe relay is WebSocket only: no
907
- fallback, and `--transport` does not apply. The rendezvous id is not written to `last_session.json`. What the Rust
908
- client does not yet do (host-key proof, channel binding, sealed bridge) is listed under the Security model. The host side
921
+ fallback, and `--transport` does not apply. The rendezvous id is not written to `last_session.json`, and the CLI never
922
+ prints it: errors and `--verbose` logs show the relay's host and the id shortened to its first characters
923
+ (`wss://relay/r/AbCd...`). The Rust client verifies the host-key proof and binds the login to it, as on a direct
924
+ connection; what it does not do (seal the pipe-relayed session) is listed under the Security model. The host side
909
925
  is any process that can open a WebSocket to `pipeUrl(..., 'host')` and hand it to `accept`.
910
926
 
911
927
  ### Sessions: attach / resume / detach
@@ -1458,7 +1474,7 @@ so options the platform gains later need no change here.
1458
1474
 
1459
1475
  | Export | Description |
1460
1476
  |--------|-------------|
1461
- | `MSG` | 105 message type constants (hex opcodes) |
1477
+ | `MSG` | 108 message type constants (hex opcodes) |
1462
1478
  | `CHANNEL_KIND` | Channel types: `pty`, `exec`, `meta`, `file`, `tcp`, `udp`, `job` |
1463
1479
  | `AUTH_METHOD` | Auth methods: `pubkey`, `password` |
1464
1480
  | `cborEncode` / `cborDecode` | CBOR codec (maps, arrays, strings, ints, bytes, bools, null, floats) |
@@ -1482,7 +1498,7 @@ instead of dragging its own toolchain and CI job into an unrelated
1482
1498
  browser-app repo. It was previously deleted from clawser by accident
1483
1499
  (2026-03-14) and restored (2026-07-05) before this move.
1484
1500
 
1485
- Four crates, workspace-versioned (currently `0.10.0`):
1501
+ Four crates, workspace-versioned (currently `0.12.0`):
1486
1502
 
1487
1503
  | Crate | Kind | Description |
1488
1504
  |-------|------|--------------|
@@ -1537,6 +1553,83 @@ cannot do what a forward needs says so (`this host does not offer unix-socket fo
1537
1553
  the gateway policy`); a malformed spec exits with status 2 before anything is dialled. Up to 128 forwarded connections are
1538
1554
  open at once. `-L`/`-R`/`-N` apply to `wsh [user@]host [command...]` and `wsh connect` only.
1539
1555
 
1556
+ ### Sharing a directory with the host: `wsh --share` (#159)
1557
+
1558
+ A host with no disk of its own (a browser tab) sometimes needs files that live on the OPERATOR's machine: `docker run -v
1559
+ $PWD:/app` through `wsh -L /tmp/docker.sock:endpoint=docker` is the case that asked for this. `--share` offers a directory of
1560
+ THIS machine to the host for the life of the session; the CLI serves file operations on it, and nothing else.
1561
+
1562
+ ```bash
1563
+ wsh -N --share src=/home/me/project --share out=/home/me/build:rw --via wss://relay/r/<id> alice@tab.example
1564
+ wsh -N -L /tmp/docker.sock:endpoint=docker --share app=$PWD alice@tab.example # one connection, both
1565
+ ```
1566
+
1567
+ `--share NAME=/abs/dir[:ro|:rw]`, repeatable (at most 16; `NAME`: letters, digits, `.`, `_`, `-`, at most 64). **Read-only unless
1568
+ `:rw`.** The path must be absolute and an existing directory, or the CLI exits with status 2 before dialling. It says once, on
1569
+ stderr, what it shares and how (`wsh: sharing "src" = /home/me/project (read-only)`). It works with `-N`, `-L`, `--via` and a
1570
+ command, applies to `wsh [user@]host [command...]` and `wsh connect` only (`scp`, `ls`, `sftp`, `copy-id` refuse it), and fails
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.
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
+
1579
+ **What the host can do.** Stat and lstat, readdir (every entry WITH its attributes, in pages), readlink, open and read (ranges; a
1580
+ small file's content rides the open, so reading it is one message), write, create, mkdir, rename, unlink, rmdir, setattr (mode,
1581
+ times, truncate) and close, each a bounded `ShareRequest` the host sends and the CLI answers with an errno-like code. At most 16
1582
+ requests are in flight (the rest are refused `EAGAIN` at once), no data in a request or reply exceeds 256 KiB, a stalled host
1583
+ cannot make the CLI queue more than a few replies, at most 64 files are open at once, and the session's total read-plus-write rate
1584
+ is capped (256 MiB/s after a 32 MiB burst). The host's own API is [`onShare(name, fs, who)`](#serving-the-operators-files-from-a-host-onshare).
1585
+
1586
+ **What it will not do, whatever the host sends** (each rule has a test that fails when it is broken; see the Security model):
1587
+ the share exists only because it was named on the command line (nothing a host sends adds or widens one); every path is resolved
1588
+ component by component from a directory descriptor opened at start-up, with `O_NOFOLLOW` on each step, so a symlink in the middle
1589
+ of a path is `ELOOP` and one swapped in between a check and its use is never followed; `..` is refused; a symlink is only ever
1590
+ seen as a symlink; sockets, devices and FIFOs do not exist (and a FIFO cannot hang the CLI); names that are not valid UTF-8 are
1591
+ skipped; another file system mounted inside the tree is not entered; the root's device and inode are re-checked before every
1592
+ request, so a root that was moved or replaced answers `ESTALE`; a file with more than one hard link is never opened for writing,
1593
+ truncated or chmod'ed; a created file or directory gets the requested mode limited to `0755`'s bits (never setuid, never
1594
+ group- or other-writable), created with `O_EXCL` so a link planted in its place is never written through; there is no operation
1595
+ that makes a link. Case-insensitive file systems (the macOS default) cannot be used to reach outside: confinement is by
1596
+ descriptor, never by comparing names, so `LINK` is the same symlink as `link` and is refused like it.
1597
+
1598
+ **Not done:** change notification (the host re-reads; nothing is cached on the CLI's side), Windows (`--share` is unix-only), a
1599
+ Rust host that uses shares (the JS host does), and sharing over `wsh reverse-connect` (a direct or pipe-relayed session only).
1600
+
1601
+ #### Serving the operator's files from a host: `onShare`
1602
+
1603
+ ```js
1604
+ const host = createMemoryHost({
1605
+ auth, hostKey: true, dataStreams: false, // a page host, reached through a pipe relay
1606
+ onShare: async (name, fs, who) => { // once per share the operator's CLI offers
1607
+ if (name !== 'app') return;
1608
+ const entries = await fs.readdir('/'); // [{ name, type, size, mode, mtimeMs, ... }] -- attributes included
1609
+ const pkg = JSON.parse(new TextDecoder().decode(await fs.readFile('/package.json')));
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 */ }
1612
+ },
1613
+ });
1614
+ ```
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
+
1623
+ `createMemoryHost`, `createWshServer` and `createReverseHost` take `onShare`; listing it makes the host state the feature
1624
+ `shares`, and a host without it never hears an offer. `fs` is an object of async operations (`stat`, `lstat`, `readlink`,
1625
+ `readdir`, `open` / `create` returning a file with `read(offset, length)` / `write` / `setattr` / `close`, `readFile`,
1626
+ `writeFile`, `mkdir`, `rename`, `unlink`, `rmdir`, `setattr`, `truncate`, `chmod`, `utimes`), `fs.writable`, `fs.signal`
1627
+ (aborted when the operator goes), `fs.stats` (requests, replies, bytes: the evidence that batching works), and the
1628
+ `operate` / `readWhole` / `writeWhole` / `writeAt` shape of an injected [`fs` backend](#in-memory-host-johnhenrywshmemory), so a share can be served on.
1629
+ Errors are `ShareError`s with `.code` (`ENOENT`, `EROFS`, `ELOOP`, `EPERM`, `EEXIST`, ...). The host keeps to the window the
1630
+ CLI offered, gives every request a deadline (30 s), treats a reply that is too big or the wrong shape as `EIO`, and rejects every
1631
+ pending call when the connection ends. Browser-safe: `src/shares.mjs` imports nothing from `node:*`.
1632
+
1540
1633
  ### Capability matrix: JS SDK vs Rust CLI/client
1541
1634
 
1542
1635
  Two implementations of one protocol will always have *some* asymmetry --
@@ -1547,7 +1640,7 @@ than left to be found.
1547
1640
  | Capability | JS SDK (browser) | Rust CLI/client | Unified via |
1548
1641
  |---|---|---|---|
1549
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 |
1550
- | 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 |
1551
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 |
1552
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 |
1553
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 |
@@ -1555,7 +1648,7 @@ than left to be found.
1555
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 |
1556
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 |
1557
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 |
1558
- | 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) |
1559
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 |
1560
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) |
1561
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 |
@@ -1567,8 +1660,10 @@ than left to be found.
1567
1660
  | Gateway destination policy by resolved address | `@johnhenry/wsh/server` `gateway`: resolved address checked, `allowPrivate` | fixed in the Rust release after `rust-v0.6.0`: a loopback/private/link-local/ULA/CGNAT/unspecified/multicast address is refused after resolution unless a rule names it, and the server connects to the address it checked | **Same rule on both sides** (a Rust server released before that still has the name-only check) |
1568
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 |
1569
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 |
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) |
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` |
1570
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) |
1571
- | Pipe relay (#118) | `@johnhenry/wsh/pipe-relay` | operator side only (#145): `wsh --via wss://relay/r/<id> user@host command...` (also `connect`, `scp`, `ls`, `sftp`, `copy-id`), or the URL as the target. The host side of a pipe is not implemented in Rust, and the Rust client does not yet verify the host-key proof or bind the login to the host (see Security model) | **Deliberately a relay without wsh parsing** -- nothing to unify on the wire. `--via` keeps `user@host` as the identity: its key is recorded in `known_hosts` under `host:port` (what a direct connection uses), never under the relay's address; a URL target is recorded under the URL's own authority, i.e. the relay's. The URL is not saved to `last_session.json` (the id is a capability) |
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 |
1572
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` |
1573
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 |
1574
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 |
@@ -1627,6 +1722,10 @@ plus one `SHA256SUMS` file covering every archive in the release. These
1627
1722
  names are a stable contract other repos (clawser) pin and download by --
1628
1723
  do not change them without coordinating downstream.
1629
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
+
1630
1729
  ## Security model
1631
1730
 
1632
1731
  wsh's protocol draws its line at authentication and message integrity: what
@@ -1840,6 +1939,25 @@ What this does **not** protect against:
1840
1939
  `bind_addr` of `0.0.0.0` (the CLI warns) hands the forward to the network, and a local unix socket is `0600` only against
1841
1940
  other users, not against your own processes. A forwarded connection is as private as the wsh connection under it (a pipe
1842
1941
  relay sees it unless the legs are TLS). The Rust host binds a created socket inside a private `0700` directory and links it into place, so it is never visible with a looser mode and the process umask is not touched.
1942
+ - **`wsh --share` hands a host a directory of YOUR machine, and the host is not trusted (#159).** What the host can do is
1943
+ exactly what the command line named: list and read everything under the directory (a read-only share still exposes every
1944
+ file in it, secrets included: share a directory made for the purpose, not `$HOME`), and with `:rw` change and delete all of it
1945
+ and fill the disk (the CLI bounds a file at 1 TiB and the read-plus-write rate, not the disk). What it cannot do is leave the
1946
+ directory: paths are resolved by descriptor with `O_NOFOLLOW` on every component (a link swapped in after a check is not
1947
+ followed), `..` is refused, a file with other hard links is never written, special files do not exist, a root that was
1948
+ replaced is refused (`ESTALE`), and nothing the host sends adds or widens a share. **Not covered:** a link that already
1949
+ exists inside the tree and points outside is simply not followed (so it appears broken to the host, but its name and target
1950
+ are listed); a local user who can write inside the shared tree is outside this model (they can race a rename, though never
1951
+ out of the root); the file *names and sizes* of everything under the share are visible to the host and to a relay that is not
1952
+ sealed (a share travels inside the session: a pipe relay sees it unless the legs are TLS and it is trusted, or the session
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
1954
+ JS side treats the CLI as untrusted too (window, size, shape and deadline of every reply are checked), but an embedder
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.
1843
1961
  - **Rust `wsh-server`'s `AuthOk.ttl` is 0 and its `token` is opaque** (as the
1844
1962
  JS host's, above): nothing is promised or enforced at connection level; do not
1845
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.39.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
@@ -82,10 +82,17 @@ export interface WshConnectionConfig extends Partial<WshResolvedBackends> {
82
82
  e2e?: { signKey: CryptoKey | null; hybrid?: boolean } | null;
83
83
  /** How long exec output waits for the client-opened data stream (default 3000). */
84
84
  bindTimeoutMs?: number;
85
+ /** Folders the operator offers (`wsh --share`, #159): called once per share; listing it makes the host state `shares`. */
86
+ onShare?: WshOnShare;
87
+ /** Told once per connection this host turned away, with a stable reason code (#163). */
88
+ onRefused?: WshOnRefused;
85
89
  log?: (line: string) => void;
86
90
  [key: string]: unknown;
87
91
  }
88
92
 
93
+ /** The `ServerHello` feature of a host that can use shares (#159). */
94
+ export const SHARES_FEATURE: 'shares';
95
+
89
96
  /** One connection over a byte pipe. */
90
97
  export interface WshConnectionPipe {
91
98
  /** Send these bytes to the peer. */
@@ -144,3 +151,93 @@ export function bindSocket(
144
151
  ready: Promise<WshConnectionAttach>,
145
152
  options?: WshAcceptOptions,
146
153
  ): Promise<{ close(): void }>;
154
+
155
+ /** A file's attributes on the operator's machine (`wsh --share`, #159). Times are milliseconds since the epoch. */
156
+ export interface WshShareAttr {
157
+ type: 'file' | 'directory' | 'symlink';
158
+ size: number;
159
+ /** Permission bits only (`0o777` at most). */
160
+ mode: number;
161
+ mtimeMs: number;
162
+ atimeMs: number;
163
+ ctimeMs: number;
164
+ nlink: number;
165
+ ino: number;
166
+ isFile(): boolean;
167
+ isDirectory(): boolean;
168
+ isSymbolicLink(): boolean;
169
+ }
170
+
171
+ /** An entry of {@link WshShareFs.readdir}: attributes included, so listing a directory needs no `stat` per entry. */
172
+ export interface WshShareEntry extends WshShareAttr { name: string; /** A symlink's target. A link is never followed. */ target?: string }
173
+
174
+ /** An open file of a share. */
175
+ export interface WshShareFile {
176
+ readonly attr: WshShareAttr;
177
+ read(offset: number, length: number): Promise<{ data: Uint8Array; eof: boolean }>;
178
+ write(offset: number, data: Uint8Array): Promise<number>;
179
+ setattr(changes: WshShareChanges): Promise<WshShareAttr>;
180
+ truncate(size: number): Promise<WshShareAttr>;
181
+ close(): Promise<void>;
182
+ }
183
+
184
+ export interface WshShareChanges { mode?: number; atimeMs?: number; mtimeMs?: number; size?: number }
185
+
186
+ /** An errno-like failure answered by the operator's client (`code`: `ENOENT`, `EROFS`, `EEXIST`, `ELOOP`, `EPERM`, ...). */
187
+ export class ShareError extends Error { readonly errno: string; readonly code: string }
188
+
189
+ /**
190
+ * One folder the operator shares with this host (`wsh --share NAME=/abs/dir[:ro|:rw]`, #159): async file operations
191
+ * answered by the operator's client, which confines every path to the folder. Paths are relative to the folder root.
192
+ * It also has the shape of a {@link WshFileBackend} (`operate`, `readWhole`, `writeWhole`, `writeAt`), so it can be served on.
193
+ */
194
+ export interface WshShareFs extends WshFileBackend {
195
+ readonly name: string;
196
+ /** Whether the operator offered writes (`:rw`). A change on a read-only share fails with `EROFS`. */
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;
206
+ /** Aborted when the connection to the operator ends; every later call fails with `EIO`. */
207
+ readonly signal: AbortSignal;
208
+ /** Requests, replies, errors, bytes each way and timeouts on this connection so far. */
209
+ readonly stats: { requests: number; replies: number; errors: number; bytesDown: number; bytesUp: number; timeouts: number };
210
+ stat(path: string): Promise<WshShareAttr>;
211
+ lstat(path: string): Promise<WshShareAttr>;
212
+ readlink(path: string): Promise<string>;
213
+ /** The whole directory with attributes, sorted by name, in as few messages as the operator's page size allows. */
214
+ readdir(path: string): Promise<WshShareEntry[]>;
215
+ open(path: string, flags?: Array<'read' | 'write' | 'create' | 'excl' | 'trunc'>, options?: { mode?: number; inlineBytes?: number }): Promise<WshShareFile>;
216
+ create(path: string, options?: { mode?: number }): Promise<WshShareFile>;
217
+ /** A small file arrives with the open (one round trip). */
218
+ readFile(path: string, options?: { maxBytes?: number }): Promise<Uint8Array>;
219
+ writeFile(path: string, data: Uint8Array, options?: { mode?: number; truncate?: boolean }): Promise<number>;
220
+ mkdir(path: string, options?: { mode?: number }): Promise<WshShareAttr>;
221
+ unlink(path: string): Promise<void>;
222
+ rmdir(path: string): Promise<void>;
223
+ rename(from: string, to: string): Promise<void>;
224
+ setattr(path: string, changes: WshShareChanges): Promise<WshShareAttr>;
225
+ truncate(path: string, size: number): Promise<WshShareAttr>;
226
+ chmod(path: string, mode: number): Promise<WshShareAttr>;
227
+ utimes(path: string, atimeMs: number, mtimeMs: number): Promise<WshShareAttr>;
228
+ }
229
+
230
+ /** Called once per share the operator offers (#159). Mount `fs` where you like; `who` is the authenticated operator. */
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
@@ -28,3 +28,5 @@ export { createConnectionFactory, hostFeatures, STREAM_ANNOUNCE } from './server
28
28
  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
+ 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 } 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,
@@ -75,8 +75,17 @@ export interface WshMemoryHostOptions {
75
75
  * Needs `hostKey`; a client older than 0.36 cannot satisfy it.
76
76
  */
77
77
  requireChannelBinding?: boolean | Array<'host'>;
78
+ /**
79
+ * Folders of the OPERATOR's machine (#159): `wsh --share NAME=/abs/dir[:ro|:rw]` offers them after login, and this is
80
+ * called once per share with an object of async file operations the page can mount (a host with no disk of its own
81
+ * can then serve `docker run -v $PWD:/app`). Listing it makes the host state the `shares` feature; a host without it
82
+ * never hears a share offer. See `WshShareFs`.
83
+ */
84
+ onShare?: WshOnShare;
78
85
  /** #155: seal the whole session end to end (needs `hostKey`; offered where `dataStreams` is false). `'require'` serves nothing unsealed. */
79
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;
80
89
  onLog?: (line: string) => void;
81
90
  }
82
91
 
@@ -38,6 +38,8 @@ import { normalizeEndpointGateway, createEndpointGatewaySession } from './server
38
38
  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
+ import { validateOnShare } from './shares.mjs';
42
+ import { validateOnRefused } from './refusal.mjs';
41
43
 
42
44
  const CONNECTING = 0;
43
45
  const OPEN = 1;
@@ -176,9 +178,21 @@ function createRegistry(sessions, log) {
176
178
  * @param {boolean | string[]} [options.requireChannelBinding=false] - Accept a key login only when its signature is bound
177
179
  * to this host's key (#119). A memory host can bind only `host` (it has no TLS of its own), so this needs `hostKey`;
178
180
  * `true` or `['host']`.
181
+ * @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => void | Promise<void>} [options.onShare]
182
+ * Folders of the OPERATOR's machine (#159): the operator's `wsh --share NAME=/abs/dir[:ro|:rw]` offers them after login and
183
+ * this is called once per share with an object of async file operations (`stat`, `readdir` with attributes, `readFile`,
184
+ * `open`, `writeFile`, `mkdir`, `rename`, `unlink`, ... and the `operate` / `readWhole` / `writeWhole` / `writeAt` shape of
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`.
179
190
  * @param {(line: string) => void} [options.onLog]
180
191
  */
181
- export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, endpoints, dataStreams = true, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, sealSession = false, onLog = () => {} } = {}) {
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 = () => {},
193
+ onShare, onRefused } = {}) {
194
+ validateOnShare(onShare, 'createMemoryHost');
195
+ validateOnRefused(onRefused, 'createMemoryHost');
182
196
  if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createMemoryHost: connectionTtlMs must be a non-negative number');
183
197
  if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
184
198
  throw new TypeError(`createMemoryHost: requireChannelBinding must be true, false or an array of kinds (${CHANNEL_BINDING_KINDS.join(', ')})`);
@@ -210,7 +224,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
210
224
 
211
225
  const ready = Promise.all([buildAuthorizer(auth), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
212
226
  authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
213
- methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost,
227
+ methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare, onRefused,
214
228
  gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
215
229
  }));
216
230
  ready.catch(() => {});
@@ -157,6 +157,11 @@ export const MSG = Object.freeze({
157
157
  // Keys
158
158
  AUTHORIZED_KEY_ADD: 0x9f,
159
159
  AUTHORIZED_KEY_RESULT: 0xa0,
160
+
161
+ // Shares
162
+ SHARE_OFFER: 0xa8,
163
+ SHARE_REQUEST: 0xa9,
164
+ SHARE_REPLY: 0xaa,
160
165
  });
161
166
 
162
167
  // Reverse lookup: number → name
@@ -986,6 +991,38 @@ export function authorizedKeyResult({ success, added = false, errorMessage } = {
986
991
  return msg;
987
992
  }
988
993
 
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;
998
+ }
999
+
1000
+ export function shareRequest({ requestId, share, op, path, to, handle, offset, length, mode, flags = [], cursor, attr = {}, data } = {}) {
1001
+ const msg = { type: MSG.SHARE_REQUEST, request_id: requestId, share, op, flags, attr };
1002
+ if (path !== undefined) msg.path = path;
1003
+ if (to !== undefined) msg.to = to;
1004
+ if (handle !== undefined) msg.handle = handle;
1005
+ if (offset !== undefined) msg.offset = offset;
1006
+ if (length !== undefined) msg.length = length;
1007
+ if (mode !== undefined) msg.mode = mode;
1008
+ if (cursor !== undefined) msg.cursor = cursor;
1009
+ if (data !== undefined) msg.data = data;
1010
+ return msg;
1011
+ }
1012
+
1013
+ export function shareReply({ requestId, ok, errno, message, attr = {}, entries = [], cursor, handle, data, eof, written, target } = {}) {
1014
+ const msg = { type: MSG.SHARE_REPLY, request_id: requestId, ok, attr, entries };
1015
+ if (errno !== undefined) msg.errno = errno;
1016
+ if (message !== undefined) msg.message = message;
1017
+ if (cursor !== undefined) msg.cursor = cursor;
1018
+ if (handle !== undefined) msg.handle = handle;
1019
+ if (data !== undefined) msg.data = data;
1020
+ if (eof !== undefined) msg.eof = eof;
1021
+ if (written !== undefined) msg.written = written;
1022
+ if (target !== undefined) msg.target = target;
1023
+ return msg;
1024
+ }
1025
+
989
1026
  // ── Relay forwarding ─────────────────────────────────────────────────
990
1027
 
991
1028
  // Message types a relay may forward inside a RelayForward wrapper.
@@ -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
+ }