@johnhenry/wsh 0.35.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.
Files changed (41) hide show
  1. package/README.md +453 -21
  2. package/package.json +18 -1
  3. package/src/bridge-seal.mjs +77 -0
  4. package/src/channel-binding.mjs +124 -0
  5. package/src/client.mjs +351 -62
  6. package/src/e2e-exchange.mjs +51 -1
  7. package/src/features.mjs +28 -0
  8. package/src/forward-node.mjs +118 -0
  9. package/src/gateway-channel.mjs +250 -0
  10. package/src/gateway-client.mjs +252 -0
  11. package/src/host-backends.mjs +100 -0
  12. package/src/host.d.ts +146 -0
  13. package/src/host.mjs +30 -0
  14. package/src/index.d.ts +114 -0
  15. package/src/index.mjs +13 -0
  16. package/src/memory-host.d.ts +34 -3
  17. package/src/memory-host.mjs +57 -13
  18. package/src/messages.gen.mjs +59 -7
  19. package/src/operator-proof.mjs +135 -0
  20. package/src/pipe-relay.d.ts +49 -0
  21. package/src/pipe-relay.mjs +274 -0
  22. package/src/reverse-host.d.ts +25 -0
  23. package/src/reverse-host.mjs +339 -0
  24. package/src/server/address-guard.mjs +164 -0
  25. package/src/server/backends.mjs +10 -16
  26. package/src/server/client-env.mjs +60 -0
  27. package/src/server/connection.mjs +100 -23
  28. package/src/server/constants.mjs +3 -0
  29. package/src/server/fs.mjs +2 -3
  30. package/src/server/gateway-core.mjs +188 -0
  31. package/src/server/gateway.mjs +483 -80
  32. package/src/server/index.d.ts +103 -5
  33. package/src/server/index.mjs +25 -4
  34. package/src/server/pty.mjs +1 -0
  35. package/src/server/relay.mjs +45 -2
  36. package/src/server/reverse-host.mjs +7 -213
  37. package/src/server/socket.mjs +25 -4
  38. package/src/server/unix-policy.mjs +120 -0
  39. package/src/server/webtransport.mjs +2 -0
  40. package/src/transport-ws.mjs +16 -0
  41. package/src/transport.mjs +11 -0
package/src/client.mjs CHANGED
@@ -8,14 +8,16 @@
8
8
  * reverse mode (client registers as a peer for incoming connections).
9
9
  */
10
10
 
11
- import { WebTransportTransport } from './transport.mjs';
11
+ import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE } from './features.mjs';
12
+ import { WebTransportTransport, normalizeWebTransportOptions } from './transport.mjs';
13
+ import { clientChannelBinding, offeredKinds, TLS_EXPORTER_LABEL, TLS_EXPORTER_LENGTH } from './channel-binding.mjs';
12
14
  import { WebSocketTransport } from './transport-ws.mjs';
