@johnhenry/wsh 0.38.1 → 0.39.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
@@ -835,11 +835,32 @@ many bytes):
835
835
  | tell the host the operator is *absent* when it is present (`ReverseClose`) | yes | yes | yes |
836
836
  | learn the operator's and host's keys, usernames, and the sizes and timing of traffic | yes | yes | yes |
837
837
 
838
+ A Rust host (`wsh reverse`, `wsh agent run`) is in the right-hand column only with `--require-operator-proof`
839
+ and an operator that seals (`wsh reverse-connect --sealed`, or a JS operator with `{ sealed: true }`); with proof alone
840
+ a relay can still inject a plain `Open` stamped with the operator's fingerprint, exactly as the middle column says.
838
841
  Not covered: an operator or host that skips the checks (the options are opt-in on both
839
- sides; a host that does not require proof is exactly as exposed as before), the Rust `wsh-server` relay and
840
- `wsh` client (they neither carry nor send these messages), and a compromised *operator* key (it proves the key, not the
842
+ sides; a host that does not require proof is exactly as exposed as before), the Rust `wsh-server` relay (it carries these
843
+ messages and seals nothing itself), and a compromised *operator* key (it proves the key, not the
841
844
  person). A relay can still refuse service by dropping the challenge.
842
845
 
846
+ #### A sealed session (#155, host: JS; client: the Rust CLI so far)
847
+
848
+ `createMemoryHost({ hostKey, dataStreams: false, sealSession: 'offer' | 'require' })` (and `createWshServer`, for a connection
849
+ accepted with `dataStreams: false`) seals the WHOLE session end to end. After login the client sends a `KeyExchange` whose
850
+ `session_id` is the connection's, signed with its login key and answered by the host with a signature of its host key (the
851
+ transcripts of the sealed bridge, bound to both identities and both ephemeral keys; hybrid X25519+ML-KEM-768). From then on every
852
+ message but the keepalive -- control messages, `GatewayData` for TCP / unix sockets / named endpoints, `GatewayCredit` -- is an
853
+ authenticated encrypted frame (`EncryptedFrame`, channel 0), so flow-control credit works as before. A plain message is not heard
854
+ once the session is sealed, and a frame that does not open (flipped bit, replay, reorder) closes it. Features: `e2e-session`
855
+ (offered), `e2e-session-required` (the host serves nothing on a session that is not sealed, and no password login). The Rust CLI
856
+ seals with `--sealed` (or on its own when the host says `e2e-session-required`) and refuses a host that does not offer it: no silent
857
+ downgrade. Only `--sealed` is a guarantee: sealing "on its own" rests on a `ServerHello` feature that a relay can strip before
858
+ login, so a client that must never talk in the clear passes `--sealed` (against a host that requires sealing, a stripped client is
859
+ refused, but what it sent before the refusal -- its commands, if any -- was already readable). What it does NOT cover: the handshake before login (the user name, the login public key and the host key proof are
860
+ readable by the relay; the signed key exchange is not secret), the sizes and timing of traffic, a host whose connection has client-opened
861
+ QMux data streams (not offered there), and a denial of service (a relay can always drop or cut). The JS client has no sealed
862
+ session yet, so against a JS client use a host that only `'offer'`s.
863
+
843
864
  #### A pipe relay (`@johnhenry/wsh/pipe-relay`, #118)
844
865
 
845
866
  When you do not want the relay to be a party at all, use a pipe: the host dials the relay, the operator dials the
@@ -869,7 +890,10 @@ for nothing, and the rendezvous id is the only thing standing between the host's
869
890
  an impostor that reaches the id first is still a stranger to the operator, who must pin the host key
870
891
  (`expectHostKey`) to notice; and the host still authenticates every operator. A pipe relay terminates the TLS of each leg, so what it copies -- the wsh
871
892
  handshake and the session traffic -- is readable by it unless the two ends seal it themselves
