@johnhenry/wsh 0.38.1 → 0.40.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 --
@@ -835,11 +835,32 @@ many bytes):
835
835
  | tell the host the operator is *absent* when it is present (`ReverseClose`) | yes | yes | yes |
836
836
  | learn the operator's and host's keys, usernames, and the sizes and timing of traffic | yes | yes | yes |
837
837
 
838
+ A Rust host (`wsh reverse`, `wsh agent run`) is in the right-hand column only with `--require-operator-proof`
839
+ and an operator that seals (`wsh reverse-connect --sealed`, or a JS operator with `{ sealed: true }`); with proof alone
840
+ a relay can still inject a plain `Open` stamped with the operator's fingerprint, exactly as the middle column says.
838
841
  Not covered: an operator or host that skips the checks (the options are opt-in on both
839
- sides; a host that does not require proof is exactly as exposed as before), the Rust `wsh-server` relay and
840
- `wsh` client (they neither carry nor send these messages), and a compromised *operator* key (it proves the key, not the
842
+ sides; a host that does not require proof is exactly as exposed as before), the Rust `wsh-server` relay (it carries these
843
+ messages and seals nothing itself), and a compromised *operator* key (it proves the key, not the
841
844
  person). A relay can still refuse service by dropping the challenge.
842
845
 
846
+ #### A sealed session (#155, host: JS; client: the Rust CLI so far)
847
+
848
+ `createMemoryHost({ hostKey, dataStreams: false, sealSession: 'offer' | 'require' })` (and `createWshServer`, for a connection
849
+ accepted with `dataStreams: false`) seals the WHOLE session end to end. After login the client sends a `KeyExchange` whose
850
+ `session_id` is the connection's, signed with its login key and answered by the host with a signature of its host key (the
851
+ transcripts of the sealed bridge, bound to both identities and both ephemeral keys; hybrid X25519+ML-KEM-768). From then on every
852
+ message but the keepalive -- control messages, `GatewayData` for TCP / unix sockets / named endpoints, `GatewayCredit` -- is an
853
+ authenticated encrypted frame (`EncryptedFrame`, channel 0), so flow-control credit works as before. A plain message is not heard
854
+ once the session is sealed, and a frame that does not open (flipped bit, replay, reorder) closes it. Features: `e2e-session`
855
+ (offered), `e2e-session-required` (the host serves nothing on a session that is not sealed, and no password login). The Rust CLI
856
+ seals with `--sealed` (or on its own when the host says `e2e-session-required`) and refuses a host that does not offer it: no silent
857
+ downgrade. Only `--sealed` is a guarantee: sealing "on its own" rests on a `ServerHello` feature that a relay can strip before
858
+ login, so a client that must never talk in the clear passes `--sealed` (against a host that requires sealing, a stripped client is
859
+ refused, but what it sent before the refusal -- its commands, if any -- was already readable). What it does NOT cover: the handshake before login (the user name, the login public key and the host key proof are
860
+ readable by the relay; the signed key exchange is not secret), the sizes and timing of traffic, a host whose connection has client-opened
861
+ QMux data streams (not offered there), and a denial of service (a relay can always drop or cut). The JS client has no sealed
862
+ session yet, so against a JS client use a host that only `'offer'`s.
863
+
843
864
  #### A pipe relay (`@johnhenry/wsh/pipe-relay`, #118)
844
865
 
845
866
  When you do not want the relay to be a party at all, use a pipe: the host dials the relay, the operator dials the
@@ -869,7 +890,10 @@ for nothing, and the rendezvous id is the only thing standing between the host's
869
890
  an impostor that reaches the id first is still a stranger to the operator, who must pin the host key
870
891
  (`expectHostKey`) to notice; and the host still authenticates every operator. A pipe relay terminates the TLS of each leg, so what it copies -- the wsh
871
892
  handshake and the session traffic -- is readable by it unless the two ends seal it themselves
