@johnhenry/wsh 0.42.0 → 0.43.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
- - **108 message types** -- handshake, channel, gateway, guest sharing, compression negotiation, copilot, policy, authorized-key management, and more
69
+ - **110 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 --
@@ -713,10 +713,20 @@ const s = await client.openSession({ type: 'exec', command: 'echo hello' });
713
713
  `ReverseConnect` at a time (a concurrent one is told `busy: ... retry in a
714
714
  moment`), since a `ReverseAccept` does not name its operator; and at the cap
715
715
  the reason is `busy: this peer already has its maximum of n operators`
716
- (`busyPeerFull(n)`). The **Rust relay is still one operator per peer**: it
717
- never sends `ReverseClose` and rejects the second operator; the new spec
718
- fields are regenerated into the Rust types and ignored there. Tracked for the
719
- Rust relay in #93.
716
+ (`busyPeerFull(n)`). The **Rust relay and the Rust peer do this too** (#93): `wsh-server --enable-relay`
717
+ with `[relay] max_operators_per_peer = n` in its config (default `1`, 1 to 64; above 1 it advertises
718
+ `relay-multi-operator`), and `wsh --max-operators n reverse ...` / `wsh --max-operators n agent run ...` on the
719
+ peer (default `1`; the peer states the feature only to a relay that advertises it, and serves one operator at a
720
+ time on any other). The Rust relay rejects a busy peer's next operator with a `ReverseReject` carrying the same
721
+ `busy:` reasons. Differences from the JS relay, kept so nothing existing changes: when an operator leaves a peer
722
+ that serves one, the Rust relay leaves the peer connected (it may take the operator back), where the JS relay
723
+ closes it; and a peer that goes away leaves its operators connected. A Rust peer serving several operators keeps
724
+ each operator's sessions, processes and files apart (when one leaves, only its work is killed), takes each
725
+ operator's `--allow-operator` decision and operator proof on its own, and **does not seal bridges** (a
726
+ connection holds one seal): `--max-operators` above 1 is refused together with `--require-operator-proof`, and
727
+ an operator that insists on `--sealed` is refused by such a peer. The Rust relay also carries
728
+ `KeyExchange.signature` and advertises `e2e-sign`, so a JS reverse host signs its half of an end-to-end
729
+ exchange through it.
720
730
  - **On the peer**, the bridged operator is served by the same connection code as
721
731
  a direct client, over an in-memory message pipe instead of a socket. Nothing a
722
732
  client opens can cross the relay but control messages, so exec sessions are
@@ -1223,6 +1233,47 @@ The host advertises `file-write` / `file-rename` in `ServerHello`; the client
1223
1233
  throws instead of sending to a host without them (the Rust `wsh-server`
1224
1234
  refuses these ops).
1225
1235
 