872
- (per-session `initiateE2E`); it cannot forge the operator's signature or the host's. It can drop, delay or
893
+ (per-session `initiateE2E`, or the **sealed session** below); it cannot forge the operator's signature or the host's.
894
+ **Until you seal the session, treat a pipe relay as trusted for secrecy AND integrity**: it can read every control message and
895
+ all gateway and endpoint data (`GatewayData`: TCP, unix sockets, named endpoints) and alter forwarded bytes after the handshake
896
+ (#155). Pin the host key, require channel binding, use `wss://` to a relay you trust, or seal the session. It can drop, delay or
873
897
  cut a connection, and it sees who dials which id and how much they send.
874
898
 
875
899
  *CLI side (#145).* `wsh --via wss://relay/r/<id> user@host [command...]` dials the operator side
@@ -1458,7 +1482,7 @@ instead of dragging its own toolchain and CI job into an unrelated
1458
1482
  browser-app repo. It was previously deleted from clawser by accident
1459
1483
  (2026-03-14) and restored (2026-07-05) before this move.
1460
1484
 
1461
- Four crates, workspace-versioned (currently `0.9.0`):
1485
+ Four crates, workspace-versioned (currently `0.10.0`):
1462
1486
 
1463
1487
  | Crate | Kind | Description |
1464
1488
  |-------|------|--------------|
@@ -1541,8 +1565,9 @@ than left to be found.
1541
1565
  | TCP reverse tunnels (`ListenRequest`, #98) | `@johnhenry/wsh/server` `gateway.reverse` (off by default; loopback unless the operator lists addresses; port allow-list, nothing below 1024 unless named; bounded listeners/connections/backlog/idle); client `listenTcp(port, { onConnection })` | `wsh-server` `[gateway] enable_reverse_tunnels` + `reverse_bind_addr` (off by default, loopback, client `bind_addr` ignored); no port allow-list; no per-listener connection, backlog or idle bounds beyond `max_connections` | **Wire-unified** (`ListenRequest`/`ListenOk`/`ListenFail`/`InboundOpen`/`InboundAccept`; the JS host sends the real `peer_addr`/`peer_port`). **Rust still needs**: a port allow-list and per-client listener / per-listener connection / idle bounds to match the JS host. Accepted connections are metered by `gateway-credit` now |
1542
1566
  | UDP (`OpenUdp`) as WebTransport datagrams (#124) | `client.openUdp()` over WebTransport when both ends list `gateway-datagram`: payloads are datagrams (4-byte flow id + payload), read from `maxDatagramSize`; oversize goes on the control stream (or drops); bounds: flows, packet and byte rates, idle; policy as TCP. Host: `gateway.udp`; Playwright test from Chromium | `wsh-server` serves `OpenUdp` over the reliable control stream only (one `GatewayData` per datagram); no datagrams, no rate bounds | **JS only for now** (negotiated by `gateway-datagram`, so a Rust peer keeps the reliable path). **Rust must implement**: list `gateway-datagram` in `ServerHello.features` on a WebTransport connection, accept/send datagrams `[gateway_id u32 BE][payload]` for `OpenUdp` flows when the client listed it (ignore the id of an unknown flow), read `maxDatagramSize` and send a bigger payload as `GatewayData` (or drop, by config), `connect()` the UDP socket to the checked address, and the same rate/flow bounds |
1543
1567
  | Gateway destination policy by resolved address | `@johnhenry/wsh/server` `gateway`: resolved address checked, `allowPrivate` | fixed in the Rust release after `rust-v0.6.0`: a loopback/private/link-local/ULA/CGNAT/unspecified/multicast address is refused after resolution unless a rule names it, and the server connects to the address it checked | **Same rule on both sides** (a Rust server released before that still has the name-only check) |
1544
- | Operator proof to the peer, sealed bridge, signed initiator half (#117) | `reverseConnect(.., { sealed, requirePeerProof })`; host `createReverseHost({ requireOperatorProof })`; relay lists `operator-proof` | **Operator proof: yes.** The Rust relay lists `operator-proof` and carries `ReverseChallenge`/`ReverseProof`/`ReverseConnect.features`; `wsh reverse-connect` answers a challenge (`--operator-proof` / `--no-operator-proof`; by default only for a peer that registered the `operator-proof` capability, because a released Rust host cannot decode the field); `wsh reverse` / `wsh agent run` challenge, verify BEFORE accepting, and take `--require-operator-proof` and `--allow-operator`. **Sealed bridge and signed `KeyExchange` halves: not yet** (no Rust E2E responder), so `--require-operator-proof` proves who connected but does not stop a relay stamping an identity on later plain messages | **Wire-unified, negotiated** (`ReverseConnect.features`, `operator-proof`, `e2e-sealed`); sealing is JS-only |
1568
+ | Operator proof to the peer, sealed bridge, signed initiator half (#117) | `reverseConnect(.., { sealed, requirePeerProof })`; host `createReverseHost({ requireOperatorProof })`; relay lists `operator-proof` | **Operator proof: yes.** The Rust relay lists `operator-proof` and carries `ReverseChallenge`/`ReverseProof`/`ReverseConnect.features`; `wsh reverse-connect` answers a challenge (`--operator-proof` / `--no-operator-proof`; by default only for a peer that registered the `operator-proof` capability, because a released Rust host cannot decode the field); `wsh reverse` / `wsh agent run` challenge, verify BEFORE accepting, and take `--require-operator-proof` and `--allow-operator`. **Sealed bridge and both signed `KeyExchange` halves: yes** (`wsh reverse-connect --sealed`; a host with an identity states `e2e` / `e2e-sign` / `e2e-sealed` in its `ReverseAccept` once it has proven the operator). The exchange is byte-identical to JS (transcripts compared against vectors printed by the JS code), hybrid X25519+ML-KEM-768 negotiated exactly as JS does, X25519 when the peer lists no ML-KEM key. A host started with `--require-operator-proof` REQUIRES the sealed bridge (the JS rule): until the key exists it hears and sends nothing but the key exchange, and drops a bridge that has not sealed in 10 s; an operator that does not seal gets no answer to its plain messages. Every message that would cross the relay travels as an `EncryptedFrame` on channel 0; a plain message (wrapped or not) is dropped; **a frame that does not open (tampered, replayed, reordered) closes the bridge** (stricter than the JS host, which drops the frame and ignores the rest). Not covered: a direct or pipe-relayed connection, and `GatewayData` outside a reverse bridge (#155) | **Wire-unified, negotiated** (`ReverseConnect.features`, `operator-proof`, `e2e-sealed`); both implementations seal a reverse bridge |
1545
1569
  | 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 |
1570
+ | 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) |
1546
1571
  | Pipe relay (#118) | `@johnhenry/wsh/pipe-relay` | operator side only (#145): `wsh --via wss://relay/r/<id> user@host command...` (also `connect`, `scp`, `ls`, `sftp`, `copy-id`), or the URL as the target. The host side of a pipe is not implemented in Rust, and the Rust client does not yet verify the host-key proof or bind the login to the host (see Security model) | **Deliberately a relay without wsh parsing** -- nothing to unify on the wire. `--via` keeps `user@host` as the identity: its key is recorded in `known_hosts` under `host:port` (what a direct connection uses), never under the relay's address; a URL target is recorded under the URL's own authority, i.e. the relay's. The URL is not saved to `last_session.json` (the id is a capability) |
1547
1572
  | `AuthOk.ttl` enforced, `token` opaque (#125) | `connectionTtlMs`; `client.authTtl` | `wsh-server` sends `ttl: 0` (no lifetime promised; `session_ttl` is the lifetime of a *detached* session) and an HMAC token that nothing accepts back | **Wire-compatible**: both fields are still sent (released peers require them). **Changed in the Rust server after `rust-v0.6.0`**: it used to send `session_ttl` (86400), which nothing enforced. The Rust client ignores `ttl` |
1548
1573
  | `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 |
@@ -1819,13 +1844,15 @@ What this does **not** protect against:
1819
1844
  JS host's, above): nothing is promised or enforced at connection level; do not
1820
1845
  treat the token as a credential.
1821
1846
  - **`wsh --via` (pipe relay from the Rust CLI) is the operator side only, and
1822
- still not sealed.** The Rust client now verifies the host-key proof
1847
+ still not sealed** (the sealed bridge of `wsh reverse-connect --sealed` covers
1848
+ reverse bridges only; #155 tracks sealing a direct or pipe-relayed connection and
1849
+ its gateway data). The Rust client now verifies the host-key proof
1823
1850
  (`host-key` / `host-key-sig` over its own `host-key-nonce`) before sending
1824
1851
  any credential, records only a PROVEN key in `known_hosts`, binds the login
1825
1852
  signature to that key (channel binding `host`), and refuses a changed key
1826
1853
  always. A replayed `ServerHello` or an impostor's key is refused as the JS
1827
1854
  client refuses it. What is still unprotected: the bridge is not sealed
1828
- end to end (the Rust side has no sealed bridge yet), so the relay sees
1855
+ end to end (a pipe-relayed session has no sealing layer yet, #155), so the relay sees
1829
1856
  session traffic in the clear unless the legs are TLS and it is trusted not
1830
1857
  to read them (it terminates each leg's TLS), and it can stamp an identity on
1831
1858
  a plain message after the handshake. A host with no host key proves nothing:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.38.1",
3
+ "version": "0.39.0",
4
4
  "description": "Web Shell \u2014 browser-native remote command execution over WebTransport and WebSocket with Ed25519 authentication",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -21,6 +21,7 @@ export const BRIDGE_CHANNEL_ID = 0;
21
21
 
22
22
  export class SealedBridge {
23
23
  #key;
24
+ #scope;
24
25
  #sessionId;
25
26
  #sendTag;
26
27
  #recvTag;
@@ -30,9 +31,13 @@ export class SealedBridge {
30
31
  #inChain = Promise.resolve();
31
32
 
32
33
  /**
33
- * @param {{ key: CryptoKey, sessionId: string, role: 'initiator' | 'responder' }} p - `initiator` is the operator
34
+ * @param {{ key: CryptoKey, sessionId: string, role: 'initiator' | 'responder', scope?: 'bridge' | 'session' }} p -
35
+ * `initiator` is the operator. `scope: 'session'` (#155) seals a whole direct or pipe-relayed connection, so any
36
+ * message may be inside a frame; the default, a bridge, accepts only what a relay may forward.
34
37
  */
35
- constructor({ key, sessionId, role }) {
38
+ constructor({ key, sessionId, role, scope = 'bridge' }) {
39
+ if (scope !== 'bridge' && scope !== 'session') throw new TypeError("SealedBridge: scope must be 'bridge' or 'session'");
40
+ this.#scope = scope;
36
41
  if (role !== 'initiator' && role !== 'responder') throw new TypeError("SealedBridge: role must be 'initiator' or 'responder'");
37
42
  this.#key = key;
38
43
  this.#sessionId = sessionId;
@@ -68,7 +73,7 @@ export class SealedBridge {
68
73
  const plain = await openFrame(this.#key, this.#sessionId, this.#recvCounter, { nonce: frame.nonce, ciphertext: frame.ciphertext, expectedRoleTag: this.#recvTag });
69
74
  this.#recvCounter += 1;
70
75
  const inner = cborDecode(plain);
71
- if (!inner || typeof inner.type !== 'number' || inner.type === MSG.RELAY_FORWARD || !isRelayForwardable(inner.type)) throw new Error('sealed message of a type that may not cross a bridge');
76
+ if (!inner || typeof inner.type !== 'number' || inner.type === MSG.RELAY_FORWARD || (this.#scope === 'bridge' && !isRelayForwardable(inner.type))) throw new Error('sealed message of a type that may not cross a bridge');
72
77
  return inner;
73
78
  });
74
79
  this.#inChain = run.catch(() => {});
@@ -151,7 +151,7 @@ export class E2EResponder {
151
151
 
152
152
  /**
153
153
  * @param {object} [opts]
154
- * @param {CryptoKey | null} [opts.signKey] - long-term Ed25519 private key; given, the reply is signed
154
+ * @param {CryptoKey | { sign: (data: Uint8Array) => Promise<Uint8Array> } | null} [opts.signKey] - long-term Ed25519 private key (or a signer); given, the reply is signed
155
155
  * @param {boolean} [opts.hybrid=true] - offer X25519+ML-KEM-768 when the initiator asks for it
156
156
  * @param {Uint8Array | null} [opts.identity] - this responder's raw 32-byte identity key (what an initiator signs as `responderIdentity`)
157
157
  * @param {{ publicKey: Uint8Array, require?: boolean } | null} [opts.initiator] - the operator's identity key, already
@@ -234,7 +234,9 @@ export class E2EResponder {
234
234
  kemPublicKey: localKem?.publicKey,
235
235
  };
236
236
  if (this.#sign) {
237
- reply.signature = await signBytes(this.#sign, keyExchangeTranscript({ sessionId, algorithm, initiatorKey: peerPub, responderKey: localPub }));
237
+ const transcript = keyExchangeTranscript({ sessionId, algorithm, initiatorKey: peerPub, responderKey: localPub });
238
+ // a CryptoKey, or a signer ({ sign }) such as a host key that is not extractable or lives elsewhere
239
+ reply.signature = typeof this.#sign.sign === 'function' ? await this.#sign.sign(transcript) : await signBytes(this.#sign, transcript);
238
240
  }
239
241
  await out(keyExchange(reply));
240
242
 
@@ -75,6 +75,8 @@ export interface WshMemoryHostOptions {
75
75
  * Needs `hostKey`; a client older than 0.36 cannot satisfy it.
76
76
  */
77
77
  requireChannelBinding?: boolean | Array<'host'>;
78
+ /** #155: seal the whole session end to end (needs `hostKey`; offered where `dataStreams` is false). `'require'` serves nothing unsealed. */
79
+ sealSession?: false | 'offer' | 'require';
78
80
  onLog?: (line: string) => void;
79
81
  }
80
82
 
@@ -140,6 +140,12 @@ function createRegistry(sessions, log) {
140
140
  * @param {{ operate: Function, readWhole: Function, writeWhole: Function, writeAt: Function, openRange?: Function, maxFileBytes?: number }} [options.fs]
141
141
  * File operations, as `createFileAccess` in `@johnhenry/wsh/server` returns them (see `normalizeFileBackend` in
142
142
  * `host-backends.mjs`). Not a root path: confining paths is the backend's job.
143
+ * @param {false | 'offer' | 'require'} [options.sealSession=false] - #155: seal the whole session end to end (needs `hostKey` and
144
+ * `dataStreams: false`, which is how a page host is served). A client that asks (a signed `KeyExchange` for the connection's
145
+ * session id, features `e2e-session`) gets every message after login -- gateway and endpoint data included -- as an
146
+ * authenticated encrypted frame, so a relay that only copies bytes (a pipe relay) can neither read nor alter it; a frame that
147
+ * does not open closes the session. `'offer'` serves a client that does not ask in the clear; `'require'` (advertised as
148
+ * `e2e-session-required`) serves nobody who has not sealed, and no password login. The keepalive stays plain.
143
149
  * @param {true | CryptoKeyPair | { publicKey: Uint8Array | CryptoKey, sign: Function }} [options.hostKey]
144
150
  * This host's own identity, so clients can pin it (TOFU): a `CryptoKeyPair` (non-extractable is fine), a signer
145
151
  * `{ publicKey, sign(data) }`, or `true` for a fresh non-extractable key.
@@ -172,13 +178,15 @@ function createRegistry(sessions, log) {
172
178
  * `true` or `['host']`.
173
179
  * @param {(line: string) => void} [options.onLog]
174
180
  */
175
- export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, endpoints, dataStreams = true, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, onLog = () => {} } = {}) {
181
+ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, endpoints, dataStreams = true, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, sealSession = false, onLog = () => {} } = {}) {
176
182
  if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createMemoryHost: connectionTtlMs must be a non-negative number');
177
183
  if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
178
184
  throw new TypeError(`createMemoryHost: requireChannelBinding must be true, false or an array of kinds (${CHANNEL_BINDING_KINDS.join(', ')})`);
179
185
  }
180
186
  if (Array.isArray(requireChannelBinding) && requireChannelBinding.some((k) => k !== 'host')) throw new TypeError('createMemoryHost: requireChannelBinding can name only "host" (a memory host has no TLS connection or certificate to bind)');
181
187
  if (requireChannelBinding && !hostKey) throw new TypeError('createMemoryHost: requireChannelBinding needs a hostKey (the only thing a memory host can bind a login to)');
188
+ if (sealSession !== false && sealSession !== 'offer' && sealSession !== 'require') throw new TypeError("createMemoryHost: sealSession must be false, 'offer' or 'require'");
189
+ if (sealSession && !hostKey) throw new TypeError('createMemoryHost: sealSession needs a hostKey (the host signs its half of the key exchange with it)');
182
190
  if (exec === true) throw new TypeError('createMemoryHost: exec must be a function (run(command, io)); there is no shell to run `true` with');
183
191
  if (exec !== undefined && typeof exec !== 'function' && typeof exec?.run !== 'function') {
184
192
  throw new TypeError('createMemoryHost: exec must be a function or { run }');
@@ -201,7 +209,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
201
209
  const gatewayCfg = endpoints === undefined || endpoints === null ? null : normalizeEndpointGateway({ endpoints });
202
210
 
203
211
  const ready = Promise.all([buildAuthorizer(auth), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
204
- authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, log: onLog,
212
+ authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
205
213
  methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost,
206
214
  gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
207
215
  }));
@@ -34,9 +34,14 @@ import { GATEWAY_DATAGRAM_FEATURE } from '../gateway-datagram.mjs';
34
34
  import { OPERATOR_PROOF_FEATURE } from '../operator-proof.mjs';
35
35
  import { clientEnvFilter } from './client-env.mjs';
36
36
  import { acceptableBindings, bindingFeatures } from '../channel-binding.mjs';
37
+ import { SealedBridge } from '../bridge-seal.mjs';
37
38
  import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMessage, toHex } from '../host-key.mjs';
38
39
 
39
40
  export const STREAM_ANNOUNCE = 'stream-announce';
41
+ /** Host feature (#155): this host seals the whole session end to end when asked (a signed `KeyExchange` for the connection's session id). */
42
+ export const SESSION_SEAL_FEATURE = 'e2e-session';
43
+ /** Host feature: this host serves nothing on a session that is not sealed. */
44
+ export const SESSION_SEAL_REQUIRED_FEATURE = 'e2e-session-required';
40
45
 
41
46
  /**
42
47
  * The features a host built from `cfg` advertises (`ServerHello.features`, minus the host-key proof).
@@ -58,6 +63,8 @@ export function hostFeatures(cfg, { dataStreams = true } = {}) {
58
63
  if (cfg.relay.maxOperatorsPerPeer > 1) features.push(MULTI_OPERATOR_FEATURE);
59
64
  }
60
65
  if (cfg.e2e && !dataStreams) features.push(E2E_FEATURE, ...(cfg.e2e.signKey ? [E2E_SIGN_FEATURE] : []));
66
+ // A sealed session (#155) needs the host's identity to sign its half, and no client-opened streams (their bytes are not frames).
67
+ if (cfg.sealSession && cfg.hostKey && !dataStreams) features.push(SESSION_SEAL_FEATURE, ...(cfg.sealSession === 'require' ? [SESSION_SEAL_REQUIRED_FEATURE] : []));
61
68
  if (cfg.rpc && dataStreams && cfg.rpc.protocols.size) {
62
69
  features.push(RPC_FEATURE, ...[...cfg.rpc.protocols.keys()].map(rpcProtocolFeature), RPC_MAX_MESSAGE_PREFIX + cfg.rpc.maxMessageBytes);
63
70
  }
@@ -155,6 +162,13 @@ export function createConnectionFactory(cfg) {
155
162
  /** Ends the connection at `connectionTtlMs` after authentication (#125). */
156
163
  let ttlTimer = null;
157
164
 
165
+ // A sealed session (#155): after login, a signed KeyExchange for this connection's session id seals everything
166
+ // that follows (control messages, gateway and endpoint data included) as EncryptedFrames on channel 0.
167
+ const sealOn = !!cfg.sealSession && !!cfg.hostKey && !dataStreams;
168
+ const sealRequired = sealOn && cfg.sealSession === 'require';
169
+ /** @type {{ bridge: SealedBridge | null, responder: E2EResponder | null }} */
170
+ const sealed = { bridge: null, responder: null };
171
+
158
172
  // The gateway needs Node sockets, so `gateway.mjs` is not imported here (a browser host must not pull it in):
159
173
  // the embedder that has them (`createWshServer`) passes `cfg.createGatewaySession` along with `cfg.gateway`; a
160
174
  // host in a page passes the endpoints-only session of `gateway-core.mjs` (`createMemoryHost({ endpoints })`).
@@ -198,6 +212,14 @@ export function createConnectionFactory(cfg) {
198
212
  };
199
213
 
200
214
  const deliver = (msg) => {
215
+ // Sealed: everything but the keepalive leaves as a frame, in the order it was sent (the bridge seals in call order).
216
+ if (sealed.bridge && msg.type !== MSG.PING && msg.type !== MSG.PONG) {
217
+ return sealed.bridge.seal(msg).then((frame) => deliverRaw(frame), (e) => { log(`could not seal: ${e.message}`); });
218
+ }
219
+ return deliverRaw(msg);
220
+ };
221
+
222
+ const deliverRaw = (msg) => {
201
223
  if (state.closed) return Promise.resolve();
202
224
  if (sendMessage) {
203
225
  try { return Promise.resolve(sendMessage(msg)).catch(() => {}); } catch { return Promise.resolve(); }
@@ -266,6 +288,11 @@ export function createConnectionFactory(cfg) {
266
288
  async function handle(m) {
267
289
  if (state.closed) return;
268
290
  if (!state.authed) return handleAuth(m);
291
+ if (sealOn) {
292
+ const inner = await sealedInput(m);
293
+ if (inner === undefined) return;
294
+ m = inner;
295
+ }
269
296
  if (await handleRelay(m)) return;
270
297
  if (gateway && await gateway.handle(m)) return;
271
298
  switch (m.type) {
@@ -363,6 +390,7 @@ export function createConnectionFactory(cfg) {
363
390
  } else {
364
391
  return refuse(`unsupported auth method ${JSON.stringify(method)}`);
365
392
  }
393
+ if (cfg.sealSession === 'require' && cfg.hostKey && !dataStreams && method !== 'pubkey') return refuse('this host requires a sealed session, which needs a key login');
366
394
  state.username = user;
367
395
  state.method = method;
368
396
  gateway?.setPeerFeatures(m.features);
@@ -438,12 +466,53 @@ export function createConnectionFactory(cfg) {
438
466
  if (!allowed) return refuse('key not authorized');
439
467
  state.authed = true;
440
468
  state.fingerprint = fp;
469
+ state.publicKey = m.public_key;
441
470
  state.nonce = null;
442
471
  await grantAuth();
443
472
  log(`authenticated ${state.username} (${fp.slice(0, 12)}...)`);
444
473
  }
445
474
  }
446
475
 
476
+ /**
477
+ * The sealed-session gate (#155) for a message from an authenticated peer: the message to handle, or undefined
478
+ * when it was consumed (the key exchange) or refused. A plain message is not heard once the session is sealed
479
+ * (a relay in the middle can inject any), and with `sealSession: 'require'` not before either.
480
+ */
481
+ async function sealedInput(m) {
482
+ if (sealed.bridge) {
483
+ if (m.type === MSG.PING) return m;
484
+ if (!sealed.bridge.isFrame(m)) { log(`dropped a plaintext message (type ${m.type}) on a sealed session`); return undefined; }
485
+ try { return await sealed.bridge.open(m); } catch (e) {
486
+ log(`a sealed frame did not open (${e.message}): closing the session`);
487
+ shutdown('sealed frame did not open');
488
+ return undefined;
489
+ }
490
+ }
491
+ if (m.type === MSG.KEY_EXCHANGE && m.session_id === state.sessionId) {
492
+ if (!state.publicKey) { log('sealed session refused: no login key to authenticate the initiator with'); shutdown('sealed session needs a key login'); return undefined; }
493
+ sealed.responder ??= new E2EResponder({
494
+ signKey: cfg.hostKey, hybrid: true, identity: cfg.hostKey.publicKey,
495
+ initiator: { publicKey: state.publicKey, require: true },
496
+ });
497
+ try {
498
+ const result = await sealed.responder.respond(m, (reply) => deliverRaw(reply));
499
+ if (result.key) {
500
+ sealed.bridge = new SealedBridge({ key: result.key, sessionId: state.sessionId, role: 'responder', scope: 'session' });
501
+ log(`session sealed${result.hybrid ? ' (hybrid)' : ''}`);
502
+ }
503
+ } catch (e) { log(`sealed session refused: ${e.message}`); shutdown('sealed session key exchange failed'); }
504
+ return undefined;
505
+ }
506
+ if (m.type === MSG.PING) return m;
507
+ if (sealRequired) {
508
+ log(`refused a plaintext message (type ${m.type}): this host requires a sealed session`);
509
+ await deliverRaw(errorMsg({ code: 1, message: 'this host requires a sealed session (e2e-session-required)' }));
510
+ setTimeout(() => shutdown('sealed session required'), 50);
511
+ return undefined;
512
+ }
513
+ return m;
514
+ }
515
+
447
516
  async function handlePasswordAuth(m) {
448
517
  state.awaitingPassword = false; // one guess per connection
449
518
  if (m.method !== 'password' || typeof m.password !== 'string') return refuse('expected a password AUTH');
@@ -86,6 +86,9 @@ function tlsChannelBinding(socket) {
86
86
  * @param {number} [options.bindTimeoutMs=3000]
87
87
  * @param {number} [options.connectionTtlMs=0] - End every authenticated connection this long after login (0 = never).
88
88
  * Advertised as `AuthOk.ttl` in whole seconds, rounded up; the client reads it as `client.authTtl`.
89
+ * @param {false | 'offer' | 'require'} [options.sealSession=false] - #155: seal a session end to end when the client asks (`e2e-session`); see
90
+ * `createMemoryHost`. Offered on connections accepted with `dataStreams: false` (a socket handed to `server.accept`); a
91
+ * byte-stream connection with QMux data streams is not sealed.
89
92
  * @param {boolean | string[]} [options.requireChannelBinding=false] - Accept a key login only when its signature is bound to
90
93
  * this connection (#119): `true` needs any binding kind, an array names kinds that must all be bound (`host` needs
91
94
  * `hostKey`; `tls-exporter` needs `wss://` served by this process, not a TLS-terminating proxy; `cert-hash` needs
@@ -94,8 +97,10 @@ function tlsChannelBinding(socket) {
94
97
  * @returns {{ listen(): Promise<{address: string, port: number}>, accept(socket: object, options?: object): Promise<{ close(): void }>, close(): Promise<void>, address(): ({address: string, port: number} | null) }}
95
98
  */
96
99
  export function createWshServer({
97
- host = '127.0.0.1', port = 0, tls, auth, exec, pty, fs, hostKey, mcp, rpc, rpcMaxMessageBytes, rpcMaxInflight, sessions, sessionSecret, relay, extensions, gateway, webTransport, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, onLog = () => {},
100
+ 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 = () => {},
98
101
  } = {}) {
102
+ if (sealSession !== false && sealSession !== 'offer' && sealSession !== 'require') throw new TypeError("createWshServer: sealSession must be false, 'offer' or 'require'");
103
+ if (sealSession && !hostKey) throw new TypeError('createWshServer: sealSession needs a hostKey (the host signs its half of the key exchange with it)');
99
104
  if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
100
105
  throw new TypeError(`createWshServer: requireChannelBinding must be true, false or an array of kinds (${CHANNEL_BINDING_KINDS.join(', ')})`);
101
106
  }
@@ -145,7 +150,7 @@ export function createWshServer({
145
150
  if (relay) hub = new RelayHub({ ...relay, log: onLog });
146
151
  if (extensions !== undefined && (extensions === null || typeof extensions !== 'object')) throw new TypeError('createWshServer: extensions must be an object of handlers');
147
152
  return createConnectionFactory({
148
- authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, log: onLog,
153
+ authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
149
154
  methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, createGatewaySession, sessions: registry, relay: hub,
150
155
  });
151
156
  })();