@johnhenry/wsh 0.41.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -843,7 +843,7 @@ sides; a host that does not require proof is exactly as exposed as before), the
843
843
  messages and seals nothing itself), and a compromised *operator* key (it proves the key, not the
844
844
  person). A relay can still refuse service by dropping the challenge.
845
845
 
846
- #### A sealed session (#155, host: JS; client: the Rust CLI so far)
846
+ #### A sealed session (#155, host: JS and the Rust `wsh-server`; client: the JS client and the Rust CLI)
847
847
 
848
848
  `createMemoryHost({ hostKey, dataStreams: false, sealSession: 'offer' | 'require' })` (and `createWshServer`, for a connection
849
849
  accepted with `dataStreams: false`) seals the WHOLE session end to end. After login the client sends a `KeyExchange` whose
@@ -858,8 +858,32 @@ downgrade. Only `--sealed` is a guarantee: sealing "on its own" rests on a `Serv
858
858
  login, so a client that must never talk in the clear passes `--sealed` (against a host that requires sealing, a stripped client is
859
859
  refused, but what it sent before the refusal -- its commands, if any -- was already readable). What it does NOT cover: the handshake before login (the user name, the login public key and the host key proof are
860
860
  readable by the relay; the signed key exchange is not secret), the sizes and timing of traffic, a host whose connection has client-opened
861
- QMux data streams (not offered there), and a denial of service (a relay can always drop or cut). The JS client has no sealed
862
- session yet, so against a JS client use a host that only `'offer'`s.
861
+ QMux data streams (not offered there), and a denial of service (a relay can always drop or cut).
862
+
863
+ The JS client is the initiator too: `client.connect(url, { sealSession: false | 'auto' | true })` (also `WshClient.exec`).
864
+ `'auto'`, the default, seals only against a host that says `e2e-session-required` (so a client written before this option keeps
865
+ talking plainly to a host that merely offers it, and a host that requires sealing no longer refuses it); `true` seals or fails --
866
+ a host that does not offer `e2e-session`, one that proved no host key, or a password login is refused BEFORE a credential is
867
+ sent, with a sentence; `false` never seals. `client.sessionSealed` says whether it is. The exchange is bound to the host key the
868
+ host PROVED on this connection: it authenticates that key, not whose it is, so pin the host as well (`expectHostKey` /
869
+ `knownHosts`), or a relay that presents its own host key and terminates the exchange is the host to this client. Once sealed, a
870
+ plain message from the host is dropped, a frame that does not open ends the connection (`onError`, then `onClose`), `openStream()`
871
+ is refused and datagrams are neither sent nor heard (UDP uses the reliable path). `'auto'` is not a guarantee, for the reason above;
872
+ `true` is.
873
+
874
+ The Rust `wsh-server` is a responder too: `[server] seal_session = "off" | "offer" | "require"` (default `off`: no feature is
875
+ advertised and no released client is affected; `offer` and `require` need `host_key`, else the config is refused at start). On a
876
+ WebSocket connection it advertises `e2e-session` (and `e2e-session-required` with `require`), and after a KEY login it answers the
877
+ signed key exchange (it verifies the login key's signature, signs its reply with the host key) with the same `SealGate` the CLI uses;
878
+ from then on every control message but ping/pong is an `EncryptedFrame` both ways, gateway data included, and a frame that does not open
879
+ closes the connection. `offer` serves a client that never asks as before. `require` serves nothing in the clear: a plain message before
880
+ the key exists is answered with an error and the connection is closed, a password login is refused, and WebTransport connections and
881
+ WISP tunnels are refused (they cannot be sealed; connect over WebSocket). **Typed rpc channels (`wsh-fs`, ...) are not offered while
882
+ `seal_session` is on** (they ride client-opened data streams, which are not frames; the server says so at start). WebTransport on an
883
+ `offer` server is served as before and does not list `e2e-session`, so a client that must seal (`sealSession: true`, `--sealed`) is
884
+ refused there before a credential is sent. The same limits apply as for the JS host: the handshake before login, sizes and timing,
885
+ and a denial of service are not covered, and sealing "on its own" (`'auto'`, the CLI without `--sealed`) against an `offer` server is
886
+ not a guarantee. Pin the server's host key on the client (`expectHostKey`, `known_hosts`): the exchange authenticates the key the server proved.
863
887
 
864
888
  #### Knowing who a host turned away: `onRefused` (#163)
865
889
 
@@ -907,7 +931,7 @@ handshake and the session traffic -- is readable by it unless the two ends seal
907
931
  (per-session `initiateE2E`, or the **sealed session** below); it cannot forge the operator's signature or the host's.
908
932
  **Until you seal the session, treat a pipe relay as trusted for secrecy AND integrity**: it can read every control message and
909
933
  all gateway and endpoint data (`GatewayData`: TCP, unix sockets, named endpoints) and alter forwarded bytes after the handshake
910
- (#155). Pin the host key, require channel binding, use `wss://` to a relay you trust, or seal the session. It can drop, delay or
934
+ (#155; the JS client's `sealSession: true` and the CLI's `--sealed` seal it against a JS host that offers it). Pin the host key, require channel binding, use `wss://` to a relay you trust, or seal the session. It can drop, delay or
911
935
  cut a connection, and it sees who dials which id and how much they send.
912
936
 
913
937
  *CLI side (#145).* `wsh --via wss://relay/r/<id> user@host [command...]` dials the operator side
@@ -1498,7 +1522,7 @@ instead of dragging its own toolchain and CI job into an unrelated
1498
1522
  browser-app repo. It was previously deleted from clawser by accident
1499
1523
  (2026-03-14) and restored (2026-07-05) before this move.
1500
1524
 
1501
- Four crates, workspace-versioned (currently `0.12.0`):
1525
+ Four crates, workspace-versioned (currently `0.13.0`):
1502
1526
 
1503
1527
  | Crate | Kind | Description |
1504
1528
  |-------|------|--------------|
@@ -1662,7 +1686,7 @@ than left to be found.
1662
1686
  | Channel binding of the login signature (#119) | `requireChannelBinding` (client and server); kinds `host`, `cert-hash`, `tls-exporter` | Kind `host`: the client binds to the proven host key (`--require-channel-binding`, and it honours `channel-binding-required`), and `wsh-server` offers it and can require it (`[server] require_channel_binding`, needs `host_key`). `cert-hash` and `tls-exporter`: not in Rust (the Rust WebTransport client has no certificate-hash pinning; `ConnectConfig.cert_hash` binds it if a caller supplies one) | **Wire-unified, negotiated** (`channel-binding:<kind>` features); verified against the spec's test vectors |
1663
1687
  | Pipe relay (#118) | `@johnhenry/wsh/pipe-relay` | operator side only (#145): `wsh --via wss://relay/r/<id> user@host command...` (also `connect`, `scp`, `ls`, `sftp`, `copy-id`), or the URL as the target. The host side of a pipe is not implemented in Rust. As on a direct connection the Rust client verifies the host-key proof (`host-key` / `host-key-sig` over its own nonce) before sending a credential, pins only a proven key, and binds the login to it (channel binding `host`; `test/rust/wsh-cli-identity.test.mjs`); the pipe-relayed session itself is not sealed (see Security model). `wsh -N -L` exits non-zero when the host drops the session (#156), and the error lines show the relay and a shortened id, never the whole rendezvous id | **Deliberately a relay without wsh parsing** -- nothing to unify on the wire. `--via` keeps `user@host` as the identity: its key is recorded in `known_hosts` under `host:port` (what a direct connection uses), never under the relay's address; a URL target is recorded under the URL's own authority, i.e. the relay's. The URL is not saved to `last_session.json` (the id is a capability) |
1664
1688
  | Operator-side shared folders (`--share`, #159) | host side: `onShare(name, fs, who)` on `createMemoryHost` / `createWshServer` / `createReverseHost` (the host *uses* the operator's directories; `fs` is an object of async file operations, also shaped like an `fs` backend; `fs.root` is the operator's advisory, unverified path for the share, #164). The JS client does not offer shares | CLI side: `wsh --share NAME=/abs/dir[:ro\|:rw]` offers them, with each directory's path unless `--share-hide-path` (`wsh_client::share`, `wsh-cli`'s `sharefs`: descriptor-relative, never follows a link, see [Sharing a directory](#sharing-a-directory-with-the-host-wsh---share-159)); unix only. **A Rust host that uses shares: not built** (`wsh-server` does not state `shares`) | **Wire-unified, negotiated**: the host states the feature `shares`; the client sends one `ShareOffer` after login (opcodes `0xa8` `ShareOffer`, `0xa9` `ShareRequest`, host to client, `0xaa` `ShareReply`). No change notification, no sharing over `reverse-connect` |
1665
- | Sealed session: any authenticated connection incl. gateway/endpoint data (#155) | host `sealSession: 'offer' \| 'require'` (stage b); the JS client does not seal yet | `wsh --sealed ...` (or automatic against `e2e-session-required`) seals a direct or pipe-relayed session; `wsh-server` does not offer it yet | **Wire-unified, negotiated** (`e2e-session`, `e2e-session-required`, `KeyExchange` for the connection's session id, `EncryptedFrame` channel 0) |
1689
+ | Sealed session: any authenticated connection incl. gateway/endpoint data (#155) | host `sealSession: 'offer' \| 'require'` (stage b); client `connect(url, { sealSession: false \| 'auto' \| true })` (stage c) | `wsh --sealed ...` (or automatic against `e2e-session-required`) seals a direct or pipe-relayed session; `wsh-server` offers or requires it on WebSocket (`[server] seal_session = "off" \| "offer" \| "require"`, needs `host_key`; `require` refuses WebTransport, WISP tunnels and password logins; no typed rpc channels while it is on) | **Wire-unified, negotiated** (`e2e-session`, `e2e-session-required`, `KeyExchange` for the connection's session id, `EncryptedFrame` channel 0) |
1666
1690
  | Refusal event with stable reason codes (`onRefused`, #163) | `onRefused({ reason, who, detail })` on `createMemoryHost` / `createWshServer` / `createReverseHost`; `REFUSAL_REASONS` from `@johnhenry/wsh/host` | none: `wsh-server` and `wsh reverse` log a refusal, they have no callback (an embedding process has none) | **JS-only** -- a host-side callback of the embedding API, no wire change |
1667
1691
  | `AuthOk.ttl` enforced, `token` opaque (#125) | `connectionTtlMs`; `client.authTtl` | `wsh-server` sends `ttl: 0` (no lifetime promised; `session_ttl` is the lifetime of a *detached* session) and an HMAC token that nothing accepts back | **Wire-compatible**: both fields are still sent (released peers require them). **Changed in the Rust server after `rust-v0.6.0`**: it used to send `session_ttl` (86400), which nothing enforced. The Rust client ignores `ttl` |
1668
1692
  | `clientEnv` allow-list (#126) | default `TERM`, `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*` | `wsh-server`: the same default; `[server] client_env = true` (everything, the old behaviour), `false` (nothing) or a list of names / `PREFIX*` (replaces the default) | **Both hosts**; wire unchanged. **Breaking default in the Rust server**, see the CHANGELOG |
@@ -1722,7 +1746,7 @@ plus one `SHA256SUMS` file covering every archive in the release. These
1722
1746
  names are a stable contract other repos (clawser) pin and download by --
1723
1747
  do not change them without coordinating downstream.
1724
1748
 
1725
- `wsh --version` and `wsh-server --version` print the workspace version the binary was built from (`wsh 0.12.0`), which is the
1749
+ `wsh --version` and `wsh-server --version` print the workspace version the binary was built from (`wsh 0.13.0`), which is the
1726
1750
  number in the `rust-vX.Y.Z` tag. Binaries of `rust-v0.9.0` to `rust-v0.10.0` printed a fixed `0.1.0`, so against one of those the
1727
1751
  version cannot be read from the binary (look for a flag in `wsh --help` instead).
1728
1752
 
@@ -1962,15 +1986,16 @@ What this does **not** protect against:
1962
1986
  JS host's, above): nothing is promised or enforced at connection level; do not
1963
1987
  treat the token as a credential.
1964
1988
  - **`wsh --via` (pipe relay from the Rust CLI) is the operator side only, and
1965
- still not sealed** (the sealed bridge of `wsh reverse-connect --sealed` covers
1966
- reverse bridges only; #155 tracks sealing a direct or pipe-relayed connection and
1967
- its gateway data). The Rust client now verifies the host-key proof
1989
+ not sealed unless you ask** (`wsh --sealed` seals a direct or pipe-relayed session, gateway
1990
+ data included, against a host that offers `e2e-session`: the JS host with `sealSession`, or
1991
+ `wsh-server` with `seal_session`; #155. Without `--sealed` the session is plain, and a relay reads
1992
+ it). The Rust client now verifies the host-key proof
1968
1993
  (`host-key` / `host-key-sig` over its own `host-key-nonce`) before sending
1969
1994
  any credential, records only a PROVEN key in `known_hosts`, binds the login
1970
1995
  signature to that key (channel binding `host`), and refuses a changed key
1971
1996
  always. A replayed `ServerHello` or an impostor's key is refused as the JS
1972
- client refuses it. What is still unprotected: the bridge is not sealed
1973
- end to end (a pipe-relayed session has no sealing layer yet, #155), so the relay sees
1997
+ client refuses it. What is still unprotected without `--sealed`: the session is not sealed
1998
+ end to end, so the relay sees
1974
1999
  session traffic in the clear unless the legs are TLS and it is trusted not
1975
2000
  to read them (it terminates each leg's TLS), and it can stamp an identity on
1976
2001
  a plain message after the handshake. A host with no host key proves nothing:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.41.0",
3
+ "version": "0.42.0",
4
4
  "description": "Web Shell \u2014 browser-native remote command execution over WebTransport and WebSocket with Ed25519 authentication",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/client.mjs CHANGED
@@ -8,7 +8,7 @@
8
8
  * reverse mode (client registers as a peer for incoming connections).
9
9
  */
10
10
 
11
- import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE } from './features.mjs';
11
+ import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE, SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE } from './features.mjs';
12
12
  import { WebTransportTransport, normalizeWebTransportOptions } from './transport.mjs';
13
13
  import { clientChannelBinding, offeredKinds, TLS_EXPORTER_LABEL, TLS_EXPORTER_LENGTH } from './channel-binding.mjs';
14
14
  import { WebSocketTransport } from './transport-ws.mjs';
@@ -183,6 +183,10 @@ function assertStdinSource(stdin) {
183
183
  throw new TypeError('exec: stdin must be a string, Uint8Array, ReadableStream or (async) iterable of those');
184
184
  }
185
185
 
186
+ function assertSealSession(v) {
187
+ if (v !== false && v !== 'auto' && v !== true) throw new TypeError("connect: sealSession must be false, 'auto' or true");
188
+ }
189
+
186
190
  /** Write `stdin` to `session` in bounded chunks, then close the write side (EOF). */
187
191
  async function pumpStdin(session, stdin) {
188
192
  const send = async (chunk) => {
@@ -274,6 +278,13 @@ export class WshClient {
274
278
  */
275
279
  #sealState = null;
276
280
 
281
+ /**
282
+ * Set from the moment this client starts sealing its whole session (#155) until the connection ends: `{ sessionId,
283
+ * bridge }`, `bridge` null until the key exists. A message that arrives from the host itself is then heard only
284
+ * as the key exchange (while pending), a frame of the session, or the keepalive.
285
+ */
286
+ #sessionSeal = null;
287
+
277
288
  /** The binding kinds the last login's signature covered (#119); empty when it was unbound. */
278
289
  #channelBindingKinds = [];
279
290
 
@@ -558,6 +569,14 @@ export class WshClient {
558
569
  return this.#hostKey;
559
570
  }
560
571
 
572
+ /**
573
+ * Is this whole session sealed end to end (#155, `connect(url, { sealSession })`)? Every message but the keepalive,
574
+ * gateway and endpoint data included, then travels as an authenticated encrypted frame a relay cannot read or alter.
575
+ */
576
+ get sessionSealed() {
577
+ return !!this.#sessionSeal?.bridge;
578
+ }
579
+
561
580
  // ── Connection ──────────────────────────────────────────────────────
562
581
 
563
582
  /**
@@ -595,15 +614,25 @@ export class WshClient {
595
614
  * to this connection (#119): `true` needs at least one binding kind (`host`, `cert-hash`, `tls-exporter`) that
596
615
  * both the host offers and this client can supply; an array names kinds that must all be bound. Not for
597
616
  * password auth (nothing is signed). Stops an intermediary from relaying a genuine challenge to the host.
617
+ * @param {false | 'auto' | true} [opts.sealSession='auto'] - Seal the WHOLE session end to end (#155): after login a
618
+ * signed key exchange with the host (bound to its proven host key and this login key), then every message but the
619
+ * keepalive -- gateway and endpoint data included -- is an authenticated encrypted frame, so a relay that copies
620
+ * bytes can neither read nor alter it, and a frame that does not open closes the connection. `'auto'` seals only
621
+ * against a host that says `e2e-session-required` (a host that merely offers it is spoken to as before); `true`
622
+ * seals or fails -- a host that does not offer `e2e-session`, one that proved no host key, or a password login is
623
+ * refused BEFORE a credential is sent; `false` never seals (a host that requires it then serves nothing). Only
624
+ * `true` is a guarantee: `'auto'` rests on a ServerHello feature that a relay can strip before login. Pin the host
625
+ * (`expectHostKey` / `knownHosts`) too: the exchange authenticates the key the host proved, not whose it is.
598
626
  * @returns {Promise<string>} The server-assigned session ID
599
627
  */
600
- async connect(url, { username, keyPair, signer, password, transport: transportHint, webTransport, timeout = DEFAULT_AUTH_TIMEOUT, requireChannelBinding = false, ...hostKeyOpts } = {}) {
628
+ async connect(url, { username, keyPair, signer, password, transport: transportHint, webTransport, timeout = DEFAULT_AUTH_TIMEOUT, requireChannelBinding = false, sealSession = 'auto', ...hostKeyOpts } = {}) {
601
629
  if (this.#state !== STATE_DISCONNECTED && this.#state !== STATE_CLOSED) {
602
630
  throw new Error(`Client already ${this.#state}`);
603
631
  }
604
632
  if (!username) {
605
633
  throw new Error('username is required');
606
634
  }
635
+ assertSealSession(sealSession);
607
636
  const cred = await resolveSigner({ keyPair, signer });
608
637
  this.#signer = cred;
609
638
  this.#loginUsername = username;
@@ -616,6 +645,7 @@ export class WshClient {
616
645
  this.#channelBindingKinds = [];
617
646
  this.#certHash = null;
618
647
  this.#sealState = null;
648
+ this.#sessionSeal = null;
619
649
  this.#peerProof = null;
620
650
  this.#sessions.clear();
621
651
  this.#channelCounter = 0;
@@ -651,6 +681,9 @@ export class WshClient {
651
681
  }
652
682
 
653
683
  let tempSessionId = null;
684
+ // Whether this session is to be sealed (#155): decided from the ServerHello and the proven host key, BEFORE a
685
+ // credential is sent, so a host that cannot seal is refused while nothing has been signed.
686
+ let seal = false;
654
687
 
655
688
  if (firstResponse.type === MSG.SERVER_HELLO) {
656
689
  // Server may proceed directly to auth if it accepted the hello.
@@ -665,6 +698,7 @@ export class WshClient {
665
698
  : null;
666
699
  challengeWait?.catch(() => {});
667
700
  await this.#verifyHostKey(firstResponse, hostCtx);
701
+ seal = this.#planSealing(sealSession, this.#serverFeatures, !!cred);
668
702
 
669
703
  if (authMethod === AUTH_METHOD.PUBKEY) {
670
704
  const challengeMsg = await challengeWait;
@@ -675,6 +709,7 @@ export class WshClient {
675
709
  this.#authToken = challengeMsg.token || null;
676
710
  this.#authTtl = Number(challengeMsg.ttl) || 0;
677
711
  this.#state = STATE_AUTHENTICATED;
712
+ if (seal) await this.#sealSession(timeout);
678
713
  this.#startPing();
679
714
  return this.#sessionId;
680
715
  }
@@ -708,6 +743,7 @@ export class WshClient {
708
743
  } else if (firstResponse.type === MSG.CHALLENGE) {
709
744
  // Some servers skip SERVER_HELLO and go straight to CHALLENGE.
710
745
  await this.#verifyHostKey(null, hostCtx);
746
+ seal = this.#planSealing(sealSession, [], !!cred);
711
747
  if (authMethod !== AUTH_METHOD.PUBKEY || !cred) {
712
748
  throw new Error('Server sent CHALLENGE but no key pair was provided');
713
749
  }
@@ -751,6 +787,7 @@ export class WshClient {
751
787
  this.#authToken = authResult.token || null;
752
788
  this.#authTtl = Number(authResult.ttl) || 0;
753
789
  this.#state = STATE_AUTHENTICATED;
790
+ if (seal) await this.#sealSession(timeout);
754
791
  this.#startPing();
755
792
 
756
793
  return this.#sessionId;
@@ -1562,7 +1599,7 @@ export class WshClient {
1562
1599
  // Datagrams for UDP flows: only on a transport that has them AND a host that listed "gateway-datagram".
1563
1600
  datagrams: () => {
1564
1601
  const t = this.#transport;
1565
- return t?.supportsDatagrams && this.hasFeature(GATEWAY_DATAGRAM_FEATURE) ? { send: (b) => t.sendDatagram(b), maxSize: () => t.maxDatagramSize } : null;
1602
+ return !this.#sessionSeal && t?.supportsDatagrams && this.hasFeature(GATEWAY_DATAGRAM_FEATURE) ? { send: (b) => t.sendDatagram(b), maxSize: () => t.maxDatagramSize } : null;
1566
1603
  },
1567
1604
  }));
1568
1605
  }
@@ -1650,6 +1687,7 @@ export class WshClient {
1650
1687
  */
1651
1688
  async openStream() {
1652
1689
  this.#assertAuthenticated('openStream');
1690
+ if (this.#sessionSeal) throw new Error('openStream: a sealed session carries no client-opened data streams (their bytes are not frames)');
1653
1691
  return this.#transport.openStream();
1654
1692
  }
1655
1693
 
@@ -2689,10 +2727,11 @@ export class WshClient {
2689
2727
  * @private
2690
2728
  */
2691
2729
  #attachTransportHandlers(transport) {
2692
- transport.onControl = (msg) => this.#handleControl(msg);
2730
+ transport.onControl = (msg) => this.#onTransportControl(msg);
2693
2731
  transport.onClose = () => this.#handleTransportClose();
2694
2732
  transport.onError = (err) => this.#handleTransportError(err);
2695
- transport.onDatagram = (bytes) => this.#gateway?.handleDatagram(bytes);
2733
+ // A datagram is not a frame: on a sealed session a relay could inject one, so none is heard (UDP uses the reliable path).
2734
+ transport.onDatagram = (bytes) => { if (!this.#sessionSeal) this.#gateway?.handleDatagram(bytes); };
2696
2735
  }
2697
2736
 
2698
2737
  /**
@@ -2853,6 +2892,90 @@ export class WshClient {
2853
2892
  }
2854
2893
  }
2855
2894
 
2895
+ // ── Internal: a sealed session (#155) ───────────────────────────────
2896
+
2897
+ /**
2898
+ * Whether this connection is to be sealed, decided from the ServerHello's features and the proven host key BEFORE
2899
+ * a credential is sent. `true` and a host that requires sealing (`'auto'`) fail here, with a sentence, when sealing
2900
+ * is not possible -- never by talking in the clear.
2901
+ * @param {false | 'auto' | true} mode
2902
+ * @param {string[]} features - the host's ServerHello features (`[]` when it sent none)
2903
+ * @param {boolean} haveKey - this login signs (a key login)
2904
+ * @returns {boolean}
2905
+ */
2906
+ #planSealing(mode, features, haveKey) {
2907
+ if (mode === false) return false;
2908
+ if (mode === 'auto' && !features.includes(SESSION_SEAL_REQUIRED_FEATURE)) return false;
2909
+ const why = !features.includes(SESSION_SEAL_FEATURE)
2910
+ ? `the host does not offer "${SESSION_SEAL_FEATURE}" (it needs a host key and a connection without client-opened data streams)`
2911
+ : !this.#hostKey?.publicKey
2912
+ ? 'the host proved no host key to authenticate the exchange against'
2913
+ : !haveKey
2914
+ ? 'a sealed session needs a key login (a password login has nothing to sign with)'
2915
+ : null;
2916
+ if (why) throw new Error(`sealed session: ${why} -- nothing was sent`);
2917
+ return true;
2918
+ }
2919
+
2920
+ /**
2921
+ * Seal this whole connection: a signed `KeyExchange` for the connection's session id (the login key signs this half,
2922
+ * the host's proven key the other), then every message but the keepalive leaves as an `EncryptedFrame` on channel 0,
2923
+ * in order. Until the key exists nothing but the key exchange may be sent, and nothing plain is heard.
2924
+ * @param {number} timeout
2925
+ */
2926
+ async #sealSession(timeout) {
2927
+ const sessionId = this.#sessionId;
2928
+ const hostKey = this.#hostKey?.publicKey;
2929
+ if (!sessionId || !hostKey || !this.#signer) throw new Error('sealed session: no session id, host key or login key -- nothing was sent');
2930
+ const transport = this.#transport;
2931
+ const plainSend = transport.sendControl.bind(transport);
2932
+ let bridge = null;
2933
+ this.#sessionSeal = { sessionId, bridge: null };
2934
+ transport.sendControl = async (msg) => {
2935
+ if (msg.type === MSG.PING || msg.type === MSG.PONG) return plainSend(msg);
2936
+ if (bridge) return plainSend(await bridge.seal(msg));
2937
+ if (msg.type === MSG.KEY_EXCHANGE && msg.session_id === sessionId) return plainSend(msg);
2938
+ throw new Error('sealed session: nothing is sent before the key exists');
2939
+ };
2940
+ const { sharedSecret } = await this.initiateE2E(sessionId, 'X25519+ML-KEM-768', timeout, {
2941
+ verifyPeer: hostKey, signAs: this.#signer, responderIdentity: hostKey,
2942
+ });
2943
+ bridge = new SealedBridge({ key: sharedSecret, sessionId, role: 'initiator', scope: 'session' });
2944
+ this.#sessionSeal = { sessionId, bridge };
2945
+ }
2946
+
2947
+ /**
2948
+ * Every message that arrives from the host itself passes here. On a sealed session only the key exchange (while the
2949
+ * key does not exist yet), the keepalive and frames of the session are heard: a relay in the middle can write any
2950
+ * plain message, so a plain one is dropped; a frame that does not open (flipped bit, replay, reorder, forged) is the
2951
+ * relay at work, and ends the connection.
2952
+ * @param {object} msg
2953
+ */
2954
+ #onTransportControl(msg) {
2955
+ const seal = this.#sessionSeal;
2956
+ if (!seal || msg.type === MSG.PING || msg.type === MSG.PONG) { this.#handleControl(msg); return; }
2957
+ if (seal.bridge) {
2958
+ if (!seal.bridge.isFrame(msg)) {
2959
+ console.warn(`[wsh:client] dropping a plaintext message (type ${msg.type}) on a sealed session`);
2960
+ return;
2961
+ }
2962
+ seal.bridge.open(msg).then(
2963
+ (inner) => { if (this.#sessionSeal === seal) this.#handleControl(inner); },
2964
+ (err) => this.#sealedFrameFailed(seal, err),
2965
+ );
2966
+ return;
2967
+ }
2968
+ if (msg.type === MSG.KEY_EXCHANGE && msg.session_id === seal.sessionId) { this.#handleControl(msg); return; }
2969
+ console.warn(`[wsh:client] dropping a plaintext message (type ${msg.type}) before the session is sealed`);
2970
+ }
2971
+
2972
+ #sealedFrameFailed(seal, err) {
2973
+ if (this.#sessionSeal !== seal || this.#state === STATE_CLOSED) return;
2974
+ this.#sessionSeal = { ...seal, failed: true };
2975
+ this.#emitError(new Error(`wsh: a sealed frame did not open (${err.message}); the session is closed`));
2976
+ this.#transport?.close().catch(() => {});
2977
+ }
2978
+
2856
2979
  // ── Internal: auth handshake ────────────────────────────────────────
2857
2980
 
2858
2981
  /**
@@ -2868,8 +2991,10 @@ export class WshClient {
2868
2991
  * @returns {Promise<string>} Session ID
2869
2992
  * @private
2870
2993
  */
2871
- async #performAuth({ username, keyPair, signer, password, timeout = DEFAULT_AUTH_TIMEOUT, url, requireChannelBinding = false, ...hostKeyOpts } = {}) {
2994
+ async #performAuth({ username, keyPair, signer, password, timeout = DEFAULT_AUTH_TIMEOUT, url, requireChannelBinding = false, sealSession = 'auto', ...hostKeyOpts } = {}) {
2872
2995
  if (!username) throw new Error('username is required');
2996
+ assertSealSession(sealSession);
2997
+ this.#sessionSeal = null;
2873
2998
  const cred = await resolveSigner({ keyPair, signer });
2874
2999
  this.#signer = cred;
2875
3000
  this.#loginUsername = username;
@@ -2895,6 +3020,7 @@ export class WshClient {
2895
3020
  }
2896
3021
 
2897
3022
  let tempSessionId = null;
3023
+ let seal = false; // see connect()
2898
3024
 
2899
3025
  if (firstResponse.type === MSG.SERVER_HELLO) {
2900
3026
  tempSessionId = firstResponse.session_id;
@@ -2905,6 +3031,7 @@ export class WshClient {
2905
3031
  : null;
2906
3032
  challengeWait?.catch(() => {});
2907
3033
  await this.#verifyHostKey(firstResponse, hostCtx);
3034
+ seal = this.#planSealing(sealSession, this.#serverFeatures, !!cred);
2908
3035
 
2909
3036
  if (authMethod === AUTH_METHOD.PUBKEY) {
2910
3037
  const challengeMsg = await challengeWait;
@@ -2914,6 +3041,7 @@ export class WshClient {
2914
3041
  this.#authToken = challengeMsg.token || null;
2915
3042
  this.#authTtl = Number(challengeMsg.ttl) || 0;
2916
3043
  this.#state = STATE_AUTHENTICATED;
3044
+ if (seal) await this.#sealSession(timeout);
2917
3045
  this.#startPing();
2918
3046
  return this.#sessionId;
2919
3047
  }
@@ -2934,6 +3062,7 @@ export class WshClient {
2934
3062
  } else if (firstResponse.type === MSG.CHALLENGE) {
2935
3063
  if (!cred) throw new Error('Server sent CHALLENGE but no key pair provided');
2936
3064
  await this.#verifyHostKey(null, hostCtx);
3065
+ seal = this.#planSealing(sealSession, [], true);
2937
3066
 
2938
3067
  // Challenge carries session_id directly — see connect()'s
2939
3068
  // CHALLENGE branch for why. Keep tempSessionId as a fallback for
@@ -2964,6 +3093,7 @@ export class WshClient {
2964
3093
  this.#authToken = authResult.token || null;
2965
3094
  this.#authTtl = Number(authResult.ttl) || 0;
2966
3095
  this.#state = STATE_AUTHENTICATED;
3096
+ if (seal) await this.#sealSession(timeout);
2967
3097
  this.#startPing();
2968
3098
 
2969
3099
  return this.#sessionId;
@@ -3053,6 +3183,10 @@ export class WshClient {
3053
3183
  const serverChannelId = msg.channel_id ?? pending.requestedChannelId;
3054
3184
  const streamIds = msg.stream_ids ?? {};
3055
3185
  const dataMode = msg.data_mode === 'virtual' ? 'virtual' : 'stream';
3186
+ if (this.#sessionSeal && dataMode !== 'virtual') {
3187
+ pending.reject(new Error('Failed to open session: the host answered with a data stream, and a sealed session carries none'));
3188
+ return;
3189
+ }
3056
3190
  const capabilities = Array.isArray(msg.capabilities) ? msg.capabilities : [];
3057
3191
 
3058
3192
  const session = new WshSession(
package/src/features.mjs CHANGED
@@ -26,3 +26,11 @@ export const MCP_CANCEL_FEATURE = 'mcp-cancel';
26
26
  */
27
27
  export const STREAM_ANNOUNCE_FEATURE = 'stream-announce';
28
28
  export const EXEC_PIPES_FEATURE = 'exec-pipes';
29
+
30
+ /**
31
+ * Host feature (#155): this host seals the whole session end to end when asked (a signed `KeyExchange` for the
32
+ * connection's session id, then every message but the keepalive as an `EncryptedFrame` on channel 0).
33
+ */
34
+ export const SESSION_SEAL_FEATURE = 'e2e-session';
35
+ /** Host feature (#155): this host serves nothing on a session that is not sealed. */
36
+ export const SESSION_SEAL_REQUIRED_FEATURE = 'e2e-session-required';
@@ -91,8 +91,10 @@ export class GatewayConnections {
91
91
  onRemoteClose: datagram ? () => channel.destroy() : undefined,
92
92
  onData,
93
93
  sendData: (data) => this.#send(gatewayDataMsg({ gatewayId: id, data })),
94
- sendCredit: (n) => this.#send(gatewayCreditMsg({ gatewayId: id, bytes: n })),
95
- sendClose: (reason) => this.#send(gatewayCloseMsg({ gatewayId: id, reason })),
94
+ sendCredit: (n) => Promise.resolve(this.#send(gatewayCreditMsg({ gatewayId: id, bytes: n }))).catch(() => {}),
95
+ // Best effort and not awaited by the channel: on a sealed session (#155) the send finishes after the frame is
96
+ // sealed, so a connection that closed meanwhile must not surface as an unhandled rejection.
97
+ sendClose: (reason) => Promise.resolve(this.#send(gatewayCloseMsg({ gatewayId: id, reason }))).catch(() => {}),
96
98
  onClose: () => { this.#channels.delete(id); this.#udp.delete(id); },
97
99
  });
98
100
  this.#channels.set(id, channel);
package/src/index.d.ts CHANGED
@@ -1839,6 +1839,16 @@ export interface WshHostKeyOptions {
1839
1839
  * kinds that must all be bound. Nothing is signed otherwise. Key logins only.
1840
1840
  */
1841
1841
  requireChannelBinding?: boolean | WshChannelBindingKind[];
1842
+ /**
1843
+ * Seal the WHOLE session end to end (#155): after login a signed key exchange with the host (bound to its proven host
1844
+ * key and this login key), then every message but the keepalive -- gateway and endpoint data included -- is an
1845
+ * authenticated encrypted frame a relay that copies bytes can neither read nor alter; a frame that does not open
1846
+ * closes the connection. Default `'auto'`: seal only against a host that says `e2e-session-required`. `true` seals or
1847
+ * fails, BEFORE a credential is sent (a host that does not offer `e2e-session`, one that proved no host key, a password
1848
+ * login). `false` never seals. Only `true` is a guarantee (a relay can strip the ServerHello feature `'auto'` rests
1849
+ * on); pin the host (`expectHostKey` / `knownHosts`) as well, since the exchange authenticates the key the host proved.
1850
+ */
1851
+ sealSession?: false | 'auto' | true;
1842
1852
  }
1843
1853
 
1844
1854
  /** What a login signature can be bound to (wsh #119). */
@@ -2235,6 +2245,9 @@ export class WshClient {
2235
2245
  */
2236
2246
  readonly hostKey: WshHostKey | null;
2237
2247
 
2248
+ /** Is this whole session sealed end to end (`connect(url, { sealSession })`, #155)? */
2249
+ readonly sessionSealed: boolean;
2250
+
2238
2251
  /** Default `onHostKey` for `connect()` (a per-call option wins). */
2239
2252
  onHostKey: ((hostKey: WshHostKey) => boolean | void | Promise<boolean | void>) | null;
2240
2253
 
@@ -24,7 +24,7 @@ import {
24
24
  generateNonce, verifyChallenge, fingerprint, importPublicKeyRaw,
25
25
  } from '../auth.mjs';
26
26
  import { FILE_CHUNK_BYTES, MAX_ATTACHMENTS } from './constants.mjs';
27
- import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE } from '../features.mjs';
27
+ import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE } from '../features.mjs';
28
28
  import { RpcChannel, RPC_FEATURE, RPC_MAX_MESSAGE_PREFIX, rpcProtocolFeature } from '../rpc.mjs';
29
29
  import { sealFrame, openFrame, ROLE_TAGS } from '../e2e-frame.mjs';
30
30
  import { E2EResponder, E2E_FEATURE, E2E_SIGN_FEATURE } from '../e2e-exchange.mjs';
@@ -40,10 +40,7 @@ import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMess
40
40
  import { SHARES_FEATURE, createShareSession } from '../shares.mjs';
41
41
 
42
42
  export const STREAM_ANNOUNCE = 'stream-announce';
43
- /** Host feature (#155): this host seals the whole session end to end when asked (a signed `KeyExchange` for the connection's session id). */
44
- export const SESSION_SEAL_FEATURE = 'e2e-session';
45
- /** Host feature: this host serves nothing on a session that is not sealed. */
46
- export const SESSION_SEAL_REQUIRED_FEATURE = 'e2e-session-required';
43
+ export { SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE };
47
44
 
48
45
  /**
49
46
  * The features a host built from `cfg` advertises (`ServerHello.features`, minus the host-key proof).