1236
+ ### Execution targets (#121)
1237
+
1238
+ A host that fronts several places to run things (containers, VMs, workers, sandboxes) names them, instead of overloading `username` or
1239
+ prefixing the command. Off unless you give `targets` (to `createWshServer`, `createMemoryHost`, or `createConnectionFactory` through
1240
+ `resolveBackends`); then the host advertises `targets` in `ServerHello.features`.
1241
+
1242
+ ```js
1243
+ createWshServer({
1244
+ auth: { authorizedKeys },
1245
+ targets: {
1246
+ web: { description: 'the web container', exec: true },
1247
+ db: { description: 'the database VM', exec: (command, io) => runInVm(io.target, command, io), fs: dbFiles,
1248
+ authorize: (who, { target, kind }) => who.fingerprint === DBA_KEY }, // kind: exec | pty | file | endpoint | list
1249
+ },
1250
+ // requireTarget: true, // an Open, FileOp or OpenEndpoint that names no target is refused: nothing runs on the host itself
1251
+ });
1252
+ const targets = await client.listTargets(); // [{ name, description?, capabilities }] -- only what THIS key may use
1253
+ await client.openSession({ type: 'exec', command: 'psql -c ...', target: 'db' }); // also exec(url, cmd, { target })
1254
+ await client.fileOperation('list', '/var/lib', { target: 'db' }); // FileOp.target
1255
+ await client.openEndpoint('metrics', { target: 'web' }); // OpenEndpoint.target
1256
+ ```
1257
+
1258
+ Each target has its own `exec`, `pty`, `fs` and `endpoints` (the same forms as the host's own, `exec: true` and `fs: { root }` included on
1259
+ Node); the host's own are used only by a request that names no target. A target without a backend for the request refuses it (`exec is
1260
+ not enabled for this target`): a request is never run somewhere else. `io.target` (exec), `{ target }` in the pty `spawn` options, in every
1261
+ file backend call and on an endpoint's `duplex.target` tell a shared function which target it serves. `authorize(who, { target, kind })` is
1262
+ asked for every request that names the target and for `listTargets()`; only `true` lets the caller on, and a refused target and one that
1263
+ does not exist get the same answer (`no such target`), so the reply does not say which targets exist. A target without `authorize` is open
1264
+ to every key the host authenticated, as the host's own `exec` is. A `target` the client sends to a host that does not advertise `targets` is
1265
+ not sent (the client throws); a raw one is refused (`this host has no targets`). `createReverseHost` takes no `targets`.
1266
+
1267
+ What it does **not** do: `requireTarget` covers `Open` (exec, pty, file, rpc), `FileOp` and `OpenEndpoint`, not the gateway (`OpenTcp`,
1268
+ `OpenUnix`, `ListenRequest`, ...), MCP, the `rpc` channels (`wsh-fs`, ... are the host's own and are refused when a target is named), or
1269
+ `Attach` to a session that already exists (it was opened on its target, and its owner may attach as before). A target is an authorization
1270
+ boundary only as far as your `authorize` and your backends make it one: the library routes and refuses, it does not isolate anything.
1271
+
1272
+ The Rust CLI names one with `wsh --target NAME [user@]host [command...]` (or `wsh --target NAME connect [user@]host`) and lists them with
1273
+ `wsh targets [user@]host [--json]`; `--target` is refused (exit 2) by file transfer, forwarding, `--share`, `-N` and every other subcommand,
1274
+ and sent only to a host that advertises `targets`. The Rust `wsh-server` has no targets (it states no feature and refuses any request that
1275
+ names one).
1276
+
1226
1277
  ### Compatibility: announce vs. primer
1227
1278
 
1228
1279
  An exec session's output flows on a second, client-opened stream, and a QMux
@@ -1297,7 +1348,7 @@ closes the channel when received.
1297
1348
  | Protocol | Methods |
1298
1349
  |---|---|
1299
1350
  | `wsh-host` | `host.info` -> `{ version, protocol, features (this connection's ServerHello), hostFingerprint, user, rpc }`; `host.ping` -> `{ time }` |
1300
- | `wsh-fs` | `stat`, `list`, `mkdir`, `remove`, `rename { path, newPath }`, `write { path, data, offset? }`, `upload { path, data, offset? }` (offset omitted/0 creates or truncates, later offsets continue in place: chunk big files), `read { path, offset?, length? }` and `download { path }` (the bytes arrive as `$/progress` chunks of at most 64 KiB; the result is `{ size, offset, length, eof }`). Same confinement as `fs`: no traversal or symlink escapes, `readOnly`, `maxFileBytes`; policy refusals are `-32003`. |
1351
+ | `wsh-fs` | `stat`, `list` (entries sorted by name in UTF-16 code-unit order on every platform and on both hosts: upper case before lower case, whatever the filesystem's case rules), `mkdir`, `remove`, `rename { path, newPath }`, `write { path, data, offset? }`, `upload { path, data, offset? }` (offset omitted/0 creates or truncates, later offsets continue in place: chunk big files), `read { path, offset?, length? }` and `download { path }` (the bytes arrive as `$/progress` chunks of at most 64 KiB; the result is `{ size, offset, length, eof }`). Same confinement as `fs`: no traversal or symlink escapes, `readOnly`, `maxFileBytes`; policy refusals are `-32003`. |
1301
1352
  | `mcp` | The MCP JSON-RPC surface verbatim; see below |
1302
1353
 
1303
1354
  When a host advertises `rpc-protocol:wsh-fs`, `fileStat` / `fileList` / `fileRead` /
@@ -1498,7 +1549,7 @@ so options the platform gains later need no change here.
1498
1549
 
1499
1550
  | Export | Description |
1500
1551
  |--------|-------------|
1501
- | `MSG` | 108 message type constants (hex opcodes) |
1552
+ | `MSG` | 110 message type constants (hex opcodes) |
1502
1553
  | `CHANNEL_KIND` | Channel types: `pty`, `exec`, `meta`, `file`, `tcp`, `udp`, `job` |
1503
1554
  | `AUTH_METHOD` | Auth methods: `pubkey`, `password` |
1504
1555
  | `cborEncode` / `cborDecode` | CBOR codec (maps, arrays, strings, ints, bytes, bools, null, floats) |
@@ -1522,7 +1573,7 @@ instead of dragging its own toolchain and CI job into an unrelated
1522
1573
  browser-app repo. It was previously deleted from clawser by accident
1523
1574
  (2026-03-14) and restored (2026-07-05) before this move.
1524
1575
 
1525
- Four crates, workspace-versioned (currently `0.13.0`):
1576
+ Four crates, workspace-versioned (currently `0.14.0`):
1526
1577
 
1527
1578
  | Crate | Kind | Description |
1528
1579
  |-------|------|--------------|
@@ -1547,6 +1598,9 @@ disconnects. `wsh connect` ends when the remote session does. Diagnostics go to
1547
1598
  never into the command's stdout. TLS uses the platform trust store, and `SSL_CERT_FILE` points it at another certificate (how a self-signed host is trusted); a plain
1548
1599
  `ws://` URL is accepted only for a loopback host.
1549
1600
 
1601
+ `wsh --target NAME [user@]host [command...]` runs on one of the host's execution targets and `wsh targets [user@]host` lists the ones this key may
1602
+ use (see [Execution targets](#execution-targets-121)); it is sent only to a host that advertises `targets`.
1603
+
1550
1604
  ### Forwarding with `wsh -L` / `-R` / `-N`
1551
1605
 
1552
1606
  Modelled on OpenSSH. The forwards live as long as the connection does (`wsh -L ... user@host` also runs the command or
@@ -1675,7 +1729,7 @@ than left to be found.
1675
1729
  | 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) |
1676
1730
  | 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 |
1677
1731
  | 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) |
1678
- | Reverse-connect / relay peer | `connectReverse()`, `trustRelayPeer()`; `@johnhenry/wsh/server`: `relay` option and `createReverseHost()` | `wsh reverse`, `wsh agent` (persistent, with startup-unit install) | **Wire-unified** (registration, discovery, signed peer records); **daemonization is CLI-only** -- a browser tab cannot be a background OS service. The Node relay is default-deny and bridges one operator per peer unless `maxOperatorsPerPeer` is raised (`busy:` reasons say so); E2E and bridged feature gates need `rust-v0.3.0`+ on the Rust side; several operators per peer and the signed `KeyExchange` are JS-relay only for now |
1732
+ | 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 (#93): both relays** (`maxOperatorsPerPeer`; `[relay] max_operators_per_peer`, default 1) **and both peers** (`createReverseHost({ maxOperators })`; `wsh --max-operators n reverse` / `agent run`, default 1), negotiated by `relay-multi-operator`; a Rust peer serving several operators does not seal bridges (see the reverse-mode notes), and the Rust relay leaves a peer connected when its operator leaves. The signed `KeyExchange` (`e2e-sign`) is carried by the Rust relay too |
1679
1733
  | Post-quantum E2E (experimental) | `initiateE2E()` (WebCrypto ML-KEM-768 or `@noble/post-quantum` fallback) | `E2eKeyExchange` (`ml-kem` crate) | **Wire-unified** algorithm and transcript; key material backends differ by platform necessity |
1680
1734
  | Unix-domain socket forwarding, both directions; named endpoints (#120) | `client.openUnix()`, `listenUnix()`, `forwardUnix()` (Node: `-L`/`-R` shapes with unix and TCP ends mixed), `openEndpoint()`; host: `gateway: { unix, endpoints }`, `createMemoryHost({ endpoints })` | `wsh-server` serves `OpenUnix`/`ListenUnix` (`[gateway] unix_connect`, `unix_listen`, `unix_replace_stale`, `unix_max_listeners`; same policy as the Node host); `wsh-client` has `open_tcp`/`open_unix`/`open_endpoint`/`listen_unix`/`listen_tcp`; CLI `wsh -L` / `-R` / `-N` with TCP, unix and `endpoint=NAME` ends, also through `--via` | **Wire-unified, both directions** (#145). A Rust host does not offer named endpoints (an in-page host does); the CLI reaches them. See [Forwarding with `wsh -L`](#forwarding-with-wsh--l---r---n) |
1681
1735
  | Gateway flow control (#123) | credit per connection (`GatewayCredit`, feature `gateway-credit`); host caps for peers without it | `wsh-server` and `wsh-client`: 256 KiB per direction when both list `gateway-credit`; without it, per-connection and per-client byte caps (`max_buffered_bytes` 4 MiB, `max_client_buffered_bytes` 32 MiB) close the connection that exceeds them | **Wire-unified, negotiated**; an older peer on either side keeps working under the caps. `OpenUdp` flows are metered too (a datagram without credit is dropped) |
@@ -1685,6 +1739,7 @@ than left to be found.
1685
1739
  | 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 |
1686
1740
  | 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 |
1687
1741
  | 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) |
1742
+ | Execution targets (#121): `Open.target`, `FileOp.target`, `OpenEndpoint.target`, `ListTargets` / `TargetList` | host: `targets` on `createWshServer` / `createMemoryHost` (own backends and `authorize(who, { target, kind })` per target, `requireTarget`); client: `openSession({ target })`, `exec(.., { target })`, `fileOperation(.., { target })`, `openEndpoint(.., { target })`, `listTargets()` | CLI: `wsh --target NAME [user@]host [command...]` and `wsh connect` (exec and shells only; every other subcommand, `-L`/`-R`/`-N` and `--share` refuse `--target`), `wsh targets [user@]host [--json]`; the client's `open_session(SessionOpts { target })` and `list_targets()` (file and endpoint calls send no target). **A Rust host with targets: not built**: `wsh-server` states no `targets`, refuses a request that names one and answers `ListTargets` with an error | **Wire-unified, negotiated** (`targets` feature; every new field optional, never sent to a host that did not advertise it) |
1688
1743
  | Operator-side shared folders (`--share`, #159) | host side: `onShare(name, fs, who)` on `createMemoryHost` / `createWshServer` / `createReverseHost` (the host *uses* the operator's directories; `fs` is an object of async file operations, also shaped like an `fs` backend; `fs.root` is the operator's advisory, unverified path for the share, #164). The JS client does not offer shares | CLI side: `wsh --share NAME=/abs/dir[:ro\|:rw]` offers them, with each directory's path unless `--share-hide-path` (`wsh_client::share`, `wsh-cli`'s `sharefs`: descriptor-relative, never follows a link, see [Sharing a directory](#sharing-a-directory-with-the-host-wsh---share-159)); unix only. **A Rust host that uses shares: not built** (`wsh-server` does not state `shares`) | **Wire-unified, negotiated**: the host states the feature `shares`; the client sends one `ShareOffer` after login (opcodes `0xa8` `ShareOffer`, `0xa9` `ShareRequest`, host to client, `0xaa` `ShareReply`). No change notification, no sharing over `reverse-connect` |
1689
1744
  | Sealed session: any authenticated connection incl. gateway/endpoint data (#155) | host `sealSession: 'offer' \| 'require'` (stage b); client `connect(url, { sealSession: false \| 'auto' \| true })` (stage c) | `wsh --sealed ...` (or automatic against `e2e-session-required`) seals a direct or pipe-relayed session; `wsh-server` offers or requires it on WebSocket (`[server] seal_session = "off" \| "offer" \| "require"`, needs `host_key`; `require` refuses WebTransport, WISP tunnels and password logins; no typed rpc channels while it is on) | **Wire-unified, negotiated** (`e2e-session`, `e2e-session-required`, `KeyExchange` for the connection's session id, `EncryptedFrame` channel 0) |
1690
1745
  | 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 |
@@ -1746,7 +1801,7 @@ plus one `SHA256SUMS` file covering every archive in the release. These
1746
1801
  names are a stable contract other repos (clawser) pin and download by --
1747
1802
  do not change them without coordinating downstream.
1748
1803
 
1749
- `wsh --version` and `wsh-server --version` print the workspace version the binary was built from (`wsh 0.13.0`), which is the
1804
+ `wsh --version` and `wsh-server --version` print the workspace version the binary was built from (`wsh 0.14.0`), which is the
1750
1805
  number in the `rust-vX.Y.Z` tag. Binaries of `rust-v0.9.0` to `rust-v0.10.0` printed a fixed `0.1.0`, so against one of those the
1751
1806
  version cannot be read from the binary (look for a flag in `wsh --help` instead).
1752
1807
 
@@ -1797,6 +1852,21 @@ out explicitly below rather than left to be discovered.
1797
1852
  entry client-side and reports a `verified` boolean, independent of
1798
1853
  trusting the relay.
1799
1854
 
1855
+ - **Execution targets: a name the client sends and the host decides on (#121).** Off unless `targets` is given. The host runs
1856
+ `authorize(who, { target, kind })` for every request that names a target (and `listTargets()`), and a refused target looks like an
1857
+ unknown one. It does NOT isolate targets from each other: a key allowed on two can use both, the library only routes and refuses, so the
1858
+ isolation a target gives is your backends'. `requireTarget` does not cover the gateway, MCP or `Attach`; without it a request with no
1859
+ target runs on the host's own backends, which any authenticated key can use, so a deployment that confines a key to one target must set
1860
+ `requireTarget` (or leave the host with no backends of its own). The Rust `wsh-server` has no targets and refuses any request that names one.
1861
+ - **Several operators per peer share one peer, and the relay decides who is who (#93).** Off unless both the relay
1862
+ (`maxOperatorsPerPeer`, `[relay] max_operators_per_peer`) and the peer (`maxOperators`, `--max-operators`) are
1863
+ set above 1. The relay stamps each message with its own record of the sender's authenticated key and removes
1864
+ `to_fingerprint`; it checks the inner of a forward a peer wrote (size, decodes, a forwardable type) and drops what it
1865
+ cannot address. It does NOT protect operators from each other beyond that: they run as the same OS user as the
1866
+ peer, so a command one operator starts can read or kill another's files and processes. A Rust peer serving several
1867
+ operators cannot seal bridges (one seal per connection), so its bridges are as private as the relay is honest;
1868
+ use one operator per peer where that matters (`--require-operator-proof` needs it and is refused otherwise).
1869
+
1800
1870
  - **The Node gateway checks where a connection goes, not only what it was called.** `gateway.allow` matches the name a
1801
1871
  client sent, and then the address it resolves to must be globally routable (or permitted by `allowPrivate` or an
1802
1872
  IP-literal rule); the connection is made to that checked address, and `ResolveDns` answers are filtered the same way.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.42.0",
3
+ "version": "0.43.0",
4
4
  "description": "Web Shell \u2014 browser-native remote command execution over WebTransport and WebSocket with Ed25519 authentication",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/client.mjs CHANGED
@@ -8,7 +8,7 @@
8
8
  * reverse mode (client registers as a peer for incoming connections).
9
9
  */
10
10
 
11
- import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE, SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE } from './features.mjs';
11
+ import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE, TARGETS_FEATURE, SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE } from './features.mjs';
12
12
  import { WebTransportTransport, normalizeWebTransportOptions } from './transport.mjs';
13
13
  import { clientChannelBinding, offeredKinds, TLS_EXPORTER_LABEL, TLS_EXPORTER_LENGTH } from './channel-binding.mjs';
14
14
  import { WebSocketTransport } from './transport-ws.mjs';
@@ -36,6 +36,7 @@ import {
36
36
  policyEval as policyEvalMsg, policyUpdate as policyUpdateMsg,
37
37
  detach as detachMsg,
38
38
  sessionListRequest as sessionListRequestMsg,
39
+ listTargets as listTargetsMsg,
39
40
  sessionGrant as sessionGrantMsg, sessionRevoke as sessionRevokeMsg,
40
41
  isRelayForwardable,
41
42
  } from './messages.mjs';
@@ -74,7 +75,16 @@ const DEFAULT_OPEN_TIMEOUT = 10_000; // ms
74
75
  const FS_RPC_OPS = new Set(['stat', 'list', 'read', 'write', 'mkdir', 'remove', 'rename']);
75
76
 
76
77
  // The feature strings live in features.mjs (a host names them without importing this file); re-exported here.
77
- export { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE };
78
+ export { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE, TARGETS_FEATURE };
79
+
80
+ /** `target` must be a non-empty string, and only a host that advertises `targets` may be sent one (#121). */
81
+ function assertTargetUsable(client, target, who) {
82
+ if (target === undefined) return;
83
+ if (typeof target !== 'string' || !target) throw new TypeError(`${who}: target must be a non-empty string`);
84
+ if (!client.hasFeature(TARGETS_FEATURE)) {
85
+ throw new Error(`${who}: this host does not advertise "${TARGETS_FEATURE}" (execution targets); it would run the request on its own default, or reject the unknown field -- it was not sent`);
86
+ }
87
+ }
78
88
 
79
89
  /** An `AbortError` for `signal`, with the signal's reason as `cause`. */
80
90
  function abortError(signal) {
@@ -825,10 +835,13 @@ export class WshClient {
825
835
  * Throws `RpcError` (`UNSUPPORTED_PROTOCOL`) before sending anything if the host does not advertise it.
826
836
  * @param {(session: WshSession) => void} [opts.attach] - Advanced: called synchronously the moment the data
827
837
  * stream is bound, before any received byte can be delivered (`openRpc` uses it to set `onData`).
838
+ * @param {string} [opts.target] - Which of the host's execution targets to run on (#121; see `listTargets()`).
839
+ * Throws before sending anything if the host does not advertise `targets`. Omitted: the host's own default.
828
840
  * @returns {Promise<WshSession>}
829
841
  */
830
- async openSession({ type = 'pty', command, protocol, cols = 80, rows = 24, env, timeout = DEFAULT_OPEN_TIMEOUT, primer = true, attach, stdio } = {}) {
842
+ async openSession({ type = 'pty', command, protocol, cols = 80, rows = 24, env, timeout = DEFAULT_OPEN_TIMEOUT, primer = true, attach, stdio, target } = {}) {
831
843
  this.#assertAuthenticated('openSession');
844
+ assertTargetUsable(this, target, 'openSession');
832
845
  if (stdio !== undefined && stdio !== 'pty' && stdio !== 'pipes') {
833
846
  throw new TypeError('openSession: stdio must be "pty" or "pipes"');
834
847
  }
@@ -845,7 +858,7 @@ export class WshClient {
845
858
  const requestedChannelId = this._nextChannelId();
846
859
 
847
860
  await this.#transport.sendControl(
848
- openMsg({ kind: type, command, cols, rows, env, stdio: stdio === 'pipes' ? 'pipes' : undefined })
861
+ openMsg({ kind: type, command, cols, rows, env, stdio: stdio === 'pipes' ? 'pipes' : undefined, target })
849
862
  );
850
863
 
851
864
  // Registered as a dedicated pending-open (not the generic
@@ -1188,10 +1201,11 @@ export class WshClient {
1188
1201
  * when the host advertises `exec-pipes` (no echo, stderr kept apart, EOF), else the host's native
1189
1202
  * mode; without `stdin`, the host's native mode (a PTY on the Rust server), exactly as before.
1190
1203
  * `'pipes'` throws if the host does not advertise `exec-pipes`; `'pty'` never asks for pipes.
1204
+ * @param {string} [opts.target] - The host's execution target to run on (#121; needs `targets`, see `openSession`).
1191
1205
  * @returns {Promise<{stdout: Uint8Array, exitCode: number, stderr?: Uint8Array}>} `stderr` is present
1192
1206
  * only when the command ran on pipes.
1193
1207
  */
1194
- static async exec(url, command, { username, keyPair, signer, password, timeout = DEFAULT_EXEC_TIMEOUT, primer = true, stdin, stdio, ...hostKeyOpts } = {}) {
1208
+ static async exec(url, command, { username, keyPair, signer, password, timeout = DEFAULT_EXEC_TIMEOUT, primer = true, stdin, stdio, target, ...hostKeyOpts } = {}) {
1195
1209
  if (stdin !== undefined) assertStdinSource(stdin);
1196
1210
  if (stdio !== undefined && stdio !== 'pipes' && stdio !== 'pty') throw new TypeError('exec: stdio must be "pipes" or "pty"');
1197
1211
  const client = new WshClient();
@@ -1206,7 +1220,7 @@ export class WshClient {
1206
1220
 
1207
1221
  // The first stdin byte (or the EOF itself) announces the data stream to a
1208
1222
  // legacy host, so the primer byte is only needed when there is no stdin.
1209
- const session = await client.openSession({ type: 'exec', command, primer: stdin === undefined ? primer : false, stdio: piped ? 'pipes' : undefined });
1223
+ const session = await client.openSession({ type: 'exec', command, primer: stdin === undefined ? primer : false, stdio: piped ? 'pipes' : undefined, target });
1210
1224
 
1211
1225
  await new Promise((resolve, reject) => {
1212
1226
  const timer = setTimeout(() => {
@@ -1385,6 +1399,22 @@ export class WshClient {
1385
1399
  return Promise.all(peers.map(async (peer) => ({ ...peer, verified: await verifyPeerInfoRecord(peer) })));
1386
1400
  }
1387
1401
 
1402
+ /**
1403
+ * The execution targets this connection may use (#121): what the host decides to show THIS key, in the host's order.
1404
+ * Each is `{ name, description?, capabilities }` (`capabilities` is a hint: any of `exec`, `pty`, `file`, `endpoint`);
1405
+ * pass `name` as `target` to `openSession`, `fileOperation` or `openEndpoint`. Throws if the host does not advertise `targets`.
1406
+ *
1407
+ * @param {number} [timeout=10000] - Timeout in ms
1408
+ * @returns {Promise<Array<{ name: string, description?: string, capabilities: string[] }>>}
1409
+ */
1410
+ async listTargets(timeout = DEFAULT_OPEN_TIMEOUT) {
1411
+ this.#assertAuthenticated('listTargets');
1412
+ if (!this.hasFeature(TARGETS_FEATURE)) throw new Error(`listTargets: this host does not advertise "${TARGETS_FEATURE}" (execution targets)`);
1413
+ await this.#transport.sendControl(listTargetsMsg());
1414
+ const response = await this.#waitForMessage([MSG.TARGET_LIST], timeout, 'Timed out waiting for the target list');
1415
+ return response.targets ?? [];
1416
+ }
1417
+
1388
1418
  /**
1389
1419
  * Initiate a reverse connection to a registered peer.
1390
1420
  *
@@ -2418,14 +2448,18 @@ export class WshClient {
2418
2448
  *
2419
2449
  * @param {string} op - Operation: 'stat', 'list', 'read', 'write', 'mkdir', 'remove', 'rename'
2420
2450
  * @param {string} path - File path
2421
- * @param {object} [opts] - Optional: offset, length for read; `data` (+ `offset`) for write; `newPath` for rename
2451
+ * @param {object} [opts] - Optional: offset, length for read; `data` (+ `offset`) for write; `newPath` for rename;
2452
+ * `target` (#121): the execution target whose files these are (needs a host that advertises `targets`; the
2453
+ * `wsh-fs` rpc is not per target, so a request with a target always goes over FileOp)
2422
2454
  * @param {number} [timeout=10000]
2423
2455
  * @returns {Promise<object>} FileResult response
2424
2456
  */
2425
2457
  async fileOperation(op, path, opts = {}, timeout = DEFAULT_OPEN_TIMEOUT) {
2426
2458
  this.#assertAuthenticated('fileOperation');
2459
+ assertTargetUsable(this, opts.target, 'fileOperation');
2460
+ const { target } = opts;
2427
2461
  // wsh #85: a host that serves the `wsh-fs` rpc protocol is preferred over the FileOp/FileResult control path.
2428
- if (this.preferRpcFiles && FS_RPC_OPS.has(op) && this.hasFeature(rpcProtocolFeature('wsh-fs'))) {
2462
+ if (target === undefined && this.preferRpcFiles && FS_RPC_OPS.has(op) && this.hasFeature(rpcProtocolFeature('wsh-fs'))) {
2429
2463
  let rpc = null;
2430
2464
  try { rpc = await this.#fsChannel(); } catch { /* fall back to FileOp */ }
2431
2465
  if (rpc) return this.#fileOperationRpc(rpc, op, path, opts, timeout);
@@ -2451,7 +2485,7 @@ export class WshClient {
2451
2485
  const result = this.#waitForMessage([MSG.FILE_RESULT], timeout, `Timed out waiting for file ${op} result`, byChannel);
2452
2486
  result.catch(() => {});
2453
2487
  await this.#transport.sendControl(fileOpMsg({
2454
- channelId, op, path, offset: op === 'write' ? opts.offset : undefined, length: data.byteLength,
2488
+ channelId, op, path, offset: op === 'write' ? opts.offset : undefined, length: data.byteLength, target,
2455
2489
  }));
2456
2490
  let off = 0;
2457
2491
  do {
@@ -2465,7 +2499,7 @@ export class WshClient {
2465
2499
  }
2466
2500
 
2467
2501
  await this.#transport.sendControl(
2468
- fileOpMsg({ channelId, op, path, offset: opts.offset, length: opts.length })
2502
+ fileOpMsg({ channelId, op, path, offset: opts.offset, length: opts.length, target })
2469
2503
  );
2470
2504
  return this.#waitForMessage(
2471
2505
  [MSG.FILE_RESULT],
package/src/features.mjs CHANGED
@@ -27,6 +27,13 @@ export const MCP_CANCEL_FEATURE = 'mcp-cancel';
27
27
  export const STREAM_ANNOUNCE_FEATURE = 'stream-announce';
28
28
  export const EXEC_PIPES_FEATURE = 'exec-pipes';
29
29
 
30
+ /**
31
+ * ServerHello feature (#121): this host serves several execution targets. `Open`, `FileOp` and `OpenEndpoint` take an optional
32
+ * `target`, and `ListTargets` is answered with `TargetList`. Negotiated rather than assumed: the Rust types deny unknown
33
+ * fields, so an older host rejects an `Open` that carries `target`.
34
+ */
35
+ export const TARGETS_FEATURE = 'targets';
36
+
30
37
  /**
31
38
  * Host feature (#155): this host seals the whole session end to end when asked (a signed `KeyExchange` for the
32
39
  * connection's session id, then every message but the keepalive as an `EncryptedFrame` on channel 0).
@@ -145,11 +145,16 @@ export class GatewayConnections {
145
145
  return this.#open((id) => openUnixMsg({ gatewayId: id, path }), opts);
146
146
  }
147
147
 
148
- /** Open a named virtual endpoint of the host. */
148
+ /** Open a named virtual endpoint of the host (`opts.target`, #121: of one of its execution targets; needs `targets`). */
149
149
  async openEndpoint(name, opts) {
150
150
  this.#need('gateway-endpoints', 'named endpoints');
151
151
  if (typeof name !== 'string' || !name) throw new TypeError('openEndpoint: name must be a non-empty string');
152
- return this.#open((id) => openEndpointMsg({ gatewayId: id, name }), opts);
152
+ const target = opts?.target;
153
+ if (target !== undefined) {
154
+ if (typeof target !== 'string' || !target) throw new TypeError('openEndpoint: target must be a non-empty string');
155
+ this.#need('targets', 'execution targets');
156
+ }
157
+ return this.#open((id) => openEndpointMsg({ gatewayId: id, name, target }), opts);
153
158
  }
154
159
 
155
160
  /** Connect to host:port FROM THE HOST (the gateway's TCP egress, subject to the host's allow list). */
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { normalizePty } from './server/pty.mjs';
8
8
  import { createMcpHost } from './server/mcp.mjs';
9
+ import { normalizeEndpoints } from './server/gateway-core.mjs';
9
10
  import { DEFAULT_MAX_FILE_BYTES } from './server/constants.mjs';
10
11
  import { generateKeyPair, resolveSigner, fingerprint, exportPublicKeySSH, importPublicKeyRaw } from './auth.mjs';
11
12
 
@@ -51,11 +52,75 @@ export function normalizeFileBackend(fs, who = 'fs') {
51
52
  return files;
52
53
  }
53
54
 
55
+ /** A target's name: what a client puts in `Open.target`. */
56
+ export const TARGET_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
57
+ const TARGET_KEYS = ['description', 'authorize', 'exec', 'pty', 'fs', 'endpoints'];
58
+
59
+ /** A file backend that tells every call which target it serves (the last argument's `target`). */
60
+ function fileBackendForTarget(files, name) {
61
+ return {
62
+ maxFileBytes: files.maxFileBytes,
63
+ operate: (op, path, opts = {}) => files.operate(op, path, { ...opts, target: name }),
64
+ readWhole: (path, opts = {}) => files.readWhole(path, { ...opts, target: name }),
65
+ writeWhole: (path, data, opts = {}) => files.writeWhole(path, data, { ...opts, target: name }),
66
+ writeAt: (path, data, offset, opts = {}) => files.writeAt(path, data, offset, { ...opts, target: name }),
67
+ ...(files.openRange ? { openRange: (path, opts = {}) => files.openRange(path, { ...opts, target: name }) } : {}),
68
+ };
69
+ }
70
+
54
71
  /**
55
- * @param {{ exec?: Function | { run: Function }, pty?: { spawn: Function }, fs?: object, mcp?: object }} options
56
- * @returns {{ execRunner: Function | null, execOptions: object, pty: object | null, files: object | null, mcp: object | null }}
72
+ * Validate the `targets` option (#121) and build one entry per target: its own exec / pty / files / endpoints
73
+ * (`buildOne({ exec, pty, fs })` makes the first three: `resolveBackends` in a browser, `buildBackends` in Node), the
74
+ * `authorize(who, { target, kind })` that decides who may use it, and a description. Nothing here is on by default: no
75
+ * `targets` option, no targets.
76
+ *
77
+ * @param {object | undefined} targets - `{ [name]: { description?, authorize?, exec?, pty?, fs?, endpoints? } }`
78
+ * @param {boolean | undefined} requireTarget
79
+ * @param {(spec: object) => { execRunner: Function | null, execOptions: object, pty: object | null, files: object | null }} buildOne
80
+ * @param {string} [who] - the host's name in error messages
81
+ * @returns {{ targets: Map<string, object> | null, requireTarget: boolean }}
57
82
  */
58
- export function resolveBackends({ exec, pty, fs, mcp } = {}) {
83
+ export function normalizeTargets(targets, requireTarget, buildOne, who = 'host') {
84
+ if (requireTarget !== undefined && typeof requireTarget !== 'boolean') throw new TypeError(`${who}: requireTarget must be a boolean`);
85
+ if (targets === undefined || targets === null) {
86
+ if (requireTarget) throw new TypeError(`${who}: requireTarget needs targets`);
87
+ return { targets: null, requireTarget: false };
88
+ }
89
+ if (typeof targets !== 'object' || Array.isArray(targets)) throw new TypeError(`${who}: targets must be an object of { name: { exec, pty, fs, endpoints, authorize, description } }`);
90
+ const map = new Map();
91
+ for (const [name, spec] of Object.entries(targets)) {
92
+ if (!TARGET_NAME_RE.test(name)) throw new TypeError(`${who}: targets: ${JSON.stringify(name)} is not a valid target name (letters, digits, ".", "_", "-"; at most 64)`);
93
+ if (spec === null || typeof spec !== 'object' || Array.isArray(spec)) throw new TypeError(`${who}: targets.${name} must be an object`);
94
+ for (const key of Object.keys(spec)) {
95
+ if (!TARGET_KEYS.includes(key)) throw new TypeError(`${who}: targets.${name}.${key} is not an option of a target (${TARGET_KEYS.join(', ')})`);
96
+ }
97
+ if (spec.authorize !== undefined && typeof spec.authorize !== 'function') throw new TypeError(`${who}: targets.${name}.authorize must be a function (who, { target, kind }) => boolean`);
98
+ if (spec.description !== undefined && typeof spec.description !== 'string') throw new TypeError(`${who}: targets.${name}.description must be a string`);
99
+ const built = buildOne({ exec: spec.exec, pty: spec.pty, fs: spec.fs });
100
+ map.set(name, {
101
+ name,
102
+ description: spec.description,
103
+ authorize: spec.authorize ?? null,
104
+ execRunner: built.execRunner,
105
+ execOptions: built.execOptions,
106
+ pty: built.pty,
107
+ files: built.files ? fileBackendForTarget(built.files, name) : null,
108
+ endpoints: normalizeEndpoints(spec.endpoints),
109
+ });
110
+ }
111
+ return { targets: map.size ? map : null, requireTarget: map.size ? !!requireTarget : false };
112
+ }
113
+
114
+ /**
115
+ * @param {{ exec?: Function | { run: Function }, pty?: { spawn: Function }, fs?: object, mcp?: object, targets?: object, requireTarget?: boolean }} options
116
+ * @returns {{ execRunner: Function | null, execOptions: object, pty: object | null, files: object | null, mcp: object | null, targets: Map<string, object> | null, requireTarget: boolean }}
117
+ */
118
+ export function resolveBackends({ exec, pty, fs, mcp, targets, requireTarget } = {}) {
119
+ const base = resolveOwnBackends({ exec, pty, fs, mcp });
120
+ return { ...base, ...normalizeTargets(targets, requireTarget, (spec) => resolveOwnBackends(spec), 'host') };
121
+ }
122
+
123
+ function resolveOwnBackends({ exec, pty, fs, mcp } = {}) {
59
124
  let execRunner = null;
60
125
  let execOptions = {};
61
126
  if (typeof exec === 'function') {
package/src/host.d.ts CHANGED
@@ -14,15 +14,15 @@ export interface WshFileBackend {
14
14
  * `read` (`offset`, `length`) -> `{ metadata: { data, size } }`; `write` (`offset`, `data`) -> `{ metadata: { written } }`;
15
15
  * `rename` (`newPath`); `mkdir`; `remove`. Anything else should throw.
16
16
  */
17
- operate(op: string, path: string, args?: { offset?: number; length?: number; newPath?: string; data?: Uint8Array }): Promise<{ metadata?: Record<string, unknown>; entries?: Array<Record<string, unknown>> }>;
17
+ operate(op: string, path: string, args?: { offset?: number; length?: number; newPath?: string; data?: Uint8Array; target?: string }): Promise<{ metadata?: Record<string, unknown>; entries?: Array<Record<string, unknown>> }>;
18
18
  /** The whole file, for a `download:` channel. Throw if it is larger than `maxFileBytes`. */
19
- readWhole(path: string): Promise<Uint8Array>;
19
+ readWhole(path: string, options?: { target?: string }): Promise<Uint8Array>;
20
20
  /** Create or replace a file (creating its directories), for an `upload:` channel. */
21
- writeWhole(path: string, data: Uint8Array): Promise<void>;
21
+ writeWhole(path: string, data: Uint8Array, options?: { target?: string }): Promise<void>;
22
22
  /** Write `data` at `offset` (omitted = replace the file), without truncating when an offset is given. */
23
- writeAt(path: string, data: Uint8Array, offset?: number, options?: { mkdirs?: boolean }): Promise<void>;
23
+ writeAt(path: string, data: Uint8Array, offset?: number, options?: { mkdirs?: boolean; target?: string }): Promise<void>;
24
24
  /** A byte range as chunks; only the `wsh-fs` rpc built-in (Node) reads it. */
25
- openRange?(path: string, options?: { offset?: number; length?: number; chunkBytes?: number }): Promise<{ size: number; offset: number; length: number; chunks: AsyncIterable<Uint8Array> }>;
25
+ openRange?(path: string, options?: { offset?: number; length?: number; chunkBytes?: number; target?: string }): Promise<{ size: number; offset: number; length: number; chunks: AsyncIterable<Uint8Array> }>;
26
26
  /** Largest file read or written whole, in bytes (default 64 MiB). */
27
27
  maxFileBytes?: number;
28
28
  }
@@ -39,12 +39,35 @@ export interface WshResolvedHostKey {
39
39
  sign(data: Uint8Array): Promise<Uint8Array>;
40
40
  }
41
41
 
42
+ /** What a host that serves several execution targets takes for each (#121). The same forms as the host's own backends. */
43
+ export interface WshTargetOptions {
44
+ /** A human line shown by `ListTargets`. */
45
+ description?: string;
46
+ /**
47
+ * Who may use this target. Called for every `Open`, `FileOp` and `OpenEndpoint` naming it (`kind`: `exec`, `pty`, `file`,
48
+ * `endpoint`) and for `ListTargets` (`kind: 'list'`); only `true` lets the caller on. Absent: any authenticated key.
49
+ * A refusal looks like an unknown target to the client.
50
+ */
51
+ authorize?: (who: { username: string | null; fingerprint: string | null }, request: { target: string; kind: 'exec' | 'pty' | 'file' | 'endpoint' | 'list' }) => boolean | Promise<boolean>;
52
+ /** `run(command, io)`; `io.target` is this target's name. (`true`, a shell, is for `createWshServer`.) */
53
+ exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: WshClientEnv };
54
+ /** `spawn` is also given `{ target }` in its options. */
55
+ pty?: WshServerPtyOptions;
56
+ /** Every call is also given `{ target }`. */
57
+ fs?: WshFileBackend;
58
+ /** Named virtual endpoints of this target; the handler's `duplex.target` is its name. */
59
+ endpoints?: Record<string, ((duplex: object, who: { username: string | null; fingerprint: string | null }) => void | Promise<void>) | { open: Function; authorize?: (who: object) => boolean | Promise<boolean> }>;
60
+ }
61
+
42
62
  export interface WshResolvedBackends {
43
63
  execRunner: WshExecRunner | null;
44
64
  execOptions: { timeoutMs?: number; clientEnv?: WshClientEnv };
45
65
  pty: { spawn: WshServerPtyOptions['spawn']; shell: string; cwd?: string; env?: Record<string, string | undefined>; term: string } | null;
46
66
  files: Required<Pick<WshFileBackend, 'operate' | 'readWhole' | 'writeWhole' | 'writeAt' | 'maxFileBytes'>> & Pick<WshFileBackend, 'openRange'> | null;
47
67
  mcp: object | null;
68
+ /** The validated `targets` option (#121), by name; null when the host has none. */
69
+ targets: Map<string, object> | null;
70
+ requireTarget: boolean;
48
71
  }
49
72
 
50
73
  /** Validate injected backends (no shell, no directory: `exec` is a function or `{ run }`, `fs` an object of operations). */
@@ -53,6 +76,10 @@ export function resolveBackends(options?: {
53
76
  pty?: WshServerPtyOptions;
54
77
  fs?: WshFileBackend;
55
78
  mcp?: WshServerMcpOptions;
79
+ /** #121: execution targets, each with its own backends. Off unless given. */
80
+ targets?: Record<string, WshTargetOptions>;
81
+ /** With `targets`: a request that names none is refused. */
82
+ requireTarget?: boolean;
56
83
  }): WshResolvedBackends;
57
84
 
58
85
  /** Validate a file backend (see {@link WshFileBackend}). */
package/src/index.d.ts CHANGED
@@ -249,6 +249,8 @@ export const MCP_CANCEL_FEATURE: 'mcp-cancel';
249
249
  export const STREAM_ANNOUNCE_FEATURE: 'stream-announce';
250
250
  /** ServerHello feature: the host runs `exec` on plain pipes (stderr apart, stdin EOF) when asked with `stdio: 'pipes'`. */
251
251
  export const EXEC_PIPES_FEATURE: 'exec-pipes';
252
+ /** ServerHello feature (#121): the host has execution targets; `Open`, `FileOp` and `OpenEndpoint` take `target`. */
253
+ export const TARGETS_FEATURE: 'targets';
252
254
 
253
255
  // ── Typed (object-mode) RPC channels -- wsh #85 ────────────────────────
254
256
 
@@ -444,6 +446,9 @@ export function open(opts?: {
444
446
  cols?: number;
445
447
  rows?: number;
446
448
  env?: Record<string, string>;
449
+ stdio?: string;
450
+ /** #121: the host's execution target (only to a host that advertises `targets`). */
451
+ target?: string;
447
452
  }): WshMessage;
448
453
 
449
454
  export function openOk(opts?: {
@@ -761,6 +766,12 @@ export function restartPty(opts?: {
761
766
 
762
767
  export function sessionListRequest(): WshMessage;
763
768
 
769
+ export function listTargets(): WshMessage;
770
+
771
+ export function targetList(opts?: {
772
+ targets?: WshTargetInfo[];
773
+ }): WshMessage;
774
+
764
775
  export function sessionList(opts?: {
765
776
  sessions?: unknown[];
766
777
  }): WshMessage;
@@ -941,6 +952,8 @@ export function fileOp(opts?: {
941
952
  path?: string;
942
953
  offset?: number;
943
954
  length?: number;
955
+ /** #121: the host's execution target (only to a host that advertises `targets`). */
956
+ target?: string;
944
957
  }): WshMessage;
945
958
 
946
959
  export function fileResult(opts?: {
@@ -1899,6 +1912,11 @@ export interface WshOpenSessionOptions {
1899
1912
  * advertises `exec-pipes`. `'pty'` or omitted: the host's native mode.
1900
1913
  */
1901
1914
  stdio?: 'pty' | 'pipes';
1915
+ /**
1916
+ * #121: which of the host's execution targets this channel runs on (see {@link WshClient.listTargets}). Throws before sending
1917
+ * anything unless the host advertises `targets`. Omitted: the host's own default, as before.
1918
+ */
1919
+ target?: string;
1902
1920
  }
1903
1921
 
1904
1922
  /**
@@ -1988,6 +2006,8 @@ export interface WshExecOptions extends WshHostKeyOptions {
1988
2006
  * `'pipes'` throws if the host lacks `exec-pipes`; `'pty'` never asks for pipes.
1989
2007
  */
1990
2008
  stdio?: 'pty' | 'pipes';
2009
+ /** See {@link WshOpenSessionOptions.target}. */
2010
+ target?: string;
1991
2011
  }
1992
2012
 
1993
2013
  /** Result from WshClient.exec(). */
@@ -2130,7 +2150,22 @@ export interface WshFileOperationResult {
2130
2150
  * reverse mode (client registers as a peer for incoming connections).
2131
2151
  */
2132
2152
  /** Options for `openUnix` / `openEndpoint` / `openTcp`. */
2133
- export interface WshGatewayOpenOptions { signal?: AbortSignal; timeoutMs?: number }
2153
+ export interface WshGatewayOpenOptions {
2154
+ signal?: AbortSignal;
2155
+ timeoutMs?: number;
2156
+ /** `openEndpoint` only (#121): the host's execution target whose endpoint this is. Needs the `targets` feature. */
2157
+ target?: string;
2158
+ }
2159
+
2160
+ /** One execution target a host shows this key (`ListTargets` / `TargetList`, #121). */
2161
+ export interface WshTargetInfo {
2162
+ /** What to pass as `target`. */
2163
+ name: string;
2164
+ /** A human line about the target; not for parsing. */
2165
+ description?: string;
2166
+ /** What the caller can do there: any of `exec`, `pty`, `file`, `endpoint` (a hint; the host decides on each request). */
2167
+ capabilities: string[];
2168
+ }
2134
2169
 
2135
2170
  /** One gateway connection as web streams with backpressure (credit-based flow control when both ends offer `gateway-credit`). */
2136
2171
  export interface WshGatewayDuplex {
@@ -2417,6 +2452,18 @@ export class WshClient {
2417
2452
  */
2418
2453
  listPeers(timeout?: number): Promise<WshPeerInfo[]>;
2419
2454
 
2455
+ /**
2456
+ * The execution targets this connection may use (#121): what the host decides to show THIS key. Pass a `name` as `target` to
2457
+ * `openSession`, `exec`, `fileOperation` or `openEndpoint`. Throws if the host does not advertise `targets`.
2458
+ */
2459
+ listTargets(timeout?: number): Promise<WshTargetInfo[]>;
2460
+
2461
+ /**
2462
+ * One structured file operation (`FileOp`), the raw wire-shaped result. `opts.target` (#121) names the execution target whose
2463
+ * files these are (needs `targets`; such a request is never sent over the `wsh-fs` rpc, which is not per target).
2464
+ */
2465
+ fileOperation(op: string, path: string, opts?: { offset?: number; length?: number; data?: Uint8Array | string; newPath?: string; target?: string }, timeout?: number): Promise<WshFileOperationResult>;
2466
+
2420
2467
  /**
2421
2468
  * Initiate a reverse connection to a registered peer.
2422
2469
  */
package/src/index.mjs CHANGED
@@ -35,6 +35,7 @@ export {
35
35
  nodeAnnounce, nodeRedirect,
36
36
  sessionGrant, sessionRevoke,
37
37
  fileOp, fileResult, fileChunk,
38
+ listTargets, targetList,
38
39
  authorizedKeyAdd, authorizedKeyResult,
39
40
  policyEval, policyResult, policyUpdate,
40
41
  terminalConfig,
@@ -75,7 +76,7 @@ export {
75
76
  // Session + Client
76
77
  export { WshSession } from './session.mjs';
77
78
  export { WshVirtualSessionBackend, normalizeSessionData } from './virtual-session.mjs';
78
- export { WshClient, MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE } from './client.mjs';
79
+ export { WshClient, MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE, TARGETS_FEATURE } from './client.mjs';
79
80
  // Gateway forwarding (unix sockets, named endpoints, flow control) -- wsh #120, #123
80
81
  export { GatewayError } from './gateway-client.mjs';
81
82
  export { GATEWAY_CREDIT_FEATURE, GATEWAY_CREDIT_WINDOW } from './gateway-channel.mjs';
@@ -86,6 +86,14 @@ export interface WshMemoryHostOptions {
86
86
  sealSession?: false | 'offer' | 'require';
87
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
88
  onRefused?: WshOnRefused;
89
+ /**
90
+ * #121: execution targets, each with its own `exec`, `pty`, `fs` and `endpoints` and an `authorize(who, { target, kind })`.
91
+ * A client names one in `Open`, `FileOp` or `OpenEndpoint` and lists what it may use with `listTargets()`. Off unless given:
92
+ * the host then advertises no `targets` and refuses a request that names one.
93
+ */
94
+ targets?: Record<string, import('./host.js').WshTargetOptions>;
95
+ /** With `targets`: an `Open`, `FileOp` or `OpenEndpoint` that names no target is refused (nothing runs on the host itself). */
96
+ requireTarget?: boolean;
89
97
  onLog?: (line: string) => void;
90
98
  }
91
99
 
@@ -172,6 +172,10 @@ function createRegistry(sessions, log) {
172
172
  * backpressure) and `who` is the authenticated `{ username, fingerprint }`, so the handler can authorise per call:
173
173
  * throw synchronously to refuse, or give `{ open, authorize(who) }`. Only the names listed here exist (an allow-list by
174
174
  * construction); nothing else of the gateway (TCP, DNS, unix sockets) is on in memory.
175
+ * @param {Record<string, { description?: string, authorize?: Function, exec?: Function | { run: Function }, pty?: object, fs?: object, endpoints?: object }>} [options.targets]
176
+ * Execution targets (#121), as for `createWshServer`: each with its own `exec`, `pty`, `fs` and `endpoints` (the injected
177
+ * forms only: there is no shell or directory here) and an `authorize(who, { target, kind })`. Off unless given.
178
+ * @param {boolean} [options.requireTarget=false] - With `targets`: a request that names no target is refused. As for `createWshServer`.
175
179
  * @param {number} [options.bindTimeoutMs=3000]
176
180
  * @param {number} [options.connectionTtlMs=0] - End each authenticated connection this long after login; advertised as
177
181
  * `AuthOk.ttl` in whole seconds (#125). 0 = never.
@@ -190,7 +194,7 @@ function createRegistry(sessions, log) {
190
194
  * @param {(line: string) => void} [options.onLog]
191
195
  */
192
196
  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 } = {}) {
197
+ onShare, onRefused, targets, requireTarget } = {}) {
194
198
  validateOnShare(onShare, 'createMemoryHost');
195
199
  validateOnRefused(onRefused, 'createMemoryHost');
196
200
  if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createMemoryHost: connectionTtlMs must be a non-negative number');
@@ -209,7 +213,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
209
213
  if (typeof dataStreams !== 'boolean') throw new TypeError('createMemoryHost: dataStreams must be true or false');
210
214
  const rpcHost = rpc === undefined || rpc === null ? null : createRpcTable(rpc, rpcMaxMessageBytes, rpcMaxInflight);
211
215
  const registry = sessions === undefined || sessions === null || sessions === false ? null : createRegistry(sessions, onLog);
212
- const { execRunner, execOptions, pty: ptyBackend, files, mcp: mcpHost } = resolveBackends({ exec, pty, fs, mcp });
216
+ const { execRunner, execOptions, pty: ptyBackend, files, mcp: mcpHost, targets: targetTable, requireTarget: mustHaveTarget } = resolveBackends({ exec, pty, fs, mcp, targets, requireTarget });
213
217
  const hostKeyReady = hostKey === undefined || hostKey === null || hostKey === false ? Promise.resolve(null) : resolveHostKey(hostKey, 'createMemoryHost: hostKey');
214
218
  const rl = auth?.rateLimit ?? {};
215
219
  const rateLimit = {
@@ -220,11 +224,14 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
220
224
  const methods = authMethods(auth);
221
225
  // Named virtual endpoints: a gateway with no TCP, DNS or unix sockets that answers only `OpenEndpoint`, built from
222
226
  // the browser-safe core (`server/gateway-core.mjs`), so a page can have it.
223
- const gatewayCfg = endpoints === undefined || endpoints === null ? null : normalizeEndpointGateway({ endpoints });
227
+ let gatewayCfg = endpoints === undefined || endpoints === null ? null : normalizeEndpointGateway({ endpoints });
228
+ // A target's own endpoints (#121) need the endpoints-only gateway too, even when the host has none of its own.
229
+ if (targetTable && [...targetTable.values()].some((t) => t.endpoints)) gatewayCfg = { ...(gatewayCfg ?? normalizeEndpointGateway({})), targetEndpoints: true };
224
230
 
225
231
  const ready = Promise.all([buildAuthorizer(auth), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
226
232
  authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
227
233
  methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare, onRefused,
234
+ targets: targetTable, requireTarget: mustHaveTarget,
228
235
  gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
229
236
  }));
230
237
  ready.catch(() => {});
@@ -162,6 +162,10 @@ export const MSG = Object.freeze({
162
162
  SHARE_OFFER: 0xa8,
163
163
  SHARE_REQUEST: 0xa9,
164
164
  SHARE_REPLY: 0xaa,
165
+
166
+ // Targets
167
+ LIST_TARGETS: 0xab,
168
+ TARGET_LIST: 0xac,
165
169
  });
166
170
 
167
171
  // Reverse lookup: number → name
@@ -252,13 +256,14 @@ export function authFail({ reason } = {}) {
252
256
  };
253
257
  }
254
258
 
255
- export function open({ kind, command, cols, rows, env, stdio } = {}) {
259
+ export function open({ kind, command, cols, rows, env, stdio, target } = {}) {
256
260
  const msg = { type: MSG.OPEN, kind };
257
261
  if (command !== undefined) msg.command = command;
258
262
  if (cols !== undefined) msg.cols = cols;
259
263
  if (rows !== undefined) msg.rows = rows;
260
264
  if (env !== undefined) msg.env = env;
261
265
  if (stdio !== undefined) msg.stdio = stdio;
266
+ if (target !== undefined) msg.target = target;
262
267
  return msg;
263
268
  }
264
269
 
@@ -595,12 +600,10 @@ export function openUnix({ gatewayId, path } = {}) {
595
600
  };
596
601
  }
597
602
 
598
- export function openEndpoint({ gatewayId, name } = {}) {
599
- return {
600
- type: MSG.OPEN_ENDPOINT,
601
- gateway_id: gatewayId,
602
- name,
603
- };
603
+ export function openEndpoint({ gatewayId, name, target } = {}) {
604
+ const msg = { type: MSG.OPEN_ENDPOINT, gateway_id: gatewayId, name };
605
+ if (target !== undefined) msg.target = target;
606
+ return msg;
604
607
  }
605
608
 
606
609
  export function listenUnix({ listenerId, path, replace } = {}) {
@@ -921,10 +924,11 @@ export function sessionRevoke({ sessionId, principal, reason } = {}) {
921
924
  return msg;
922
925
  }
923
926
 
924
- export function fileOp({ channelId, op, path, offset, length } = {}) {
927
+ export function fileOp({ channelId, op, path, offset, length, target } = {}) {
925
928
  const msg = { type: MSG.FILE_OP, channel_id: channelId, op, path };
926
929
  if (offset !== undefined) msg.offset = offset;
927
930
  if (length !== undefined) msg.length = length;
931
+ if (target !== undefined) msg.target = target;
928
932
  return msg;
929
933
  }
930
934
 
@@ -1023,6 +1027,17 @@ export function shareReply({ requestId, ok, errno, message, attr = {}, entries =
1023
1027
  return msg;
1024
1028
  }
1025
1029
 
1030
+ export function listTargets() {
1031
+ return { type: MSG.LIST_TARGETS };
1032
+ }
1033
+
1034
+ export function targetList({ targets } = {}) {
1035
+ return {
1036
+ type: MSG.TARGET_LIST,
1037
+ targets,
1038
+ };
1039
+ }
1040
+
1026
1041
  // ── Relay forwarding ─────────────────────────────────────────────────
1027
1042
 
1028
1043
  // Message types a relay may forward inside a RelayForward wrapper.
@@ -97,6 +97,7 @@ export function createReverseHostWith({
97
97
  if (typeof requireOperatorProof !== 'boolean') throw new TypeError('createReverseHost: requireOperatorProof must be a boolean');
98
98
  if (requireOperatorProof && e2e === false) throw new TypeError('createReverseHost: requireOperatorProof seals the bridge, which needs e2e (do not set e2e: false)');
99
99
  if (requireOperatorProof && !reportFeatures) throw new TypeError('createReverseHost: requireOperatorProof needs reportFeatures (the operator learns "e2e-sealed" from ReverseAccept.features)');
100
+ if (backends.targets) throw new TypeError('createReverseHost: targets are not supported by a reverse host (a bridged operator reaches the one machine behind it); use createWshServer or createMemoryHost');
100
101
  if (!url) throw new TypeError('createReverseHost: url is required');
101
102
  if (!username) throw new TypeError('createReverseHost: username is required');
102
103
  if (!keyPair) throw new TypeError('createReverseHost: keyPair is required (the relay keys peers by fingerprint)');
@@ -10,13 +10,10 @@
10
10
 
11
11
  import { spawnRunner } from './exec.mjs';
12
12
  import { createFileAccess } from './fs.mjs';
13
- import { resolveBackends } from '../host-backends.mjs';
13
+ import { resolveBackends, normalizeTargets } from '../host-backends.mjs';
14
14
 
15
- /**
16
- * @param {{ exec?: true | object | Function, pty?: object, fs?: object, mcp?: object }} options
17
- * @returns {{ execRunner: Function | null, execOptions: object, pty: object | null, files: object | null, mcp: object | null }}
18
- */
19
- export function buildBackends({ exec, pty, fs, mcp } = {}) {
15
+ /** The backends of one host (or one target) from `exec`, `pty`, `fs`, `mcp`, with the Node forms (`exec: true`, `fs: { root }`). */
16
+ function buildOwnBackends({ exec, pty, fs, mcp } = {}) {
20
17
  let hostExec = exec;
21
18
  if (exec && typeof exec !== 'function') {
22
19
  const execOptions = exec === true ? {} : exec;
@@ -24,3 +21,11 @@ export function buildBackends({ exec, pty, fs, mcp } = {}) {
24
21
  }
25
22
  return resolveBackends({ exec: hostExec, pty, fs: fs && typeof fs.root === 'string' ? createFileAccess(fs) : fs, mcp });
26
23
  }
24
+
25
+ /**
26
+ * @param {{ exec?: true | object | Function, pty?: object, fs?: object, mcp?: object, targets?: object, requireTarget?: boolean }} options
27
+ * @returns {{ execRunner: Function | null, execOptions: object, pty: object | null, files: object | null, mcp: object | null, targets: Map<string, object> | null, requireTarget: boolean }}
28
+ */
29
+ export function buildBackends({ exec, pty, fs, mcp, targets, requireTarget } = {}) {
30
+ return { ...buildOwnBackends({ exec, pty, fs, mcp }), ...normalizeTargets(targets, requireTarget, buildOwnBackends, 'createWshServer') };
31
+ }
@@ -19,12 +19,14 @@ import {
19
19
  MSG, serverHello, challenge, authOk, authFail, openOk, openFail, sessionData,
20
20
  exit as exitMsg, close as closeMsg, encryptedFrame as encryptedFrameMsg, pong, fileResult, fileChunk, mcpTools, mcpResult,
21
21
  presence as presenceMsg, error as errorMsg, sessionList, detachOk, detachFail, reversePeers, reverseReject,
22
+ targetList as targetListMsg,
22
23
  } from '../messages.gen.mjs';
23
24
  import {
24
25
  generateNonce, verifyChallenge, fingerprint, importPublicKeyRaw,
25
26
  } from '../auth.mjs';
26
27
  import { FILE_CHUNK_BYTES, MAX_ATTACHMENTS } from './constants.mjs';
27
- import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE } from '../features.mjs';
28
+ import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE, TARGETS_FEATURE } from '../features.mjs';
29
+ import { TARGET_NAME_RE } from '../host-backends.mjs';
28
30
  import { RpcChannel, RPC_FEATURE, RPC_MAX_MESSAGE_PREFIX, rpcProtocolFeature } from '../rpc.mjs';
29
31
  import { sealFrame, openFrame, ROLE_TAGS } from '../e2e-frame.mjs';
30
32
  import { E2EResponder, E2E_FEATURE, E2E_SIGN_FEATURE } from '../e2e-exchange.mjs';
@@ -53,6 +55,12 @@ export function hostFeatures(cfg, { dataStreams = true } = {}) {
53
55
  if (cfg.mcp) features.push(MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE);
54
56
  if (cfg.gateway) features.push(...gatewayFeatures(cfg.gateway));
55
57
  if (cfg.files) features.push('file-transfer', 'file-write', 'file-rename');
58
+ // Execution targets (#121): `Open`, `FileOp` and `OpenEndpoint` take `target`, and `ListTargets` is answered. A target with files is
59
+ // reached over FileOp, so the file features are stated for it too (the host's own may have none).
60
+ if (cfg.targets) {
61
+ features.push(TARGETS_FEATURE);
62
+ if (!cfg.files && [...cfg.targets.values()].some((t) => t.files)) features.push('file-transfer', 'file-write', 'file-rename');
63
+ }
56
64
  if (cfg.onShare) features.push(SHARES_FEATURE); // #159: this host can use folders the operator's client offers
57
65
  // End-to-end encryption (#90) is the virtual-mode EncryptedFrame layer, so it is offered where there are no
58
66
  // client-opened streams: over a relay bridge.
@@ -128,6 +136,17 @@ export function createConnectionFactory(cfg) {
128
136
  // What a client may put in `Open.env` (#126): an allow-list unless the host says otherwise.
129
137
  const execEnv = clientEnvFilter(cfg.execOptions?.clientEnv);
130
138
  const ptyEnv = clientEnvFilter(cfg.pty?.clientEnv);
139
+ // Execution targets (#121): each has its own backends (and its own `clientEnv` rules). A request that names no target uses
140
+ // the host's own, unless `requireTarget` says nothing may run on the host itself.
141
+ /** @type {Map<string, object> | null} */
142
+ const targetTable = cfg.targets && cfg.targets.size
143
+ ? new Map([...cfg.targets].map(([name, spec]) => [name, { ...spec, execEnv: clientEnvFilter(spec.execOptions?.clientEnv), ptyEnv: clientEnvFilter(spec.pty?.clientEnv) }]))
144
+ : null;
145
+ const requireTarget = !!targetTable && !!cfg.requireTarget;
146
+ const ownBackends = { execRunner: cfg.execRunner, execOptions: cfg.execOptions, execEnv, pty: cfg.pty, ptyEnv, files: cfg.files, ownHost: true };
147
+ /** One answer for a target that does not exist and for one the caller may not use: the reply does not say which targets exist. */
148
+ const NO_SUCH_TARGET = 'no such target';
149
+ const targetCapabilities = (spec) => [...(spec.execRunner ? ['exec'] : []), ...(spec.pty ? ['pty'] : []), ...(spec.files ? ['file'] : []), ...(spec.endpoints ? ['endpoint'] : [])];
131
150
 
132
151
  /**
133
152
  * Attach one connection. Two shapes:
@@ -176,7 +195,13 @@ export function createConnectionFactory(cfg) {
176
195
  // host in a page passes the endpoints-only session of `gateway-core.mjs` (`createMemoryHost({ endpoints })`).
177
196
  if (cfg.gateway && typeof cfg.createGatewaySession !== 'function') throw new TypeError('createConnectionFactory: gateway needs createGatewaySession (only @johnhenry/wsh/server provides one)');
178
197
  const gateway = cfg.gateway
179
- ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, { who: () => ({ username: state.username, fingerprint: state.fingerprint }), datagrams })
198
+ ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, {
199
+ who: () => ({ username: state.username, fingerprint: state.fingerprint }),
200
+ datagrams,
201
+ // #121: a named target's own endpoints, once `authorize` has let the caller onto it
202
+ target: async (name) => { const r = await resolveTarget(name, 'endpoint'); return r.refuse ? { refuse: r.refuse } : { endpoints: r.b.endpoints ?? null }; },
203
+ requireTarget: () => requireTarget,
204
+ })
180
205
  : null;
181
206
 
182
207
  // Operator-side shared folders (#159): created with the connection, used only after the client's ShareOffer.
@@ -322,6 +347,7 @@ export function createConnectionFactory(cfg) {
322
347
  case MSG.RESUME: return handleAttach(m, true);
323
348
  case MSG.DETACH: return handleDetach(m);
324
349
  case MSG.SESSION_LIST_REQUEST: return handleSessionList();
350
+ case MSG.LIST_TARGETS: return handleListTargets();
325
351
  case MSG.MCP_DISCOVER: return handleMcpDiscover();
326
352
  // Not awaited: the handler chain is serial, and a slow tool must not hold up
327
353
  // the next call (or a Close) behind it.
@@ -669,13 +695,55 @@ export function createConnectionFactory(cfg) {
669
695
 
670
696
  // ── Open ──────────────────────────────────────────────────────────
671
697
 
672
- function handleOpen(m) {
698
+ /**
699
+ * The backends a request is served by (#121): the host's own when it names no target (and `requireTarget` is off), else the
700
+ * target's, once the host knows the name and its `authorize(who, { target, kind })` lets this caller on. `{ refuse }`
701
+ * otherwise, never a fallback to the host's own: a request for somewhere else is not run here.
702
+ * @returns {Promise<{ b: object } | { refuse: string }>}
703
+ */
704
+ async function resolveTarget(target, kind) {
705
+ if (target === undefined || target === null) return requireTarget ? { refuse: 'a target is required' } : { b: ownBackends };
706
+ if (!targetTable) return { refuse: 'this host has no targets' };
707
+ const spec = typeof target === 'string' && TARGET_NAME_RE.test(target) ? targetTable.get(target) : undefined;
708
+ if (!spec) return { refuse: NO_SUCH_TARGET };
709
+ if (spec.authorize) {
710
+ let allowed = false;
711
+ try { allowed = (await spec.authorize({ username: state.username, fingerprint: state.fingerprint }, { target, kind })) === true; } catch (e) { log(`target ${target} authorize threw: ${e.message}`); }
712
+ if (!allowed) {
713
+ log(`target ${target} refused for ${state.username ?? '?'} (${kind})`);
714
+ return { refuse: NO_SUCH_TARGET };
715
+ }
716
+ }
717
+ return { b: spec };
718
+ }
719
+
720
+ /** `ListTargets`: the targets this caller may use, as the host shows them. */
721
+ async function handleListTargets() {
722
+ if (!targetTable) return send(errorMsg({ code: 3, message: 'this host has no targets' }));
723
+ const out = [];
724
+ for (const [name, spec] of targetTable) {
725
+ const r = await resolveTarget(name, 'list');
726
+ if (r.refuse) continue;
727
+ out.push({ name, ...(spec.description !== undefined ? { description: spec.description } : {}), capabilities: targetCapabilities(spec) });
728
+ }
729
+ return send(targetListMsg({ targets: out }));
730
+ }
731
+
732
+ async function handleOpen(m) {
673
733
  if (channels.size >= MAX_CHANNELS) return send(openFail({ reason: 'too many open channels' }));
734
+ const target = m.target ?? undefined;
674
735
  switch (m.kind) {
675
- case 'exec': return openExec(m);
676
- case 'pty': return openPty(m);
677
- case 'file': return openFile(m);
678
- case 'rpc': return openRpc(m);
736
+ case 'exec': case 'pty': case 'file': {
737
+ const r = await resolveTarget(target, m.kind);
738
+ if (r.refuse) return send(openFail({ reason: r.refuse }));
739
+ if (m.kind === 'exec') return openExec(m, r.b, target);
740
+ return m.kind === 'pty' ? openPty(m, r.b, target) : openFile(m, r.b);
741
+ }
742
+ case 'rpc':
743
+ // rpc channels (`wsh-fs`, `wsh-host`, `mcp`) are the host's own, not per target.
744
+ if (target !== undefined) return send(openFail({ reason: 'rpc channels do not take a target' }));
745
+ if (requireTarget) return send(openFail({ reason: 'a target is required' }));
746
+ return openRpc(m);
679
747
  default: return send(openFail({ reason: `kind "${m.kind}" is not supported by this server` }));
680
748
  }
681
749
  }
@@ -798,8 +866,8 @@ export function createConnectionFactory(cfg) {
798
866
  return send(sessionList({ sessions }));
799
867
  }
800
868
 
801
- async function openExec(m) {
802
- if (!cfg.execRunner) return send(openFail({ reason: 'exec is not enabled on this server' }));
869
+ async function openExec(m, b, target) {
870
+ if (!b.execRunner) return send(openFail({ reason: `exec is not enabled ${b.ownHost ? 'on this server' : 'for this target'}` }));
803
871
  const command = String(m.command ?? '').trim();
804
872
  if (!command) return send(openFail({ reason: 'command is required for kind "exec"' }));
805
873
 
@@ -847,7 +915,7 @@ export function createConnectionFactory(cfg) {
847
915
  else ch.input = (d) => { for (const cb of inputCbs) cb(d); };
848
916
 
849
917
  let timer = null;
850
- if (cfg.execOptions.timeoutMs > 0) timer = setTimeout(() => abort.abort(), cfg.execOptions.timeoutMs);
918
+ if (b.execOptions.timeoutMs > 0) timer = setTimeout(() => abort.abort(), b.execOptions.timeoutMs);
851
919
 
852
920
  // Output to the opening connection's data stream (held until the client has opened it).
853
921
  const toStream = (bytes) => {
@@ -898,7 +966,9 @@ export function createConnectionFactory(cfg) {
898
966
 
899
967
  const io = {
900
968
  user: state.username,
901
- env: execEnv(m.env),
969
+ // Which execution target this command runs on (#121); undefined on the host's own.
970
+ target,
971
+ env: b.execEnv(m.env),
902
972
  cols: m.cols || 80,
903
973
  rows: m.rows || 24,
904
974
  signal: abort.signal,
@@ -925,7 +995,7 @@ export function createConnectionFactory(cfg) {
925
995
 
926
996
  async function runExec() {
927
997
  let code;
928
- try { code = await cfg.execRunner(command, io); } catch (e) {
998
+ try { code = await b.execRunner(command, io); } catch (e) {
929
999
  await io.write(`wsh: ${e.message}\n`);
930
1000
  code = 1;
931
1001
  }
@@ -990,18 +1060,20 @@ export function createConnectionFactory(cfg) {
990
1060
  log(`rpc channel ${channelId}: ${protocol}`);
991
1061
  }
992
1062
 
993
- async function openPty(m) {
994
- if (!cfg.pty) return send(openFail({ reason: 'pty is not enabled on this server' }));
1063
+ async function openPty(m, b, target) {
1064
+ if (!b.pty) return send(openFail({ reason: `pty is not enabled ${b.ownHost ? 'on this server' : 'for this target'}` }));
995
1065
  const channelId = ++state.nextChannel;
996
1066
  const cols = m.cols || 80;
997
1067
  const rows = m.rows || 24;
998
- const p = cfg.pty;
1068
+ const p = b.pty;
999
1069
  let proc;
1000
1070
  try {
1001
1071
  const args = m.command ? ['-c', String(m.command)] : [];
1002
1072
  proc = p.spawn(p.shell, args, {
1003
1073
  name: p.term, cols, rows, cwd: p.cwd,
1004
- env: { ...(p.env ?? globalThis.process?.env), TERM: p.term, ...ptyEnv(m.env) },
1074
+ env: { ...(p.env ?? globalThis.process?.env), TERM: p.term, ...b.ptyEnv(m.env) },
1075
+ // Which execution target this shell is for (#121); absent on the host's own.
1076
+ ...(target !== undefined ? { target } : {}),
1005
1077
  });
1006
1078
  } catch (e) {
1007
1079
  return send(openFail({ reason: `pty spawn failed: ${e.message}` }));
@@ -1045,8 +1117,9 @@ export function createConnectionFactory(cfg) {
1045
1117
  log(`pty channel ${channelId} opened (${cols}x${rows})`);
1046
1118
  }
1047
1119
 
1048
- async function openFile(m) {
1049
- if (!cfg.files) return send(openFail({ reason: 'file access is not enabled on this server' }));
1120
+ async function openFile(m, b) {
1121
+ const files = b.files;
1122
+ if (!files) return send(openFail({ reason: `file access is not enabled ${b.ownHost ? 'on this server' : 'for this target'}` }));
1050
1123
  const spec = String(m.command ?? '');
1051
1124
  const mm = spec.match(/^(upload|download):(.*)$/s);
1052
1125
  if (!mm) return send(openFail({ reason: 'file channel expects upload:<path> or download:<path>' }));
@@ -1055,7 +1128,7 @@ export function createConnectionFactory(cfg) {
1055
1128
 
1056
1129
  if (direction === 'download') {
1057
1130
  let data;
1058
- try { data = await cfg.files.readWhole(filePath); } catch (e) { return send(openFail({ reason: e.message })); }
1131
+ try { data = await files.readWhole(filePath); } catch (e) { return send(openFail({ reason: e.message })); }
1059
1132
  let cancelled = false;
1060
1133
  channels.set(channelId, { kill: () => { if (channels.delete(channelId)) { cancelled = true; log(`download ${filePath}: closed before completion`); } } });
1061
1134
  await send(openOk({ channelId, dataMode: 'virtual', capabilities: [] }));
@@ -1081,13 +1154,13 @@ export function createConnectionFactory(cfg) {
1081
1154
  ch.chunk = async (c) => {
1082
1155
  if (ch.failed) return;
1083
1156
  const total = Number(c.total_size ?? 0);
1084
- if (total > cfg.files.maxFileBytes) { ch.failed = true; return done(1, `refused: ${total} B exceeds ${cfg.files.maxFileBytes} B`); }
1157
+ if (total > files.maxFileBytes) { ch.failed = true; return done(1, `refused: ${total} B exceeds ${files.maxFileBytes} B`); }
1085
1158
  ch.buf ??= new Uint8Array(total);
1086
1159
  const data = c.data instanceof Uint8Array ? c.data : new Uint8Array(0);
1087
1160
  if (c.offset + data.byteLength > ch.buf.byteLength) { ch.failed = true; return done(1, 'chunk past total_size'); }
1088
1161
  ch.buf.set(data, c.offset);
1089
1162
  if (c.is_final) {
1090
- try { await cfg.files.writeWhole(filePath, ch.buf); } catch (e) { ch.failed = true; return done(1, e.message); }
1163
+ try { await files.writeWhole(filePath, ch.buf); } catch (e) { ch.failed = true; return done(1, e.message); }
1091
1164
  return done(0, `stored ${ch.buf.byteLength} B`);
1092
1165
  }
1093
1166
  };
@@ -1096,10 +1169,14 @@ export function createConnectionFactory(cfg) {
1096
1169
 
1097
1170
  async function handleFileOp(m) {
1098
1171
  const channelId = m.channel_id;
1099
- if (!cfg.files) return send(fileResult({ channelId, success: false, errorMessage: 'file access is not enabled on this server' }));
1100
- if (m.op === 'write' || m.op === 'rename') return startPayloadOp(m);
1172
+ const target = m.target ?? undefined;
1173
+ const r0 = await resolveTarget(target, 'file');
1174
+ if (r0.refuse) return send(fileResult({ channelId, success: false, errorMessage: r0.refuse }));
1175
+ const files = r0.b.files;
1176
+ if (!files) return send(fileResult({ channelId, success: false, errorMessage: `file access is not enabled ${r0.b.ownHost ? 'on this server' : 'for this target'}` }));
1177
+ if (m.op === 'write' || m.op === 'rename') return startPayloadOp(m, files);
1101
1178
  try {
1102
- const r = await cfg.files.operate(m.op, m.path, { offset: m.offset, length: m.length });
1179
+ const r = await files.operate(m.op, m.path, { offset: m.offset, length: m.length });
1103
1180
  return send(fileResult({ channelId, success: true, metadata: r.metadata ?? {}, entries: r.entries ?? [] }));
1104
1181
  } catch (e) {
1105
1182
  const message = e.wsh ? e.message : (e.code === 'ENOENT' ? 'no such file or directory' : `${m.op} failed`);
@@ -1111,17 +1188,17 @@ export function createConnectionFactory(cfg) {
1111
1188
  // write / rename = FileOp then FileChunk frame(s) on the same channel id
1112
1189
  // (rename's payload is the UTF-8 destination path); one FileResult once
1113
1190
  // the last chunk lands (see WshClient.fileOperation).
1114
- async function startPayloadOp(m) {
1191
+ async function startPayloadOp(m, files) {
1115
1192
  const channelId = m.channel_id;
1116
1193
  const failWrite = (errorMessage) => send(fileResult({ channelId, success: false, errorMessage }));
1117
1194
  const rename = m.op === 'rename';
1118
1195
  const length = Number(m.length);
1119
1196
  if (!Number.isSafeInteger(length) || length < 0) return failWrite(`${m.op} needs a length`);
1120
- const limit = rename ? MAX_RENAME_PATH_BYTES : cfg.files.maxFileBytes;
1197
+ const limit = rename ? MAX_RENAME_PATH_BYTES : files.maxFileBytes;
1121
1198
  if (length > limit) return failWrite(`${m.op} payload of ${length} bytes exceeds the ${limit} byte limit`);
1122
1199
  if (channels.has(channelId) || fileWrites.has(channelId)) return failWrite('channel id already in use');
1123
1200
  if (fileWrites.size >= MAX_PENDING_WRITES) return failWrite('too many writes in flight');
1124
- const w = { rename, path: m.path, offset: m.offset, length, buf: new Uint8Array(length), next: 0, timer: null };
1201
+ const w = { rename, files, path: m.path, offset: m.offset, length, buf: new Uint8Array(length), next: 0, timer: null };
1125
1202
  const arm = () => {
1126
1203
  clearTimeout(w.timer);
1127
1204
  w.timer = setTimeout(() => {
@@ -1153,8 +1230,8 @@ export function createConnectionFactory(cfg) {
1153
1230
  if (w.next !== w.length) return send(fileResult({ channelId, success: false, errorMessage: 'payload ended short of the declared length' }));
1154
1231
  try {
1155
1232
  const r = w.rename
1156
- ? await cfg.files.operate('rename', w.path, { newPath: new TextDecoder('utf-8', { fatal: true }).decode(w.buf) })
1157
- : await cfg.files.operate('write', w.path, { offset: w.offset, data: w.buf });
1233
+ ? await w.files.operate('rename', w.path, { newPath: new TextDecoder('utf-8', { fatal: true }).decode(w.buf) })
1234
+ : await w.files.operate('write', w.path, { offset: w.offset, data: w.buf });
1158
1235
  return send(fileResult({ channelId, success: true, metadata: r.metadata ?? {} }));
1159
1236
  } catch (e) {
1160
1237
  const message = e.wsh ? e.message : (e.code === 'ENOENT' ? 'no such file or directory' : `${w.rename ? 'rename' : 'write'} failed`);
@@ -62,7 +62,7 @@ export function gatewayFeatures(cfg) {
62
62
  if (cfg.tcp || cfg.reverse) f.push('gateway');
63
63
  f.push(GATEWAY_CREDIT_FEATURE);
64
64
  if (cfg.unix) f.push('gateway-unix');
65
- if (cfg.endpoints) f.push('gateway-endpoints');
65
+ if (cfg.endpoints || cfg.targetEndpoints) f.push('gateway-endpoints');
66
66
  return f;
67
67
  }
68
68
 
@@ -104,7 +104,17 @@ export function createGatewayCore(cfg, send, log = () => {}, ctx = {}) {
104
104
  const id = m.gateway_id;
105
105
  if (!Number.isInteger(id) || typeof m.name !== 'string') return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'malformed OpenEndpoint');
106
106
  if (idInUse(id)) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'gateway_id already in use');
107
- const ep = cfg.endpoints && ENDPOINT_NAME_RE.test(m.name) ? cfg.endpoints.get(m.name) : undefined;
107
+ // Execution targets (#121): a named target has its own endpoints, and the host decides (`ctx.target`) whether the caller
108
+ // may use it; the answer for a target that does not exist and one that is refused is the same. Without a target, the host's own.
109
+ let endpoints = cfg.endpoints;
110
+ if (m.target !== undefined && m.target !== null) {
111
+ const t = ctx.target ? await ctx.target(m.target) : { refuse: 'this host has no targets' };
112
+ if (t.refuse) return fail(id, GATEWAY_FAIL.POLICY_DENIED, t.refuse);
113
+ endpoints = t.endpoints;
114
+ } else if (ctx.requireTarget?.()) {
115
+ return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'a target is required');
116
+ }
117
+ const ep = endpoints && ENDPOINT_NAME_RE.test(m.name) ? endpoints.get(m.name) : undefined;
108
118
  if (!ep) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'no such endpoint');
109
119
  if (active() >= cfg.maxConnections) return fail(id, GATEWAY_FAIL.QUEUE_FULL, 'too many gateway connections');
110
120
  const who = ctx.who?.() ?? { username: null, fingerprint: null };
@@ -119,6 +129,8 @@ export function createGatewayCore(cfg, send, log = () => {}, ctx = {}) {
119
129
  const { readable, writable } = channel.streams();
120
130
  const duplex = {
121
131
  readable, writable, who,
132
+ /** The execution target this endpoint belongs to (#121); undefined for the host's own. */
133
+ target: m.target ?? undefined,
122
134
  /** Half-close: nothing more will be sent. */
123
135
  close: (reason) => channel.end(reason),
124
136
  /** Tear the connection down now. */
@@ -60,6 +60,8 @@ export type WshClientEnv = boolean | string[] | ((name: string, value: string) =
60
60
  /** What a custom `exec` runner receives for one session. */
61
61
  export interface WshExecIo {
62
62
  user: string;
63
+ /** #121: the execution target this command runs on; undefined on the host's own. */
64
+ target?: string;
63
65
  /** Environment the client asked for (empty when `clientEnv: false`). */
64
66
  env: Record<string, string>;
65
67
  cols: number;
@@ -115,6 +117,8 @@ export interface WshGatewayEndpointDuplex {
115
117
  readable: ReadableStream<Uint8Array>;
116
118
  writable: WritableStream<Uint8Array>;
117
119
  who: WshGatewayWho;
120
+ /** #121: the execution target this endpoint belongs to; undefined for the host's own. */
121
+ target?: string;
118
122
  /** Half-close: nothing more will be sent. */
119
123
  close(reason?: string): void;
120
124
  /** Tear the connection down now. */
@@ -487,6 +491,15 @@ export interface WshServerOptions {
487
491
  onShare?: import('../host.js').WshOnShare;
488
492
  /** #163: told once per connection this host turned away (an operator, on a reverse host), with a stable reason code (`REFUSAL_REASONS`, from `@johnhenry/wsh/host`). */
489
493
  onRefused?: import('../host.js').WshOnRefused;
494
+ /**
495
+ * #121: execution targets (containers, VMs, workers, sandboxes), each with its own `exec` (`true` = a shell), `pty`, `fs`
496
+ * (`{ root }` or operations) and `endpoints`, and an `authorize(who, { target, kind })`. A client names one in `Open`,
497
+ * `FileOp` or `OpenEndpoint` and lists what it may use with `listTargets()`. Off unless given: the host then advertises no
498
+ * `targets` and refuses a request that names one. A refused target and one that does not exist look the same to the client.
499
+ */
500
+ targets?: Record<string, Omit<import('../host.js').WshTargetOptions, 'exec' | 'fs'> & { exec?: true | WshServerExecOptions | WshExecRunner; fs?: WshServerFsOptions | import('../host.js').WshFileBackend }>;
501
+ /** With `targets`: an `Open`, `FileOp` or `OpenEndpoint` that names no target is refused, so nothing runs on the host itself (`rpc` channels too). Does not cover the gateway, MCP or `Attach`. */
502
+ requireTarget?: boolean;
490
503
  onLog?: (line: string) => void;
491
504
  }
492
505
 
@@ -85,6 +85,15 @@ function tlsChannelBinding(socket) {
85
85
  * Answer the gateway opcodes (OpenTcp, ResolveDns, GatewayData/Close): the client opens TCP connections and resolves
86
86
  * names from this host. Default deny: a destination must match `allow` (`"*"`, `"host"`, `"host:port"`). `socks` dials
87
87
  * through a SOCKS5 proxy (Tor) with the name unresolved. UDP (`udp`: bounds, WebTransport datagrams) and TCP reverse tunnels (`reverse`, off unless given) are served. Off unless given. See `gateway.mjs`.
88
+ * @param {Record<string, { description?: string, authorize?: Function, exec?: true | object | Function, pty?: object, fs?: object, endpoints?: object }>} [options.targets]
89
+ * Execution targets (#121): the host fronts several (containers, VMs, workers, sandboxes), each with its own `exec`, `pty`,
90
+ * `fs` and `endpoints` (the same forms as the host's own) and an `authorize(who, { target, kind })` (`kind`: `exec`, `pty`,
91
+ * `file`, `endpoint`, `list`) deciding who may use it; a client names one in `Open`, `FileOp` or `OpenEndpoint` and lists
92
+ * what it may use with `ListTargets`. Off unless given (the host then advertises no `targets` and refuses a request that
93
+ * names one). A refused target and one that does not exist look the same to the client.
94
+ * @param {boolean} [options.requireTarget=false] - With `targets`: an `Open`, `FileOp` or `OpenEndpoint` that names no target is
95
+ * refused, so nothing runs on the host itself (`kind: 'rpc'` channels, which are not per target, are refused too). Does NOT
96
+ * cover the gateway (`OpenTcp`, `OpenUnix`, ...), MCP, or `Attach` to a session already open.
88
97
  * @param {number} [options.bindTimeoutMs=3000]
89
98
  * @param {number} [options.connectionTtlMs=0] - End every authenticated connection this long after login (0 = never).
90
99
  * Advertised as `AuthOk.ttl` in whole seconds, rounded up; the client reads it as `client.authTtl`.
@@ -106,7 +115,7 @@ function tlsChannelBinding(socket) {
106
115
  */
107
116
  export function createWshServer({
108
117
  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 = () => {},
109
- onShare, onRefused,
118
+ onShare, onRefused, targets, requireTarget,
110
119
  } = {}) {
111
120
  validateOnShare(onShare, 'createWshServer');
112
121
  validateOnRefused(onRefused, 'createWshServer');
@@ -120,7 +129,7 @@ export function createWshServer({
120
129
  let httpsServer = null;
121
130
  let bound = null;
122
131
 
123
- const { execRunner, execOptions, pty: ptyConfig, files, mcp: mcpHost } = buildBackends({ exec, pty, fs, mcp });
132
+ const { execRunner, execOptions, pty: ptyConfig, files, mcp: mcpHost, targets: targetTable, requireTarget: mustHaveTarget } = buildBackends({ exec, pty, fs, mcp, targets, requireTarget });
124
133
  const methods = authMethods(auth);
125
134
  const rl = auth?.rateLimit ?? {};
126
135
  const rateLimit = {
@@ -136,7 +145,10 @@ export function createWshServer({
136
145
  let registry = null;
137
146
  let hub = null;
138
147
  let wt = null;
139
- const gatewayCfg = gateway === undefined ? null : normalizeGateway(gateway);
148
+ let gatewayCfg = gateway === undefined ? null : normalizeGateway(gateway);
149
+ // A target's own named endpoints (#121) are served by the gateway session even when the host has no gateway of its own:
150
+ // an endpoints-only one (no TCP, DNS or unix sockets), which advertises `gateway-endpoints`.
151
+ if (targetTable && [...targetTable.values()].some((t) => t.endpoints)) gatewayCfg = { ...(gatewayCfg ?? normalizeGateway({ tcp: false })), targetEndpoints: true };
140
152
  const sessionOptions = sessions ? (sessions === true ? {} : sessions) : null;
141
153
 
142
154
  /** Sockets handed to `accept()` that are still open. */
@@ -163,7 +175,7 @@ export function createWshServer({
163
175
  return createConnectionFactory({
164
176
  authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
165
177
  methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, createGatewaySession, sessions: registry, relay: hub,
166
- onShare, onRefused,
178
+ onShare, onRefused, targets: targetTable, requireTarget: mustHaveTarget,
167
179
  });
168
180
  })();
169
181
  ready.catch(() => { ready = null; });