@johnhenry/wsh 0.36.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,92 @@ 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
+ * TCP reverse tunnels (`ListenRequest`). OFF unless given (`true` = the defaults). The host binds `bindAddr` (default
163
+ * 127.0.0.1) and ignores the client's `bind_addr` unless it is listed in `allowBindAddrs`; `ports` (default `[0, "1024-65535"]`)
164
+ * is what a client may ask for, privileged ports only if listed.
165
+ */
166
+ reverse?: boolean | {
167
+ enabled?: boolean;
168
+ bindAddr?: string;
169
+ allowBindAddrs?: string[];
170
+ ports?: Array<number | string>;
171
+ /** Reverse listeners per client (default 4). */
172
+ maxListeners?: number;
173
+ /** Open connections per listener (default 16); the next one is closed unannounced. */
174
+ maxConnectionsPerListener?: number;
175
+ /** `listen()` backlog (default 8). */
176
+ backlog?: number;
177
+ /** An accepted connection with no traffic either way for this long is closed (default 300000; 0 = never). */
178
+ idleMs?: number;
179
+ };
180
+ /** Bounds of UDP flows (`OpenUdp`); all rates drop, not queue. */
181
+ udp?: {
182
+ /** Use WebTransport datagrams for a flow when the transport and the client have them (default true). */
183
+ datagrams?: boolean;
184
+ /** Concurrent UDP flows per client (default 16). */
185
+ maxFlows?: number;
186
+ /** Datagrams per second per flow (500), per client (2000), both directions. `Infinity` = unlimited. */
187
+ packetsPerSecondPerFlow?: number;
188
+ packetsPerSecondPerClient?: number;
189
+ /** Payload bytes per second per client, both directions (default 4 MiB): bounds amplification. */
190
+ bytesPerSecondPerClient?: number;
191
+ /** A reply that does not fit one datagram: 'reliable' sends it on the control stream (default), 'drop' drops it and counts it. */
192
+ oversize?: 'reliable' | 'drop';
193
+ };
194
+ }
195
+
103
196
  export interface WshServerPtyOptions {
104
197
  /** `node-pty`'s `spawn(file, args, options)`, or anything shaped like it. */
105
198
  spawn(file: string, args: string[], options: {
@@ -111,6 +204,8 @@ export interface WshServerPtyOptions {
111
204
  env?: Record<string, string | undefined>;
112
205
  /** `TERM` value (default `xterm-256color`). */
113
206
  term?: string;
207
+ /** Which `env` variables a client may add to the shell's environment; same forms and default as `exec.clientEnv`. */
208
+ clientEnv?: WshClientEnv;
114
209
  }
115
210
 
116
211
  export interface WshServerFsOptions {
@@ -343,9 +438,14 @@ export interface WshServerOptions {
343
438
  * Answer the gateway opcodes (OpenTcp, ResolveDns, GatewayData, GatewayClose) so a client can open TCP connections and
344
439
  * resolve names from this host. Default deny: a destination must match `allow` (`"*"`, `"host"` any port, `"host:port"`).
345
440
  * `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.
441
+ * refused. UDP and TCP reverse tunnels are answered with a failure. Off by default.
442
+ *
443
+ * The ADDRESS a name resolves to is checked too: the host resolves once, refuses every address
444
+ * that is not globally routable (loopback, private, link-local, CGNAT, ULA, multicast, reserved, and IPv4 wrapped as
445
+ * mapped / NAT64 / 6to4 IPv6) unless `allowPrivate` or an IP-literal `allow` entry says so, and connects to that
446
+ * address. `ResolveDns` answers are filtered the same way. Gateway data is flow controlled (`gateway-credit`).
347
447
  */
348
- gateway?: { allow: string[]; maxConnections?: number; connectTimeoutMs?: number; socks?: string | { host: string; port: number } };
448
+ gateway?: WshServerGatewayOptions;
349
449
  /**
350
450
  * Handlers for application-defined control messages: one whose `type` is a string (protocol messages are numeric, so
351
451
  * there is no collision) from an authenticated connection is handed to `extensions[type]`. A throw is logged.
@@ -372,6 +472,14 @@ export interface WshServerOptions {
372
472
  rpcMaxInflight?: number;
373
473
  /** How long exec output waits for a client that has not yet opened its data stream (default 3000). */
374
474
  bindTimeoutMs?: number;
475
+ /** End every authenticated connection this long after login; advertised as `AuthOk.ttl` (whole seconds, rounded up). 0 / omitted = never. */
476
+ connectionTtlMs?: number;
477
+ /**
478
+ * Accept a key login only when its signature is bound to this connection (#119): `true` needs any binding kind, an array
479
+ * names kinds that must all be bound (`host` needs `hostKey`; `tls-exporter` needs `wss://` served by this process, not a
480
+ * TLS-terminating proxy; `cert-hash` needs WebTransport with `selfSigned`). Clients older than 0.36 cannot satisfy it.
481
+ */
482
+ requireChannelBinding?: boolean | Array<'cert-hash' | 'host' | 'tls-exporter'>;
375
483
  onLog?: (line: string) => void;
376
484
  }
377
485
 
@@ -455,6 +563,8 @@ export interface WshServer {
455
563
  rotateCertificate(options?: { activate?: boolean }): Promise<{ current: WshServerCertificateInfo; next: WshServerCertificateInfo | null }>;
456
564
  /** Fingerprints of the peers currently registered with this relay (`[]` when it is not one). */
457
565
  peerFingerprints(): string[];
566
+ /** Counters of the gateway's UDP flows (datagrams in/out, drops by cause, oversize handling) and reverse listeners; null without a gateway. */
567
+ gatewayStats(): { udp: Record<string, number>; reverse: Record<string, number> } | null;
458
568
  /** The advertised host identity; `null` before `listen()` resolves or without a `hostKey`. */
459
569
  hostKey(): WshServerHostKey | null;
460
570
  }
@@ -474,7 +584,14 @@ export interface WshReverseHostOptions {
474
584
  /** This host's identity; its fingerprint is what operators connect to. */
475
585
  keyPair: CryptoKeyPair;
476
586
  /** Who may be bridged to this host. Default: nobody. */
477
- accept?: (operator: { fingerprint: string; username: string }) => boolean | Promise<boolean>;
587
+ accept?: (operator: {
588
+ fingerprint: string;
589
+ username: string;
590
+ /** 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. */
591
+ proven: boolean;
592
+ /** The operator's raw Ed25519 key, when `proven`. */
593
+ publicKey?: Uint8Array;
594
+ }) => boolean | Promise<boolean>;
478
595
  exec?: true | WshServerExecOptions | WshExecRunner;
479
596
  pty?: WshServerPtyOptions;
480
597
  fs?: WshServerFsOptions;
@@ -501,6 +618,16 @@ export interface WshReverseHostOptions {
501
618
  * `hybrid` (default true) offers X25519+ML-KEM-768 when asked and available.
502
619
  */
503
620
  e2e?: false | { sign?: boolean | 'auto'; hybrid?: boolean };
621
+ /**
622
+ * Require the operator to prove its identity to this host (wsh #117) and seal the bridge: an operator that does not
623
+ * offer proof is refused, `accept` runs only after the proof verifies (with the identity taken from the proof, not
624
+ * the relay), and this host acts only on messages sealed under a key exchange both sides signed -- a relay cannot
625
+ * inject an `Open`. Needs `e2e` and `reportFeatures`. Without it the proof is still requested when the relay and the
626
+ * operator can do it, and reported as `proven`.
627
+ */
628
+ requireOperatorProof?: boolean;
629
+ /** How long an operator has to answer the challenge (default 5000). */
630
+ proofTimeoutMs?: number;
504
631
  onLog?: (line: string) => void;
505
632
  }
506
633
 
@@ -18,11 +18,21 @@ import { createConnectionFactory, STREAM_ANNOUNCE } from './connection.mjs';
18
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']
@@ -72,14 +82,24 @@ export { generateSelfSignedCertificate } from './self-signed.mjs';
72
82
  * @param {{ allow: string[], maxConnections?: number, connectTimeoutMs?: number, socks?: string | { host: string, port: number } }} [options.gateway]
73
83
  * Answer the gateway opcodes (OpenTcp, ResolveDns, GatewayData/Close): the client opens TCP connections and resolves
74
84
  * names from this host. Default deny: a destination must match `allow` (`"*"`, `"host"`, `"host:port"`). `socks` dials
75
- * through a SOCKS5 proxy (Tor) with the name unresolved. UDP and reverse tunnels are refused. Off unless given. See `gateway.mjs`.
85
+ * through a SOCKS5 proxy (Tor) with the name unresolved. UDP (`udp`: bounds, WebTransport datagrams) and TCP reverse tunnels (`reverse`, off unless given) are served. 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,7 +145,7 @@ 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,
148
+ authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, log: onLog,
129
149
  methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, createGatewaySession, sessions: registry, relay: hub,
130
150
  });
131
151
  })();
