@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
@@ -54,6 +54,9 @@ export interface WshServerHostKey {
54
54
  openssh: string;
55
55
  }
56
56
 
57
+ /** The `clientEnv` option of `exec` and `pty`: see {@link WshServerExecOptions.clientEnv}. */
58
+ export type WshClientEnv = boolean | string[] | ((name: string, value: string) => boolean);
59
+
57
60
  /** What a custom `exec` runner receives for one session. */
58
61
  export interface WshExecIo {
59
62
  user: string;
@@ -85,8 +88,12 @@ export interface WshServerExecOptions {
85
88
  shell?: boolean | string;
86
89
  /** Kill a session after this long (0 / omitted = never). */
87
90
  timeoutMs?: number;
88
- /** Apply `env` sent by the client (default `true`). */
89
- clientEnv?: boolean;
91
+ /**
92
+ * Which `env` variables a client may set. Default: an allow-list (`TERM`, `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*`).
93
+ * `true` accepts everything (the behaviour before 0.36), `false` nothing, a list names exact variables or `PREFIX_*`
94
+ * patterns (replacing the default list), a function decides per variable.
95
+ */
96
+ clientEnv?: WshClientEnv;
90
97
  /** Replace the child_process runner entirely (e.g. a restricted, no-shell host). */
91
98
  run?: WshExecRunner;
92
99
  }
@@ -100,6 +107,59 @@ export interface WshPtyProcess {
100
107
  kill(signal?: string): void;
101
108
  }
102
109
 
110
+ /** Who is calling a named endpoint: the authenticated identity of the connection. */
111
+ export interface WshGatewayWho { username: string | null; fingerprint: string | null }
112
+
113
+ /** What a named endpoint handler (or a client's `openEndpoint`) gets: web streams with backpressure. */
114
+ export interface WshGatewayEndpointDuplex {
115
+ readable: ReadableStream<Uint8Array>;
116
+ writable: WritableStream<Uint8Array>;
117
+ who: WshGatewayWho;
118
+ /** Half-close: nothing more will be sent. */
119
+ close(reason?: string): void;
120
+ /** Tear the connection down now. */
121
+ destroy(reason?: string): void;
122
+ /** Settles when the connection is over (either side, or the client disconnected). */
123
+ closed: Promise<string | undefined>;
124
+ }
125
+
126
+ export type WshGatewayEndpointHandler = (duplex: WshGatewayEndpointDuplex, who: WshGatewayWho) => void | Promise<void>;
127
+
128
+ export interface WshServerGatewayOptions {
129
+ /** Destinations a client may reach: `"*"`, `"host"` (any port), `"host:port"`. Default deny. An IP-literal entry permits exactly that address even if private. */
130
+ allow: string[];
131
+ /** CIDR blocks or addresses the host may dial although they are not globally routable (`"10.0.0.0/8"`, `"127.0.0.1"`, `"fd00::/8"`). Default none. */
132
+ allowPrivate?: string[];
133
+ /** Concurrent gateway connections per client (default 32). */
134
+ maxConnections?: number;
135
+ connectTimeoutMs?: number;
136
+ /** A UDP flow with no datagram in either direction for this long is closed (default 60000). */
137
+ udpIdleMs?: number;
138
+ /** Bytes received from a client for one connection and not yet taken by its origin before it is closed (default 4 MiB; at least 262144). */
139
+ maxBufferedBytes?: number;
140
+ /** The same, summed over one client's connections (default 32 MiB). */
141
+ maxClientBufferedBytes?: number;
142
+ socks?: string | { host: string; port: number };
143
+ /**
144
+ * Unix-domain sockets a client may reach (`OpenUnix`, feature `gateway-unix`) or ask the host to create
145
+ * (`ListenUnix`). Off unless given; each entry is an absolute path (exact), a directory prefix with a trailing `/`,
146
+ * or `@name` / `@prefix/` for the Linux abstract namespace. Checked after `realpath` of the parent directory; the
147
+ * file must be a socket, not a symlink. Sockets the host creates are mode 0600 and removed on close.
148
+ */
149
+ unix?: {
150
+ connect?: string[];
151
+ listen?: string[];
152
+ /** Let a client replace an existing STALE socket file when it asks to (OpenSSH `StreamLocalBindUnlink`). Default false. */
153
+ replaceStale?: boolean;
154
+ /** Unix listeners per client (default 4). */
155
+ maxListeners?: number;
156
+ };
157
+ /** Named virtual endpoints (`OpenEndpoint`, feature `gateway-endpoints`): only these names exist. */
158
+ endpoints?: Record<string, WshGatewayEndpointHandler | { open: WshGatewayEndpointHandler; authorize?: (who: WshGatewayWho) => boolean | Promise<boolean> }>;
159
+ /** `false`: no TCP or DNS at all (an endpoints-only gateway). Default true. */
160
+ tcp?: boolean;
161
+ }
162
+
103
163
  export interface WshServerPtyOptions {
104
164
  /** `node-pty`'s `spawn(file, args, options)`, or anything shaped like it. */
105
165
  spawn(file: string, args: string[], options: {
@@ -111,6 +171,8 @@ export interface WshServerPtyOptions {
111
171
  env?: Record<string, string | undefined>;
112
172
  /** `TERM` value (default `xterm-256color`). */
113
173
  term?: string;
174
+ /** Which `env` variables a client may add to the shell's environment; same forms and default as `exec.clientEnv`. */
175
+ clientEnv?: WshClientEnv;
114
176
  }
115
177
 
116
178
  export interface WshServerFsOptions {
@@ -343,9 +405,14 @@ export interface WshServerOptions {
343
405
  * Answer the gateway opcodes (OpenTcp, ResolveDns, GatewayData, GatewayClose) so a client can open TCP connections and
344
406
  * resolve names from this host. Default deny: a destination must match `allow` (`"*"`, `"host"` any port, `"host:port"`).
345
407
  * `socks` dials through a SOCKS5 proxy (e.g. Tor at `127.0.0.1:9050`) with the name left unresolved; `ResolveDns` is then
346
- * refused. UDP and reverse tunnels are answered with a failure. Off by default.
408
+ * refused. UDP and TCP reverse tunnels are answered with a failure. Off by default.
409
+ *
410
+ * The ADDRESS a name resolves to is checked too: the host resolves once, refuses every address
411
+ * that is not globally routable (loopback, private, link-local, CGNAT, ULA, multicast, reserved, and IPv4 wrapped as
412
+ * mapped / NAT64 / 6to4 IPv6) unless `allowPrivate` or an IP-literal `allow` entry says so, and connects to that
413
+ * address. `ResolveDns` answers are filtered the same way. Gateway data is flow controlled (`gateway-credit`).
347
414
  */
348
- gateway?: { allow: string[]; maxConnections?: number; connectTimeoutMs?: number; socks?: string | { host: string; port: number } };
415
+ gateway?: WshServerGatewayOptions;
349
416
  /**
350
417
  * Handlers for application-defined control messages: one whose `type` is a string (protocol messages are numeric, so
351
418
  * there is no collision) from an authenticated connection is handed to `extensions[type]`. A throw is logged.
@@ -372,6 +439,14 @@ export interface WshServerOptions {
372
439
  rpcMaxInflight?: number;
373
440
  /** How long exec output waits for a client that has not yet opened its data stream (default 3000). */
374
441
  bindTimeoutMs?: number;
442
+ /** End every authenticated connection this long after login; advertised as `AuthOk.ttl` (whole seconds, rounded up). 0 / omitted = never. */
443
+ connectionTtlMs?: number;
444
+ /**
445
+ * Accept a key login only when its signature is bound to this connection (#119): `true` needs any binding kind, an array
446
+ * names kinds that must all be bound (`host` needs `hostKey`; `tls-exporter` needs `wss://` served by this process, not a
447
+ * TLS-terminating proxy; `cert-hash` needs WebTransport with `selfSigned`). Clients older than 0.36 cannot satisfy it.
448
+ */
449
+ requireChannelBinding?: boolean | Array<'cert-hash' | 'host' | 'tls-exporter'>;
375
450
  onLog?: (line: string) => void;
376
451
  }
377
452
 
@@ -417,6 +492,12 @@ export interface WshAcceptableSocket {
417
492
  export interface WshAcceptOptions {
418
493
  /** What the embedder knows of the peer; `address` keys the password-failure throttle. */
419
494
  remote?: { address?: string; headers?: Record<string, unknown> };
495
+ /**
496
+ * Serve this connection without client-opened QMux data streams: exec output rides `SessionData`
497
+ * (`data_mode: 'virtual'`) and `stream-announce` / `rpc` are not offered. For a peer that cannot open streams
498
+ * (the released Rust client over WebSocket). Default `true`.
499
+ */
500
+ dataStreams?: boolean;
420
501
  }
421
502
 
422
503
  export interface WshServer {
@@ -468,7 +549,14 @@ export interface WshReverseHostOptions {
468
549
  /** This host's identity; its fingerprint is what operators connect to. */
469
550
  keyPair: CryptoKeyPair;
470
551
  /** Who may be bridged to this host. Default: nobody. */
471
- accept?: (operator: { fingerprint: string; username: string }) => boolean | Promise<boolean>;
552
+ accept?: (operator: {
553
+ fingerprint: string;
554
+ username: string;
555
+ /** True when the operator signed a challenge from THIS host (wsh #117): `fingerprint` and `username` are then the operator's own claim, not the relay's. */
556
+ proven: boolean;
557
+ /** The operator's raw Ed25519 key, when `proven`. */
558
+ publicKey?: Uint8Array;
559
+ }) => boolean | Promise<boolean>;
472
560
  exec?: true | WshServerExecOptions | WshExecRunner;
473
561
  pty?: WshServerPtyOptions;
474
562
  fs?: WshServerFsOptions;
@@ -495,6 +583,16 @@ export interface WshReverseHostOptions {
495
583
  * `hybrid` (default true) offers X25519+ML-KEM-768 when asked and available.
496
584
  */
497
585
  e2e?: false | { sign?: boolean | 'auto'; hybrid?: boolean };
586
+ /**
587
+ * Require the operator to prove its identity to this host (wsh #117) and seal the bridge: an operator that does not
588
+ * offer proof is refused, `accept` runs only after the proof verifies (with the identity taken from the proof, not
589
+ * the relay), and this host acts only on messages sealed under a key exchange both sides signed -- a relay cannot
590
+ * inject an `Open`. Needs `e2e` and `reportFeatures`. Without it the proof is still requested when the relay and the
591
+ * operator can do it, and reported as `proven`.
592
+ */
593
+ requireOperatorProof?: boolean;
594
+ /** How long an operator has to answer the challenge (default 5000). */
595
+ proofTimeoutMs?: number;
498
596
  onLog?: (line: string) => void;
499
597
  }
500
598
 
@@ -15,14 +15,24 @@ import { SessionRegistry } from './sessions.mjs';
15
15
  import { RelayHub } from './relay.mjs';
16
16
  import { startWebTransport } from './webtransport.mjs';
17
17
  import { createConnectionFactory, STREAM_ANNOUNCE } from './connection.mjs';
18
- import { normalizeGateway } from './gateway.mjs';
18
+ import { normalizeGateway, createGatewaySession } from './gateway.mjs';
19
19
  import { createRpcHost, mcpServerAdapter } from './rpc.mjs';
20
20
  import { bindSocket } from './socket.mjs';
21
+ import { TLS_EXPORTER_LABEL, TLS_EXPORTER_LENGTH, CHANNEL_BINDING_KINDS } from '../channel-binding.mjs';
21
22
 
22
23
  export { parseAuthorizedKeys, STREAM_ANNOUNCE, mcpServerAdapter };
23
24
  export { createReverseHost } from './reverse-host.mjs';
24
25
  export { generateSelfSignedCertificate } from './self-signed.mjs';
25
26
 
27
+ /** The TLS exporter of a `wss://` connection as a channel binding (#119); null on a plain socket or a TLS-terminating proxy hop. */
28
+ function tlsChannelBinding(socket) {
29
+ try {
30
+ if (!socket || socket.encrypted !== true || typeof socket.exportKeyingMaterial !== 'function') return null;
31
+ const out = socket.exportKeyingMaterial(TLS_EXPORTER_LENGTH, TLS_EXPORTER_LABEL);
32
+ return out?.length === TLS_EXPORTER_LENGTH ? { 'tls-exporter': [new Uint8Array(out.buffer, out.byteOffset, out.byteLength).slice()] } : null;
33
+ } catch { return null; }
34
+ }
35
+
26
36
  /**
27
37
  * @param {object} [options]
28
38
  * @param {string} [options.host='127.0.0.1']
@@ -74,12 +84,22 @@ export { generateSelfSignedCertificate } from './self-signed.mjs';
74
84
  * names from this host. Default deny: a destination must match `allow` (`"*"`, `"host"`, `"host:port"`). `socks` dials
75
85
  * through a SOCKS5 proxy (Tor) with the name unresolved. UDP and reverse tunnels are refused. Off unless given. See `gateway.mjs`.
76
86
  * @param {number} [options.bindTimeoutMs=3000]
87
+ * @param {number} [options.connectionTtlMs=0] - End every authenticated connection this long after login (0 = never).
88
+ * Advertised as `AuthOk.ttl` in whole seconds, rounded up; the client reads it as `client.authTtl`.
89
+ * @param {boolean | string[]} [options.requireChannelBinding=false] - Accept a key login only when its signature is bound to
90
+ * this connection (#119): `true` needs any binding kind, an array names kinds that must all be bound (`host` needs
91
+ * `hostKey`; `tls-exporter` needs `wss://` served by this process, not a TLS-terminating proxy; `cert-hash` needs
92
+ * WebTransport with `selfSigned`). Clients older than 0.36 cannot satisfy it. Off by default.
77
93
  * @param {(line: string) => void} [options.onLog]
78
94
  * @returns {{ listen(): Promise<{address: string, port: number}>, accept(socket: object, options?: object): Promise<{ close(): void }>, close(): Promise<void>, address(): ({address: string, port: number} | null) }}
79
95
  */
80
96
  export function createWshServer({
81
- host = '127.0.0.1', port = 0, tls, auth, exec, pty, fs, hostKey, mcp, rpc, rpcMaxMessageBytes, rpcMaxInflight, sessions, sessionSecret, relay, extensions, gateway, webTransport, bindTimeoutMs = 3000, onLog = () => {},
97
+ host = '127.0.0.1', port = 0, tls, auth, exec, pty, fs, hostKey, mcp, rpc, rpcMaxMessageBytes, rpcMaxInflight, sessions, sessionSecret, relay, extensions, gateway, webTransport, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, onLog = () => {},
82
98
  } = {}) {
99
+ if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
100
+ throw new TypeError(`createWshServer: requireChannelBinding must be true, false or an array of kinds (${CHANNEL_BINDING_KINDS.join(', ')})`);
101
+ }
102
+ if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createWshServer: connectionTtlMs must be a non-negative number of milliseconds (0 = no limit)');
83
103
  let wss = null;
84
104
  let httpsServer = null;
85
105
  let bound = null;
@@ -125,8 +145,8 @@ export function createWshServer({
125
145
  if (relay) hub = new RelayHub({ ...relay, log: onLog });
126
146
  if (extensions !== undefined && (extensions === null || typeof extensions !== 'object')) throw new TypeError('createWshServer: extensions must be an object of handlers');
127
147
  return createConnectionFactory({
128
- authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, log: onLog,
129
- methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, sessions: registry, relay: hub,
148
+ authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, log: onLog,
149
+ methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, createGatewaySession, sessions: registry, relay: hub,
130
150
  });
131
151
  })();
132
152
  ready.catch(() => { ready = null; });
@@ -156,6 +176,7 @@ export function createWshServer({
156
176
  send: (b) => { if (ws.readyState === 1) ws.send(b); },
157
177
  remote: { address: req?.socket?.remoteAddress, headers: req?.headers ?? {} },
158
178
  closeTransport: () => ws.close(1000),
179
+ channelBinding: tlsChannelBinding(req?.socket),
159
180
  });
160
181
  ws.on('message', (d) => {
161
182
  const buf = Array.isArray(d) ? Buffer.concat(d) : Buffer.isBuffer(d) ? d : Buffer.from(d);
@@ -21,5 +21,6 @@ export function normalizePty(pty) {
21
21
  cwd: pty.cwd,
22
22
  env: pty.env,
23
23
  term: pty.term ?? 'xterm-256color',
24
+ clientEnv: pty.clientEnv,
24
25
  };
25
26
  }
@@ -36,6 +36,7 @@ const MAX_REMEMBERED_SEQS = 4096;
36
36
  const MAX_CAPABILITIES = 32;
37
37
  const MAX_FEATURES = 64;
38
38
  const MAX_FEATURE_LENGTH = 128;
39
+ const MAX_OPERATOR_FEATURES = 16;
39
40
  const SHORT_PREFIX_MIN = 8;
40
41
 
41
42
  /** `ReverseReject.reason` for a peer that already has an operator (or a request awaiting its answer). */
@@ -245,12 +246,15 @@ export class RelayHub {
245
246
  timer.unref?.();
246
247
  this.#pending.set(target.handle, { operator, timer });
247
248
  // The relay speaks for the operator's identity; whatever the client wrote in these fields is discarded.
248
- target.handle.send({
249
+ const forwarded = {
249
250
  type: MSG.REVERSE_CONNECT,
250
251
  target_fingerprint: target.meta.fingerprint,
251
252
  username: operator.username,
252
253
  from_fingerprint: operator.fingerprint,
253
- });
254
+ };
255
+ // What the operator says it can do (#117), bounded; it is the operator's own claim and decides nothing here.
256
+ if (Array.isArray(msg.features) && msg.features.length <= MAX_OPERATOR_FEATURES && msg.features.every((f) => isStr(f, MAX_FEATURE_LENGTH))) forwarded.features = [...msg.features];
257
+ target.handle.send(forwarded);
254
258
  this.log(`relay: ${operator.fingerprint.slice(0, 12)} -> ${target.meta.fingerprint.slice(0, 12)} requested`);
255
259
  }
256
260
 
@@ -278,6 +282,45 @@ export class RelayHub {
278
282
  }
279
283
  }
280
284
 
285
+ /**
286
+ * `ReverseChallenge` from a peer to the operator whose `ReverseConnect` it is answering (#117). Carried, not
287
+ * interpreted: the relay cannot forge it (the peer signed it) and gains nothing by reading it.
288
+ */
289
+ challenge(peer, msg) {
290
+ const p = this.#pending.get(peer);
291
+ if (!p || !(msg.public_key instanceof Uint8Array) || !(msg.signature instanceof Uint8Array) || !(msg.nonce instanceof Uint8Array)
292
+ || !isStr(msg.session_id, 256) || !isStr(msg.operator_fingerprint, 256) || msg.public_key.length > 64 || msg.signature.length > 128 || msg.nonce.length > 64) return;
293
+ p.operator.send({
294
+ type: MSG.REVERSE_CHALLENGE,
295
+ target_fingerprint: peer.fingerprint,
296
+ public_key: msg.public_key,
297
+ operator_fingerprint: msg.operator_fingerprint,
298
+ nonce: msg.nonce,
299
+ session_id: msg.session_id,
300
+ signature: msg.signature,
301
+ });
302
+ }
303
+
304
+ /** `ReverseProof` from an operator to the peer it has a pending `ReverseConnect` with (#117). */
305
+ proof(operator, msg) {
306
+ for (const [target, p] of this.#pending) {
307
+ if (p.operator !== operator) continue;
308
+ if (!(msg.public_key instanceof Uint8Array) || !(msg.signature instanceof Uint8Array) || !(msg.nonce instanceof Uint8Array)
309
+ || !isStr(msg.session_id, 256) || !isStr(msg.username, 64) || msg.public_key.length > 64 || msg.signature.length > 128 || msg.nonce.length > 64) return;
310
+ target.send({
311
+ type: MSG.REVERSE_PROOF,
312
+ target_fingerprint: target.fingerprint,
313
+ public_key: msg.public_key,
314
+ username: msg.username,
315
+ nonce: msg.nonce,
316
+ session_id: msg.session_id,
317
+ signature: msg.signature,
318
+ from_fingerprint: operator.fingerprint,
319
+ });
320
+ return;
321
+ }
322
+ }
323
+
281
324
  /** Is `handle` one end of a bridge? */
282
325
  bridged(handle) {
283
326
  return this.#operatorPeer.has(handle) || (this.#peerOperators.get(handle)?.size ?? 0) > 0;
@@ -1,219 +1,13 @@
1
1
  /**
2
- * A reverse host: this process dials OUT to a relay (`createWshServer({ relay })`),
3
- * registers itself as a peer, and serves whichever operator the relay bridges to
4
- * it -- with the same exec / pty / fs / mcp backends `createWshServer` serves
5
- * direct clients with. Use it for a machine that cannot accept connections.
6
- *
7
- * The relay has already authenticated the operator (its key), so the bridged
8
- * connection is pre-authenticated; what a relay-asserted identity is worth is
9
- * yours to decide in `accept`, which defaults to refusing everyone.
10
- *
11
- * One operator at a time by default. With `maxOperators` > 1 (and a relay
12
- * configured with `relay.maxOperatorsPerPeer`) several operators are served at
13
- * once, each with its own connection state -- channels, processes, files -- and
14
- * when one leaves only what belongs to it is cleaned up (wsh #89).
2
+ * `createReverseHost` for `@johnhenry/wsh/server`: the browser-safe reverse host (`../reverse-host.mjs`, also
3
+ * `@johnhenry/wsh/reverse`) with the Node-only backends added -- `exec: true` (a shell through child_process)
4
+ * and `fs: { root }` (a directory). The reverse host itself lives in `../reverse-host.mjs`.
15
5
  */
16
6
 
17
- import { WshClient } from '../client.mjs';
18
- import { exportPublicKeyRaw, fingerprint } from '../auth.mjs';
19
- import { reverseAccept, reverseReject } from '../messages.gen.mjs';
20
- import { MULTI_OPERATOR_FEATURE } from './relay.mjs';
21
- import { E2E_SIGN_FEATURE } from '../e2e-exchange.mjs';
7
+ import { createReverseHostWith } from '../reverse-host.mjs';
22
8
  import { buildBackends } from './backends.mjs';
23
- import { createConnectionFactory, hostFeatures } from './connection.mjs';
24
9
 
25
- const BACKOFF_START_MS = 500;
26
- const BACKOFF_MAX_MS = 30_000;
27
-
28
- /**
29
- * @param {object} options
30
- * @param {string} options.url - The relay (`ws://` or `wss://`).
31
- * @param {string} options.username
32
- * @param {CryptoKeyPair} options.keyPair - This host's identity; its fingerprint is what operators connect to.
33
- * @param {(operator: { fingerprint: string, username: string }) => boolean | Promise<boolean>} [options.accept]
34
- * Who may be bridged to this host. Default: nobody.
35
- * @param {true | object | Function} [options.exec]
36
- * @param {object} [options.pty]
37
- * @param {object} [options.fs]
38
- * @param {object} [options.mcp]
39
- * @param {boolean} [options.reconnect=true] - Dial again (with backoff) after the relay connection ends. A relay ends it when a bridge does.
40
- * @param {object} [options.connect] - Extra options for the relay connection (`expectHostKey`, `knownHosts`, ...).
41
- * @param {string} [options.peerType='host']
42
- * @param {false | { sign?: boolean | 'auto', hybrid?: boolean }} [options.e2e] - End-to-end encryption for the bridged operator (wsh #90).
43
- * On by default: this host answers an operator's `KeyExchange` (for a session it has opened), then seals that
44
- * session's output and opens its input as `EncryptedFrame`s the relay cannot read, and ignores plaintext input for it.
45
- * `sign` signs the reply with `keyPair` so the operator can authenticate this host
46
- * (`initiateE2E(..., { verifyPeer })`). Default `'auto'`: sign when the relay says (`e2e-sign` in its ServerHello) it
47
- * carries a signed `KeyExchange` -- a relay that predates the `signature` field (a Rust relay built before it)
48
- * would drop the connection on one. `true` signs regardless; `false` never does. `hybrid` (default true) offers
49
- * X25519+ML-KEM-768 when asked.
50
- * `false` turns the layer off: no `e2e` feature, `KeyExchange` unanswered.
51
- * @param {number} [options.maxOperators=1] - Operators served at once. Above 1 this host states `relay-multi-operator`
52
- * (it addresses each reply to its operator and handles `ReverseClose`), so it needs `reportFeatures` and a relay with
53
- * `relay.maxOperatorsPerPeer` above 1 (which says so in its ServerHello); against any other relay it serves one
54
- * operator, as before. Each operator is passed through `accept` on its own identity.
55
- * @param {boolean} [options.reportFeatures=true] - State this host's features in `ReverseAccept.features`, so the operator's
56
- * feature gates follow this host rather than the relay. Turn off only for a relay (a Rust `wsh-server` older than the field)
57
- * that rejects a `ReverseAccept` carrying it.
58
- * @param {(line: string) => void} [options.onLog]
59
- */
60
- export function createReverseHost({
61
- url, username, keyPair, accept, exec, pty, fs, mcp, reconnect = true, connect = {}, peerType = 'host', reportFeatures = true, maxOperators = 1, e2e = {}, onLog = () => {},
62
- } = {}) {
63
- if (!url) throw new TypeError('createReverseHost: url is required');
64
- if (!username) throw new TypeError('createReverseHost: username is required');
65
- if (!keyPair) throw new TypeError('createReverseHost: keyPair is required (the relay keys peers by fingerprint)');
66
- if (accept !== undefined && typeof accept !== 'function') throw new TypeError('createReverseHost: accept must be a function');
67
- if (!Number.isSafeInteger(maxOperators) || maxOperators < 1) throw new TypeError('createReverseHost: maxOperators must be a positive integer');
68
- if (maxOperators > 1 && !reportFeatures) throw new TypeError('createReverseHost: maxOperators > 1 needs reportFeatures (the relay learns "relay-multi-operator" from ReverseAccept.features)');
69
- if (e2e !== false && (e2e === null || typeof e2e !== 'object')) throw new TypeError('createReverseHost: e2e must be false or an options object');
70
- const multi = maxOperators > 1;
71
- if (e2e !== false && e2e.sign !== undefined && e2e.sign !== 'auto' && typeof e2e.sign !== 'boolean') throw new TypeError("createReverseHost: e2e.sign must be true, false or 'auto'");
72
- const e2eSign = e2e === false ? false : (e2e.sign ?? 'auto');
73
-
74
- const backends = buildBackends({ exec, pty, fs, mcp });
75
- const expose = { shell: !!backends.pty, exec: !!backends.execRunner, fs: !!backends.files, tools: !!backends.mcp };
76
- const capabilities = Object.entries(expose).filter(([, on]) => on).map(([k]) => k);
77
- const shellBackend = backends.pty ? 'pty' : 'exec-only';
78
- // What this host can do over a bridge, for the operator's feature gates (`ReverseAccept.features`).
79
- // `reportFeatures: false` leaves them out (a Rust peer or relay older than the field rejects a ReverseAccept that has it).
80
- /** What this host does with end-to-end encryption on a given relay connection (null = off). */
81
- const e2eFor = (c) => (e2e === false ? null : {
82
- signKey: e2eSign === true || (e2eSign === 'auto' && c.hasFeature(E2E_SIGN_FEATURE)) ? keyPair.privateKey : null,
83
- hybrid: e2e.hybrid !== false,
84
- });
85
- /** Features for `ReverseAccept` on this relay connection. */
86
- const bridgeFeatures = (c, e2eConfig, manyOperators) => [
87
- ...hostFeatures({ mcp: backends.mcp, files: backends.files, e2e: e2eConfig }, { dataStreams: false }),
88
- ...(manyOperators ? [MULTI_OPERATOR_FEATURE] : []),
89
- ];
90
- const factory = createConnectionFactory({
91
- authorize: async () => false, methods: { pubkey: false, password: null }, hostKey: null, rateLimit: null,
92
- execRunner: backends.execRunner, execOptions: backends.execOptions, pty: backends.pty, files: backends.files, mcp: backends.mcp,
93
- sessions: null, relay: null, e2e: null, bindTimeoutMs: 3000, log: (l) => onLog(`[reverse] ${l}`),
94
- });
95
-
96
- let client = null;
97
- /** The live connection's bridges (operator fingerprint -> connection), for `operators`. */
98
- let operatorsNow = new Map();
99
- /** Ends every bridge of the live connection (the client's own `disconnect()` does not call its `onClose`). */
100
- let endAllBridges = () => {};
101
- let myFingerprint = null;
102
- let closed = false;
103
- let timer = null;
104
- let backoff = BACKOFF_START_MS;
105
-
106
- async function dial() {
107
- const c = new WshClient();
108
- /** operator fingerprint -> that operator's connection (its own channels, processes, files). */
109
- const bridges = new Map();
110
- // Several operators only on a relay that says it can route to them; anywhere else, one, and bare messages.
111
- const manyOperators = () => multi && c.hasFeature(MULTI_OPERATOR_FEATURE);
112
- const operatorLimit = () => (manyOperators() ? maxOperators : 1);
113
- /** Operators whose `accept` is still running: they count towards the cap. */
114
- const reserved = new Set();
115
- operatorsNow = bridges;
116
-
117
- const endBridge = (fp) => {
118
- const bridge = bridges.get(fp);
119
- if (!bridge) return;
120
- bridges.delete(fp);
121
- c.untrustRelayPeer(fp);
122
- bridge.close();
123
- onLog(`[reverse] operator ${fp.slice(0, 12)} left (${bridges.size} still bridged)`);
124
- };
125
- const endAll = () => { for (const fp of [...bridges.keys()]) endBridge(fp); };
126
- endAllBridges = endAll;
127
- c.onRelayMessage = (msg, from) => bridges.get(from)?.receiveMessage(msg);
128
- // The relay says one operator left; the others carry on (it sends this only to a host that stated multi-operator support).
129
- c.onReverseClose = (m) => endBridge(String(m.target_fingerprint ?? ''));
130
- c.onReverseConnect = async (req) => {
131
- const from = req.from_fingerprint;
132
- const answer = (m) => c.sendRelayControl(m).catch(() => {});
133
- const refuse = (reason) => answer(reverseReject({ targetFingerprint: myFingerprint, username, reason }));
134
- if (typeof from !== 'string' || !from) { await refuse('busy: this host is already serving an operator'); return; }
135
- if (bridges.has(from) || reserved.has(from)) { await refuse('busy: you already have a bridge with this host'); return; }
136
- if (bridges.size + reserved.size >= operatorLimit()) {
137
- await refuse(manyOperators() ? `busy: this host is already serving its maximum of ${maxOperators} operators` : 'busy: this host is already serving an operator');
138
- return;
139
- }
140
- reserved.add(from);
141
- let ok = false;
142
- try {
143
- try { ok = (await accept?.({ fingerprint: from, username: String(req.username ?? '') })) === true; } catch (e) { onLog(`[reverse] accept threw: ${e.message}`); }
144
- if (!ok || bridges.size >= operatorLimit()) { await refuse('not accepted'); return; }
145
- c.trustRelayPeer(from);
146
- const bridge = factory({
147
- // With several operators every message names its recipient; with one the relay knows.
148
- sendMessage: (m) => c.sendRelayControl(m, manyOperators() ? { to: from } : undefined),
149
- authenticated: { username: String(req.username ?? 'operator'), fingerprint: from },
150
- dataStreams: false,
151
- e2e: e2eFor(c),
152
- });
153
- bridges.set(from, bridge);
154
- onLog(`[reverse] bridged to ${from.slice(0, 12)}`);
155
- await answer(reverseAccept({
156
- targetFingerprint: myFingerprint, username, capabilities, peerType, shellBackend,
157
- supportsAttach: false, supportsReplay: false, supportsEcho: false, supportsTermSync: false,
158
- features: reportFeatures ? bridgeFeatures(c, e2eFor(c), manyOperators()) : undefined,
159
- }));
160
- } finally { reserved.delete(from); }
161
- };
162
- c.onClose = () => {
163
- endAll();
164
- if (operatorsNow === bridges) operatorsNow = new Map();
165
- if (client === c) client = null;
166
- if (closed || !reconnect) return;
167
- onLog(`[reverse] relay connection ended; redialling in ${backoff}ms`);
168
- timer = setTimeout(() => { redial().catch(() => {}); }, backoff);
169
- timer.unref?.();
170
- backoff = Math.min(backoff * 2, BACKOFF_MAX_MS);
171
- };
172
-
173
- await c.connectReverse(url, {
174
- username, keyPair, expose, peerType, shellBackend,
175
- supportsAttach: false, supportsReplay: false, supportsEcho: false, supportsTermSync: false,
176
- ...connect,
177
- });
178
- client = c;
179
- backoff = BACKOFF_START_MS;
180
- onLog(`[reverse] registered ${myFingerprint.slice(0, 12)} on ${url}`);
181
- }
182
-
183
- async function redial() {
184
- if (closed) return;
185
- try { await dial(); } catch (e) {
186
- onLog(`[reverse] redial failed: ${e.message}`);
187
- if (closed || !reconnect) return;
188
- timer = setTimeout(() => { redial().catch(() => {}); }, backoff);
189
- timer.unref?.();
190
- backoff = Math.min(backoff * 2, BACKOFF_MAX_MS);
191
- }
192
- }
193
-
194
- return {
195
- /** Dial the relay and register. Rejects if the first attempt fails; later drops are retried. */
196
- async start() {
197
- if (client) throw new Error('createReverseHost: already started');
198
- closed = false;
199
- myFingerprint = await fingerprint(await exportPublicKeyRaw(keyPair.publicKey));
200
- await dial();
201
- return { fingerprint: myFingerprint };
202
- },
203
- /** Leave the relay and end any bridged session. */
204
- async close() {
205
- closed = true;
206
- clearTimeout(timer);
207
- const c = client;
208
- client = null;
209
- endAllBridges(); // no operator's process may outlive the host
210
- await c?.disconnect().catch(() => {});
211
- },
212
- /** This host's fingerprint (what operators `reverseConnect()` to); `null` before `start()`. */
213
- get fingerprint() { return myFingerprint; },
214
- /** Is the relay connection up right now? */
215
- get connected() { return client !== null; },
216
- /** Fingerprints of the operators bridged right now. */
217
- get operators() { return [...operatorsNow.keys()]; },
218
- };
10
+ /** @param {Parameters<typeof import('../reverse-host.mjs').createReverseHost>[0]} [options] - see `../reverse-host.mjs` */
11
+ export function createReverseHost(options = {}) {
12
+ return createReverseHostWith(options, buildBackends(options));
219
13
  }
@@ -8,7 +8,10 @@
8
8
  * is ignored, as the QMux framing never carries one.
9
9
  */
10
10
 
11
+ const CONNECTING = 0;
11
12
  const OPEN = 1;
13
+ /** Most bytes held for a socket that is still connecting (a handshake is a few hundred). */
14
+ const MAX_WAITING_BYTES = 256 * 1024;
12
15
 
13
16
  /** @param {unknown} data - a message payload as `ws` (Buffer, ArrayBuffer, Buffer[]) or a browser (ArrayBuffer, view, Blob) delivers it */
14
17
  async function toBytes(data) {
@@ -29,11 +32,13 @@ async function toBytes(data) {
29
32
  /**
30
33
  * @param {object} socket - the WebSocket-like duplex
31
34
  * @param {Promise<(opts: object) => { receive: Function, close: Function }>} ready - resolves to the connection factory's `attach`
32
- * @param {{ remote?: { address?: string, headers?: object } }} [options] - what the host knows about the peer
33
- * (`address` keys the password-failure throttle; the default key is shared by every socket without one)
35
+ * @param {{ remote?: { address?: string, headers?: object }, dataStreams?: boolean }} [options] - what the host knows about the peer
36
+ * (`address` keys the password-failure throttle; the default key is shared by every socket without one).
37
+ * `dataStreams: false` serves this connection without client-opened data streams (exec output rides SessionData), for a
38
+ * client that cannot open them (the Rust client over WebSocket, #132).
34
39
  * @returns {Promise<{ close(): void }>} resolves once the connection is attached; `close()` drops it
35
40
  */
36
- export function bindSocket(socket, ready, { remote = {} } = {}) {
41
+ export function bindSocket(socket, ready, { remote = {}, dataStreams } = {}) {
37
42
  if (!socket || typeof socket.send !== 'function' || typeof socket.close !== 'function') {
38
43
  throw new TypeError('accept: socket must be a WebSocket-like duplex with send() and close()');
39
44
  }
@@ -49,11 +54,26 @@ export function bindSocket(socket, ready, { remote = {} } = {}) {
49
54
  // chained behind `ready`: a peer that speaks first (a client's QMux handshake) is not dropped.
50
55
  let conn = null;
51
56
  let closed = false;
57
+ // A socket handed over while it is still connecting (`accept(new WebSocket(url))`) cannot be written to yet, but the host
58
+ // speaks first (its QMux handshake): those bytes wait for `open`, in order, and are dropped if it never opens.
59
+ let waiting = [];
60
+ let waitingBytes = 0;
61
+ const flush = () => {
62
+ const out = waiting;
63
+ waiting = []; waitingBytes = 0;
64
+ if (socket.readyState !== OPEN) return;
65
+ for (const b of out) socket.send(b);
66
+ };
67
+ const write = (bytes) => {
68
+ if (socket.readyState === OPEN) { if (waiting.length) flush(); socket.send(bytes); return; }
69
+ if (socket.readyState === CONNECTING && waitingBytes + bytes.byteLength <= MAX_WAITING_BYTES) { waiting.push(bytes); waitingBytes += bytes.byteLength; }
70
+ };
52
71
  let chain = ready.then((attach) => {
53
72
  if (closed) return;
54
73
  conn = attach({
55
- send: (bytes) => { if (socket.readyState === OPEN) socket.send(bytes); },
74
+ send: write,
56
75
  remote: { address: remote.address, headers: remote.headers ?? {} },
76
+ dataStreams,
57
77
  closeTransport: () => { try { socket.close(1000); } catch { /* already closed */ } },
58
78
  });
59
79
  });
@@ -65,6 +85,7 @@ export function bindSocket(socket, ready, { remote = {} } = {}) {
65
85
  if (bytes && !closed) conn.receive(bytes);
66
86
  }).catch(() => {});
67
87
  });
88
+ listen('open', flush);
68
89
  listen('close', drop);
69
90
  listen('error', () => {});
70
91
  return chain.then(() => ({