872
- (per-session `initiateE2E`); it cannot forge the operator's signature or the host's. It can drop, delay or
893
+ (per-session `initiateE2E`, or the **sealed session** below); it cannot forge the operator's signature or the host's.
894
+ **Until you seal the session, treat a pipe relay as trusted for secrecy AND integrity**: it can read every control message and
895
+ all gateway and endpoint data (`GatewayData`: TCP, unix sockets, named endpoints) and alter forwarded bytes after the handshake
896
+ (#155). Pin the host key, require channel binding, use `wss://` to a relay you trust, or seal the session. It can drop, delay or
873
897
  cut a connection, and it sees who dials which id and how much they send.
874
898
 
875
899
  *CLI side (#145).* `wsh --via wss://relay/r/<id> user@host [command...]` dials the operator side
@@ -880,8 +904,10 @@ host whichever relay carried it and a different host behind that name is refused
880
904
  command is sent. A plain URL target (`wsh alice@wss://relay/r/<id> ...`) also dials but is recorded under the URL's
881
905
  authority, which is the relay's, so prefer `--via`. `--via` works with `wsh [user@]host`, `connect`, `scp`, `ls`, `sftp`
882
906
  and `copy-id`; it is an error elsewhere, and cannot be combined with a URL target. A pipe relay is WebSocket only: no
883
- fallback, and `--transport` does not apply. The rendezvous id is not written to `last_session.json`. What the Rust
884
- client does not yet do (host-key proof, channel binding, sealed bridge) is listed under the Security model. The host side
907
+ fallback, and `--transport` does not apply. The rendezvous id is not written to `last_session.json`, and the CLI never
908
+ prints it: errors and `--verbose` logs show the relay's host and the id shortened to its first characters
909
+ (`wss://relay/r/AbCd...`). The Rust client verifies the host-key proof and binds the login to it, as on a direct
910
+ connection; what it does not do (seal the pipe-relayed session) is listed under the Security model. The host side
885
911
  is any process that can open a WebSocket to `pipeUrl(..., 'host')` and hand it to `accept`.
886
912
 
887
913
  ### Sessions: attach / resume / detach
@@ -1434,7 +1460,7 @@ so options the platform gains later need no change here.
1434
1460
 
1435
1461
  | Export | Description |
1436
1462
  |--------|-------------|
1437
- | `MSG` | 105 message type constants (hex opcodes) |
1463
+ | `MSG` | 108 message type constants (hex opcodes) |
1438
1464
  | `CHANNEL_KIND` | Channel types: `pty`, `exec`, `meta`, `file`, `tcp`, `udp`, `job` |
1439
1465
  | `AUTH_METHOD` | Auth methods: `pubkey`, `password` |
1440
1466
  | `cborEncode` / `cborDecode` | CBOR codec (maps, arrays, strings, ints, bytes, bools, null, floats) |
@@ -1458,7 +1484,7 @@ instead of dragging its own toolchain and CI job into an unrelated
1458
1484
  browser-app repo. It was previously deleted from clawser by accident
1459
1485
  (2026-03-14) and restored (2026-07-05) before this move.
1460
1486
 
1461
- Four crates, workspace-versioned (currently `0.9.0`):
1487
+ Four crates, workspace-versioned (currently `0.11.0`):
1462
1488
 
1463
1489
  | Crate | Kind | Description |
1464
1490
  |-------|------|--------------|
@@ -1513,6 +1539,69 @@ cannot do what a forward needs says so (`this host does not offer unix-socket fo
1513
1539
  the gateway policy`); a malformed spec exits with status 2 before anything is dialled. Up to 128 forwarded connections are
1514
1540
  open at once. `-L`/`-R`/`-N` apply to `wsh [user@]host [command...]` and `wsh connect` only.
1515
1541
 
1542
+ ### Sharing a directory with the host: `wsh --share` (#159)
1543
+
1544
+ A host with no disk of its own (a browser tab) sometimes needs files that live on the OPERATOR's machine: `docker run -v
1545
+ $PWD:/app` through `wsh -L /tmp/docker.sock:endpoint=docker` is the case that asked for this. `--share` offers a directory of
1546
+ THIS machine to the host for the life of the session; the CLI serves file operations on it, and nothing else.
1547
+
1548
+ ```bash
1549
+ wsh -N --share src=/home/me/project --share out=/home/me/build:rw --via wss://relay/r/<id> alice@tab.example
1550
+ wsh -N -L /tmp/docker.sock:endpoint=docker --share app=$PWD alice@tab.example # one connection, both
1551
+ ```
1552
+
1553
+ `--share NAME=/abs/dir[:ro|:rw]`, repeatable (at most 16; `NAME`: letters, digits, `.`, `_`, `-`, at most 64). **Read-only unless
1554
+ `:rw`.** The path must be absolute and an existing directory, or the CLI exits with status 2 before dialling. It says once, on
1555
+ stderr, what it shares and how (`wsh: sharing "src" = /home/me/project (read-only)`). It works with `-N`, `-L`, `--via` and a
1556
+ command, applies to `wsh [user@]host [command...]` and `wsh connect` only (`scp`, `ls`, `sftp`, `copy-id` refuse it), and fails
1557
+ 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
+
1559
+ **What the host can do.** Stat and lstat, readdir (every entry WITH its attributes, in pages), readlink, open and read (ranges; a
1560
+ small file's content rides the open, so reading it is one message), write, create, mkdir, rename, unlink, rmdir, setattr (mode,
1561
+ times, truncate) and close, each a bounded `ShareRequest` the host sends and the CLI answers with an errno-like code. At most 16
1562
+ requests are in flight (the rest are refused `EAGAIN` at once), no data in a request or reply exceeds 256 KiB, a stalled host
1563
+ 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
1564
+ 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).
1565
+
1566
+ **What it will not do, whatever the host sends** (each rule has a test that fails when it is broken; see the Security model):
1567
+ the share exists only because it was named on the command line (nothing a host sends adds or widens one); every path is resolved
1568
+ component by component from a directory descriptor opened at start-up, with `O_NOFOLLOW` on each step, so a symlink in the middle
1569
+ 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
1570
+ 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
1571
+ skipped; another file system mounted inside the tree is not entered; the root's device and inode are re-checked before every
1572
+ request, so a root that was moved or replaced answers `ESTALE`; a file with more than one hard link is never opened for writing,
1573
+ truncated or chmod'ed; a created file or directory gets the requested mode limited to `0755`'s bits (never setuid, never
1574
+ group- or other-writable), created with `O_EXCL` so a link planted in its place is never written through; there is no operation
1575
+ that makes a link. Case-insensitive file systems (the macOS default) cannot be used to reach outside: confinement is by
1576
+ descriptor, never by comparing names, so `LINK` is the same symlink as `link` and is refused like it.
1577
+
1578
+ **Not done:** change notification (the host re-reads; nothing is cached on the CLI's side), Windows (`--share` is unix-only), a
1579
+ Rust host that uses shares (the JS host does), and sharing over `wsh reverse-connect` (a direct or pipe-relayed session only).
1580
+
1581
+ #### Serving the operator's files from a host: `onShare`
1582
+
1583
+ ```js
1584
+ const host = createMemoryHost({
1585
+ auth, hostKey: true, dataStreams: false, // a page host, reached through a pipe relay
1586
+ onShare: async (name, fs, who) => { // once per share the operator's CLI offers
1587
+ if (name !== 'app') return;
1588
+ const entries = await fs.readdir('/'); // [{ name, type, size, mode, mtimeMs, ... }] -- attributes included
1589
+ const pkg = JSON.parse(new TextDecoder().decode(await fs.readFile('/package.json')));
1590
+ if (fs.writable) await fs.writeFile('/out/built.txt', new TextEncoder().encode('done'));
1591
+ },
1592
+ });
1593
+ ```
1594
+
1595
+ `createMemoryHost`, `createWshServer` and `createReverseHost` take `onShare`; listing it makes the host state the feature
1596
+ `shares`, and a host without it never hears an offer. `fs` is an object of async operations (`stat`, `lstat`, `readlink`,
1597
+ `readdir`, `open` / `create` returning a file with `read(offset, length)` / `write` / `setattr` / `close`, `readFile`,
1598
+ `writeFile`, `mkdir`, `rename`, `unlink`, `rmdir`, `setattr`, `truncate`, `chmod`, `utimes`), `fs.writable`, `fs.signal`
1599
+ (aborted when the operator goes), `fs.stats` (requests, replies, bytes: the evidence that batching works), and the
1600
+ `operate` / `readWhole` / `writeWhole` / `writeAt` shape of an injected [`fs` backend](#in-memory-host-johnhenrywshmemory), so a share can be served on.
1601
+ Errors are `ShareError`s with `.code` (`ENOENT`, `EROFS`, `ELOOP`, `EPERM`, `EEXIST`, ...). The host keeps to the window the
1602
+ 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
1603
+ pending call when the connection ends. Browser-safe: `src/shares.mjs` imports nothing from `node:*`.
1604
+
1516
1605
  ### Capability matrix: JS SDK vs Rust CLI/client
1517
1606
 
1518
1607
  Two implementations of one protocol will always have *some* asymmetry --
@@ -1541,9 +1630,11 @@ than left to be found.
1541
1630
  | TCP reverse tunnels (`ListenRequest`, #98) | `@johnhenry/wsh/server` `gateway.reverse` (off by default; loopback unless the operator lists addresses; port allow-list, nothing below 1024 unless named; bounded listeners/connections/backlog/idle); client `listenTcp(port, { onConnection })` | `wsh-server` `[gateway] enable_reverse_tunnels` + `reverse_bind_addr` (off by default, loopback, client `bind_addr` ignored); no port allow-list; no per-listener connection, backlog or idle bounds beyond `max_connections` | **Wire-unified** (`ListenRequest`/`ListenOk`/`ListenFail`/`InboundOpen`/`InboundAccept`; the JS host sends the real `peer_addr`/`peer_port`). **Rust still needs**: a port allow-list and per-client listener / per-listener connection / idle bounds to match the JS host. Accepted connections are metered by `gateway-credit` now |
1542
1631
  | UDP (`OpenUdp`) as WebTransport datagrams (#124) | `client.openUdp()` over WebTransport when both ends list `gateway-datagram`: payloads are datagrams (4-byte flow id + payload), read from `maxDatagramSize`; oversize goes on the control stream (or drops); bounds: flows, packet and byte rates, idle; policy as TCP. Host: `gateway.udp`; Playwright test from Chromium | `wsh-server` serves `OpenUdp` over the reliable control stream only (one `GatewayData` per datagram); no datagrams, no rate bounds | **JS only for now** (negotiated by `gateway-datagram`, so a Rust peer keeps the reliable path). **Rust must implement**: list `gateway-datagram` in `ServerHello.features` on a WebTransport connection, accept/send datagrams `[gateway_id u32 BE][payload]` for `OpenUdp` flows when the client listed it (ignore the id of an unknown flow), read `maxDatagramSize` and send a bigger payload as `GatewayData` (or drop, by config), `connect()` the UDP socket to the checked address, and the same rate/flow bounds |
1543
1632
  | 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) |
1544
- | 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 signed `KeyExchange` halves: not yet** (no Rust E2E responder), so `--require-operator-proof` proves who connected but does not stop a relay stamping an identity on later plain messages | **Wire-unified, negotiated** (`ReverseConnect.features`, `operator-proof`, `e2e-sealed`); sealing is JS-only |
1633
+ | 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 |
1545
1634
  | 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 |
1546
- | 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) |
1635
+ | Pipe relay (#118) | `@johnhenry/wsh/pipe-relay` | operator side only (#145): `wsh --via wss://relay/r/<id> user@host command...` (also `connect`, `scp`, `ls`, `sftp`, `copy-id`), or the URL as the target. The host side of a pipe is not implemented in Rust. As on a direct connection the Rust client verifies the host-key proof (`host-key` / `host-key-sig` over its own nonce) before sending a credential, pins only a proven key, and binds the login to it (channel binding `host`; `test/rust/wsh-cli-identity.test.mjs`); the pipe-relayed session itself is not sealed (see Security model). `wsh -N -L` exits non-zero when the host drops the session (#156), and the error lines show the relay and a shortened id, never the whole rendezvous id | **Deliberately a relay without wsh parsing** -- nothing to unify on the wire. `--via` keeps `user@host` as the identity: its key is recorded in `known_hosts` under `host:port` (what a direct connection uses), never under the relay's address; a URL target is recorded under the URL's own authority, i.e. the relay's. The URL is not saved to `last_session.json` (the id is a capability) |
1636
+ | Operator-side shared folders (`--share`, #159) | host side: `onShare(name, fs, who)` on `createMemoryHost` / `createWshServer` / `createReverseHost` (the host *uses* the operator's directories; `fs` is an object of async file operations, also shaped like an `fs` backend). The JS client does not offer shares | CLI side: `wsh --share NAME=/abs/dir[:ro\|:rw]` offers them (`wsh_client::share`, `wsh-cli`'s `sharefs`: descriptor-relative, never follows a link, see [Sharing a directory](#sharing-a-directory-with-the-host-wsh---share-159)); unix only. **A Rust host that uses shares: not built** (`wsh-server` does not state `shares`) | **Wire-unified, negotiated**: the host states the feature `shares`; the client sends one `ShareOffer` after login (opcodes `0xa8` `ShareOffer`, `0xa9` `ShareRequest`, host to client, `0xaa` `ShareReply`). No change notification, no sharing over `reverse-connect` |
1637
+ | Sealed session: any authenticated connection incl. gateway/endpoint data (#155) | host `sealSession: 'offer' \| 'require'` (stage b); the JS client does not seal yet | `wsh --sealed ...` (or automatic against `e2e-session-required`) seals a direct or pipe-relayed session; `wsh-server` does not offer it yet | **Wire-unified, negotiated** (`e2e-session`, `e2e-session-required`, `KeyExchange` for the connection's session id, `EncryptedFrame` channel 0) |
1547
1638
  | `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` |
1548
1639
  | `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 |
1549
1640
  | 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 |
@@ -1815,17 +1906,33 @@ What this does **not** protect against:
1815
1906
  `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
1816
1907
  other users, not against your own processes. A forwarded connection is as private as the wsh connection under it (a pipe
1817
1908
  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.
1909
+ - **`wsh --share` hands a host a directory of YOUR machine, and the host is not trusted (#159).** What the host can do is
1910
+ exactly what the command line named: list and read everything under the directory (a read-only share still exposes every
1911
+ file in it, secrets included: share a directory made for the purpose, not `$HOME`), and with `:rw` change and delete all of it
1912
+ 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
1913
+ directory: paths are resolved by descriptor with `O_NOFOLLOW` on every component (a link swapped in after a check is not
1914
+ followed), `..` is refused, a file with other hard links is never written, special files do not exist, a root that was
1915
+ replaced is refused (`ESTALE`), and nothing the host sends adds or widens a share. **Not covered:** a link that already
1916
+ exists inside the tree and points outside is simply not followed (so it appears broken to the host, but its name and target
1917
+ are listed); a local user who can write inside the shared tree is outside this model (they can race a rename, though never
1918
+ 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
1919
+ sealed (a share travels inside the session: a pipe relay sees it unless the legs are TLS and it is trusted, or the session
1920
+ 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
+ JS side treats the CLI as untrusted too (window, size, shape and deadline of every reply are checked), but an embedder
1922
+ that mounts `fs` is responsible for what it does with the files.
1818
1923
  - **Rust `wsh-server`'s `AuthOk.ttl` is 0 and its `token` is opaque** (as the
1819
1924
  JS host's, above): nothing is promised or enforced at connection level; do not
1820
1925
  treat the token as a credential.
1821
1926
  - **`wsh --via` (pipe relay from the Rust CLI) is the operator side only, and
1822
- still not sealed.** The Rust client now verifies the host-key proof
1927
+ still not sealed** (the sealed bridge of `wsh reverse-connect --sealed` covers
1928
+ reverse bridges only; #155 tracks sealing a direct or pipe-relayed connection and
1929
+ its gateway data). The Rust client now verifies the host-key proof
1823
1930
  (`host-key` / `host-key-sig` over its own `host-key-nonce`) before sending
1824
1931
  any credential, records only a PROVEN key in `known_hosts`, binds the login
1825
1932
  signature to that key (channel binding `host`), and refuses a changed key
1826
1933
  always. A replayed `ServerHello` or an impostor's key is refused as the JS
1827
1934
  client refuses it. What is still unprotected: the bridge is not sealed
1828
- end to end (the Rust side has no sealed bridge yet), so the relay sees
1935
+ end to end (a pipe-relayed session has no sealing layer yet, #155), so the relay sees
1829
1936
  session traffic in the clear unless the legs are TLS and it is trusted not
1830
1937
  to read them (it terminates each leg's TLS), and it can stamp an identity on
1831
1938
  a plain message after the handshake. A host with no host key proves nothing:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.38.1",
3
+ "version": "0.40.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",
@@ -21,6 +21,7 @@ export const BRIDGE_CHANNEL_ID = 0;
21
21
 
22
22
  export class SealedBridge {
23
23
  #key;
24
+ #scope;
24
25
  #sessionId;
25
26
  #sendTag;
26
27
  #recvTag;
@@ -30,9 +31,13 @@ export class SealedBridge {
30
31
  #inChain = Promise.resolve();
31
32
 
32
33
  /**
33
- * @param {{ key: CryptoKey, sessionId: string, role: 'initiator' | 'responder' }} p - `initiator` is the operator
34
+ * @param {{ key: CryptoKey, sessionId: string, role: 'initiator' | 'responder', scope?: 'bridge' | 'session' }} p -
35
+ * `initiator` is the operator. `scope: 'session'` (#155) seals a whole direct or pipe-relayed connection, so any
36
+ * message may be inside a frame; the default, a bridge, accepts only what a relay may forward.
34
37
  */
35
- constructor({ key, sessionId, role }) {
38
+ constructor({ key, sessionId, role, scope = 'bridge' }) {
39
+ if (scope !== 'bridge' && scope !== 'session') throw new TypeError("SealedBridge: scope must be 'bridge' or 'session'");
40
+ this.#scope = scope;
36
41
  if (role !== 'initiator' && role !== 'responder') throw new TypeError("SealedBridge: role must be 'initiator' or 'responder'");
37
42
  this.#key = key;
38
43
  this.#sessionId = sessionId;
@@ -68,7 +73,7 @@ export class SealedBridge {
68
73
  const plain = await openFrame(this.#key, this.#sessionId, this.#recvCounter, { nonce: frame.nonce, ciphertext: frame.ciphertext, expectedRoleTag: this.#recvTag });
69
74
  this.#recvCounter += 1;
70
75
  const inner = cborDecode(plain);
71
- if (!inner || typeof inner.type !== 'number' || inner.type === MSG.RELAY_FORWARD || !isRelayForwardable(inner.type)) throw new Error('sealed message of a type that may not cross a bridge');
76
+ if (!inner || typeof inner.type !== 'number' || inner.type === MSG.RELAY_FORWARD || (this.#scope === 'bridge' && !isRelayForwardable(inner.type))) throw new Error('sealed message of a type that may not cross a bridge');
72
77
  return inner;
73
78
  });
74
79
  this.#inChain = run.catch(() => {});
@@ -151,7 +151,7 @@ export class E2EResponder {
151
151
 
152
152
  /**
153
153
  * @param {object} [opts]
154
- * @param {CryptoKey | null} [opts.signKey] - long-term Ed25519 private key; given, the reply is signed
154
+ * @param {CryptoKey | { sign: (data: Uint8Array) => Promise<Uint8Array> } | null} [opts.signKey] - long-term Ed25519 private key (or a signer); given, the reply is signed
155
155
  * @param {boolean} [opts.hybrid=true] - offer X25519+ML-KEM-768 when the initiator asks for it
156
156
  * @param {Uint8Array | null} [opts.identity] - this responder's raw 32-byte identity key (what an initiator signs as `responderIdentity`)
157
157
  * @param {{ publicKey: Uint8Array, require?: boolean } | null} [opts.initiator] - the operator's identity key, already
@@ -234,7 +234,9 @@ export class E2EResponder {
234
234
  kemPublicKey: localKem?.publicKey,
235
235
  };
236
236
  if (this.#sign) {
237
- reply.signature = await signBytes(this.#sign, keyExchangeTranscript({ sessionId, algorithm, initiatorKey: peerPub, responderKey: localPub }));
237
+ const transcript = keyExchangeTranscript({ sessionId, algorithm, initiatorKey: peerPub, responderKey: localPub });
238
+ // a CryptoKey, or a signer ({ sign }) such as a host key that is not extractable or lives elsewhere
239
+ reply.signature = typeof this.#sign.sign === 'function' ? await this.#sign.sign(transcript) : await signBytes(this.#sign, transcript);
238
240
  }
239
241
  await out(keyExchange(reply));
240
242
 
package/src/host.d.ts CHANGED
@@ -82,10 +82,15 @@ 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;
85
87
  log?: (line: string) => void;
86
88
  [key: string]: unknown;
87
89
  }
88
90
 
91
+ /** The `ServerHello` feature of a host that can use shares (#159). */
92
+ export const SHARES_FEATURE: 'shares';
93
+
89
94
  /** One connection over a byte pipe. */
90
95
  export interface WshConnectionPipe {
91
96
  /** Send these bytes to the peer. */
@@ -144,3 +149,73 @@ export function bindSocket(
144
149
  ready: Promise<WshConnectionAttach>,
145
150
  options?: WshAcceptOptions,
146
151
  ): Promise<{ close(): void }>;
152
+
153
+ /** A file's attributes on the operator's machine (`wsh --share`, #159). Times are milliseconds since the epoch. */
154
+ export interface WshShareAttr {
155
+ type: 'file' | 'directory' | 'symlink';
156
+ size: number;
157
+ /** Permission bits only (`0o777` at most). */
158
+ mode: number;
159
+ mtimeMs: number;
160
+ atimeMs: number;
161
+ ctimeMs: number;
162
+ nlink: number;
163
+ ino: number;
164
+ isFile(): boolean;
165
+ isDirectory(): boolean;
166
+ isSymbolicLink(): boolean;
167
+ }
168
+
169
+ /** An entry of {@link WshShareFs.readdir}: attributes included, so listing a directory needs no `stat` per entry. */
170
+ export interface WshShareEntry extends WshShareAttr { name: string; /** A symlink's target. A link is never followed. */ target?: string }
171
+
172
+ /** An open file of a share. */
173
+ export interface WshShareFile {
174
+ readonly attr: WshShareAttr;
175
+ read(offset: number, length: number): Promise<{ data: Uint8Array; eof: boolean }>;
176
+ write(offset: number, data: Uint8Array): Promise<number>;
177
+ setattr(changes: WshShareChanges): Promise<WshShareAttr>;
178
+ truncate(size: number): Promise<WshShareAttr>;
179
+ close(): Promise<void>;
180
+ }
181
+
182
+ export interface WshShareChanges { mode?: number; atimeMs?: number; mtimeMs?: number; size?: number }
183
+
184
+ /** An errno-like failure answered by the operator's client (`code`: `ENOENT`, `EROFS`, `EEXIST`, `ELOOP`, `EPERM`, ...). */
185
+ export class ShareError extends Error { readonly errno: string; readonly code: string }
186
+
187
+ /**
188
+ * One folder the operator shares with this host (`wsh --share NAME=/abs/dir[:ro|:rw]`, #159): async file operations
189
+ * answered by the operator's client, which confines every path to the folder. Paths are relative to the folder root.
190
+ * It also has the shape of a {@link WshFileBackend} (`operate`, `readWhole`, `writeWhole`, `writeAt`), so it can be served on.
191
+ */
192
+ export interface WshShareFs extends WshFileBackend {
193
+ readonly name: string;
194
+ /** Whether the operator offered writes (`:rw`). A change on a read-only share fails with `EROFS`. */
195
+ readonly writable: boolean;
196
+ /** Aborted when the connection to the operator ends; every later call fails with `EIO`. */
197
+ readonly signal: AbortSignal;
198
+ /** Requests, replies, errors, bytes each way and timeouts on this connection so far. */
199
+ readonly stats: { requests: number; replies: number; errors: number; bytesDown: number; bytesUp: number; timeouts: number };
200
+ stat(path: string): Promise<WshShareAttr>;
201
+ lstat(path: string): Promise<WshShareAttr>;
202
+ readlink(path: string): Promise<string>;
203
+ /** The whole directory with attributes, sorted by name, in as few messages as the operator's page size allows. */
204
+ readdir(path: string): Promise<WshShareEntry[]>;
205
+ open(path: string, flags?: Array<'read' | 'write' | 'create' | 'excl' | 'trunc'>, options?: { mode?: number; inlineBytes?: number }): Promise<WshShareFile>;
206
+ create(path: string, options?: { mode?: number }): Promise<WshShareFile>;
207
+ /** A small file arrives with the open (one round trip). */
208
+ readFile(path: string, options?: { maxBytes?: number }): Promise<Uint8Array>;
209
+ writeFile(path: string, data: Uint8Array, options?: { mode?: number; truncate?: boolean }): Promise<number>;
210
+ mkdir(path: string, options?: { mode?: number }): Promise<WshShareAttr>;
211
+ unlink(path: string): Promise<void>;
212
+ rmdir(path: string): Promise<void>;
213
+ rename(from: string, to: string): Promise<void>;
214
+ setattr(path: string, changes: WshShareChanges): Promise<WshShareAttr>;
215
+ truncate(path: string, size: number): Promise<WshShareAttr>;
216
+ chmod(path: string, mode: number): Promise<WshShareAttr>;
217
+ utimes(path: string, atimeMs: number, mtimeMs: number): Promise<WshShareAttr>;
218
+ }
219
+
220
+ /** Called once per share the operator offers (#159). Mount `fs` where you like; `who` is the authenticated operator. */
221
+ export type WshOnShare = (name: string, fs: WshShareFs, who: { username: string | null; fingerprint: string | null }) => void | Promise<void>;
package/src/host.mjs CHANGED
@@ -28,3 +28,4 @@ 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';
@@ -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 } from './host.js';
4
4
  import type {
5
5
  WshServerAuthOptions, WshServerPrincipal, WshServerMcpOptions, WshExecRunner, WshServerOptions, WshServerPtyOptions, WshClientEnv,
6
6
  WshAcceptableSocket, WshAcceptOptions, WshGatewayEndpointHandler as WshMemoryEndpointHandler,
@@ -75,6 +75,15 @@ 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;
85
+ /** #155: seal the whole session end to end (needs `hostKey`; offered where `dataStreams` is false). `'require'` serves nothing unsealed. */
86
+ sealSession?: false | 'offer' | 'require';
78
87
  onLog?: (line: string) => void;
79
88
  }
80
89
 
@@ -38,6 +38,7 @@ 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';
41
42
 
42
43
  const CONNECTING = 0;
43
44
  const OPEN = 1;
@@ -140,6 +141,12 @@ function createRegistry(sessions, log) {
140
141
  * @param {{ operate: Function, readWhole: Function, writeWhole: Function, writeAt: Function, openRange?: Function, maxFileBytes?: number }} [options.fs]
141
142
  * File operations, as `createFileAccess` in `@johnhenry/wsh/server` returns them (see `normalizeFileBackend` in
142
143
  * `host-backends.mjs`). Not a root path: confining paths is the backend's job.
144
+ * @param {false | 'offer' | 'require'} [options.sealSession=false] - #155: seal the whole session end to end (needs `hostKey` and
145
+ * `dataStreams: false`, which is how a page host is served). A client that asks (a signed `KeyExchange` for the connection's
146
+ * session id, features `e2e-session`) gets every message after login -- gateway and endpoint data included -- as an
147
+ * authenticated encrypted frame, so a relay that only copies bytes (a pipe relay) can neither read nor alter it; a frame that
148
+ * does not open closes the session. `'offer'` serves a client that does not ask in the clear; `'require'` (advertised as
149
+ * `e2e-session-required`) serves nobody who has not sealed, and no password login. The keepalive stays plain.
143
150
  * @param {true | CryptoKeyPair | { publicKey: Uint8Array | CryptoKey, sign: Function }} [options.hostKey]
144
151
  * This host's own identity, so clients can pin it (TOFU): a `CryptoKeyPair` (non-extractable is fine), a signer
145
152
  * `{ publicKey, sign(data) }`, or `true` for a fresh non-extractable key.
@@ -170,15 +177,24 @@ function createRegistry(sessions, log) {
170
177
  * @param {boolean | string[]} [options.requireChannelBinding=false] - Accept a key login only when its signature is bound
171
178
  * to this host's key (#119). A memory host can bind only `host` (it has no TLS of its own), so this needs `hostKey`;
172
179
  * `true` or `['host']`.
180
+ * @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => void | Promise<void>} [options.onShare]
181
+ * Folders of the OPERATOR's machine (#159): the operator's `wsh --share NAME=/abs/dir[:ro|:rw]` offers them after login and
182
+ * this is called once per share with an object of async file operations (`stat`, `readdir` with attributes, `readFile`,
183
+ * `open`, `writeFile`, `mkdir`, `rename`, `unlink`, ... and the `operate` / `readWhole` / `writeWhole` / `writeAt` shape of
184
+ * an `fs` backend) that the embedder can mount. Listing it makes the host state the `shares` feature. See `shares.mjs`.
173
185
  * @param {(line: string) => void} [options.onLog]
174
186
  */
175
- export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, endpoints, dataStreams = true, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, onLog = () => {} } = {}) {
187
+ 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 } = {}) {
189
+ validateOnShare(onShare, 'createMemoryHost');
176
190
  if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createMemoryHost: connectionTtlMs must be a non-negative number');
177
191
  if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
178
192
  throw new TypeError(`createMemoryHost: requireChannelBinding must be true, false or an array of kinds (${CHANNEL_BINDING_KINDS.join(', ')})`);
179
193
  }
180
194
  if (Array.isArray(requireChannelBinding) && requireChannelBinding.some((k) => k !== 'host')) throw new TypeError('createMemoryHost: requireChannelBinding can name only "host" (a memory host has no TLS connection or certificate to bind)');
181
195
  if (requireChannelBinding && !hostKey) throw new TypeError('createMemoryHost: requireChannelBinding needs a hostKey (the only thing a memory host can bind a login to)');
196
+ if (sealSession !== false && sealSession !== 'offer' && sealSession !== 'require') throw new TypeError("createMemoryHost: sealSession must be false, 'offer' or 'require'");
197
+ if (sealSession && !hostKey) throw new TypeError('createMemoryHost: sealSession needs a hostKey (the host signs its half of the key exchange with it)');
182
198
  if (exec === true) throw new TypeError('createMemoryHost: exec must be a function (run(command, io)); there is no shell to run `true` with');
183
199
  if (exec !== undefined && typeof exec !== 'function' && typeof exec?.run !== 'function') {
184
200
  throw new TypeError('createMemoryHost: exec must be a function or { run }');
@@ -201,8 +217,8 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
201
217
  const gatewayCfg = endpoints === undefined || endpoints === null ? null : normalizeEndpointGateway({ endpoints });
202
218
 
203
219
  const ready = Promise.all([buildAuthorizer(auth), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
204
- authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, log: onLog,
205
- methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost,
220
+ authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
221
+ methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare,
206
222
  gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
207
223
  }));
208
224
  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,42 @@ export function authorizedKeyResult({ success, added = false, errorMessage } = {
986
991
  return msg;
987
992
  }
988
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
+ };
1002
+ }
1003
+
1004
+ export function shareRequest({ requestId, share, op, path, to, handle, offset, length, mode, flags = [], cursor, attr = {}, data } = {}) {
1005
+ const msg = { type: MSG.SHARE_REQUEST, request_id: requestId, share, op, flags, attr };
1006
+ if (path !== undefined) msg.path = path;
1007
+ if (to !== undefined) msg.to = to;
1008
+ if (handle !== undefined) msg.handle = handle;
1009
+ if (offset !== undefined) msg.offset = offset;
1010
+ if (length !== undefined) msg.length = length;
1011
+ if (mode !== undefined) msg.mode = mode;
1012
+ if (cursor !== undefined) msg.cursor = cursor;
1013
+ if (data !== undefined) msg.data = data;
1014
+ return msg;
1015
+ }
1016
+
1017
+ export function shareReply({ requestId, ok, errno, message, attr = {}, entries = [], cursor, handle, data, eof, written, target } = {}) {
1018
+ const msg = { type: MSG.SHARE_REPLY, request_id: requestId, ok, attr, entries };
1019
+ if (errno !== undefined) msg.errno = errno;
1020
+ if (message !== undefined) msg.message = message;
1021
+ if (cursor !== undefined) msg.cursor = cursor;
1022
+ if (handle !== undefined) msg.handle = handle;
1023
+ if (data !== undefined) msg.data = data;
1024
+ if (eof !== undefined) msg.eof = eof;
1025
+ if (written !== undefined) msg.written = written;
1026
+ if (target !== undefined) msg.target = target;
1027
+ return msg;
1028
+ }
1029
+
989
1030
  // ── Relay forwarding ─────────────────────────────────────────────────
990
1031
 
991
1032
  // Message types a relay may forward inside a RelayForward wrapper.
@@ -23,6 +23,7 @@ import { OPERATOR_PROOF_FEATURE, E2E_SEALED_FEATURE, createReverseChallenge, ver
23
23
  import { SealedBridge } from './bridge-seal.mjs';
24
24
  import { resolveBackends } from './host-backends.mjs';
25
25
  import { createConnectionFactory, hostFeatures } from './server/connection.mjs';
26
+ import { validateOnShare } from './shares.mjs';
26
27
 
27
28
  const BACKOFF_START_MS = 500;
28
29
  const BACKOFF_MAX_MS = 30_000;
@@ -67,6 +68,9 @@ const BACKOFF_MAX_MS = 30_000;
67
68
  * plain message (it could inject an `Open`). Needs `e2e` (on by default) and `reportFeatures`. Without this option the
68
69
  * proof is requested when it can be and reported as `proven`, and the bridge is sealed only if the operator asks.
69
70
  * @param {number} [options.proofTimeoutMs=5000] - How long an operator has to answer the challenge.
71
+ * @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => void | Promise<void>} [options.onShare]
72
+ * Folders an operator offers (`ShareOffer`, #159), once per share, as an object of async file operations. The Rust CLI
73
+ * offers shares on a direct or pipe-relayed session (`wsh --share`), not over `wsh reverse-connect` yet.
70
74
  * @param {(line: string) => void} [options.onLog]
71
75
  */
72
76
  export function createReverseHost(options = {}) {
@@ -81,8 +85,9 @@ export function createReverseHost(options = {}) {
81
85
  */
82
86
  export function createReverseHostWith({
83
87
  url, username, keyPair, accept, reconnect = true, connect = {}, peerType = 'host', reportFeatures = true, maxOperators = 1, e2e = {},
84
- requireOperatorProof = false, proofTimeoutMs = 5000, onLog = () => {},
88
+ requireOperatorProof = false, proofTimeoutMs = 5000, onLog = () => {}, onShare,
85
89
  } = {}, backends) {
90
+ validateOnShare(onShare, 'createReverseHost');
86
91
  if (typeof requireOperatorProof !== 'boolean') throw new TypeError('createReverseHost: requireOperatorProof must be a boolean');
87
92
  if (requireOperatorProof && e2e === false) throw new TypeError('createReverseHost: requireOperatorProof seals the bridge, which needs e2e (do not set e2e: false)');
88
93
  if (requireOperatorProof && !reportFeatures) throw new TypeError('createReverseHost: requireOperatorProof needs reportFeatures (the operator learns "e2e-sealed" from ReverseAccept.features)');
@@ -109,13 +114,13 @@ export function createReverseHostWith({
109
114
  });
110
115
  /** Features for `ReverseAccept` on this relay connection. */
111
116
  const bridgeFeatures = (c, e2eConfig, manyOperators) => [
112
- ...hostFeatures({ mcp: backends.mcp, files: backends.files, e2e: e2eConfig }, { dataStreams: false }),
117
+ ...hostFeatures({ mcp: backends.mcp, files: backends.files, e2e: e2eConfig, onShare }, { dataStreams: false }),
113
118
  ...(manyOperators ? [MULTI_OPERATOR_FEATURE] : []),
114
119
  ];
115
120
  const factory = createConnectionFactory({
116
121
  authorize: async () => false, methods: { pubkey: false, password: null }, hostKey: null, rateLimit: null,
117
122
  execRunner: backends.execRunner, execOptions: backends.execOptions, pty: backends.pty, files: backends.files, mcp: backends.mcp,
118
- sessions: null, relay: null, e2e: null, bindTimeoutMs: 3000, log: (l) => onLog(`[reverse] ${l}`),
123
+ sessions: null, relay: null, e2e: null, bindTimeoutMs: 3000, log: (l) => onLog(`[reverse] ${l}`), onShare,
119
124
  });
120
125
 
121
126
  let client = null;
@@ -34,9 +34,15 @@ import { GATEWAY_DATAGRAM_FEATURE } from '../gateway-datagram.mjs';
34
34
  import { OPERATOR_PROOF_FEATURE } from '../operator-proof.mjs';
35
35
  import { clientEnvFilter } from './client-env.mjs';
36
36
  import { acceptableBindings, bindingFeatures } from '../channel-binding.mjs';
37
+ import { SealedBridge } from '../bridge-seal.mjs';
37
38
  import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMessage, toHex } from '../host-key.mjs';
39
+ import { SHARES_FEATURE, createShareSession } from '../shares.mjs';
38
40
 
39
41
  export const STREAM_ANNOUNCE = 'stream-announce';
42
+ /** Host feature (#155): this host seals the whole session end to end when asked (a signed `KeyExchange` for the connection's session id). */
43
+ export const SESSION_SEAL_FEATURE = 'e2e-session';
44
+ /** Host feature: this host serves nothing on a session that is not sealed. */
45
+ export const SESSION_SEAL_REQUIRED_FEATURE = 'e2e-session-required';
40
46
 
41
47
  /**
42
48
  * The features a host built from `cfg` advertises (`ServerHello.features`, minus the host-key proof).
@@ -49,6 +55,7 @@ export function hostFeatures(cfg, { dataStreams = true } = {}) {
49
55
  if (cfg.mcp) features.push(MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE);
50
56
  if (cfg.gateway) features.push(...gatewayFeatures(cfg.gateway));
51
57
  if (cfg.files) features.push('file-transfer', 'file-write', 'file-rename');
58
+ if (cfg.onShare) features.push(SHARES_FEATURE); // #159: this host can use folders the operator's client offers
52
59
  // End-to-end encryption (#90) is the virtual-mode EncryptedFrame layer, so it is offered where there are no
53
60
  // client-opened streams: over a relay bridge.
54
61
  // A relay carries a signed KeyExchange untouched, and (when configured) several operators per peer: peers read
@@ -58,6 +65,8 @@ export function hostFeatures(cfg, { dataStreams = true } = {}) {
58
65
  if (cfg.relay.maxOperatorsPerPeer > 1) features.push(MULTI_OPERATOR_FEATURE);
59
66
  }
60
67
  if (cfg.e2e && !dataStreams) features.push(E2E_FEATURE, ...(cfg.e2e.signKey ? [E2E_SIGN_FEATURE] : []));
68
+ // A sealed session (#155) needs the host's identity to sign its half, and no client-opened streams (their bytes are not frames).
69
+ if (cfg.sealSession && cfg.hostKey && !dataStreams) features.push(SESSION_SEAL_FEATURE, ...(cfg.sealSession === 'require' ? [SESSION_SEAL_REQUIRED_FEATURE] : []));
61
70
  if (cfg.rpc && dataStreams && cfg.rpc.protocols.size) {
62
71
  features.push(RPC_FEATURE, ...[...cfg.rpc.protocols.keys()].map(rpcProtocolFeature), RPC_MAX_MESSAGE_PREFIX + cfg.rpc.maxMessageBytes);
63
72
  }
@@ -155,6 +164,13 @@ export function createConnectionFactory(cfg) {
155
164
  /** Ends the connection at `connectionTtlMs` after authentication (#125). */
156
165
  let ttlTimer = null;
157
166
 
167
+ // A sealed session (#155): after login, a signed KeyExchange for this connection's session id seals everything
168
+ // that follows (control messages, gateway and endpoint data included) as EncryptedFrames on channel 0.
169
+ const sealOn = !!cfg.sealSession && !!cfg.hostKey && !dataStreams;
170
+ const sealRequired = sealOn && cfg.sealSession === 'require';
171
+ /** @type {{ bridge: SealedBridge | null, responder: E2EResponder | null }} */
172
+ const sealed = { bridge: null, responder: null };
173
+
158
174
  // The gateway needs Node sockets, so `gateway.mjs` is not imported here (a browser host must not pull it in):
159
175
  // the embedder that has them (`createWshServer`) passes `cfg.createGatewaySession` along with `cfg.gateway`; a
160
176
  // host in a page passes the endpoints-only session of `gateway-core.mjs` (`createMemoryHost({ endpoints })`).
@@ -163,6 +179,11 @@ export function createConnectionFactory(cfg) {
163
179
  ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, { who: () => ({ username: state.username, fingerprint: state.fingerprint }), datagrams })
164
180
  : null;
165
181
 
182
+ // Operator-side shared folders (#159): created with the connection, used only after the client's ShareOffer.
183
+ const shares = cfg.onShare
184
+ ? createShareSession({ send: (m) => send(m), onShare: cfg.onShare, who: () => ({ username: state.username, fingerprint: state.fingerprint }), log, timeoutMs: cfg.shareTimeoutMs })
185
+ : null;
186
+
166
187
  const qmux = sendMessage ? null : new QMuxConnection({ isClient: false, send: (b) => { if (!state.closed) sendBytes(b); } });
167
188
 
168
189
  // ── End-to-end encryption (#90) ──────────────────────────────────
@@ -198,6 +219,14 @@ export function createConnectionFactory(cfg) {
198
219
  };
199
220
 
200
221
  const deliver = (msg) => {
222
+ // Sealed: everything but the keepalive leaves as a frame, in the order it was sent (the bridge seals in call order).
223
+ if (sealed.bridge && msg.type !== MSG.PING && msg.type !== MSG.PONG) {
224
+ return sealed.bridge.seal(msg).then((frame) => deliverRaw(frame), (e) => { log(`could not seal: ${e.message}`); });
225
+ }
226
+ return deliverRaw(msg);
227
+ };
228
+
229
+ const deliverRaw = (msg) => {
201
230
  if (state.closed) return Promise.resolve();
202
231
  if (sendMessage) {
203
232
  try { return Promise.resolve(sendMessage(msg)).catch(() => {}); } catch { return Promise.resolve(); }
@@ -218,6 +247,7 @@ export function createConnectionFactory(cfg) {
218
247
  channels.clear();
219
248
  responder?.close();
220
249
  gateway?.close();
250
+ shares?.close();
221
251
  e2eSessions.clear();
222
252
  for (const c of mcpCalls) c.abort(new Error('connection closed'));
223
253
  mcpCalls.clear();
@@ -266,8 +296,14 @@ export function createConnectionFactory(cfg) {
266
296
  async function handle(m) {
267
297
  if (state.closed) return;
268
298
  if (!state.authed) return handleAuth(m);
299
+ if (sealOn) {
300
+ const inner = await sealedInput(m);
301
+ if (inner === undefined) return;
302
+ m = inner;
303
+ }
269
304
  if (await handleRelay(m)) return;
270
305
  if (gateway && await gateway.handle(m)) return;
306
+ if (shares && shares.handle(m)) return;
271
307
  switch (m.type) {
272
308
  case MSG.PING: return send(pong({ id: m.id }));
273
309
  case MSG.OPEN: return handleOpen(m);
@@ -363,6 +399,7 @@ export function createConnectionFactory(cfg) {
363
399
  } else {
364
400
  return refuse(`unsupported auth method ${JSON.stringify(method)}`);
365
401
  }
402
+ if (cfg.sealSession === 'require' && cfg.hostKey && !dataStreams && method !== 'pubkey') return refuse('this host requires a sealed session, which needs a key login');
366
403
  state.username = user;
367
404
  state.method = method;
368
405
  gateway?.setPeerFeatures(m.features);
@@ -438,12 +475,53 @@ export function createConnectionFactory(cfg) {
438
475
  if (!allowed) return refuse('key not authorized');
439
476
  state.authed = true;
440
477
  state.fingerprint = fp;
478
+ state.publicKey = m.public_key;
441
479
  state.nonce = null;
442
480
  await grantAuth();
443
481
  log(`authenticated ${state.username} (${fp.slice(0, 12)}...)`);
444
482
  }
445
483
  }
446
484
 
485
+ /**
486
+ * The sealed-session gate (#155) for a message from an authenticated peer: the message to handle, or undefined
487
+ * when it was consumed (the key exchange) or refused. A plain message is not heard once the session is sealed
488
+ * (a relay in the middle can inject any), and with `sealSession: 'require'` not before either.
489
+ */
490
+ async function sealedInput(m) {
491
+ if (sealed.bridge) {
492
+ if (m.type === MSG.PING) return m;
493
+ if (!sealed.bridge.isFrame(m)) { log(`dropped a plaintext message (type ${m.type}) on a sealed session`); return undefined; }
494
+ try { return await sealed.bridge.open(m); } catch (e) {
495
+ log(`a sealed frame did not open (${e.message}): closing the session`);
496
+ shutdown('sealed frame did not open');
497
+ return undefined;
498
+ }
499
+ }
500
+ 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; }
502
+ sealed.responder ??= new E2EResponder({
503
+ signKey: cfg.hostKey, hybrid: true, identity: cfg.hostKey.publicKey,
504
+ initiator: { publicKey: state.publicKey, require: true },
505
+ });
506
+ try {
507
+ const result = await sealed.responder.respond(m, (reply) => deliverRaw(reply));
508
+ if (result.key) {
509
+ sealed.bridge = new SealedBridge({ key: result.key, sessionId: state.sessionId, role: 'responder', scope: 'session' });
510
+ log(`session sealed${result.hybrid ? ' (hybrid)' : ''}`);
511
+ }
512
+ } catch (e) { log(`sealed session refused: ${e.message}`); shutdown('sealed session key exchange failed'); }
513
+ return undefined;
514
+ }
515
+ if (m.type === MSG.PING) return m;
516
+ if (sealRequired) {
517
+ log(`refused a plaintext message (type ${m.type}): this host requires a sealed session`);
518
+ await deliverRaw(errorMsg({ code: 1, message: 'this host requires a sealed session (e2e-session-required)' }));
519
+ setTimeout(() => shutdown('sealed session required'), 50);
520
+ return undefined;
521
+ }
522
+ return m;
523
+ }
524
+
447
525
  async function handlePasswordAuth(m) {
448
526
  state.awaitingPassword = false; // one guess per connection
449
527
  if (m.method !== 'password' || typeof m.password !== 'string') return refuse('expected a password AUTH');
@@ -480,6 +480,11 @@ export interface WshServerOptions {
480
480
  * TLS-terminating proxy; `cert-hash` needs WebTransport with `selfSigned`). Clients older than 0.36 cannot satisfy it.
481
481
  */
482
482
  requireChannelBinding?: boolean | Array<'cert-hash' | 'host' | 'tls-exporter'>;
483
+ /**
484
+ * Folders the operator's `wsh --share NAME=/abs/dir[:ro|:rw]` offers (#159): called once per share with an object of
485
+ * async file operations to mount. Listing it makes the host state the `shares` feature.
486
+ */
487
+ onShare?: import('../host.js').WshOnShare;
483
488
  onLog?: (line: string) => void;
484
489
  }
485
490
 
@@ -628,6 +633,8 @@ export interface WshReverseHostOptions {
628
633
  requireOperatorProof?: boolean;
629
634
  /** How long an operator has to answer the challenge (default 5000). */
630
635
  proofTimeoutMs?: number;
636
+ /** Folders an operator offers over a bridge (#159), once per share, as an object of async file operations. */
637
+ onShare?: import('../host.js').WshOnShare;
631
638
  onLog?: (line: string) => void;
632
639
  }
633
640
 
@@ -15,6 +15,7 @@ import { SessionRegistry } from './sessions.mjs';
15
15
  import { RelayHub } from './relay.mjs';
16
16
  import { startWebTransport } from './webtransport.mjs';
17
17
  import { createConnectionFactory, STREAM_ANNOUNCE } from './connection.mjs';
18
+ import { validateOnShare } from '../shares.mjs';
18
19
  import { normalizeGateway, createGatewaySession } from './gateway.mjs';
19
20
  import { createRpcHost, mcpServerAdapter } from './rpc.mjs';
20
21
  import { bindSocket } from './socket.mjs';
@@ -86,16 +87,26 @@ function tlsChannelBinding(socket) {
86
87
  * @param {number} [options.bindTimeoutMs=3000]
87
88
  * @param {number} [options.connectionTtlMs=0] - End every authenticated connection this long after login (0 = never).
88
89
  * Advertised as `AuthOk.ttl` in whole seconds, rounded up; the client reads it as `client.authTtl`.
90
+ * @param {false | 'offer' | 'require'} [options.sealSession=false] - #155: seal a session end to end when the client asks (`e2e-session`); see
91
+ * `createMemoryHost`. Offered on connections accepted with `dataStreams: false` (a socket handed to `server.accept`); a
92
+ * byte-stream connection with QMux data streams is not sealed.
89
93
  * @param {boolean | string[]} [options.requireChannelBinding=false] - Accept a key login only when its signature is bound to
90
94
  * this connection (#119): `true` needs any binding kind, an array names kinds that must all be bound (`host` needs
91
95
  * `hostKey`; `tls-exporter` needs `wss://` served by this process, not a TLS-terminating proxy; `cert-hash` needs
92
96
  * WebTransport with `selfSigned`). Clients older than 0.36 cannot satisfy it. Off by default.
97
+ * @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => void | Promise<void>} [options.onShare]
98
+ * Folders of the operator's machine (`wsh --share`, #159), once per share, as an object of async file operations to mount;
99
+ * listing it makes the host state the `shares` feature. As for `createMemoryHost`.
93
100
  * @param {(line: string) => void} [options.onLog]
94
101
  * @returns {{ listen(): Promise<{address: string, port: number}>, accept(socket: object, options?: object): Promise<{ close(): void }>, close(): Promise<void>, address(): ({address: string, port: number} | null) }}
95
102
  */
96
103
  export function createWshServer({
97
- host = '127.0.0.1', port = 0, tls, auth, exec, pty, fs, hostKey, mcp, rpc, rpcMaxMessageBytes, rpcMaxInflight, sessions, sessionSecret, relay, extensions, gateway, webTransport, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, onLog = () => {},
104
+ 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,
98
106
  } = {}) {
107
+ validateOnShare(onShare, 'createWshServer');
108
+ if (sealSession !== false && sealSession !== 'offer' && sealSession !== 'require') throw new TypeError("createWshServer: sealSession must be false, 'offer' or 'require'");
109
+ if (sealSession && !hostKey) throw new TypeError('createWshServer: sealSession needs a hostKey (the host signs its half of the key exchange with it)');
99
110
  if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
100
111
  throw new TypeError(`createWshServer: requireChannelBinding must be true, false or an array of kinds (${CHANNEL_BINDING_KINDS.join(', ')})`);
101
112
  }
@@ -145,8 +156,9 @@ export function createWshServer({
145
156
  if (relay) hub = new RelayHub({ ...relay, log: onLog });
146
157
  if (extensions !== undefined && (extensions === null || typeof extensions !== 'object')) throw new TypeError('createWshServer: extensions must be an object of handlers');
147
158
  return createConnectionFactory({
148
- authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, log: onLog,
159
+ authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
149
160
  methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, createGatewaySession, sessions: registry, relay: hub,
161
+ onShare,
150
162
  });
151
163
  })();
152
164
  ready.catch(() => { ready = null; });
package/src/shares.mjs ADDED
@@ -0,0 +1,425 @@
1
+ /**
2
+ * Operator-side shared folders, the HOST half (#159). Browser-safe: it imports nothing from `node:*`.
3
+ *
4
+ * A host that has no disk of its own (a tab) can use directories that live on the OPERATOR's machine for the life of
5
+ * a session: the operator's `wsh --share NAME=/abs/dir[:ro|:rw]` offers them (`ShareOffer`), and this module hands the
6
+ * embedder an object of async file operations per share -- `onShare(name, fs, who)` -- that it can mount. Every
7
+ * operation is a bounded `ShareRequest` this host sends and the operator's client answers (`ShareReply`).
8
+ *
9
+ * The client is the file server and enforces confinement; this side enforces what a host can: the request window the
10
+ * offer promised (`max_inflight`), a per-request deadline, the size of a reply, the shape of what comes back (a client
11
+ * that answers nonsense gets an `EIO`, never a thrown TypeError in the embedder's code), and that nothing is asked
12
+ * before an offer. Share names, counts and limits from the offer are validated and clamped.
13
+ *
14
+ * Negotiation: a host that passes `onShare` lists the feature `shares` in `ServerHello.features`. A client with shares
15
+ * to offer sends ONE `ShareOffer` after login (inside whatever sealing the session has, so a sealed session protects
16
+ * file data with no extra crypto here). A host without `onShare` never lists the feature and ignores an offer.
17
+ */
18
+
19
+ import { MSG, shareRequest } from './messages.gen.mjs';
20
+
21
+ /** The `ServerHello` feature of a host that can use shares. */
22
+ export const SHARES_FEATURE = 'shares';
23
+
24
+ const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
25
+ const ERRNOS = new Set(['ENOENT', 'EEXIST', 'ENOTDIR', 'EISDIR', 'ENOTEMPTY', 'EACCES', 'EPERM', 'EROFS', 'EINVAL', 'EBADF', 'ELOOP',
26
+ 'ENAMETOOLONG', 'ENOSPC', 'EMFILE', 'EBUSY', 'EAGAIN', 'EXDEV', 'EFBIG', 'ENOTSUP', 'ESTALE', 'EIO']);
27
+ const MAX_SHARES = 16;
28
+ const MAX_INFLIGHT = 64;
29
+ const MIN_BYTES = 4096;
30
+ const MAX_BYTES = 4 * 1024 * 1024;
31
+ /** Requests waiting for a slot of the window, per connection; beyond that a call fails with `EAGAIN` at once. */
32
+ const QUEUE_LIMIT = 4096;
33
+ const DEFAULT_TIMEOUT_MS = 30_000;
34
+ const DEFAULT_MAX_FILE_BYTES = 64 * 1024 * 1024;
35
+ const MAX_LIST_ENTRIES = 2_000_000;
36
+
37
+ /** An error from the operator's side of a share, with the errno-like code the wire carries (`error.code === error.errno`). */
38
+ export class ShareError extends Error {
39
+ constructor(errno, message) {
40
+ super(`${errno}: ${message}`);
41
+ this.name = 'ShareError';
42
+ this.errno = errno;
43
+ this.code = errno;
44
+ this.wsh = true;
45
+ }
46
+ }
47
+
48
+ const clampInt = (v, lo, hi) => Math.min(hi, Math.max(lo, Number.isFinite(v) ? Math.trunc(v) : lo));
49
+ const text = (v, max = 200) => (typeof v === 'string' ? v.replace(/[\u0000-\u001f\u007f]/g, ' ').slice(0, max) : '');
50
+
51
+ /** An attribute map from the wire, as a plain object a caller can rely on. */
52
+ function toAttr(a) {
53
+ if (!a || typeof a !== 'object') throw new ShareError('EIO', 'the operator sent no attributes');
54
+ const type = a.type === 'file' || a.type === 'directory' || a.type === 'symlink' ? a.type : null;
55
+ if (!type) throw new ShareError('EIO', 'the operator sent an unknown file type');
56
+ const n = (v) => (Number.isFinite(v) ? Number(v) : 0);
57
+ return {
58
+ type, size: n(a.size), mode: n(a.mode) & 0o777, mtimeMs: n(a.mtime_ms), atimeMs: n(a.atime_ms), ctimeMs: n(a.ctime_ms), nlink: n(a.nlink), ino: n(a.ino),
59
+ isFile: () => type === 'file', isDirectory: () => type === 'directory', isSymbolicLink: () => type === 'symlink',
60
+ };
61
+ }
62
+
63
+ const toBytes = (v, what) => {
64
+ if (v instanceof Uint8Array) return v;
65
+ if (v === undefined || v === null) return new Uint8Array(0);
66
+ throw new ShareError('EIO', `the operator sent ${what} that is not bytes`);
67
+ };
68
+
69
+ /**
70
+ * The per-connection engine: one request window shared by every share of the connection.
71
+ * @param {{ send: (m: object) => unknown, log?: (line: string) => void, timeoutMs?: number }} io
72
+ */
73
+ function createCore({ send, log = () => {}, timeoutMs = DEFAULT_TIMEOUT_MS }) {
74
+ let window = 1;
75
+ let maxBytes = MIN_BYTES;
76
+ let nextId = 1;
77
+ let closed = false;
78
+ const inflight = new Map(); // id -> { job, abandoned }
79
+ const queue = [];
80
+ const stats = { requests: 0, replies: 0, errors: 0, bytesDown: 0, bytesUp: 0, timeouts: 0 };
81
+
82
+ function pump() {
83
+ while (!closed && inflight.size < window && queue.length) start(queue.shift());
84
+ }
85
+
86
+ function start(job) {
87
+ if (job.done) return;
88
+ let id = nextId;
89
+ for (let i = 0; inflight.has(id); i += 1) { id = (id % 0xffffffff) + 1; if (i > 0xffff) { finish(job, new ShareError('EAGAIN', 'no request id free')); return; } }
90
+ nextId = (id % 0xffffffff) + 1;
91
+ job.id = id;
92
+ inflight.set(id, { job, abandoned: false });
93
+ stats.requests += 1;
94
+ if (job.fields.data) stats.bytesUp += job.fields.data.byteLength;
95
+ try {
96
+ Promise.resolve(send(shareRequest({ requestId: id, share: job.share, op: job.op, ...job.fields }))).catch(() => {});
97
+ } catch (e) { inflight.delete(id); finish(job, new ShareError('EIO', `could not send: ${e.message}`)); }
98
+ }
99
+
100
+ function finish(job, err, value) {
101
+ if (job.done) return;
102
+ job.done = true;
103
+ clearTimeout(job.timer);
104
+ if (err) job.reject(err); else job.resolve(value);
105
+ }
106
+
107
+ return {
108
+ stats,
109
+ get maxBytes() { return maxBytes; },
110
+ configure(offer) { window = offer.maxInflight; maxBytes = offer.maxBytes; pump(); },
111
+ /** Send one request and resolve with the (validated-as-ok) reply. */
112
+ call(share, op, fields = {}) {
113
+ return new Promise((resolve, reject) => {
114
+ if (closed) { reject(new ShareError('EIO', 'the connection to the operator is gone')); return; }
115
+ const job = { share, op, fields, resolve, reject, done: false, id: 0, timer: null };
116
+ if (queue.length >= QUEUE_LIMIT) { reject(new ShareError('EAGAIN', 'too many share requests are waiting')); return; }
117
+ job.timer = setTimeout(() => {
118
+ stats.timeouts += 1;
119
+ const q = queue.indexOf(job);
120
+ if (q >= 0) queue.splice(q, 1);
121
+ // A request already sent keeps its slot until the operator answers (or the connection ends): the window
122
+ // the offer promised is not exceeded because one answer is slow.
123
+ const entry = inflight.get(job.id);
124
+ if (entry) entry.abandoned = true;
125
+ finish(job, new ShareError('EIO', `the operator did not answer ${op} within ${timeoutMs} ms`));
126
+ }, timeoutMs);
127
+ job.timer.unref?.();
128
+ queue.push(job);
129
+ pump();
130
+ });
131
+ },
132
+ reply(m) {
133
+ const entry = inflight.get(m.request_id);
134
+ if (!entry) return; // unknown or already answered: ignored
135
+ inflight.delete(m.request_id);
136
+ stats.replies += 1;
137
+ const { job, abandoned } = entry;
138
+ if (!abandoned) {
139
+ if (m.ok === true) {
140
+ const data = m.data;
141
+ if (data instanceof Uint8Array) {
142
+ stats.bytesDown += data.byteLength;
143
+ if (data.byteLength > maxBytes) { stats.errors += 1; finish(job, new ShareError('EIO', 'the operator sent more data than it offered')); pump(); return; }
144
+ }
145
+ finish(job, null, m);
146
+ } else {
147
+ stats.errors += 1;
148
+ const errno = ERRNOS.has(m.errno) ? m.errno : 'EIO';
149
+ finish(job, new ShareError(errno, text(m.message) || errno));
150
+ }
151
+ }
152
+ pump();
153
+ },
154
+ close() {
155
+ if (closed) return;
156
+ closed = true;
157
+ const gone = () => new ShareError('EIO', 'the connection to the operator is gone');
158
+ for (const { job } of inflight.values()) finish(job, gone());
159
+ inflight.clear();
160
+ for (const job of queue.splice(0)) finish(job, gone());
161
+ },
162
+ get closed() { return closed; },
163
+ log,
164
+ };
165
+ }
166
+
167
+ /** An open file on the operator's machine. */
168
+ class ShareFile {
169
+ #core; #share; #handle; #inline; #writable; #closed = false;
170
+ constructor(core, share, handle, attr, { inline = null, writable = false } = {}) {
171
+ this.#core = core; this.#share = share; this.#handle = handle; this.#inline = inline; this.#writable = writable;
172
+ this.attr = attr;
173
+ }
174
+
175
+ /** Read up to `length` bytes at `offset`: `{ data, eof }`. */
176
+ async read(offset, length) {
177
+ if (this.#closed) throw new ShareError('EBADF', 'the file is closed');
178
+ if (!(Number.isSafeInteger(offset) && offset >= 0) || !(Number.isSafeInteger(length) && length >= 0)) throw new ShareError('EINVAL', 'read needs a non-negative offset and length');
179
+ if (this.#inline) {
180
+ const data = this.#inline.subarray(offset, offset + length);
181
+ return { data, eof: offset + length >= this.#inline.byteLength };
182
+ }
183
+ const n = Math.min(length, this.#core.maxBytes);
184
+ const r = await this.#core.call(this.#share, 'read', { handle: this.#handle, offset, length: n });
185
+ return { data: toBytes(r.data, 'read data'), eof: r.eof === true };
186
+ }
187
+
188
+ /** Write `data` at `offset` (a share offered `:rw`); resolves with the bytes written. */
189
+ async write(offset, data) {
190
+ if (this.#closed) throw new ShareError('EBADF', 'the file is closed');
191
+ if (!this.#writable) throw new ShareError('EBADF', 'the file is not open for writing');
192
+ let done = 0;
193
+ while (done < data.byteLength) {
194
+ const chunk = data.subarray(done, done + this.#core.maxBytes);
195
+ const r = await this.#core.call(this.#share, 'write', { handle: this.#handle, offset: offset + done, data: chunk });
196
+ const w = Number(r.written);
197
+ if (!Number.isSafeInteger(w) || w < 0 || w > chunk.byteLength) throw new ShareError('EIO', 'the operator reported a bad write size');
198
+ done += w;
199
+ if (w === 0) break;
200
+ }
201
+ return done;
202
+ }
203
+
204
+ async setattr(changes) {
205
+ if (this.#closed) throw new ShareError('EBADF', 'the file is closed');
206
+ if (!this.#handle) throw new ShareError('EBADF', 'this file is read-only and complete: use fs.setattr(path, ...)');
207
+ const r = await this.#core.call(this.#share, 'setattr', { handle: this.#handle, attr: wireAttr(changes) });
208
+ return toAttr(r.attr);
209
+ }
210
+
211
+ async truncate(size) { return this.setattr({ size }); }
212
+
213
+ async close() {
214
+ if (this.#closed) return;
215
+ this.#closed = true;
216
+ if (this.#handle) await this.#core.call(this.#share, 'close', { handle: this.#handle }).catch(() => {});
217
+ }
218
+ }
219
+
220
+ function wireAttr(c = {}) {
221
+ const out = {};
222
+ if (c.mode !== undefined) out.mode = c.mode;
223
+ if (c.atimeMs !== undefined) out.atime_ms = c.atimeMs;
224
+ if (c.mtimeMs !== undefined) out.mtime_ms = c.mtimeMs;
225
+ if (c.size !== undefined) out.size = c.size;
226
+ return out;
227
+ }
228
+
229
+ /**
230
+ * The object an embedder mounts: async file operations on one share. Paths are relative to the share root
231
+ * ("/"-separated; a leading "/" means the root); `..` is refused by the operator's client. Errors are `ShareError`s
232
+ * with `.code` an errno-like string (`ENOENT`, `EROFS`, ...).
233
+ */
234
+ function createShareFs(core, name, writable, signal) {
235
+ const call = (op, fields) => core.call(name, op, fields);
236
+ const norm = (p) => { if (typeof p !== 'string') throw new ShareError('EINVAL', 'a path must be a string'); return p; };
237
+ const maxFileBytes = DEFAULT_MAX_FILE_BYTES;
238
+
239
+ const fs = {
240
+ name,
241
+ /** Whether the operator offered writes. */
242
+ writable,
243
+ maxFileBytes,
244
+ /** Aborted when the connection to the operator ends. */
245
+ signal,
246
+ /** Counters for this connection (requests, replies, errors, bytes each way): the evidence that batching works. */
247
+ get stats() { return { ...core.stats }; },
248
+
249
+ async stat(path) { return toAttr((await call('stat', { path: norm(path) })).attr); },
250
+ async lstat(path) { return toAttr((await call('lstat', { path: norm(path) })).attr); },
251
+ async readlink(path) {
252
+ const r = await call('readlink', { path: norm(path) });
253
+ if (typeof r.target !== 'string') throw new ShareError('EIO', 'the operator sent no link target');
254
+ return r.target;
255
+ },
256
+
257
+ /** Every entry of a directory WITH its attributes, sorted by name (the pages are followed): `[{ name, type, size, mode, mtimeMs, ..., target? }]`. */
258
+ async readdir(path) {
259
+ const out = [];
260
+ let cursor;
261
+ for (;;) {
262
+ const r = await call('readdir', { path: norm(path), ...(cursor !== undefined ? { cursor } : {}) });
263
+ if (!Array.isArray(r.entries)) throw new ShareError('EIO', 'the operator sent no entries');
264
+ for (const e of r.entries) {
265
+ if (!e || typeof e.name !== 'string' || !e.name || e.name.includes('/') || e.name.includes('\0') || e.name === '.' || e.name === '..') throw new ShareError('EIO', 'the operator sent a bad directory entry');
266
+ const entry = { name: e.name, ...toAttr(e) };
267
+ if (typeof e.target === 'string') entry.target = e.target;
268
+ out.push(entry);
269
+ }
270
+ if (out.length > MAX_LIST_ENTRIES) throw new ShareError('EFBIG', 'directory has too many entries');
271
+ if (r.cursor === undefined || r.cursor === null) break;
272
+ if (typeof r.cursor !== 'string' || (cursor !== undefined && r.cursor <= cursor)) throw new ShareError('EIO', 'the operator\'s directory cursor did not advance');
273
+ cursor = r.cursor;
274
+ }
275
+ return out;
276
+ },
277
+
278
+ /** Open a file. `flags`: any of `read`, `write`, `create`, `excl`, `trunc`. */
279
+ async open(path, flags = ['read'], { mode, inlineBytes } = {}) {
280
+ const f = [...flags];
281
+ const wantsWrite = f.includes('write') || f.includes('create') || f.includes('trunc');
282
+ const r = await call('open', { path: norm(path), flags: f, ...(mode !== undefined ? { mode } : {}), ...(inlineBytes !== undefined ? { length: inlineBytes } : {}) });
283
+ const attr = toAttr(r.attr);
284
+ if (r.handle === undefined || r.handle === null) {
285
+ // Whole file, read-only, no handle: it came with the open.
286
+ if (wantsWrite || r.eof !== true || !(r.data instanceof Uint8Array)) throw new ShareError('EIO', 'the operator sent no file handle');
287
+ return new ShareFile(core, name, 0, attr, { inline: r.data });
288
+ }
289
+ if (!Number.isSafeInteger(r.handle) || r.handle <= 0) throw new ShareError('EIO', 'the operator sent a bad handle');
290
+ return new ShareFile(core, name, r.handle, attr, { writable: wantsWrite, inline: r.eof === true && r.data instanceof Uint8Array && !wantsWrite ? r.data : null });
291
+ },
292
+
293
+ /** Create a NEW file (`EEXIST` if the name is taken, a link included) and open it for writing. */
294
+ async create(path, { mode } = {}) {
295
+ const r = await call('create', { path: norm(path), ...(mode !== undefined ? { mode } : {}) });
296
+ if (!Number.isSafeInteger(r.handle) || r.handle <= 0) throw new ShareError('EIO', 'the operator sent a bad handle');
297
+ return new ShareFile(core, name, r.handle, toAttr(r.attr), { writable: true });
298
+ },
299
+
300
+ /** The whole content of a file: one round trip when it is small (it rides the open), else ranges of the offered size. */
301
+ async readFile(path, { maxBytes = maxFileBytes } = {}) {
302
+ const file = await fs.open(path, ['read'], { inlineBytes: core.maxBytes });
303
+ try {
304
+ if (file.attr.size > maxBytes) throw new ShareError('EFBIG', `the file is ${file.attr.size} bytes, more than ${maxBytes}`);
305
+ const parts = [];
306
+ let offset = 0;
307
+ for (;;) {
308
+ const { data, eof } = await file.read(offset, core.maxBytes);
309
+ if (data.byteLength) parts.push(data);
310
+ offset += data.byteLength;
311
+ if (offset > maxBytes) throw new ShareError('EFBIG', `the file is bigger than ${maxBytes} bytes`);
312
+ if (eof || data.byteLength === 0) break;
313
+ }
314
+ if (parts.length === 1) return parts[0];
315
+ const all = new Uint8Array(offset);
316
+ let at = 0;
317
+ for (const p of parts) { all.set(p, at); at += p.byteLength; }
318
+ return all;
319
+ } finally { await file.close(); }
320
+ },
321
+
322
+ /** Replace (or create) a file with `data`. Needs `:rw`. */
323
+ async writeFile(path, data, { mode, truncate = true } = {}) {
324
+ const file = await fs.open(path, ['write', 'create', ...(truncate ? ['trunc'] : [])], { mode });
325
+ try { return await file.write(0, data); } finally { await file.close(); }
326
+ },
327
+
328
+ async mkdir(path, { mode } = {}) { return toAttr((await call('mkdir', { path: norm(path), ...(mode !== undefined ? { mode } : {}) })).attr); },
329
+ async unlink(path) { await call('unlink', { path: norm(path) }); },
330
+ async rmdir(path) { await call('rmdir', { path: norm(path) }); },
331
+ async rename(from, to) { await call('rename', { path: norm(from), to: norm(to) }); },
332
+ /** `changes`: any of `mode`, `atimeMs`, `mtimeMs`, `size` (a new size is a truncate). */
333
+ async setattr(path, changes) { return toAttr((await call('setattr', { path: norm(path), attr: wireAttr(changes) })).attr); },
334
+ async truncate(path, size) { return fs.setattr(path, { size }); },
335
+ async chmod(path, mode) { return fs.setattr(path, { mode }); },
336
+ async utimes(path, atimeMs, mtimeMs) { return fs.setattr(path, { atimeMs, mtimeMs }); },
337
+
338
+ // ── the shape of an injected `fs` backend (`createMemoryHost({ fs })`, `createWshServer({ fs })`) ───────────────
339
+ // A share can be served onward as a host's own file backend: `createMemoryHost({ fs: share })`.
340
+ async operate(op, clientPath, { offset, length, newPath, data } = {}) {
341
+ const entry = (e, nameOf) => ({ name: nameOf, size: e.size, modified: Math.floor(e.mtimeMs / 1000), type: e.type, ...(e.target !== undefined ? { symlink_target: e.target } : {}) });
342
+ switch (op) {
343
+ case 'list': return { entries: (await fs.readdir(clientPath || '/')).map((e) => entry(e, e.name)), metadata: { path: clientPath || '/' } };
344
+ case 'stat': { const a = await fs.lstat(clientPath); return { metadata: entry(a, String(clientPath).split('/').filter(Boolean).pop() ?? '') }; }
345
+ case 'read': {
346
+ const file = await fs.open(clientPath, ['read']);
347
+ try {
348
+ const want = Math.min(Number(length ?? core.maxBytes), core.maxBytes);
349
+ const { data: bytes } = await file.read(Math.max(0, Number(offset ?? 0)), want);
350
+ return { metadata: { data: bytes, size: file.attr.size } };
351
+ } finally { await file.close(); }
352
+ }
353
+ case 'write': { await fs.writeAt(clientPath, data, offset); return { metadata: { written: data.byteLength } }; }
354
+ case 'mkdir': await fs.mkdir(clientPath); return { metadata: {} };
355
+ case 'remove': { const a = await fs.lstat(clientPath); await (a.isDirectory() ? fs.rmdir(clientPath) : fs.unlink(clientPath)); return { metadata: { removed: clientPath } }; }
356
+ case 'rename': await fs.rename(clientPath, newPath); return { metadata: { renamed: clientPath, to: newPath } };
357
+ default: throw new ShareError('ENOTSUP', `"${op}" is not offered (list, stat, read, write, rename, mkdir, remove)`);
358
+ }
359
+ },
360
+ async readWhole(clientPath) { return fs.readFile(clientPath); },
361
+ async writeWhole(clientPath, bytes) { await fs.writeFile(clientPath, bytes); },
362
+ async writeAt(clientPath, bytes, offset = 0) {
363
+ const file = await fs.open(clientPath, ['write', 'create']);
364
+ try { await file.write(Number(offset), bytes); } finally { await file.close(); }
365
+ },
366
+ };
367
+ return fs;
368
+ }
369
+
370
+ /**
371
+ * The shares of ONE connection. `handle(m)` takes the messages that are about shares; `close()` ends everything.
372
+ * @param {object} io
373
+ * @param {(m: object) => unknown} io.send - send a message to the operator (through the connection's sealing, if any)
374
+ * @param {(name: string, fs: object, who: { username: string | null, fingerprint: string | null }) => unknown} io.onShare
375
+ * @param {() => { username: string | null, fingerprint: string | null }} io.who
376
+ * @param {(line: string) => void} [io.log]
377
+ * @param {number} [io.timeoutMs]
378
+ */
379
+ export function createShareSession({ send, onShare, who, log = () => {}, timeoutMs }) {
380
+ const core = createCore({ send, log, timeoutMs });
381
+ const abort = new AbortController();
382
+ let offered = false;
383
+ const shares = new Map();
384
+
385
+ function offer(m) {
386
+ if (offered) { log('ignored a second ShareOffer'); return; }
387
+ offered = true;
388
+ const names = Array.isArray(m.shares) ? m.shares : [];
389
+ if (!names.length || names.length > MAX_SHARES || names.some((n) => typeof n !== 'string' || !NAME_RE.test(n)) || new Set(names).size !== names.length) {
390
+ log('ignored a ShareOffer with bad share names');
391
+ return;
392
+ }
393
+ const writable = new Set(Array.isArray(m.writable) ? m.writable.filter((n) => names.includes(n)) : []);
394
+ 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);
397
+ shares.set(name, fs);
398
+ Promise.resolve()
399
+ .then(() => onShare(name, fs, who()))
400
+ .catch((e) => log(`onShare(${JSON.stringify(name)}) threw: ${e?.message ?? e}`));
401
+ }
402
+ log(`shares offered: ${names.map((n) => `${n}${writable.has(n) ? ' (rw)' : ''}`).join(', ')}`);
403
+ }
404
+
405
+ return {
406
+ /** The shares offered so far, by name. */
407
+ shares,
408
+ stats: core.stats,
409
+ /** @returns {boolean} whether `m` was about shares (and has been dealt with). */
410
+ handle(m) {
411
+ switch (m.type) {
412
+ case MSG.SHARE_OFFER: offer(m); return true;
413
+ case MSG.SHARE_REPLY: core.reply(m); return true;
414
+ case MSG.SHARE_REQUEST: log('ignored a ShareRequest from the operator (only the host asks)'); return true;
415
+ default: return false;
416
+ }
417
+ },
418
+ close() { abort.abort(); core.close(); },
419
+ };
420
+ }
421
+
422
+ /** Validate an `onShare` option (a function, or absent). */
423
+ export function validateOnShare(onShare, who) {
424
+ if (onShare !== undefined && onShare !== null && typeof onShare !== 'function') throw new TypeError(`${who}: onShare must be a function (name, fs, who) => void`);
425
+ }