@@ -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);
@@ -263,6 +284,11 @@ export function createWshServer({
263
284
  return wt.rotateCertificate(options);
264
285
  },
265
286
 
287
+ /** Counters of the gateway's UDP flows and reverse listeners (drops by cause, oversize handling), or `null` without a gateway. */
288
+ gatewayStats() {
289
+ return gatewayCfg ? JSON.parse(JSON.stringify(gatewayCfg.stats)) : null;
290
+ },
291
+
266
292
  /** Fingerprints of the peers currently registered with this relay (`[]` when it is not one). */
267
293
  peerFingerprints() {
268
294
  return hub ? hub.peerFingerprints() : [];
@@ -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;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Policy of the Node host's TCP reverse tunnels (`ListenRequest`, #98): the host binds a port on the client's behalf
3
+ * and hands each inbound connection to the client. This is the dangerous direction (it puts a port of the HOST on the
4
+ * network), so everything here is explicit and bounded:
5
+ *
6
+ * - OFF unless `gateway.reverse` is given (a separate switch from outbound gateway use: `allow` has no say here).
7
+ * - The host binds `bindAddr` (default 127.0.0.1). The `bind_addr` the client sends is IGNORED unless it is one of the
8
+ * addresses the operator listed in `allowBindAddrs`; this matches the Rust server's `reverse_bind_addr`.
9
+ * - `ports`: which ports a client may ask for, numbers and `"lo-hi"` ranges. The default is `[0, "1024-65535"]`
10
+ * (ephemeral, or any unprivileged port). A list you give REPLACES the default, so nothing is allowed that it does not
11
+ * name, and a port below 1024 is allowed only when listed.
12
+ * - Bounds: `maxListeners` per client, `maxConnectionsPerListener`, `backlog` of the listening socket, `idleMs` of an
13
+ * accepted connection.
14
+ *
15
+ * Imports no Node built-in (the address parser it uses is pure).
16
+ */
17
+
18
+ import { parseIp } from './address-guard.mjs';
19
+
20
+ export const DEFAULT_REVERSE = Object.freeze({
21
+ bindAddr: '127.0.0.1',
22
+ maxListeners: 4,
23
+ maxConnectionsPerListener: 16,
24
+ backlog: 8,
25
+ idleMs: 300_000,
26
+ });
27
+
28
+ const DEFAULT_PORTS = [[0, 0], [1024, 65535]];
29
+
30
+ function parsePortRule(rule) {
31
+ const bad = () => new TypeError(`gateway.reverse.ports: ${JSON.stringify(rule)} is not a port (0-65535) or a "lo-hi" range`);
32
+ if (typeof rule === 'number') {
33
+ if (!Number.isInteger(rule) || rule < 0 || rule > 65535) throw bad();
34
+ return [rule, rule];
35
+ }
36
+ if (typeof rule !== 'string') throw bad();
37
+ const m = /^\s*(\d{1,5})\s*(?:-\s*(\d{1,5})\s*)?$/.exec(rule);
38
+ if (!m) throw bad();
39
+ const lo = Number(m[1]);
40
+ const hi = m[2] === undefined ? lo : Number(m[2]);
41
+ if (lo > 65535 || hi > 65535 || lo > hi) throw bad();
42
+ return [lo, hi];
43
+ }
44
+
45
+ const positive = (v, what, min = 1) => {
46
+ if (!Number.isInteger(v) || v < min) throw new TypeError(`gateway.reverse.${what} must be an integer of at least ${min}`);
47
+ return v;
48
+ };
49
+
50
+ /**
51
+ * @param {unknown} opts `gateway.reverse`: `true`, or `{ bindAddr, allowBindAddrs, ports, maxListeners, maxConnectionsPerListener, backlog, idleMs }`
52
+ * @returns {null | { bindAddr: string, allowBindAddrs: string[], ports: Array<[number, number]>, maxListeners: number, maxConnectionsPerListener: number, backlog: number, idleMs: number }}
53
+ */
54
+ export function normalizeReverse(opts) {
55
+ if (opts === undefined || opts === null || opts === false) return null;
56
+ if (opts === true) opts = {};
57
+ if (typeof opts !== 'object' || Array.isArray(opts)) throw new TypeError('gateway.reverse must be true or an options object');
58
+ if (opts.enabled === false) return null;
59
+ const bindAddr = opts.bindAddr ?? DEFAULT_REVERSE.bindAddr;
60
+ if (typeof bindAddr !== 'string' || !parseIp(bindAddr)) throw new TypeError('gateway.reverse.bindAddr must be an IP address (e.g. "127.0.0.1"), not a name');
61
+ const allowBindAddrs = opts.allowBindAddrs ?? [];
62
+ if (!Array.isArray(allowBindAddrs) || allowBindAddrs.some((a) => typeof a !== 'string' || !parseIp(a))) {
63
+ throw new TypeError('gateway.reverse.allowBindAddrs must be an array of IP addresses (no names, no wildcard)');
64
+ }
65
+ let ports = DEFAULT_PORTS;
66
+ if (opts.ports !== undefined) {
67
+ if (!Array.isArray(opts.ports)) throw new TypeError('gateway.reverse.ports must be an array of ports and "lo-hi" ranges');
68
+ ports = opts.ports.map(parsePortRule);
69
+ }
70
+ return {
71
+ bindAddr,
72
+ allowBindAddrs: [...allowBindAddrs],
73
+ ports,
74
+ maxListeners: positive(opts.maxListeners ?? DEFAULT_REVERSE.maxListeners, 'maxListeners', 0),
75
+ maxConnectionsPerListener: positive(opts.maxConnectionsPerListener ?? DEFAULT_REVERSE.maxConnectionsPerListener, 'maxConnectionsPerListener'),
76
+ backlog: positive(opts.backlog ?? DEFAULT_REVERSE.backlog, 'backlog'),
77
+ idleMs: positive(opts.idleMs ?? DEFAULT_REVERSE.idleMs, 'idleMs', 0),
78
+ };
79
+ }
80
+
81
+ /** May a client ask for this port? */
82
+ export function reversePortAllowed(reverse, port) {
83
+ return Number.isInteger(port) && port >= 0 && port <= 65535 && reverse.ports.some(([lo, hi]) => port >= lo && port <= hi);
84
+ }
85
+
86
+ /** The refusal sentence for a port the policy does not allow. */
87
+ export function reversePortRefusal(reverse, port) {
88
+ if (port < 1024 && !reverse.ports.some(([lo, hi]) => lo <= port && port <= hi)) {
89
+ return `port ${port} is not allowed by the reverse-tunnel policy (ports below 1024 must be listed explicitly by the host operator)`;
90
+ }
91
+ return `port ${port} is not allowed by the reverse-tunnel policy`;
92
+ }
93
+
94
+ /** The address to bind: the client's choice only if the operator listed it, else the configured one. */
95
+ export function reverseBindAddress(reverse, requested) {
96
+ if (typeof requested === 'string' && reverse.allowBindAddrs.some((a) => a.toLowerCase() === requested.toLowerCase())) return requested;
97
+ return reverse.bindAddr;
98
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Bounds of the Node host's UDP flows (`gateway.udp`, #98 / #124). A UDP flow is a socket the host opens on the client's
3
+ * behalf, to ONE destination fixed at `OpenUdp`, so the risks are the host being used as a packet cannon and as an
4
+ * amplifier: a small query that makes a big answer, repeated. Everything is therefore rate-limited in both directions
5
+ * and bounded in count. Browser-safe (pure).
6
+ *
7
+ * - `datagrams` (default true): use WebTransport datagrams for a flow when the transport and the peer have them.
8
+ * - `maxFlows` (16): concurrent UDP flows per client (they also count against `maxConnections`).
9
+ * - `packetsPerSecondPerFlow` (500) and `packetsPerSecondPerClient` (2000): token buckets over datagrams in BOTH
10
+ * directions; a datagram over the limit is dropped (and counted), as a congested network would.
11
+ * - `bytesPerSecondPerClient` (4 MiB): the same over payload bytes in both directions. This is what bounds
12
+ * amplification: no matter how many bytes an origin answers with, no more than this reach the client per second.
13
+ * - `oversize` ('reliable'): a payload from the origin that does not fit one datagram goes on the reliable control
14
+ * stream rather than being lost; 'drop' drops it (strict UDP semantics) and counts it.
15
+ */
16
+
17
+ export const DEFAULT_UDP = Object.freeze({
18
+ datagrams: true,
19
+ maxFlows: 16,
20
+ packetsPerSecondPerFlow: 500,
21
+ packetsPerSecondPerClient: 2000,
22
+ bytesPerSecondPerClient: 4 * 1024 * 1024,
23
+ oversize: 'reliable',
24
+ });
25
+
26
+ const rate = (v, what) => {
27
+ if (v === Infinity) return v;
28
+ if (!Number.isFinite(v) || v <= 0) throw new TypeError(`gateway.udp.${what} must be a positive number (or Infinity for no limit)`);
29
+ return v;
30
+ };
31
+
32
+ /** @param {unknown} opts `gateway.udp` (`undefined` = the defaults) */
33
+ export function normalizeUdp(opts) {
34
+ if (opts === undefined || opts === null || opts === true) opts = {};
35
+ if (typeof opts !== 'object' || Array.isArray(opts)) throw new TypeError('gateway.udp must be an options object');
36
+ const maxFlows = opts.maxFlows ?? DEFAULT_UDP.maxFlows;
37
+ if (!Number.isInteger(maxFlows) || maxFlows < 0) throw new TypeError('gateway.udp.maxFlows must be a non-negative integer');
38
+ const oversize = opts.oversize ?? DEFAULT_UDP.oversize;
39
+ if (oversize !== 'reliable' && oversize !== 'drop') throw new TypeError('gateway.udp.oversize must be "reliable" or "drop"');
40
+ return {
41
+ datagrams: opts.datagrams !== false,
42
+ maxFlows,
43
+ packetsPerSecondPerFlow: rate(opts.packetsPerSecondPerFlow ?? DEFAULT_UDP.packetsPerSecondPerFlow, 'packetsPerSecondPerFlow'),
44
+ packetsPerSecondPerClient: rate(opts.packetsPerSecondPerClient ?? DEFAULT_UDP.packetsPerSecondPerClient, 'packetsPerSecondPerClient'),
45
+ bytesPerSecondPerClient: rate(opts.bytesPerSecondPerClient ?? DEFAULT_UDP.bytesPerSecondPerClient, 'bytesPerSecondPerClient'),
46
+ oversize,
47
+ };
48
+ }
49
+
50
+ /** A fresh counter set (one per gateway configuration, shared by its client connections). */
51
+ export function newGatewayStats() {
52
+ return {
53
+ udp: {
54
+ flowsOpened: 0, datagramsFromClient: 0, datagramsToClient: 0, reliableFromClient: 0, reliableToClient: 0,
55
+ oversizeReliable: 0, oversizeDropped: 0, rateDropped: 0, backpressureDropped: 0, unknownFlow: 0, malformed: 0,
56
+ },
57
+ reverse: { listeners: 0, accepted: 0, refusedConnections: 0, idleClosed: 0 },
58
+ };
59
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Which unix-domain socket paths may a client reach on (or create on) the host? Default deny: nothing unless the
3
+ * operator listed it. Node only (it touches the file system); loaded lazily by the gateway so the browser-safe
4
+ * memory host never imports it.
5
+ *
6
+ * A pattern is an absolute path, exact (`/var/run/docker.sock`) or a directory prefix with a trailing slash
7
+ * (`/run/user/1000/wsh/`), or, for the Linux abstract namespace, `@name` / `@prefix/`. A requested path is accepted
8
+ * only when, AFTER the parent directory has been resolved with `realpath`, it equals an exact pattern or lies under
9
+ * a prefix (patterns are resolved the same way, so `/var/run` and `/private/var/run` agree). The file itself must
10
+ * be a socket and not a symlink. A `..` segment is refused outright. This closes the "allowed directory contains a
11
+ * symlink to somewhere else" escape; it cannot close the window between the check and the connect (the path is
12
+ * connected by its resolved name, which narrows it), so allow only directories no other local user can write to.
13
+ */
14
+
15
+ import path from 'node:path';
16
+
17
+ let fsp = null;
18
+ const loadFs = async () => (fsp ??= (await import('node:fs/promises')).default);
19
+
20
+ export const ABSTRACT_PREFIX = '@';
21
+ const MAX_PATH = 4096;
22
+
23
+ /** @param {string[] | undefined} list @param {string} what */
24
+ function checkPatterns(list, what) {
25
+ if (list === undefined) return [];
26
+ if (!Array.isArray(list) || list.some((p) => typeof p !== 'string' || !p)) throw new TypeError(`gateway.unix.${what} must be an array of non-empty strings`);
27
+ for (const p of list) {
28
+ if (p.includes('\0') || p.length > MAX_PATH) throw new TypeError(`gateway.unix.${what}: bad pattern ${JSON.stringify(p.slice(0, 80))}`);
29
+ if (!p.startsWith('/') && !p.startsWith(ABSTRACT_PREFIX)) throw new TypeError(`gateway.unix.${what}: ${JSON.stringify(p)} must be an absolute path or an abstract name starting with "@"`);
30
+ if (p === '/' || p === ABSTRACT_PREFIX || p === `${ABSTRACT_PREFIX}/`) throw new TypeError(`gateway.unix.${what}: ${JSON.stringify(p)} would allow everything; list a specific path or directory`);
31
+ if (p.split('/').includes('..')) throw new TypeError(`gateway.unix.${what}: ${JSON.stringify(p)} must not contain ".."`);
32
+ }
33
+ return [...list];
34
+ }
35
+
36
+ /**
37
+ * @param {object} [opts]
38
+ * @param {string[]} [opts.connect] sockets a client may connect to (`OpenUnix`)
39
+ * @param {string[]} [opts.listen] sockets a client may ask the host to create (`ListenUnix`)
40
+ * @param {boolean} [opts.replaceStale=false] a client may ask to replace a stale socket file (OpenSSH `StreamLocalBindUnlink`)
41
+ * @param {number} [opts.maxListeners=4] unix listeners per client connection
42
+ */
43
+ export function normalizeUnixPolicy(opts) {
44
+ if (opts === undefined || opts === null || opts === false) return null;
45
+ if (opts === true || typeof opts !== 'object') throw new TypeError('gateway.unix needs explicit paths (default deny): { connect: [...], listen: [...] }');
46
+ const maxListeners = opts.maxListeners ?? 4;
47
+ if (!Number.isInteger(maxListeners) || maxListeners < 0) throw new TypeError('gateway.unix.maxListeners must be a non-negative integer');
48
+ return {
49
+ connect: checkPatterns(opts.connect, 'connect'),
50
+ listen: checkPatterns(opts.listen, 'listen'),
51
+ replaceStale: opts.replaceStale === true,
52
+ maxListeners,
53
+ };
54
+ }
55
+
56
+ /** Is `target` the pattern, or under it (prefix patterns end with "/")? Both already resolved. */
57
+ function matches(pattern, target) {
58
+ return pattern.endsWith('/') ? target.startsWith(pattern) : target === pattern;
59
+ }
60
+
61
+ /** The pattern as the file system sees it today: its parent (or itself, for a prefix) through realpath. */
62
+ async function resolvePattern(p) {
63
+ const fs = await loadFs();
64
+ try {
65
+ if (p.endsWith('/')) return `${(await fs.realpath(p)).replace(/\/+$/, '')}/`;
66
+ return path.join(await fs.realpath(path.dirname(p)), path.basename(p));
67
+ } catch { return null; } // a pattern whose directory does not exist matches nothing
68
+ }
69
+
70
+ /**
71
+ * @param {string} requested what the client sent
72
+ * @param {string[]} patterns
73
+ * @returns {Promise<{ ok: true, abstract: boolean, path: string } | { ok: false, reason: string }>}
74
+ * `path` is what to connect to or bind: the resolved path, or `\0name` for an abstract socket.
75
+ */
76
+ export async function checkUnixPath(requested, patterns) {
77
+ if (typeof requested !== 'string' || !requested || requested.length > MAX_PATH || requested.indexOf('\0', 1) !== -1) return { ok: false, reason: 'malformed path' };
78
+ // Abstract namespace: refused unless a pattern lists it; there is no file system to resolve.
79
+ if (requested.startsWith(ABSTRACT_PREFIX) || requested.startsWith('\0')) {
80
+ const name = ABSTRACT_PREFIX + requested.slice(1);
81
+ if (name.length < 2) return { ok: false, reason: 'malformed path' };
82
+ if (name.split('/').includes('..')) return { ok: false, reason: 'malformed path' };
83
+ const listed = patterns.some((p) => p.startsWith(ABSTRACT_PREFIX) && matches(p, name));
84
+ return listed ? { ok: true, abstract: true, path: `\0${name.slice(1)}` } : { ok: false, reason: 'path not allowed by the gateway policy' };
85
+ }
86
+ if (!requested.startsWith('/') || requested.split('/').includes('..')) return { ok: false, reason: 'path must be absolute and without ".."' };
87
+ const base = path.basename(requested);
88
+ if (!base || base === '.' || base === '..' || requested.endsWith('/')) return { ok: false, reason: 'malformed path' };
89
+ const fs = await loadFs();
90
+ let resolved;
91
+ try { resolved = path.join(await fs.realpath(path.dirname(requested)), base); } catch { return { ok: false, reason: 'path not allowed by the gateway policy' }; }
92
+ for (const p of patterns) {
93
+ if (p.startsWith(ABSTRACT_PREFIX)) continue;
94
+ const rp = await resolvePattern(p);
95
+ if (rp && matches(rp, resolved)) return { ok: true, abstract: false, path: resolved };
96
+ }
97
+ return { ok: false, reason: 'path not allowed by the gateway policy' };
98
+ }
99
+
100
+ /** `lstat` of an allowed path: `null` when absent, else `{ socket, ino, dev }` (a symlink is never a socket here). */
101
+ export async function statSocket(p) {
102
+ const fs = await loadFs();
103
+ try {
104
+ const st = await fs.lstat(p);
105
+ return { socket: st.isSocket(), ino: st.ino, dev: st.dev };
106
+ } catch (e) {
107
+ if (e.code === 'ENOENT') return null;
108
+ throw e;
109
+ }
110
+ }
111
+
112
+ export async function unlinkIfSocket(p, expect) {
113
+ const fs = await loadFs();
114
+ try {
115
+ const st = await fs.lstat(p);
116
+ if (!st.isSocket()) return;
117
+ if (expect && (st.ino !== expect.ino || st.dev !== expect.dev)) return; // someone else's socket now
118
+ await fs.unlink(p);
119
+ } catch { /* already gone */ }
120
+ }