13
15
  import {
14
16
  MSG, AUTH_METHOD,
15
17
  hello, auth as authMsg, open as openMsg, close as closeMsg,
16
18
  attach as attachMsg, resume as resumeMsg, ping as pingMsg, pong as pongMsg,
17
19
  reverseRegister as reverseRegisterMsg, reverseList as reverseListMsg,
18
- reverseConnect as reverseConnectMsg, relayForward as relayForwardMsg,
20
+ reverseConnect as reverseConnectMsg, relayForward as relayForwardMsg, reverseProof as reverseProofMsg,
19
21
  mcpDiscover as mcpDiscoverMsg, mcpCall as mcpCallMsg, mcpCancel as mcpCancelMsg,
20
22
  suspendSession as suspendSessionMsg, restartPty as restartPtyMsg,
21
23
  metricsRequest as metricsRequestMsg,
@@ -39,8 +41,12 @@ import {
39
41
  } from './messages.mjs';
40
42
  import { resolveSigner, signChallengeWith, signPeerRecordWith, verifyPeerRecord, importPublicKeyRaw, fingerprint as computeFingerprint } from './auth.mjs';
41
43
  import { generateMlKemKeyPair, mlKemEncapsulate, mlKemDecapsulate } from './mlkem.mjs';
42
- 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';
43
47
  import { WshSession } from './session.mjs';
48
+ import { GatewayConnections } from './gateway-client.mjs';
49
+ import { GATEWAY_CREDIT_FEATURE } from './gateway-channel.mjs';
44
50
  import { cborDecode, cborEncode } from './cbor.mjs';
45
51
  import {
46
52
  RpcChannel, RpcError, RPC_ERROR, RPC_FEATURE, RPC_PROTOCOL_NAME_RE, RPC_DEFAULT_MAX_MESSAGE,
@@ -66,21 +72,8 @@ const DEFAULT_AUTH_TIMEOUT = 10_000; // ms
66
72
  const DEFAULT_OPEN_TIMEOUT = 10_000; // ms
67
73
  const FS_RPC_OPS = new Set(['stat', 'list', 'read', 'write', 'mkdir', 'remove', 'rename']);
68
74
 
69
- /**
70
- * ServerHello feature advertising that McpResult echoes McpCall's call_id.
71
- *
72
- * Negotiated rather than assumed: McpCallPayload is `deny_unknown_fields` on
73
- * the Rust side, so sending call_id to a server predating it does not
74
- * degrade -- it makes the server reject the call.
75
- */
76
- export const MCP_CALL_ID_FEATURE = 'mcp-call-id';
77
-
78
- /**
79
- * ServerHello feature advertising that the host understands `McpCancel` (stop an in-flight `McpCall`).
80
- * Negotiated rather than assumed: McpCancelPayload is `deny_unknown_fields` on the Rust side, so an older
81
- * server would reject it. Implies `mcp-call-id` (the cancel names a call by its id).
82
- */
83
- export const MCP_CANCEL_FEATURE = 'mcp-cancel';
75
+ // The feature strings live in features.mjs (a host names them without importing this file); re-exported here.
76
+ export { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE };
84
77
 
85
78
  /** An `AbortError` for `signal`, with the signal's reason as `cause`. */
86
79
  function abortError(signal) {
@@ -89,13 +82,6 @@ function abortError(signal) {
89
82
  return e;
90
83
  }
91
84
 
92
- /**
93
- * ServerHello feature: the host discovers a client-opened exec data stream
94
- * on its own (the transport announces it), so the client must NOT write the
95
- * one-byte "primer" -- against such a host it would reach the process's stdin.
96
- */
97
- export const STREAM_ANNOUNCE_FEATURE = 'stream-announce';
98
- export const EXEC_PIPES_FEATURE = 'exec-pipes';
99
85
 
100
86
  /**
101
87
  * Reject a missing argument that maps to a `required: true` wire field.
@@ -224,6 +210,20 @@ async function pumpStdin(session, stdin) {
224
210
  await session.closeStdin();
225
211
  }
226
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
+
227
227
  export class WshClient {
228
228
 
229
229
  /** @type {'disconnected'|'connecting'|'connected'|'authenticated'|'closed'} */
@@ -245,12 +245,40 @@ export class WshClient {
245
245
  */
246
246
  #authToken = null;
247
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
+
248
254
  /** @type {import('./transport.mjs').WshTransport|null} Active transport. */
249
255
  #transport = null;
250
256
 
251
257
  /** @type {{fingerprint: string, publicKey: Uint8Array, openssh: string, status: string}|null} */
252
258
  #hostKey = null;
253
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
+
254
282
  /**
255
283
  * Called with the host's verified key before any credential is sent.
256
284
  * Return `false` (or throw) to refuse the host. See `connect({ onHostKey })`.
@@ -333,6 +361,9 @@ export class WshClient {
333
361
  */
334
362
  #bridgedFeatures = null;
335
363
 
364
+ /** @type {GatewayConnections|null} Created by the first openUnix()/openEndpoint()/openTcp()/listenUnix(). */
365
+ #gateway = null;
366
+
336
367
  /** @type {number|null} Ping interval handle. */
337
368
  #pingTimer = null;
338
369
 
@@ -372,6 +403,13 @@ export class WshClient {
372
403
  */
373
404
  onReverseConnect = null;
374
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
+
375
413
  /**
376
414
  * Called when a clipboard sync message arrives (OSC 52).
377
415
  * The default handler writes to navigator.clipboard automatically.
@@ -451,6 +489,15 @@ export class WshClient {
451
489
  return this.#authToken;
452
490
  }
453
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
+
454
501
  /** Read-only view of active sessions. */
455
502
  get sessions() {
456
503
  return new Map(this.#sessions);
@@ -543,9 +590,13 @@ export class WshClient {
543
590
  * @param {string} [opts.hostLabel] - Key under which `knownHosts` records
544
591
  * this host (default: the URL's `host:port`).
545
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.
546
597
  * @returns {Promise<string>} The server-assigned session ID
547
598
  */
548
- 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 } = {}) {
549
600
  if (this.#state !== STATE_DISCONNECTED && this.#state !== STATE_CLOSED) {
550
601
  throw new Error(`Client already ${this.#state}`);
551
602
  }
@@ -553,16 +604,24 @@ export class WshClient {
553
604
  throw new Error('username is required');
554
605
  }
555
606
  const cred = await resolveSigner({ keyPair, signer });
607
+ this.#signer = cred;
608
+ this.#loginUsername = username;
556
609
  if (!cred && !password) {
557
610
  throw new Error('Either keyPair, signer or password is required for authentication');
558
611
  }
612
+ if (requireChannelBinding && !cred) throw new Error('requireChannelBinding needs a key: a password login signs nothing to bind');
559
613
 
560
614
  this.#state = STATE_CONNECTING;
615
+ this.#channelBindingKinds = [];
616
+ this.#certHash = null;
617
+ this.#sealState = null;
618
+ this.#peerProof = null;
561
619
  this.#sessions.clear();
562
620
  this.#channelCounter = 0;
563
621
  this.#waiters.clear();
564
622
  this.#sessionId = null;
565
623
  this.#authToken = null;
624
+ this.#authTtl = 0;
566
625
  this.#hostKey = null;
567
626
 
568
627
  try {
@@ -575,7 +634,7 @@ export class WshClient {
575
634
  const authMethod = cred ? AUTH_METHOD.PUBKEY : AUTH_METHOD.PASSWORD;
576
635
  const hostKeyNonce = newHostKeyNonce();
577
636
  await transport.sendControl(
578
- hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce] })
637
+ hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce, GATEWAY_CREDIT_FEATURE] })
579
638
  );
580
639
  const hostCtx = { ...hostKeyOpts, url, username, nonce: hostKeyNonce };
581
640
 
@@ -613,6 +672,7 @@ export class WshClient {
613
672
  // Server accepted without challenge (e.g. trusted key).
614
673
  this.#sessionId = challengeMsg.session_id || tempSessionId;
615
674
  this.#authToken = challengeMsg.token || null;
675
+ this.#authTtl = Number(challengeMsg.ttl) || 0;
616
676
  this.#state = STATE_AUTHENTICATED;
617
677
  this.#startPing();
618
678
  return this.#sessionId;
@@ -625,7 +685,7 @@ export class WshClient {
625
685
  cred,
626
686
  challengeMsg.session_id,
627
687
  challengeMsg.nonce,
628
- { username }
688
+ { username, channelBinding: await this.#bindingFor(this.#serverFeatures, requireChannelBinding) }
629
689
  );
630
690
 
631
691
  await transport.sendControl(
@@ -663,7 +723,7 @@ export class WshClient {
663
723
  cred,
664
724
  firstResponse.session_id,
665
725
  firstResponse.nonce,
666
- { username }
726
+ { username, channelBinding: await this.#bindingFor([], requireChannelBinding) }
667
727
  );
668
728
 
669
729
  await transport.sendControl(
@@ -688,6 +748,7 @@ export class WshClient {
688
748
 
689
749
  this.#sessionId = authResult.session_id || tempSessionId;
690
750
  this.#authToken = authResult.token || null;
751
+ this.#authTtl = Number(authResult.ttl) || 0;
691
752
  this.#state = STATE_AUTHENTICATED;
692
753
  this.#startPing();
693
754
 
@@ -1046,6 +1107,7 @@ export class WshClient {
1046
1107
  this.#stopPing();
1047
1108
  this.#state = STATE_CLOSED;
1048
1109
  this.#bridgedFeatures = null;
1110
+ this.#gateway?.abandonAll('client disconnected');
1049
1111
 
1050
1112
  // Close all sessions concurrently.
1051
1113
  const closePromises = [];
@@ -1204,6 +1266,8 @@ export class WshClient {
1204
1266
 
1205
1267
  // Export public key for peer identification.
1206
1268
  const cred = await resolveSigner({ keyPair, signer });
1269
+ this.#signer = cred;
1270
+ this.#loginUsername = username;
1207
1271
  let publicKey = null;
1208
1272
  if (cred) publicKey = cred.publicKeyRaw;
1209
1273
 
@@ -1298,23 +1362,95 @@ export class WshClient {
1298
1362
  * @param {number} [timeout=10000]
1299
1363
  * @returns {Promise<object>}
1300
1364
  */
1301
- async reverseConnect(targetFingerprint, timeout = DEFAULT_OPEN_TIMEOUT) {
1365
+ async reverseConnect(targetFingerprint, timeout = DEFAULT_OPEN_TIMEOUT, { proof = 'auto', requirePeerProof = false, sealed = false } = {}) {
1302
1366
  this.#assertAuthenticated('reverseConnect');
1303
1367
 
1304
- 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
1305
1407
  // fromFingerprint is ignored by the server -- it overwrites it with
1306
1408
  // this connection's own authenticated fingerprint before forwarding.
1307
- reverseConnectMsg({ targetFingerprint, username: '', fromFingerprint: '' })
1308
- );
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
+ }
1309
1425
 
1310
- const response = await this.#waitForMessage(
1311
- [MSG.REVERSE_ACCEPT, MSG.REVERSE_REJECT],
1312
- timeout,
1313
- 'Timed out waiting for reverse-connect response'
1314
- );
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
+ }
1315
1452
 
1316
1453
  if (response.type === MSG.REVERSE_ACCEPT) {
1317
- this.trustRelayPeer(response.target_fingerprint);
1318
1454
  // The relay's SERVER_HELLO describes the relay, not the host behind the
1319
1455
  // bridge: when that host says what it supports, feature gates
1320
1456
  // (file-write, file-rename, mcp-call-id) follow it instead.
@@ -1381,6 +1517,75 @@ export class WshClient {
1381
1517
  await this.#transport.sendControl(msg);
1382
1518
  }
1383
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
+
1384
1589
  /**
1385
1590
  * Open a raw bidirectional stream on the underlying transport.
1386
1591
  *
@@ -1956,9 +2161,11 @@ export class WshClient {
1956
2161
  * @param {number} [timeout=10000]
1957
2162
  * @param {object} [opts]
1958
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)
1959
2166
  * @returns {Promise<{sharedSecret: CryptoKey, peerPublicKey: Uint8Array, hybrid: boolean, peerAuthenticated: boolean}>}
1960
2167
  */
1961
- async initiateE2E(sessionId, algorithm = 'X25519', timeout = DEFAULT_OPEN_TIMEOUT, { verifyPeer } = {}) {
2168
+ async initiateE2E(sessionId, algorithm = 'X25519', timeout = DEFAULT_OPEN_TIMEOUT, { verifyPeer, signAs, responderIdentity } = {}) {
1962
2169
  this.#assertAuthenticated('initiateE2E');
1963
2170
  const wantHybrid = algorithm === 'X25519+ML-KEM-768';
1964
2171
 
@@ -1998,32 +2205,27 @@ export class WshClient {
1998
2205
  );
1999
2206
  const localKem = wantHybrid ? await generateMlKemKeyPair() : null;
2000
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
+
2001
2217
  await this.#transport.sendControl(
2002
- keyExchangeMsg({ algorithm, publicKey: localPub, sessionId, kemPublicKey: localKem?.publicKey })
2218
+ keyExchangeMsg({ algorithm, publicKey: localPub, sessionId, kemPublicKey: localKem?.publicKey, signature: initiatorSignature })
2003
2219
  );
2004
2220
 
2005
2221
  const peerMsg = await peerMsgPromise;
2006
2222
 
2007
- let peerAuthenticated = false;
2008
- if (verifyPeer !== undefined) {
2009
- const ok = await verifyKeyExchangeSignature(verifyPeer, peerMsg.signature, {
2010
- sessionId, algorithm, initiatorKey: localPub, responderKey: new Uint8Array(peerMsg.public_key ?? []),
2011
- });
2012
- if (!ok) {
2013
- throw Object.assign(
2014
- new Error(peerMsg.signature === undefined
2015
- ? 'initiateE2E: the peer did not sign its key exchange (verifyPeer was given)'
2016
- : 'initiateE2E: the peer\'s key exchange signature does not verify against verifyPeer'),
2017
- { code: 'E2E_PEER_UNAUTHENTICATED' },
2018
- );
2019
- }
2020
- peerAuthenticated = true;
2021
- }
2022
-
2023
2223
  // Round 2 has the same shape as round 1, so it needs the same treatment.
2024
2224
  // Whether we encapsulate or decapsulate is decided entirely by data
2025
2225
  // already in hand, so decide it now and register the ciphertext waiter
2026
- // 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
2027
2229
  // importKey and deriveBits, let the peer's ciphertext arrive while this
2028
2230
  // side was still deriving -- dropped, then a full-timeout wait for a
2029
2231
  // message already sent. That surfaced as "Timed out waiting for peer
@@ -2043,6 +2245,22 @@ export class WshClient {
2043
2245
  ctMsgPromise.catch(() => {});
2044
2246
  }
2045
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
+
2046
2264
  // Import peer's public key and derive the classical shared secret.
2047
2265
  const peerKey = await crypto.subtle.importKey(
2048
2266
  'raw',
@@ -2348,6 +2566,7 @@ export class WshClient {
2348
2566
  const transport = this.#createTransport(attempt.kind);
2349
2567
  try {
2350
2568
  await transport.connect(attempt.url, attempt.kind === 'wt' ? webTransport : undefined);
2569
+ this.#certHash = attempt.kind === 'wt' ? webTransportCertHash(webTransport) : null;
2351
2570
  this.#attachTransportHandlers(transport);
2352
2571
  return transport;
2353
2572
  } catch (err) {
@@ -2453,6 +2672,41 @@ export class WshClient {
2453
2672
  return this.#performAuth({ ...opts, url });
2454
2673
  }
2455
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
+
2456
2710
  // ── Internal: host key (TOFU / pinning) ─────────────────────────────
2457
2711
 
2458
2712
  /**
@@ -2556,16 +2810,20 @@ export class WshClient {
2556
2810
  * @returns {Promise<string>} Session ID
2557
2811
  * @private
2558
2812
  */
2559
- 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 } = {}) {
2560
2814
  if (!username) throw new Error('username is required');
2561
2815
  const cred = await resolveSigner({ keyPair, signer });
2816
+ this.#signer = cred;
2817
+ this.#loginUsername = username;
2562
2818
  if (!cred && !password) throw new Error('Either keyPair, signer or password is required');
2563
2819
 
2564
2820
  this.#hostKey = null;
2821
+ this.#channelBindingKinds = [];
2822
+ this.#certHash = null;
2565
2823
  try {
2566
2824
  const authMethod = cred ? AUTH_METHOD.PUBKEY : AUTH_METHOD.PASSWORD;
2567
2825
  const hostKeyNonce = newHostKeyNonce();
2568
- 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] }));
2569
2827
  const hostCtx = { ...hostKeyOpts, url, username, nonce: hostKeyNonce };
2570
2828
 
2571
2829
  const firstResponse = await this.#waitForMessage(
@@ -2596,13 +2854,15 @@ export class WshClient {
2596
2854
  if (challengeMsg.type === MSG.AUTH_OK) {
2597
2855
  this.#sessionId = challengeMsg.session_id || tempSessionId;
2598
2856
  this.#authToken = challengeMsg.token || null;
2857
+ this.#authTtl = Number(challengeMsg.ttl) || 0;
2599
2858
  this.#state = STATE_AUTHENTICATED;
2600
2859
  this.#startPing();
2601
2860
  return this.#sessionId;
2602
2861
  }
2603
2862
 
2604
2863
  const { signature, publicKeyRaw } = await signChallengeWith(
2605
- cred, challengeMsg.session_id, challengeMsg.nonce, { username }
2864
+ cred, challengeMsg.session_id, challengeMsg.nonce,
2865
+ { username, channelBinding: await this.#bindingFor(this.#serverFeatures, requireChannelBinding) }
2606
2866
  );
2607
2867
 
2608
2868
  await this.#transport.sendControl(authMsg({
@@ -2623,7 +2883,8 @@ export class WshClient {
2623
2883
  // absent.
2624
2884
  tempSessionId = firstResponse.session_id;
2625
2885
  const { signature, publicKeyRaw } = await signChallengeWith(
2626
- cred, firstResponse.session_id, firstResponse.nonce, { username }
2886
+ cred, firstResponse.session_id, firstResponse.nonce,
2887
+ { username, channelBinding: await this.#bindingFor([], requireChannelBinding) }
2627
2888
  );
2628
2889
 
2629
2890
  await this.#transport.sendControl(authMsg({
@@ -2643,6 +2904,7 @@ export class WshClient {
2643
2904
 
2644
2905
  this.#sessionId = authResult.session_id || tempSessionId;
2645
2906
  this.#authToken = authResult.token || null;
2907
+ this.#authTtl = Number(authResult.ttl) || 0;
2646
2908
  this.#state = STATE_AUTHENTICATED;
2647
2909
  this.#startPing();
2648
2910
 
@@ -2689,6 +2951,22 @@ export class WshClient {
2689
2951
  console.warn('[wsh:client] dropping RelayForward wrapping a non-forwardable type:', inner.type);
2690
2952
  return;
2691
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
+ }
2692
2970
  this.#handleControl(inner, msg.from_fingerprint);
2693
2971
  return;
2694
2972
  }
@@ -2830,6 +3108,8 @@ export class WshClient {
2830
3108
 
2831
3109
  // Route gateway messages (0x70–0x7f) to the gateway handler.
2832
3110
  if (type >= 0x70 && type <= 0x7f) {
3111
+ // Connections opened through openUnix()/openEndpoint()/openTcp()/listenUnix() own their ids.
3112
+ if (this.#gateway?.handle(msg)) return;
2833
3113
  try {
2834
3114
  this.onGatewayMessage?.(msg);
2835
3115
  } catch (err) {
@@ -2901,6 +3181,14 @@ export class WshClient {
2901
3181
  }
2902
3182
  break;
2903
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
+
2904
3192
  case MSG.REVERSE_CONNECT:
2905
3193
  try {
2906
3194
  this.onReverseConnect?.(msg);
@@ -2978,6 +3266,7 @@ export class WshClient {
2978
3266
 
2979
3267
  this.#state = STATE_CLOSED;
2980
3268
  this.#bridgedFeatures = null;
3269
+ this.#gateway?.abandonAll('transport closed');
2981
3270
  this.#stopPing();
2982
3271
  this.#rejectAllWaiters(new Error('Transport closed'));
2983
3272