@johnhenry/wsh 0.36.0 → 0.37.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,12 @@ 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';
45
50
  import { cborDecode, cborEncode } from './cbor.mjs';
46
51
  import {
47
52
  RpcChannel, RpcError, RPC_ERROR, RPC_FEATURE, RPC_PROTOCOL_NAME_RE, RPC_DEFAULT_MAX_MESSAGE,
@@ -205,6 +210,20 @@ async function pumpStdin(session, stdin) {
205
210
  await session.closeStdin();
206
211
  }
207
212
 
213
+ /**
214
+ * The single certificate hash a WebTransport connection was pinned to (`serverCertificateHashes`), or null: with
215
+ * several the browser does not say which one the server presented, so none is bound.
216
+ * @returns {Uint8Array | null}
217
+ */
218
+ function webTransportCertHash(webTransport) {
219
+ try {
220
+ const list = normalizeWebTransportOptions(webTransport)?.serverCertificateHashes;
221
+ if (list?.length !== 1 || list[0].algorithm !== 'sha-256') return null;
222
+ const v = list[0].value;
223
+ return v instanceof Uint8Array ? v : new Uint8Array(v);
224
+ } catch { return null; }
225
+ }
226
+
208
227
  export class WshClient {
209
228
 
210
229
  /** @type {'disconnected'|'connecting'|'connected'|'authenticated'|'closed'} */
@@ -226,12 +245,40 @@ export class WshClient {
226
245
  */
227
246
  #authToken = null;
228
247
 
248
+ /**
249
+ * `AuthOk.ttl`: how many seconds the host says it will keep this connection (it ends it then), `0` = no limit
250
+ * promised (#125).
251
+ */
252
+ #authTtl = 0;
253
+
229
254
  /** @type {import('./transport.mjs').WshTransport|null} Active transport. */
230
255
  #transport = null;
231
256
 
232
257
  /** @type {{fingerprint: string, publicKey: Uint8Array, openssh: string, status: string}|null} */
233
258
  #hostKey = null;
234
259
 
260
+ /** This login's signer, kept so `reverseConnect()` can prove the operator's identity to a peer (#117). */
261
+ #signer = null;
262
+
263
+ /** The username of the last login: what a ReverseProof claims. */
264
+ #loginUsername = '';
265
+
266
+ /** The peer that proved itself to this operator on its last reverseConnect, if any. */
267
+ #peerProof = null;
268
+
269
+ /**
270
+ * Set while a sealed reverse bridge is being set up or is up (#117): `{ sessionId, bridge }`, `bridge` null until
271
+ * the key exists. Everything a relay forwards to this operator is then dropped unless it is the key exchange (while
272
+ * pending) or a frame of the bridge (after).
273
+ */
274
+ #sealState = null;
275
+
276
+ /** The binding kinds the last login's signature covered (#119); empty when it was unbound. */
277
+ #channelBindingKinds = [];
278
+
279
+ /** The one certificate hash this connection was pinned to over WebTransport, if any (a `cert-hash` binding). */
280
+ #certHash = null;
281
+
235
282
  /**
236
283
  * Called with the host's verified key before any credential is sent.
237
284
  * Return `false` (or throw) to refuse the host. See `connect({ onHostKey })`.
@@ -314,6 +361,9 @@ export class WshClient {
314
361
  */
315
362
  #bridgedFeatures = null;
316
363
 
364
+ /** @type {GatewayConnections|null} Created by the first openUnix()/openEndpoint()/openTcp()/listenUnix(). */
365
+ #gateway = null;
366
+
317
367
  /** @type {number|null} Ping interval handle. */
318
368
  #pingTimer = null;
319
369
 
@@ -353,6 +403,13 @@ export class WshClient {
353
403
  */
354
404
  onReverseConnect = null;
355
405
 
406
+ /**
407
+ * Called when an operator's `ReverseProof` arrives, answering the `ReverseChallenge` this peer sent (reverse
408
+ * mode only, wsh #117). `createReverseHost` uses it; a hand-written handler pairs it with `operator-proof.mjs`.
409
+ * @type {function(object): void|null}
410
+ */
411
+ onReverseProof = null;
412
+
356
413
  /**
357
414
  * Called when a clipboard sync message arrives (OSC 52).
358
415
  * The default handler writes to navigator.clipboard automatically.
@@ -432,6 +489,15 @@ export class WshClient {
432
489
  return this.#authToken;
433
490
  }
434
491
 
492
+ /**
493
+ * Seconds the host said it will keep this connection (`AuthOk.ttl`), `0` when it promised no limit. A host that
494
+ * sets one ends the connection then (`createWshServer({ connectionTtlMs })`); reconnect to continue. Hosts older
495
+ * than 0.36 sent a fixed 3600 that nothing enforced.
496
+ */
497
+ get authTtl() {
498
+ return this.#authTtl;
499
+ }
500
+
435
501
  /** Read-only view of active sessions. */
436
502
  get sessions() {
437
503
  return new Map(this.#sessions);
@@ -524,9 +590,13 @@ export class WshClient {
524
590
  * @param {string} [opts.hostLabel] - Key under which `knownHosts` records
525
591
  * this host (default: the URL's `host:port`).
526
592
  * @param {Function} [opts.onHostKey] - Per-connect `onHostKey`.
593
+ * @param {boolean | string[]} [opts.requireChannelBinding] - Refuse to authenticate unless the signature can be bound
594
+ * to this connection (#119): `true` needs at least one binding kind (`host`, `cert-hash`, `tls-exporter`) that
595
+ * both the host offers and this client can supply; an array names kinds that must all be bound. Not for
596
+ * password auth (nothing is signed). Stops an intermediary from relaying a genuine challenge to the host.
527
597
  * @returns {Promise<string>} The server-assigned session ID
528
598
  */
529
- async connect(url, { username, keyPair, signer, password, transport: transportHint, webTransport, timeout = DEFAULT_AUTH_TIMEOUT, ...hostKeyOpts } = {}) {
599
+ async connect(url, { username, keyPair, signer, password, transport: transportHint, webTransport, timeout = DEFAULT_AUTH_TIMEOUT, requireChannelBinding = false, ...hostKeyOpts } = {}) {
530
600
  if (this.#state !== STATE_DISCONNECTED && this.#state !== STATE_CLOSED) {
531
601
  throw new Error(`Client already ${this.#state}`);
532
602
  }
@@ -534,16 +604,24 @@ export class WshClient {
534
604
  throw new Error('username is required');
535
605
  }
536
606
  const cred = await resolveSigner({ keyPair, signer });
607
+ this.#signer = cred;
608
+ this.#loginUsername = username;
537
609
  if (!cred && !password) {
538
610
  throw new Error('Either keyPair, signer or password is required for authentication');
539
611
  }
612
+ if (requireChannelBinding && !cred) throw new Error('requireChannelBinding needs a key: a password login signs nothing to bind');
540
613
 
541
614
  this.#state = STATE_CONNECTING;
615
+ this.#channelBindingKinds = [];
616
+ this.#certHash = null;
617
+ this.#sealState = null;
618
+ this.#peerProof = null;
542
619
  this.#sessions.clear();
543
620
  this.#channelCounter = 0;
544
621
  this.#waiters.clear();
545
622
  this.#sessionId = null;
546
623
  this.#authToken = null;
624
+ this.#authTtl = 0;
547
625
  this.#hostKey = null;
548
626
 
549
627
  try {
@@ -556,7 +634,7 @@ export class WshClient {
556
634
  const authMethod = cred ? AUTH_METHOD.PUBKEY : AUTH_METHOD.PASSWORD;
557
635
  const hostKeyNonce = newHostKeyNonce();
558
636
  await transport.sendControl(
559
- hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce] })
637
+ hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce, GATEWAY_CREDIT_FEATURE] })
560
638
  );
561
639
  const hostCtx = { ...hostKeyOpts, url, username, nonce: hostKeyNonce };
562
640
 
@@ -594,6 +672,7 @@ export class WshClient {
594
672
  // Server accepted without challenge (e.g. trusted key).
595
673
  this.#sessionId = challengeMsg.session_id || tempSessionId;
596
674
  this.#authToken = challengeMsg.token || null;
675
+ this.#authTtl = Number(challengeMsg.ttl) || 0;
597
676
  this.#state = STATE_AUTHENTICATED;
598
677
  this.#startPing();
599
678
  return this.#sessionId;
@@ -606,7 +685,7 @@ export class WshClient {
606
685
  cred,
607
686
  challengeMsg.session_id,
608
687
  challengeMsg.nonce,
609
- { username }
688
+ { username, channelBinding: await this.#bindingFor(this.#serverFeatures, requireChannelBinding) }
610
689
  );
611
690
 
612
691
  await transport.sendControl(
@@ -644,7 +723,7 @@ export class WshClient {
644
723
  cred,
645
724
  firstResponse.session_id,
646
725
  firstResponse.nonce,
647
- { username }
726
+ { username, channelBinding: await this.#bindingFor([], requireChannelBinding) }
648
727
  );
649
728
 
650
729
  await transport.sendControl(
@@ -669,6 +748,7 @@ export class WshClient {
669
748
 
670
749
  this.#sessionId = authResult.session_id || tempSessionId;
671
750
  this.#authToken = authResult.token || null;
751
+ this.#authTtl = Number(authResult.ttl) || 0;
672
752
  this.#state = STATE_AUTHENTICATED;
673
753
  this.#startPing();
674
754
 
@@ -1027,6 +1107,7 @@ export class WshClient {
1027
1107
  this.#stopPing();
1028
1108
  this.#state = STATE_CLOSED;
1029
1109
  this.#bridgedFeatures = null;
1110
+ this.#gateway?.abandonAll('client disconnected');
1030
1111
 
1031
1112
  // Close all sessions concurrently.
1032
1113
  const closePromises = [];
@@ -1185,6 +1266,8 @@ export class WshClient {
1185
1266
 
1186
1267
  // Export public key for peer identification.
1187
1268
  const cred = await resolveSigner({ keyPair, signer });
1269
+ this.#signer = cred;
1270
+ this.#loginUsername = username;
1188
1271
  let publicKey = null;
1189
1272
  if (cred) publicKey = cred.publicKeyRaw;
1190
1273
 
@@ -1279,23 +1362,95 @@ export class WshClient {
1279
1362
  * @param {number} [timeout=10000]
1280
1363
  * @returns {Promise<object>}
1281
1364
  */
1282
- async reverseConnect(targetFingerprint, timeout = DEFAULT_OPEN_TIMEOUT) {
1365
+ async reverseConnect(targetFingerprint, timeout = DEFAULT_OPEN_TIMEOUT, { proof = 'auto', requirePeerProof = false, sealed = false } = {}) {
1283
1366
  this.#assertAuthenticated('reverseConnect');
1284
1367
 
1285
- await this.#transport.sendControl(
1368
+ // Proving this operator's identity to the PEER (wsh #117) needs a relay that carries the challenge and a key to sign with.
1369
+ const relayCarriesProof = this.#serverFeatures.includes(OPERATOR_PROOF_FEATURE);
1370
+ const sealOpts = sealed === true ? {} : (sealed || null);
1371
+ if ((sealOpts || requirePeerProof || proof === true) && !relayCarriesProof) {
1372
+ 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`);
1373
+ }
1374
+ if ((sealOpts || requirePeerProof || proof === true) && !this.#signer) throw new Error('reverseConnect: proof needs a key login (a password login has nothing to sign with)');
1375
+ const offerProof = proof !== false && relayCarriesProof && !!this.#signer;
1376
+
1377
+ // A sealed bridge sends nothing that names a command, a path or a session before the key exists: from here on a
1378
+ // message the relay may forward is refused locally until the bridge key is in place.
1379
+ const transport = this.#transport;
1380
+ const plainSend = transport.sendControl.bind(transport);
1381
+ let bridge = null;
1382
+ let sealing = null; // { sessionId }
1383
+ if (sealOpts) {
1384
+ this.#sealState = { sessionId: null, bridge: null };
1385
+ transport.sendControl = async (msg) => {
1386
+ if (!isRelayForwardable(msg.type)) return plainSend(msg);
1387
+ if (bridge) return plainSend(await bridge.seal(msg));
1388
+ if (msg.type === MSG.KEY_EXCHANGE && sealing && msg.session_id === sealing.sessionId) return plainSend(msg);
1389
+ throw new Error('sealed bridge: nothing is sent over it before the key exists');
1390
+ };
1391
+ }
1392
+ const undoSealGate = () => { if (!bridge) { transport.sendControl = plainSend; this.#sealState = null; } };
1393
+
1394
+ let response = null;
1395
+ let challenge = null;
1396
+ try {
1397
+ const ownFingerprint = this.#signer ? await computeFingerprint(this.#signer.publicKeyRaw) : null;
1398
+ // Register before sending: the answer can follow the request closely.
1399
+ const first = this.#waitForMessage(
1400
+ [MSG.REVERSE_ACCEPT, MSG.REVERSE_REJECT, MSG.REVERSE_CHALLENGE],
1401
+ timeout,
1402
+ 'Timed out waiting for reverse-connect response'
1403
+ );
1404
+ first.catch(() => {});
1405
+ const connectMsg = reverseConnectMsg({ targetFingerprint, username: '', fromFingerprint: '' });
1406
+ if (offerProof) connectMsg.features = [OPERATOR_PROOF_FEATURE]; // only a relay that lists it may be sent the field
1286
1407
  // fromFingerprint is ignored by the server -- it overwrites it with
1287
1408
  // this connection's own authenticated fingerprint before forwarding.
1288
- reverseConnectMsg({ targetFingerprint, username: '', fromFingerprint: '' })
1289
- );
1409
+ await plainSend(connectMsg);
1410
+
1411
+ response = await first;
1412
+ challenge = null;
1413
+ if (response.type === MSG.REVERSE_CHALLENGE) {
1414
+ // The peer asks who is at this end. Verify it is the peer we asked for and that it saw OUR fingerprint
1415
+ // (a relay that rewrote from_fingerprint shows here), then answer; the answer names the peer, its nonce
1416
+ // and the bridge's session, so it is good for nothing else.
1417
+ const answer = this.#waitForMessage([MSG.REVERSE_ACCEPT, MSG.REVERSE_REJECT], timeout, 'Timed out waiting for reverse-connect response');
1418
+ answer.catch(() => {});
1419
+ try {
1420
+ challenge = await verifyReverseChallenge(response, { target: targetFingerprint, ownFingerprint });
1421
+ await plainSend(reverseProofMsg({ targetFingerprint: challenge.peerFingerprint, ...await createOperatorProof(this.#signer, challenge, this.#loginUsername) }));
1422
+ } catch (e) { answer.catch(() => {}); throw e; }
1423
+ response = await answer;
1424
+ }
1290
1425
 
1291
- const response = await this.#waitForMessage(
1292
- [MSG.REVERSE_ACCEPT, MSG.REVERSE_REJECT],
1293
- timeout,
1294
- 'Timed out waiting for reverse-connect response'
1295
- );
1426
+ if (response.type === MSG.REVERSE_ACCEPT) {
1427
+ if (requirePeerProof && !challenge) throw new Error('reverseConnect: the peer did not prove its identity (requirePeerProof) -- nothing was sent over the bridge');
1428
+ if (challenge && response.target_fingerprint !== challenge.peerFingerprint) throw new Error('reverseConnect: the relay named a different peer than the one that signed the challenge');
1429
+ if (sealOpts) {
1430
+ if (!challenge) throw new Error('reverseConnect: a sealed bridge needs the peer to answer with a challenge (does it require operator proof support?)');
1431
+ 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`);
1432
+ }
1433
+ this.trustRelayPeer(challenge?.peerFingerprint ?? response.target_fingerprint);
1434
+ if (sealOpts) {
1435
+ sealing = { sessionId: challenge.sessionId };
1436
+ this.#sealState = { sessionId: challenge.sessionId, bridge: null };
1437
+ const algorithm = sealOpts.hybrid === false ? 'X25519' : 'X25519+ML-KEM-768';
1438
+ const { sharedSecret } = await this.initiateE2E(challenge.sessionId, algorithm, timeout, {
1439
+ verifyPeer: challenge.peerPublicKey, signAs: this.#signer, responderIdentity: challenge.peerPublicKey,
1440
+ });
1441
+ bridge = new SealedBridge({ key: sharedSecret, sessionId: challenge.sessionId, role: 'initiator' });
1442
+ this.#sealState = { sessionId: challenge.sessionId, bridge };
1443
+ }
1444
+ this.#peerProof = challenge ? { peerFingerprint: challenge.peerFingerprint, sealed: !!sealOpts } : null;
1445
+ } else {
1446
+ undoSealGate();
1447
+ }
1448
+ } catch (e) {
1449
+ undoSealGate();
1450
+ throw e;
1451
+ }
1296
1452
 
1297
1453
  if (response.type === MSG.REVERSE_ACCEPT) {
1298
- this.trustRelayPeer(response.target_fingerprint);
1299
1454
  // The relay's SERVER_HELLO describes the relay, not the host behind the
1300
1455
  // bridge: when that host says what it supports, feature gates
1301
1456
  // (file-write, file-rename, mcp-call-id) follow it instead.
@@ -1362,6 +1517,75 @@ export class WshClient {
1362
1517
  await this.#transport.sendControl(msg);
1363
1518
  }
1364
1519
 
1520
+ // ── Gateway: unix sockets, named endpoints, TCP egress ──────────────
1521
+ // Streams with backpressure over the gateway messages (`gateway-unix`, `gateway-endpoints`, `gateway`; credit-based
1522
+ // flow control when both ends offer `gateway-credit`). See `gateway-client.mjs`.
1523
+
1524
+ #gw() {
1525
+ this.#assertAuthenticated('gateway');
1526
+ return (this.#gateway ??= new GatewayConnections({ send: (m) => this.sendControl(m), hasFeature: (f) => this.hasFeature(f) }));
1527
+ }
1528
+
1529
+ /**
1530
+ * Connect to a unix-domain socket on the HOST (OpenSSH streamlocal), if the host's policy lists the path.
1531
+ * @param {string} path
1532
+ * @param {{ signal?: AbortSignal, timeoutMs?: number }} [opts]
1533
+ * @returns {Promise<import('./gateway-client.mjs').GatewayDuplex>} streams with backpressure; rejects with a `GatewayError` (`.code` 4 = refused by policy)
1534
+ */
1535
+ async openUnix(path, opts) { return this.#gw().openUnix(path, opts); }
1536
+
1537
+ /**
1538
+ * Open the host's named virtual endpoint `name` (a host with no file system exposes these instead of sockets).
1539
+ * @param {string} name
1540
+ * @param {{ signal?: AbortSignal, timeoutMs?: number }} [opts]
1541
+ */
1542
+ async openEndpoint(name, opts) { return this.#gw().openEndpoint(name, opts); }
1543
+
1544
+ /**
1545
+ * Connect to host:port FROM THE HOST (the gateway's TCP egress; refused unless the host's `gateway.allow` lists it).
1546
+ * @param {string} host @param {number} port
1547
+ * @param {{ signal?: AbortSignal, timeoutMs?: number }} [opts]
1548
+ */
1549
+ async openTcp(host, port, opts) { return this.#gw().openTcp(host, port, opts); }
1550
+
1551
+ /**
1552
+ * A UDP flow to host:port FROM THE HOST over the reliable control stream: each chunk written or read is one datagram
1553
+ * (at most 65507 bytes), so it is ordered and retransmitted (WebTransport datagrams are not used yet), and datagrams the
1554
+ * receiver cannot keep up with are dropped by the host. Same destination policy as TCP.
1555
+ * @param {string} host @param {number} port
1556
+ * @param {{ signal?: AbortSignal, timeoutMs?: number }} [opts]
1557
+ */
1558
+ async openUdp(host, port, opts) { return this.#gw().openUdp(host, port, opts); }
1559
+
1560
+ /**
1561
+ * Ask the host to listen on a unix-domain socket (OpenSSH `-R /remote.sock:...`) and hand each connection to
1562
+ * `onConnection(duplex)`. The host creates the socket 0600 and removes it when the listener or the connection closes.
1563
+ * @param {string} path
1564
+ * @param {{ replace?: boolean, onConnection: (duplex: import('./gateway-client.mjs').GatewayDuplex) => void, timeoutMs?: number }} opts
1565
+ * @returns {Promise<{ path: string, close(): Promise<void> }>}
1566
+ */
1567
+ async listenUnix(path, opts) { return this.#gw().listenUnix(path, opts); }
1568
+
1569
+ /**
1570
+ * Node only: forward between a local endpoint and a remote one, like `ssh -L` / `ssh -R` with unix sockets mixed in.
1571
+ * `local` and `remote` are each a socket path (starts with "/" or "./") or `host:port`.
1572
+ * - `{ local: '/tmp/docker.sock', remote: '/var/run/docker.sock' }` listens locally and connects on the host.
1573
+ * - `{ 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`).
1574
+ * - `{ local: '/tmp/x.sock', remote: 'db.internal:5432' }` the host's TCP egress, from a local socket.
1575
+ * - `{ reverse: true, remote: '/run/app.sock', local: '127.0.0.1:8080' }` the HOST listens on `remote` (a unix path) and
1576
+ * connections are made to `local` from here (`-R`).
1577
+ * @param {{ local: string, remote: string, reverse?: boolean, replace?: boolean, onError?: (err: Error) => void }} opts
1578
+ * @returns {Promise<{ local: string, remote: string, address?: object, close(): Promise<void> }>}
1579
+ */
1580
+ async forwardUnix(opts) {
1581
+ // The specifier is a variable on purpose: a bundler for the browser must not follow it into `node:net` / `node:fs`
1582
+ // (the browser-bundle test fails on a Node built-in). Node resolves it relative to this file as usual.
1583
+ const specifier = './forward-node.mjs';
1584
+ let mod;
1585
+ try { mod = await import(specifier); } catch (e) { throw new Error(`forwardUnix needs Node (${e?.message ?? e})`); }
1586
+ return mod.forward(this, opts);
1587
+ }
1588
+
1365
1589
  /**
1366
1590
  * Open a raw bidirectional stream on the underlying transport.
1367
1591
  *
@@ -1937,9 +2161,11 @@ export class WshClient {
1937
2161
  * @param {number} [timeout=10000]
1938
2162
  * @param {object} [opts]
1939
2163
  * @param {Uint8Array | CryptoKey} [opts.verifyPeer] - the peer's Ed25519 public key (raw 32 bytes or imported)
2164
+ * @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`
2165
+ * @param {Uint8Array} [opts.responderIdentity] - the responder's raw identity key, bound into the initiator signature (default: `verifyPeer` when raw)
1940
2166
  * @returns {Promise<{sharedSecret: CryptoKey, peerPublicKey: Uint8Array, hybrid: boolean, peerAuthenticated: boolean}>}
1941
2167
  */
1942
- async initiateE2E(sessionId, algorithm = 'X25519', timeout = DEFAULT_OPEN_TIMEOUT, { verifyPeer } = {}) {
2168
+ async initiateE2E(sessionId, algorithm = 'X25519', timeout = DEFAULT_OPEN_TIMEOUT, { verifyPeer, signAs, responderIdentity } = {}) {
1943
2169
  this.#assertAuthenticated('initiateE2E');
1944
2170
  const wantHybrid = algorithm === 'X25519+ML-KEM-768';
1945
2171
 
@@ -1979,32 +2205,27 @@ export class WshClient {
1979
2205
  );
1980
2206
  const localKem = wantHybrid ? await generateMlKemKeyPair() : null;
1981
2207
 
2208
+ // The initiator signs its half too (wsh #117) when it has a signer and knows whom it is talking to: the host
2209
+ // verifies it against the operator key it proved, so neither ephemeral key can be swapped by the relay.
2210
+ let initiatorSignature;
2211
+ if (signAs) {
2212
+ const responder = responderIdentity ?? (verifyPeer instanceof Uint8Array ? verifyPeer : null);
2213
+ if (!responder) throw new TypeError('initiateE2E: signAs needs responderIdentity (or a raw verifyPeer key)');
2214
+ initiatorSignature = await signAs.sign(initiatorTranscript({ sessionId, algorithm, initiatorKey: localPub, responderIdentity: responder }));
2215
+ }
2216
+
1982
2217
  await this.#transport.sendControl(
1983
- keyExchangeMsg({ algorithm, publicKey: localPub, sessionId, kemPublicKey: localKem?.publicKey })
2218
+ keyExchangeMsg({ algorithm, publicKey: localPub, sessionId, kemPublicKey: localKem?.publicKey, signature: initiatorSignature })
1984
2219
  );
1985
2220
 
1986
2221
  const peerMsg = await peerMsgPromise;
1987
2222
 
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
2223
  // Round 2 has the same shape as round 1, so it needs the same treatment.
2005
2224
  // Whether we encapsulate or decapsulate is decided entirely by data
2006
2225
  // already in hand, so decide it now and register the ciphertext waiter
2007
- // BEFORE the derive below. Registering it inside the `else` branch, after
2226
+ // BEFORE the signature check and the derive below (the check is async too: the ciphertext of a responder that
2227
+ // signs follows its reply at once, and was dropped while this side was still verifying -- a ~50% stall of a sealed
2228
+ // reverse bridge with a host in Chromium). Registering it inside the `else` branch, after
2008
2229
  // importKey and deriveBits, let the peer's ciphertext arrive while this
2009
2230
  // side was still deriving -- dropped, then a full-timeout wait for a
2010
2231
  // message already sent. That surfaced as "Timed out waiting for peer
@@ -2024,6 +2245,22 @@ export class WshClient {
2024
2245
  ctMsgPromise.catch(() => {});
2025
2246
  }
2026
2247
 
2248
+ let peerAuthenticated = false;
2249
+ if (verifyPeer !== undefined) {
2250
+ const ok = await verifyKeyExchangeSignature(verifyPeer, peerMsg.signature, {
2251
+ sessionId, algorithm, initiatorKey: localPub, responderKey: new Uint8Array(peerMsg.public_key ?? []),
2252
+ });
2253
+ if (!ok) {
2254
+ throw Object.assign(
2255
+ new Error(peerMsg.signature === undefined
2256
+ ? 'initiateE2E: the peer did not sign its key exchange (verifyPeer was given)'
2257
+ : 'initiateE2E: the peer\'s key exchange signature does not verify against verifyPeer'),
2258
+ { code: 'E2E_PEER_UNAUTHENTICATED' },
2259
+ );
2260
+ }
2261
+ peerAuthenticated = true;
2262
+ }
2263
+
2027
2264
  // Import peer's public key and derive the classical shared secret.
2028
2265
  const peerKey = await crypto.subtle.importKey(
2029
2266
  'raw',
@@ -2329,6 +2566,7 @@ export class WshClient {
2329
2566
  const transport = this.#createTransport(attempt.kind);
2330
2567
  try {
2331
2568
  await transport.connect(attempt.url, attempt.kind === 'wt' ? webTransport : undefined);
2569
+ this.#certHash = attempt.kind === 'wt' ? webTransportCertHash(webTransport) : null;
2332
2570
  this.#attachTransportHandlers(transport);
2333
2571
  return transport;
2334
2572
  } catch (err) {
@@ -2434,6 +2672,41 @@ export class WshClient {
2434
2672
  return this.#performAuth({ ...opts, url });
2435
2673
  }
2436
2674
 
2675
+ // ── Internal: channel binding (#119) ────────────────────────────────
2676
+
2677
+ /**
2678
+ * The channel binding for the login signature: every kind the host offers (`channel-binding:<kind>` in its
2679
+ * ServerHello) that this connection can supply. Throws when `required` and the result is not enough.
2680
+ * @param {string[]} serverFeatures - `[]` when the host sent no ServerHello
2681
+ * @param {boolean | string[]} required
2682
+ * @returns {Promise<Uint8Array>}
2683
+ */
2684
+ async #bindingFor(serverFeatures, required) {
2685
+ const exporter = this.#transport?.tlsExporter?.(TLS_EXPORTER_LABEL, TLS_EXPORTER_LENGTH) ?? null;
2686
+ const { binding, kinds } = await clientChannelBinding(serverFeatures, {
2687
+ host: this.#hostKey?.publicKey ?? null,
2688
+ 'cert-hash': this.#certHash,
2689
+ 'tls-exporter': exporter,
2690
+ });
2691
+ if (required) {
2692
+ const needed = Array.isArray(required) ? required : [];
2693
+ const missing = needed.filter((k) => !kinds.includes(k));
2694
+ if (kinds.length === 0 || missing.length) {
2695
+ const offered = offeredKinds(serverFeatures);
2696
+ throw new Error(
2697
+ `channel binding required but not available (host offers: ${offered.join(', ') || 'none'}; bound: ${kinds.join(', ') || 'none'}${missing.length ? `; missing: ${missing.join(', ')}` : ''}) -- nothing was signed`,
2698
+ );
2699
+ }
2700
+ }
2701
+ this.#channelBindingKinds = kinds;
2702
+ return binding;
2703
+ }
2704
+
2705
+ /** The binding kinds the login signature covered (`'host'`, `'cert-hash'`, `'tls-exporter'`); empty when unbound. */
2706
+ get channelBinding() {
2707
+ return [...this.#channelBindingKinds];
2708
+ }
2709
+
2437
2710
  // ── Internal: host key (TOFU / pinning) ─────────────────────────────
2438
2711
 
2439
2712
  /**
@@ -2537,16 +2810,20 @@ export class WshClient {
2537
2810
  * @returns {Promise<string>} Session ID
2538
2811
  * @private
2539
2812
  */
2540
- async #performAuth({ username, keyPair, signer, password, timeout = DEFAULT_AUTH_TIMEOUT, url, ...hostKeyOpts } = {}) {
2813
+ async #performAuth({ username, keyPair, signer, password, timeout = DEFAULT_AUTH_TIMEOUT, url, requireChannelBinding = false, ...hostKeyOpts } = {}) {
2541
2814
  if (!username) throw new Error('username is required');
2542
2815
  const cred = await resolveSigner({ keyPair, signer });
2816
+ this.#signer = cred;
2817
+ this.#loginUsername = username;
2543
2818
  if (!cred && !password) throw new Error('Either keyPair, signer or password is required');
2544
2819
 
2545
2820
  this.#hostKey = null;
2821
+ this.#channelBindingKinds = [];
2822
+ this.#certHash = null;
2546
2823
  try {
2547
2824
  const authMethod = cred ? AUTH_METHOD.PUBKEY : AUTH_METHOD.PASSWORD;
2548
2825
  const hostKeyNonce = newHostKeyNonce();
2549
- await this.#transport.sendControl(hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce] }));
2826
+ await this.#transport.sendControl(hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce, GATEWAY_CREDIT_FEATURE] }));
2550
2827
  const hostCtx = { ...hostKeyOpts, url, username, nonce: hostKeyNonce };
2551
2828
 
2552
2829
  const firstResponse = await this.#waitForMessage(
@@ -2577,13 +2854,15 @@ export class WshClient {
2577
2854
  if (challengeMsg.type === MSG.AUTH_OK) {
2578
2855
  this.#sessionId = challengeMsg.session_id || tempSessionId;
2579
2856
  this.#authToken = challengeMsg.token || null;
2857
+ this.#authTtl = Number(challengeMsg.ttl) || 0;
2580
2858
  this.#state = STATE_AUTHENTICATED;
2581
2859
  this.#startPing();
2582
2860
  return this.#sessionId;
2583
2861
  }
2584
2862
 
2585
2863
  const { signature, publicKeyRaw } = await signChallengeWith(
2586
- cred, challengeMsg.session_id, challengeMsg.nonce, { username }
2864
+ cred, challengeMsg.session_id, challengeMsg.nonce,
2865
+ { username, channelBinding: await this.#bindingFor(this.#serverFeatures, requireChannelBinding) }
2587
2866
  );
2588
2867
 
2589
2868
  await this.#transport.sendControl(authMsg({
@@ -2604,7 +2883,8 @@ export class WshClient {
2604
2883
  // absent.
2605
2884
  tempSessionId = firstResponse.session_id;
2606
2885
  const { signature, publicKeyRaw } = await signChallengeWith(
2607
- cred, firstResponse.session_id, firstResponse.nonce, { username }
2886
+ cred, firstResponse.session_id, firstResponse.nonce,
2887
+ { username, channelBinding: await this.#bindingFor([], requireChannelBinding) }
2608
2888
  );
2609
2889
 
2610
2890
  await this.#transport.sendControl(authMsg({
@@ -2624,6 +2904,7 @@ export class WshClient {
2624
2904
 
2625
2905
  this.#sessionId = authResult.session_id || tempSessionId;
2626
2906
  this.#authToken = authResult.token || null;
2907
+ this.#authTtl = Number(authResult.ttl) || 0;
2627
2908
  this.#state = STATE_AUTHENTICATED;
2628
2909
  this.#startPing();
2629
2910
 
@@ -2670,6 +2951,22 @@ export class WshClient {
2670
2951
  console.warn('[wsh:client] dropping RelayForward wrapping a non-forwardable type:', inner.type);
2671
2952
  return;
2672
2953
  }
2954
+ // A sealed bridge (#117): from_fingerprint is whatever the relay stamped, so plain traffic proves nothing --
2955
+ // only the key exchange that sets the bridge up (while it is pending) and frames of the bridge are heard.
2956
+ const sealState = this.#sealState;
2957
+ if (sealState) {
2958
+ if (sealState.bridge?.isFrame(inner)) {
2959
+ sealState.bridge.open(inner)
2960
+ .then((opened) => this.#handleControl(opened, msg.from_fingerprint))
2961
+ .catch((err) => console.warn('[wsh:client] dropping a sealed frame:', err.message));
2962
+ return;
2963
+ }
2964
+ const setup = !sealState.bridge && inner.type === MSG.KEY_EXCHANGE && inner.session_id === sealState.sessionId;
2965
+ if (!setup) {
2966
+ console.warn('[wsh:client] dropping a plaintext message on a sealed bridge');
2967
+ return;
2968
+ }
2969
+ }
2673
2970
  this.#handleControl(inner, msg.from_fingerprint);
2674
2971
  return;
2675
2972
  }
@@ -2811,6 +3108,8 @@ export class WshClient {
2811
3108
 
2812
3109
  // Route gateway messages (0x70–0x7f) to the gateway handler.
2813
3110
  if (type >= 0x70 && type <= 0x7f) {
3111
+ // Connections opened through openUnix()/openEndpoint()/openTcp()/listenUnix() own their ids.
3112
+ if (this.#gateway?.handle(msg)) return;
2814
3113
  try {
2815
3114
  this.onGatewayMessage?.(msg);
2816
3115
  } catch (err) {
@@ -2882,6 +3181,14 @@ export class WshClient {
2882
3181
  }
2883
3182
  break;
2884
3183
 
3184
+ case MSG.REVERSE_PROOF:
3185
+ try {
3186
+ this.onReverseProof?.(msg);
3187
+ } catch (err) {
3188
+ console.error('[wsh:client] onReverseProof handler error:', err);
3189
+ }
3190
+ break;
3191
+
2885
3192
  case MSG.REVERSE_CONNECT:
2886
3193
  try {
2887
3194
  this.onReverseConnect?.(msg);
@@ -2959,6 +3266,7 @@ export class WshClient {
2959
3266
 
2960
3267
  this.#state = STATE_CLOSED;
2961
3268
  this.#bridgedFeatures = null;
3269
+ this.#gateway?.abandonAll('transport closed');
2962
3270
  this.#stopPing();
2963
3271
  this.#rejectAllWaiters(new Error('Transport closed'));
2964
3272