@johnhenry/wsh 0.36.0 → 0.38.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/src/client.mjs CHANGED
@@ -9,14 +9,15 @@
9
9
  */
10
10
 
11
11
  import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE } from './features.mjs';
12
- import { WebTransportTransport } from './transport.mjs';
12
+ import { WebTransportTransport, normalizeWebTransportOptions } from './transport.mjs';
13
+ import { clientChannelBinding, offeredKinds, TLS_EXPORTER_LABEL, TLS_EXPORTER_LENGTH } from './channel-binding.mjs';
13
14
  import { WebSocketTransport } from './transport-ws.mjs';
14
15
  import {
15
16
  MSG, AUTH_METHOD,
16
17
  hello, auth as authMsg, open as openMsg, close as closeMsg,
17
18
  attach as attachMsg, resume as resumeMsg, ping as pingMsg, pong as pongMsg,
18
19
  reverseRegister as reverseRegisterMsg, reverseList as reverseListMsg,
19
- reverseConnect as reverseConnectMsg, relayForward as relayForwardMsg,
20
+ reverseConnect as reverseConnectMsg, relayForward as relayForwardMsg, reverseProof as reverseProofMsg,
20
21
  mcpDiscover as mcpDiscoverMsg, mcpCall as mcpCallMsg, mcpCancel as mcpCancelMsg,
21
22
  suspendSession as suspendSessionMsg, restartPty as restartPtyMsg,
22
23
  metricsRequest as metricsRequestMsg,
@@ -40,8 +41,13 @@ import {
40
41
  } from './messages.mjs';
41
42
  import { resolveSigner, signChallengeWith, signPeerRecordWith, verifyPeerRecord, importPublicKeyRaw, fingerprint as computeFingerprint } from './auth.mjs';
42
43
  import { generateMlKemKeyPair, mlKemEncapsulate, mlKemDecapsulate } from './mlkem.mjs';
43
- import { compareBytes, combineHybridSecret, verifyKeyExchangeSignature } from './e2e-exchange.mjs';
44
+ import { compareBytes, combineHybridSecret, verifyKeyExchangeSignature, initiatorTranscript } from './e2e-exchange.mjs';
45
+ import { OPERATOR_PROOF_FEATURE, E2E_SEALED_FEATURE, verifyReverseChallenge, createOperatorProof } from './operator-proof.mjs';
46
+ import { SealedBridge } from './bridge-seal.mjs';
44
47
  import { WshSession } from './session.mjs';
48
+ import { GatewayConnections } from './gateway-client.mjs';
49
+ import { GATEWAY_CREDIT_FEATURE } from './gateway-channel.mjs';
50
+ import { GATEWAY_DATAGRAM_FEATURE } from './gateway-datagram.mjs';
45
51
  import { cborDecode, cborEncode } from './cbor.mjs';
46
52
  import {
47
53
  RpcChannel, RpcError, RPC_ERROR, RPC_FEATURE, RPC_PROTOCOL_NAME_RE, RPC_DEFAULT_MAX_MESSAGE,
@@ -205,6 +211,20 @@ async function pumpStdin(session, stdin) {
205
211
  await session.closeStdin();
206
212
  }
207
213
 
214
+ /**
215
+ * The single certificate hash a WebTransport connection was pinned to (`serverCertificateHashes`), or null: with
216
+ * several the browser does not say which one the server presented, so none is bound.
217
+ * @returns {Uint8Array | null}
218
+ */
219
+ function webTransportCertHash(webTransport) {
220
+ try {
221
+ const list = normalizeWebTransportOptions(webTransport)?.serverCertificateHashes;
222
+ if (list?.length !== 1 || list[0].algorithm !== 'sha-256') return null;
223
+ const v = list[0].value;
224
+ return v instanceof Uint8Array ? v : new Uint8Array(v);
225
+ } catch { return null; }
226
+ }
227
+
208
228
  export class WshClient {
209
229
 
210
230
  /** @type {'disconnected'|'connecting'|'connected'|'authenticated'|'closed'} */
@@ -226,12 +246,40 @@ export class WshClient {
226
246
  */
227
247
  #authToken = null;
228
248
 
249
+ /**
250
+ * `AuthOk.ttl`: how many seconds the host says it will keep this connection (it ends it then), `0` = no limit
251
+ * promised (#125).
252
+ */
253
+ #authTtl = 0;
254
+
229
255
  /** @type {import('./transport.mjs').WshTransport|null} Active transport. */
230
256
  #transport = null;
231
257
 
232
258
  /** @type {{fingerprint: string, publicKey: Uint8Array, openssh: string, status: string}|null} */
233
259
  #hostKey = null;
234
260
 
261
+ /** This login's signer, kept so `reverseConnect()` can prove the operator's identity to a peer (#117). */
262
+ #signer = null;
263
+
264
+ /** The username of the last login: what a ReverseProof claims. */
265
+ #loginUsername = '';
266
+
267
+ /** The peer that proved itself to this operator on its last reverseConnect, if any. */
268
+ #peerProof = null;
269
+
270
+ /**
271
+ * Set while a sealed reverse bridge is being set up or is up (#117): `{ sessionId, bridge }`, `bridge` null until
272
+ * the key exists. Everything a relay forwards to this operator is then dropped unless it is the key exchange (while
273
+ * pending) or a frame of the bridge (after).
274
+ */
275
+ #sealState = null;
276
+
277
+ /** The binding kinds the last login's signature covered (#119); empty when it was unbound. */
278
+ #channelBindingKinds = [];
279
+
280
+ /** The one certificate hash this connection was pinned to over WebTransport, if any (a `cert-hash` binding). */
281
+ #certHash = null;
282
+
235
283
  /**
236
284
  * Called with the host's verified key before any credential is sent.
237
285
  * Return `false` (or throw) to refuse the host. See `connect({ onHostKey })`.
@@ -314,6 +362,9 @@ export class WshClient {
314
362
  */
315
363
  #bridgedFeatures = null;
316
364
 
365
+ /** @type {GatewayConnections|null} Created by the first openUnix()/openEndpoint()/openTcp()/listenUnix(). */
366
+ #gateway = null;
367
+
317
368
  /** @type {number|null} Ping interval handle. */
318
369
  #pingTimer = null;
319
370
 
@@ -353,6 +404,13 @@ export class WshClient {
353
404
  */
354
405
  onReverseConnect = null;
355
406
 
407
+ /**
408
+ * Called when an operator's `ReverseProof` arrives, answering the `ReverseChallenge` this peer sent (reverse
409
+ * mode only, wsh #117). `createReverseHost` uses it; a hand-written handler pairs it with `operator-proof.mjs`.
410
+ * @type {function(object): void|null}
411
+ */
412
+ onReverseProof = null;
413
+
356
414
  /**
357
415
  * Called when a clipboard sync message arrives (OSC 52).
358
416
  * The default handler writes to navigator.clipboard automatically.
@@ -432,6 +490,15 @@ export class WshClient {
432
490
  return this.#authToken;
433
491
  }
434
492
 
493
+ /**
494
+ * Seconds the host said it will keep this connection (`AuthOk.ttl`), `0` when it promised no limit. A host that
495
+ * sets one ends the connection then (`createWshServer({ connectionTtlMs })`); reconnect to continue. Hosts older
496
+ * than 0.36 sent a fixed 3600 that nothing enforced.
497
+ */
498
+ get authTtl() {
499
+ return this.#authTtl;
500
+ }
501
+
435
502
  /** Read-only view of active sessions. */
436
503
  get sessions() {
437
504
  return new Map(this.#sessions);
@@ -524,9 +591,13 @@ export class WshClient {
524
591
  * @param {string} [opts.hostLabel] - Key under which `knownHosts` records
525
592
  * this host (default: the URL's `host:port`).
526
593
  * @param {Function} [opts.onHostKey] - Per-connect `onHostKey`.
594
+ * @param {boolean | string[]} [opts.requireChannelBinding] - Refuse to authenticate unless the signature can be bound
595
+ * to this connection (#119): `true` needs at least one binding kind (`host`, `cert-hash`, `tls-exporter`) that
596
+ * both the host offers and this client can supply; an array names kinds that must all be bound. Not for
597
+ * password auth (nothing is signed). Stops an intermediary from relaying a genuine challenge to the host.
527
598
  * @returns {Promise<string>} The server-assigned session ID
528
599
  */
529
- async connect(url, { username, keyPair, signer, password, transport: transportHint, webTransport, timeout = DEFAULT_AUTH_TIMEOUT, ...hostKeyOpts } = {}) {
600
+ async connect(url, { username, keyPair, signer, password, transport: transportHint, webTransport, timeout = DEFAULT_AUTH_TIMEOUT, requireChannelBinding = false, ...hostKeyOpts } = {}) {
530
601
  if (this.#state !== STATE_DISCONNECTED && this.#state !== STATE_CLOSED) {
531
602
  throw new Error(`Client already ${this.#state}`);
532
603
  }
@@ -534,16 +605,24 @@ export class WshClient {
534
605
  throw new Error('username is required');
535
606
  }
536
607
  const cred = await resolveSigner({ keyPair, signer });
608
+ this.#signer = cred;
609
+ this.#loginUsername = username;
537
610
  if (!cred && !password) {
538
611
  throw new Error('Either keyPair, signer or password is required for authentication');
539
612
  }
613
+ if (requireChannelBinding && !cred) throw new Error('requireChannelBinding needs a key: a password login signs nothing to bind');
540
614
 
541
615
  this.#state = STATE_CONNECTING;
616
+ this.#channelBindingKinds = [];
617
+ this.#certHash = null;
618
+ this.#sealState = null;
619
+ this.#peerProof = null;
542
620
  this.#sessions.clear();
543
621
  this.#channelCounter = 0;
544
622
  this.#waiters.clear();
545
623
  this.#sessionId = null;
546
624
  this.#authToken = null;
625
+ this.#authTtl = 0;
547
626
  this.#hostKey = null;
548
627
 
549
628
  try {
@@ -556,7 +635,7 @@ export class WshClient {
556
635
  const authMethod = cred ? AUTH_METHOD.PUBKEY : AUTH_METHOD.PASSWORD;
557
636
  const hostKeyNonce = newHostKeyNonce();
558
637
  await transport.sendControl(
559
- hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce] })
638
+ hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce, GATEWAY_CREDIT_FEATURE, ...(transport.supportsDatagrams ? [GATEWAY_DATAGRAM_FEATURE] : [])] })
560
639
  );
561
640
  const hostCtx = { ...hostKeyOpts, url, username, nonce: hostKeyNonce };
562
641
 
@@ -594,6 +673,7 @@ export class WshClient {
594
673
  // Server accepted without challenge (e.g. trusted key).
595
674
  this.#sessionId = challengeMsg.session_id || tempSessionId;
596
675
  this.#authToken = challengeMsg.token || null;
676
+ this.#authTtl = Number(challengeMsg.ttl) || 0;
597
677
  this.#state = STATE_AUTHENTICATED;
598
678
  this.#startPing();
599
679
  return this.#sessionId;
@@ -606,7 +686,7 @@ export class WshClient {
606
686
  cred,
607
687
  challengeMsg.session_id,
608
688
  challengeMsg.nonce,
609
- { username }
689
+ { username, channelBinding: await this.#bindingFor(this.#serverFeatures, requireChannelBinding) }
610
690
  );
611
691
 
612
692
  await transport.sendControl(
@@ -644,7 +724,7 @@ export class WshClient {
644
724
  cred,
645
725
  firstResponse.session_id,
646
726
  firstResponse.nonce,
647
- { username }
727
+ { username, channelBinding: await this.#bindingFor([], requireChannelBinding) }
648
728
  );
649
729
 
650
730
  await transport.sendControl(
@@ -669,6 +749,7 @@ export class WshClient {
669
749
 
670
750
  this.#sessionId = authResult.session_id || tempSessionId;
671
751
  this.#authToken = authResult.token || null;
752
+ this.#authTtl = Number(authResult.ttl) || 0;
672
753
  this.#state = STATE_AUTHENTICATED;
673
754
  this.#startPing();
674
755
 
@@ -1027,6 +1108,7 @@ export class WshClient {
1027
1108
  this.#stopPing();
1028
1109
  this.#state = STATE_CLOSED;
1029
1110
  this.#bridgedFeatures = null;
1111
+ this.#gateway?.abandonAll('client disconnected');
1030
1112
 
1031
1113
  // Close all sessions concurrently.
1032
1114
  const closePromises = [];
@@ -1185,6 +1267,8 @@ export class WshClient {
1185
1267
 
1186
1268
  // Export public key for peer identification.
1187
1269
  const cred = await resolveSigner({ keyPair, signer });
1270
+ this.#signer = cred;
1271
+ this.#loginUsername = username;
1188
1272
  let publicKey = null;
1189
1273
  if (cred) publicKey = cred.publicKeyRaw;
1190
1274
 
@@ -1279,23 +1363,95 @@ export class WshClient {
1279
1363
  * @param {number} [timeout=10000]
1280
1364
  * @returns {Promise<object>}
1281
1365
  */
1282
- async reverseConnect(targetFingerprint, timeout = DEFAULT_OPEN_TIMEOUT) {
1366
+ async reverseConnect(targetFingerprint, timeout = DEFAULT_OPEN_TIMEOUT, { proof = 'auto', requirePeerProof = false, sealed = false } = {}) {
1283
1367
  this.#assertAuthenticated('reverseConnect');
1284
1368
 
1285
- await this.#transport.sendControl(
1369
+ // Proving this operator's identity to the PEER (wsh #117) needs a relay that carries the challenge and a key to sign with.
1370
+ const relayCarriesProof = this.#serverFeatures.includes(OPERATOR_PROOF_FEATURE);
1371
+ const sealOpts = sealed === true ? {} : (sealed || null);
1372
+ if ((sealOpts || requirePeerProof || proof === true) && !relayCarriesProof) {
1373
+ throw new Error(`reverseConnect: this relay does not carry operator proof (no "${OPERATOR_PROOF_FEATURE}" in its features), so ${sealOpts ? 'a sealed bridge' : 'proof'} is not available -- nothing was sent`);
1374
+ }
1375
+ if ((sealOpts || requirePeerProof || proof === true) && !this.#signer) throw new Error('reverseConnect: proof needs a key login (a password login has nothing to sign with)');
1376
+ const offerProof = proof !== false && relayCarriesProof && !!this.#signer;
1377
+
1378
+ // A sealed bridge sends nothing that names a command, a path or a session before the key exists: from here on a
1379
+ // message the relay may forward is refused locally until the bridge key is in place.
1380
+ const transport = this.#transport;
1381
+ const plainSend = transport.sendControl.bind(transport);
1382
+ let bridge = null;
1383
+ let sealing = null; // { sessionId }
1384
+ if (sealOpts) {
1385
+ this.#sealState = { sessionId: null, bridge: null };
1386
+ transport.sendControl = async (msg) => {
1387
+ if (!isRelayForwardable(msg.type)) return plainSend(msg);
1388
+ if (bridge) return plainSend(await bridge.seal(msg));
1389
+ if (msg.type === MSG.KEY_EXCHANGE && sealing && msg.session_id === sealing.sessionId) return plainSend(msg);
1390
+ throw new Error('sealed bridge: nothing is sent over it before the key exists');
1391
+ };
1392
+ }
1393
+ const undoSealGate = () => { if (!bridge) { transport.sendControl = plainSend; this.#sealState = null; } };
1394
+
1395
+ let response = null;
1396
+ let challenge = null;
1397
+ try {
1398
+ const ownFingerprint = this.#signer ? await computeFingerprint(this.#signer.publicKeyRaw) : null;
1399
+ // Register before sending: the answer can follow the request closely.
1400
+ const first = this.#waitForMessage(
1401
+ [MSG.REVERSE_ACCEPT, MSG.REVERSE_REJECT, MSG.REVERSE_CHALLENGE],
1402
+ timeout,
1403
+ 'Timed out waiting for reverse-connect response'
1404
+ );
1405
+ first.catch(() => {});
1406
+ const connectMsg = reverseConnectMsg({ targetFingerprint, username: '', fromFingerprint: '' });
1407
+ if (offerProof) connectMsg.features = [OPERATOR_PROOF_FEATURE]; // only a relay that lists it may be sent the field
1286
1408
  // fromFingerprint is ignored by the server -- it overwrites it with
1287
1409
  // this connection's own authenticated fingerprint before forwarding.
1288
- reverseConnectMsg({ targetFingerprint, username: '', fromFingerprint: '' })
1289
- );
1410
+ await plainSend(connectMsg);
1411
+
1412
+ response = await first;
1413
+ challenge = null;
1414
+ if (response.type === MSG.REVERSE_CHALLENGE) {
1415
+ // The peer asks who is at this end. Verify it is the peer we asked for and that it saw OUR fingerprint
1416
+ // (a relay that rewrote from_fingerprint shows here), then answer; the answer names the peer, its nonce
1417
+ // and the bridge's session, so it is good for nothing else.
1418
+ const answer = this.#waitForMessage([MSG.REVERSE_ACCEPT, MSG.REVERSE_REJECT], timeout, 'Timed out waiting for reverse-connect response');
1419
+ answer.catch(() => {});
1420
+ try {
1421
+ challenge = await verifyReverseChallenge(response, { target: targetFingerprint, ownFingerprint });
1422
+ await plainSend(reverseProofMsg({ targetFingerprint: challenge.peerFingerprint, ...await createOperatorProof(this.#signer, challenge, this.#loginUsername) }));
1423
+ } catch (e) { answer.catch(() => {}); throw e; }
1424
+ response = await answer;
1425
+ }
1290
1426
 
1291
- const response = await this.#waitForMessage(
1292
- [MSG.REVERSE_ACCEPT, MSG.REVERSE_REJECT],
1293
- timeout,
1294
- 'Timed out waiting for reverse-connect response'
1295
- );
1427
+ if (response.type === MSG.REVERSE_ACCEPT) {
1428
+ if (requirePeerProof && !challenge) throw new Error('reverseConnect: the peer did not prove its identity (requirePeerProof) -- nothing was sent over the bridge');
1429
+ if (challenge && response.target_fingerprint !== challenge.peerFingerprint) throw new Error('reverseConnect: the relay named a different peer than the one that signed the challenge');
1430
+ if (sealOpts) {
1431
+ if (!challenge) throw new Error('reverseConnect: a sealed bridge needs the peer to answer with a challenge (does it require operator proof support?)');
1432
+ if (!(response.features ?? []).includes(E2E_SEALED_FEATURE)) throw new Error(`reverseConnect: the peer does not state "${E2E_SEALED_FEATURE}", so a sealed bridge is not available -- nothing was sent`);
1433
+ }
1434
+ this.trustRelayPeer(challenge?.peerFingerprint ?? response.target_fingerprint);
1435
+ if (sealOpts) {
1436
+ sealing = { sessionId: challenge.sessionId };
1437
+ this.#sealState = { sessionId: challenge.sessionId, bridge: null };
1438
+ const algorithm = sealOpts.hybrid === false ? 'X25519' : 'X25519+ML-KEM-768';
1439
+ const { sharedSecret } = await this.initiateE2E(challenge.sessionId, algorithm, timeout, {
1440
+ verifyPeer: challenge.peerPublicKey, signAs: this.#signer, responderIdentity: challenge.peerPublicKey,
1441
+ });
1442
+ bridge = new SealedBridge({ key: sharedSecret, sessionId: challenge.sessionId, role: 'initiator' });
1443
+ this.#sealState = { sessionId: challenge.sessionId, bridge };
1444
+ }
1445
+ this.#peerProof = challenge ? { peerFingerprint: challenge.peerFingerprint, sealed: !!sealOpts } : null;
1446
+ } else {
1447
+ undoSealGate();
1448
+ }
1449
+ } catch (e) {
1450
+ undoSealGate();
1451
+ throw e;
1452
+ }
1296
1453
 
1297
1454
  if (response.type === MSG.REVERSE_ACCEPT) {
1298
- this.trustRelayPeer(response.target_fingerprint);
1299
1455
  // The relay's SERVER_HELLO describes the relay, not the host behind the
1300
1456
  // bridge: when that host says what it supports, feature gates
1301
1457
  // (file-write, file-rename, mcp-call-id) follow it instead.
@@ -1362,6 +1518,99 @@ export class WshClient {
1362
1518
  await this.#transport.sendControl(msg);
1363
1519
  }
1364
1520
 
1521
+ // ── Gateway: unix sockets, named endpoints, TCP egress ──────────────
1522
+ // Streams with backpressure over the gateway messages (`gateway-unix`, `gateway-endpoints`, `gateway`; credit-based
1523
+ // flow control when both ends offer `gateway-credit`). See `gateway-client.mjs`.
1524
+
1525
+ #gw() {
1526
+ this.#assertAuthenticated('gateway');
1527
+ return (this.#gateway ??= new GatewayConnections({
1528
+ send: (m) => this.sendControl(m),
1529
+ hasFeature: (f) => this.hasFeature(f),
1530
+ // Datagrams for UDP flows: only on a transport that has them AND a host that listed "gateway-datagram".
1531
+ datagrams: () => {
1532
+ const t = this.#transport;
1533
+ return t?.supportsDatagrams && this.hasFeature(GATEWAY_DATAGRAM_FEATURE) ? { send: (b) => t.sendDatagram(b), maxSize: () => t.maxDatagramSize } : null;
1534
+ },
1535
+ }));
1536
+ }
1537
+
1538
+ /**
1539
+ * Connect to a unix-domain socket on the HOST (OpenSSH streamlocal), if the host's policy lists the path.
1540
+ * @param {string} path
1541
+ * @param {{ signal?: AbortSignal, timeoutMs?: number }} [opts]
1542
+ * @returns {Promise<import('./gateway-client.mjs').GatewayDuplex>} streams with backpressure; rejects with a `GatewayError` (`.code` 4 = refused by policy)
1543
+ */
1544
+ async openUnix(path, opts) { return this.#gw().openUnix(path, opts); }
1545
+
1546
+ /**
1547
+ * Open the host's named virtual endpoint `name` (a host with no file system exposes these instead of sockets).
1548
+ * @param {string} name
1549
+ * @param {{ signal?: AbortSignal, timeoutMs?: number }} [opts]
1550
+ */
1551
+ async openEndpoint(name, opts) { return this.#gw().openEndpoint(name, opts); }
1552
+
1553
+ /**
1554
+ * Connect to host:port FROM THE HOST (the gateway's TCP egress; refused unless the host's `gateway.allow` lists it).
1555
+ * @param {string} host @param {number} port
1556
+ * @param {{ signal?: AbortSignal, timeoutMs?: number }} [opts]
1557
+ */
1558
+ async openTcp(host, port, opts) { return this.#gw().openTcp(host, port, opts); }
1559
+
1560
+ /**
1561
+ * A UDP flow to ONE destination, host:port, FROM THE HOST (same destination policy as TCP). Each payload is one
1562
+ * datagram, which MAY BE DROPPED: over WebTransport, when the host lists "gateway-datagram", payloads travel as WebTransport
1563
+ * datagrams (unordered, not retransmitted, no head-of-line blocking against other flows); over WebSocket, or against a
1564
+ * host without the feature, they ride the reliable control stream (ordered, retransmitted, and the host still drops
1565
+ * what you cannot take fast enough). The result has `send(bytes) => Promise<boolean>`, `readable`, `writable`, `close()`,
1566
+ * `transport` ('datagram' | 'stream'), `maxDatagramSize` and `stats`; see `UdpFlow`.
1567
+ * @param {string} host @param {number} port
1568
+ * @param {{ signal?: AbortSignal, timeoutMs?: number, oversize?: 'reliable' | 'drop' }} [opts]
1569
+ * `oversize`: what to do with a payload that does not fit one datagram: 'reliable' (default) sends it on the control
1570
+ * stream, 'drop' makes `send()` reject with a RangeError.
1571
+ * @returns {Promise<import('./gateway-datagram.mjs').UdpFlow>}
1572
+ */
1573
+ async openUdp(host, port, opts) { return this.#gw().openUdp(host, port, opts); }
1574
+
1575
+ /**
1576
+ * Ask the HOST to listen on a TCP port (a reverse tunnel, OpenSSH `-R`) and hand each connection to `onConnection(duplex, { peer, peerPort })`.
1577
+ * Off unless the host's `gateway.reverse` is set; the host chooses the address it binds (loopback by default) and which ports are allowed.
1578
+ * @param {number} port 0 = any port the host's policy allows
1579
+ * @param {{ bindAddr?: string, onConnection: (duplex: import('./gateway-client.mjs').GatewayDuplex, info: { peer: string, peerPort: number }) => void, timeoutMs?: number }} opts
1580
+ * `bindAddr` is a request: the host ignores it unless its operator listed that address.
1581
+ * @returns {Promise<{ port: number, close: () => Promise<void> }>} `port` is the port the host bound
1582
+ */
1583
+ async listenTcp(port, opts) { return this.#gw().listenTcp(port, opts); }
1584
+
1585
+ /**
1586
+ * Ask the host to listen on a unix-domain socket (OpenSSH `-R /remote.sock:...`) and hand each connection to
1587
+ * `onConnection(duplex)`. The host creates the socket 0600 and removes it when the listener or the connection closes.
1588
+ * @param {string} path
1589
+ * @param {{ replace?: boolean, onConnection: (duplex: import('./gateway-client.mjs').GatewayDuplex) => void, timeoutMs?: number }} opts
1590
+ * @returns {Promise<{ path: string, close(): Promise<void> }>}
1591
+ */
1592
+ async listenUnix(path, opts) { return this.#gw().listenUnix(path, opts); }
1593
+
1594
+ /**
1595
+ * Node only: forward between a local endpoint and a remote one, like `ssh -L` / `ssh -R` with unix sockets mixed in.
1596
+ * `local` and `remote` are each a socket path (starts with "/" or "./") or `host:port`.
1597
+ * - `{ local: '/tmp/docker.sock', remote: '/var/run/docker.sock' }` listens locally and connects on the host.
1598
+ * - `{ local: '127.0.0.1:2375', remote: '/var/run/docker.sock' }` the same from a TCP port (`-L 127.0.0.1:2375:/var/run/docker.sock`).
1599
+ * - `{ local: '/tmp/x.sock', remote: 'db.internal:5432' }` the host's TCP egress, from a local socket.
1600
+ * - `{ reverse: true, remote: '/run/app.sock', local: '127.0.0.1:8080' }` the HOST listens on `remote` (a unix path) and
1601
+ * connections are made to `local` from here (`-R`).
1602
+ * @param {{ local: string, remote: string, reverse?: boolean, replace?: boolean, onError?: (err: Error) => void }} opts
1603
+ * @returns {Promise<{ local: string, remote: string, address?: object, close(): Promise<void> }>}
1604
+ */
1605
+ async forwardUnix(opts) {
1606
+ // The specifier is a variable on purpose: a bundler for the browser must not follow it into `node:net` / `node:fs`
1607
+ // (the browser-bundle test fails on a Node built-in). Node resolves it relative to this file as usual.
1608
+ const specifier = './forward-node.mjs';
1609
+ let mod;
1610
+ try { mod = await import(specifier); } catch (e) { throw new Error(`forwardUnix needs Node (${e?.message ?? e})`); }
1611
+ return mod.forward(this, opts);
1612
+ }
1613
+
1365
1614
  /**
1366
1615
  * Open a raw bidirectional stream on the underlying transport.
1367
1616
  *
@@ -1937,9 +2186,11 @@ export class WshClient {
1937
2186
  * @param {number} [timeout=10000]
1938
2187
  * @param {object} [opts]
1939
2188
  * @param {Uint8Array | CryptoKey} [opts.verifyPeer] - the peer's Ed25519 public key (raw 32 bytes or imported)
2189
+ * @param {{ sign: (data: Uint8Array) => Promise<Uint8Array> }} [opts.signAs] - sign this (initiator) half with the operator's key (`resolveSigner` shape); send only to a peer that stated `e2e-sealed`
2190
+ * @param {Uint8Array} [opts.responderIdentity] - the responder's raw identity key, bound into the initiator signature (default: `verifyPeer` when raw)
1940
2191
  * @returns {Promise<{sharedSecret: CryptoKey, peerPublicKey: Uint8Array, hybrid: boolean, peerAuthenticated: boolean}>}
1941
2192
  */
1942
- async initiateE2E(sessionId, algorithm = 'X25519', timeout = DEFAULT_OPEN_TIMEOUT, { verifyPeer } = {}) {
2193
+ async initiateE2E(sessionId, algorithm = 'X25519', timeout = DEFAULT_OPEN_TIMEOUT, { verifyPeer, signAs, responderIdentity } = {}) {
1943
2194
  this.#assertAuthenticated('initiateE2E');
1944
2195
  const wantHybrid = algorithm === 'X25519+ML-KEM-768';
1945
2196
 
@@ -1979,32 +2230,27 @@ export class WshClient {
1979
2230
  );
1980
2231
  const localKem = wantHybrid ? await generateMlKemKeyPair() : null;
1981
2232
 
2233
+ // The initiator signs its half too (wsh #117) when it has a signer and knows whom it is talking to: the host
2234
+ // verifies it against the operator key it proved, so neither ephemeral key can be swapped by the relay.
2235
+ let initiatorSignature;
2236
+ if (signAs) {
2237
+ const responder = responderIdentity ?? (verifyPeer instanceof Uint8Array ? verifyPeer : null);
2238
+ if (!responder) throw new TypeError('initiateE2E: signAs needs responderIdentity (or a raw verifyPeer key)');
2239
+ initiatorSignature = await signAs.sign(initiatorTranscript({ sessionId, algorithm, initiatorKey: localPub, responderIdentity: responder }));
2240
+ }
2241
+
1982
2242
  await this.#transport.sendControl(
1983
- keyExchangeMsg({ algorithm, publicKey: localPub, sessionId, kemPublicKey: localKem?.publicKey })
2243
+ keyExchangeMsg({ algorithm, publicKey: localPub, sessionId, kemPublicKey: localKem?.publicKey, signature: initiatorSignature })
1984
2244
  );
1985
2245
 
1986
2246
  const peerMsg = await peerMsgPromise;
1987
2247
 
1988
- let peerAuthenticated = false;
1989
- if (verifyPeer !== undefined) {
1990
- const ok = await verifyKeyExchangeSignature(verifyPeer, peerMsg.signature, {
1991
- sessionId, algorithm, initiatorKey: localPub, responderKey: new Uint8Array(peerMsg.public_key ?? []),
1992
- });
1993
- if (!ok) {
1994
- throw Object.assign(
1995
- new Error(peerMsg.signature === undefined
1996
- ? 'initiateE2E: the peer did not sign its key exchange (verifyPeer was given)'
1997
- : 'initiateE2E: the peer\'s key exchange signature does not verify against verifyPeer'),
1998
- { code: 'E2E_PEER_UNAUTHENTICATED' },
1999
- );
2000
- }
2001
- peerAuthenticated = true;
2002
- }
2003
-
2004
2248
  // Round 2 has the same shape as round 1, so it needs the same treatment.
2005
2249
  // Whether we encapsulate or decapsulate is decided entirely by data
2006
2250
  // already in hand, so decide it now and register the ciphertext waiter
2007
- // BEFORE the derive below. Registering it inside the `else` branch, after
2251
+ // BEFORE the signature check and the derive below (the check is async too: the ciphertext of a responder that
2252
+ // signs follows its reply at once, and was dropped while this side was still verifying -- a ~50% stall of a sealed
2253
+ // reverse bridge with a host in Chromium). Registering it inside the `else` branch, after
2008
2254
  // importKey and deriveBits, let the peer's ciphertext arrive while this
2009
2255
  // side was still deriving -- dropped, then a full-timeout wait for a
2010
2256
  // message already sent. That surfaced as "Timed out waiting for peer
@@ -2024,6 +2270,22 @@ export class WshClient {
2024
2270
  ctMsgPromise.catch(() => {});
2025
2271
  }
2026
2272
 
2273
+ let peerAuthenticated = false;
2274
+ if (verifyPeer !== undefined) {
2275
+ const ok = await verifyKeyExchangeSignature(verifyPeer, peerMsg.signature, {
2276
+ sessionId, algorithm, initiatorKey: localPub, responderKey: new Uint8Array(peerMsg.public_key ?? []),
2277
+ });
2278
+ if (!ok) {
2279
+ throw Object.assign(
2280
+ new Error(peerMsg.signature === undefined
2281
+ ? 'initiateE2E: the peer did not sign its key exchange (verifyPeer was given)'
2282
+ : 'initiateE2E: the peer\'s key exchange signature does not verify against verifyPeer'),
2283
+ { code: 'E2E_PEER_UNAUTHENTICATED' },
2284
+ );
2285
+ }
2286
+ peerAuthenticated = true;
2287
+ }
2288
+
2027
2289
  // Import peer's public key and derive the classical shared secret.
2028
2290
  const peerKey = await crypto.subtle.importKey(
2029
2291
  'raw',
@@ -2329,6 +2591,7 @@ export class WshClient {
2329
2591
  const transport = this.#createTransport(attempt.kind);
2330
2592
  try {
2331
2593
  await transport.connect(attempt.url, attempt.kind === 'wt' ? webTransport : undefined);
2594
+ this.#certHash = attempt.kind === 'wt' ? webTransportCertHash(webTransport) : null;
2332
2595
  this.#attachTransportHandlers(transport);
2333
2596
  return transport;
2334
2597
  } catch (err) {
@@ -2397,6 +2660,7 @@ export class WshClient {
2397
2660
  transport.onControl = (msg) => this.#handleControl(msg);
2398
2661
  transport.onClose = () => this.#handleTransportClose();
2399
2662
  transport.onError = (err) => this.#handleTransportError(err);
2663
+ transport.onDatagram = (bytes) => this.#gateway?.handleDatagram(bytes);
2400
2664
  }
2401
2665
 
2402
2666
  /**
@@ -2434,6 +2698,41 @@ export class WshClient {
2434
2698
  return this.#performAuth({ ...opts, url });
2435
2699
  }
2436
2700
 
2701
+ // ── Internal: channel binding (#119) ────────────────────────────────
2702
+
2703
+ /**
2704
+ * The channel binding for the login signature: every kind the host offers (`channel-binding:<kind>` in its
2705
+ * ServerHello) that this connection can supply. Throws when `required` and the result is not enough.
2706
+ * @param {string[]} serverFeatures - `[]` when the host sent no ServerHello
2707
+ * @param {boolean | string[]} required
2708
+ * @returns {Promise<Uint8Array>}
2709
+ */
2710
+ async #bindingFor(serverFeatures, required) {
2711
+ const exporter = this.#transport?.tlsExporter?.(TLS_EXPORTER_LABEL, TLS_EXPORTER_LENGTH) ?? null;
2712
+ const { binding, kinds } = await clientChannelBinding(serverFeatures, {
2713
+ host: this.#hostKey?.publicKey ?? null,
2714
+ 'cert-hash': this.#certHash,
2715
+ 'tls-exporter': exporter,
2716
+ });
2717
+ if (required) {
2718
+ const needed = Array.isArray(required) ? required : [];
2719
+ const missing = needed.filter((k) => !kinds.includes(k));
2720
+ if (kinds.length === 0 || missing.length) {
2721
+ const offered = offeredKinds(serverFeatures);
2722
+ throw new Error(
2723
+ `channel binding required but not available (host offers: ${offered.join(', ') || 'none'}; bound: ${kinds.join(', ') || 'none'}${missing.length ? `; missing: ${missing.join(', ')}` : ''}) -- nothing was signed`,
2724
+ );
2725
+ }
2726
+ }
2727
+ this.#channelBindingKinds = kinds;
2728
+ return binding;
2729
+ }
2730
+
2731
+ /** The binding kinds the login signature covered (`'host'`, `'cert-hash'`, `'tls-exporter'`); empty when unbound. */
2732
+ get channelBinding() {
2733
+ return [...this.#channelBindingKinds];
2734
+ }
2735
+
2437
2736
  // ── Internal: host key (TOFU / pinning) ─────────────────────────────
2438
2737
 
2439
2738
  /**
@@ -2537,16 +2836,20 @@ export class WshClient {
2537
2836
  * @returns {Promise<string>} Session ID
2538
2837
  * @private
2539
2838
  */
2540
- async #performAuth({ username, keyPair, signer, password, timeout = DEFAULT_AUTH_TIMEOUT, url, ...hostKeyOpts } = {}) {
2839
+ async #performAuth({ username, keyPair, signer, password, timeout = DEFAULT_AUTH_TIMEOUT, url, requireChannelBinding = false, ...hostKeyOpts } = {}) {
2541
2840
  if (!username) throw new Error('username is required');
2542
2841
  const cred = await resolveSigner({ keyPair, signer });
2842
+ this.#signer = cred;
2843
+ this.#loginUsername = username;
2543
2844
  if (!cred && !password) throw new Error('Either keyPair, signer or password is required');
2544
2845
 
2545
2846
  this.#hostKey = null;
2847
+ this.#channelBindingKinds = [];
2848
+ this.#certHash = null;
2546
2849
  try {
2547
2850
  const authMethod = cred ? AUTH_METHOD.PUBKEY : AUTH_METHOD.PASSWORD;
2548
2851
  const hostKeyNonce = newHostKeyNonce();
2549
- await this.#transport.sendControl(hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce] }));
2852
+ await this.#transport.sendControl(hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce, GATEWAY_CREDIT_FEATURE, ...(this.#transport.supportsDatagrams ? [GATEWAY_DATAGRAM_FEATURE] : [])] }));
2550
2853
  const hostCtx = { ...hostKeyOpts, url, username, nonce: hostKeyNonce };
2551
2854
 
2552
2855
  const firstResponse = await this.#waitForMessage(
@@ -2577,13 +2880,15 @@ export class WshClient {
2577
2880
  if (challengeMsg.type === MSG.AUTH_OK) {
2578
2881
  this.#sessionId = challengeMsg.session_id || tempSessionId;
2579
2882
  this.#authToken = challengeMsg.token || null;
2883
+ this.#authTtl = Number(challengeMsg.ttl) || 0;
2580
2884
  this.#state = STATE_AUTHENTICATED;
2581
2885
  this.#startPing();
2582
2886
  return this.#sessionId;
2583
2887
  }
2584
2888
 
2585
2889
  const { signature, publicKeyRaw } = await signChallengeWith(
2586
- cred, challengeMsg.session_id, challengeMsg.nonce, { username }
2890
+ cred, challengeMsg.session_id, challengeMsg.nonce,
2891
+ { username, channelBinding: await this.#bindingFor(this.#serverFeatures, requireChannelBinding) }
2587
2892
  );
2588
2893
 
2589
2894
  await this.#transport.sendControl(authMsg({
@@ -2604,7 +2909,8 @@ export class WshClient {
2604
2909
  // absent.
2605
2910
  tempSessionId = firstResponse.session_id;
2606
2911
  const { signature, publicKeyRaw } = await signChallengeWith(
2607
- cred, firstResponse.session_id, firstResponse.nonce, { username }
2912
+ cred, firstResponse.session_id, firstResponse.nonce,
2913
+ { username, channelBinding: await this.#bindingFor([], requireChannelBinding) }
2608
2914
  );
2609
2915
 
2610
2916
  await this.#transport.sendControl(authMsg({
@@ -2624,6 +2930,7 @@ export class WshClient {
2624
2930
 
2625
2931
  this.#sessionId = authResult.session_id || tempSessionId;
2626
2932
  this.#authToken = authResult.token || null;
2933
+ this.#authTtl = Number(authResult.ttl) || 0;
2627
2934
  this.#state = STATE_AUTHENTICATED;
2628
2935
  this.#startPing();
2629
2936
 
@@ -2670,6 +2977,22 @@ export class WshClient {
2670
2977
  console.warn('[wsh:client] dropping RelayForward wrapping a non-forwardable type:', inner.type);
2671
2978
  return;
2672
2979
  }
2980
+ // A sealed bridge (#117): from_fingerprint is whatever the relay stamped, so plain traffic proves nothing --
2981
+ // only the key exchange that sets the bridge up (while it is pending) and frames of the bridge are heard.
2982
+ const sealState = this.#sealState;
2983
+ if (sealState) {
2984
+ if (sealState.bridge?.isFrame(inner)) {
2985
+ sealState.bridge.open(inner)
2986
+ .then((opened) => this.#handleControl(opened, msg.from_fingerprint))
2987
+ .catch((err) => console.warn('[wsh:client] dropping a sealed frame:', err.message));
2988
+ return;
2989
+ }
2990
+ const setup = !sealState.bridge && inner.type === MSG.KEY_EXCHANGE && inner.session_id === sealState.sessionId;
2991
+ if (!setup) {
2992
+ console.warn('[wsh:client] dropping a plaintext message on a sealed bridge');
2993
+ return;
2994
+ }
2995
+ }
2673
2996
  this.#handleControl(inner, msg.from_fingerprint);
2674
2997
  return;
2675
2998
  }
@@ -2811,6 +3134,8 @@ export class WshClient {
2811
3134
 
2812
3135
  // Route gateway messages (0x70–0x7f) to the gateway handler.
2813
3136
  if (type >= 0x70 && type <= 0x7f) {
3137
+ // Connections opened through openUnix()/openEndpoint()/openTcp()/listenUnix() own their ids.
3138
+ if (this.#gateway?.handle(msg)) return;
2814
3139
  try {
2815
3140
  this.onGatewayMessage?.(msg);
2816
3141
  } catch (err) {
@@ -2882,6 +3207,14 @@ export class WshClient {
2882
3207
  }
2883
3208
  break;
2884
3209
 
3210
+ case MSG.REVERSE_PROOF:
3211
+ try {
3212
+ this.onReverseProof?.(msg);
3213
+ } catch (err) {
3214
+ console.error('[wsh:client] onReverseProof handler error:', err);
3215
+ }
3216
+ break;
3217
+
2885
3218
  case MSG.REVERSE_CONNECT:
2886
3219
  try {
2887
3220
  this.onReverseConnect?.(msg);
@@ -2959,6 +3292,7 @@ export class WshClient {
2959
3292
 
2960
3293
  this.#state = STATE_CLOSED;
2961
3294
  this.#bridgedFeatures = null;
3295
+ this.#gateway?.abandonAll('transport closed');
2962
3296
  this.#stopPing();
2963
3297
  this.#rejectAllWaiters(new Error('Transport closed'));
2964
3298