@johnhenry/wsh 0.37.0 → 0.38.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +223 -32
- package/package.json +2 -2
- package/src/client.mjs +68 -10
- package/src/gateway-client.mjs +64 -9
- package/src/gateway-datagram.mjs +191 -0
- package/src/index.d.ts +35 -3
- package/src/index.mjs +1 -0
- package/src/server/connection.mjs +7 -2
- package/src/server/gateway-core.mjs +2 -1
- package/src/server/gateway.mjs +133 -21
- package/src/server/index.d.ts +35 -0
- package/src/server/index.mjs +6 -1
- package/src/server/relay.mjs +6 -1
- package/src/server/reverse-policy.mjs +98 -0
- package/src/server/udp-policy.mjs +59 -0
- package/src/server/webtransport.mjs +29 -0
- package/src/transport.mjs +60 -0
package/src/server/gateway.mjs
CHANGED
|
@@ -21,10 +21,15 @@
|
|
|
21
21
|
* `src/gateway-channel.mjs`); with an older peer the host bounds its buffering by `maxBufferedBytes` per connection
|
|
22
22
|
* and `maxClientBufferedBytes` per client and closes a connection that exceeds them.
|
|
23
23
|
*
|
|
24
|
-
* `OpenUdp`
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
24
|
+
* `OpenUdp` flows go to ONE destination chosen at open (same destination policy as TCP, resolved-address check
|
|
25
|
+
* included; replies are accepted only from that address and port, the socket is `connect()`ed to it). Over a
|
|
26
|
+
* WebSocket (or any peer without "gateway-datagram") one GatewayData is one datagram on the reliable control stream; over
|
|
27
|
+
* WebTransport, when both ends list "gateway-datagram", the payloads are WebTransport datagrams with a 4-byte flow-id
|
|
28
|
+
* header (`src/gateway-datagram.mjs`), so loss on one flow delays no other and nothing is retransmitted. Bounds
|
|
29
|
+
* (`udp: {...}`): flows per client, packets per second per flow and per client, bytes per second per client, idle flows
|
|
30
|
+
* closed after `udpIdleMs`; a payload bigger than the datagram limit goes on the reliable stream (or is dropped, by `udp.oversize`).
|
|
31
|
+
*
|
|
32
|
+
* `reverse: {...}` (off unless given): TCP reverse tunnels (`ListenRequest`), see `reverse-policy.mjs`.
|
|
28
33
|
*
|
|
29
34
|
* `socks`: dial through a SOCKS5 proxy (`'host:port'`, `socks5://host:port` or `{ host, port }`), e.g. a local Tor
|
|
30
35
|
* client (`127.0.0.1:9050`). Commands carry the destination as a domain name (ATYP 3), so name resolution happens at
|
|
@@ -39,6 +44,12 @@ import {
|
|
|
39
44
|
GATEWAY_FAIL, HALF_CLOSE_GRACE_MS, gatewayFeatures, createGatewayCore, normalizeGatewayLimits, normalizeEndpoints,
|
|
40
45
|
} from './gateway-core.mjs';
|
|
41
46
|
import { isPublicAddress, parseCidr, addressInCidr, parseIp, sameAddress } from './address-guard.mjs';
|
|
47
|
+
import { normalizeReverse, reversePortAllowed, reversePortRefusal, reverseBindAddress } from './reverse-policy.mjs';
|
|
48
|
+
import { normalizeUdp, newGatewayStats } from './udp-policy.mjs';
|
|
49
|
+
import { TokenBucket, encodeDatagram, decodeDatagram, MAX_UDP_PAYLOAD, GATEWAY_DATAGRAM_FEATURE } from '../gateway-datagram.mjs';
|
|
50
|
+
|
|
51
|
+
export { normalizeReverse, reversePortAllowed } from './reverse-policy.mjs';
|
|
52
|
+
export { normalizeUdp } from './udp-policy.mjs';
|
|
42
53
|
|
|
43
54
|
// Loaded on first use so that importing the connection handler (which serves the gateway opcodes)
|
|
44
55
|
// does not pull `node:net` into a browser bundle (see `src/memory-host.mjs`).
|
|
@@ -55,7 +66,7 @@ const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;
|
|
|
55
66
|
const MAX_PENDING_INBOUND = 16;
|
|
56
67
|
const INBOUND_ACCEPT_TIMEOUT_MS = 30_000;
|
|
57
68
|
const DEFAULT_UDP_IDLE_MS = 60_000;
|
|
58
|
-
const MAX_DATAGRAM =
|
|
69
|
+
const MAX_DATAGRAM = MAX_UDP_PAYLOAD;
|
|
59
70
|
const UDP_OUTBOX_BYTES = 256 * 1024;
|
|
60
71
|
|
|
61
72
|
/** @param {string|{host:string,port:number}} socks */
|
|
@@ -232,6 +243,8 @@ export async function dialChecked(cfg, host, port, explicitLiteral, timeoutMs =
|
|
|
232
243
|
* @param {number} [opts.maxClientBufferedBytes=33554432] the same, summed over one client's connections
|
|
233
244
|
* @param {string|{host:string,port:number}} [opts.socks] dial through this SOCKS5 proxy (Tor)
|
|
234
245
|
* @param {{ connect?: string[], listen?: string[], replaceStale?: boolean, maxListeners?: number }} [opts.unix] unix-domain sockets (see unix-policy.mjs)
|
|
246
|
+
* @param {boolean | object} [opts.reverse] TCP reverse tunnels, off unless given (see reverse-policy.mjs)
|
|
247
|
+
* @param {object} [opts.udp] UDP bounds (see udp-policy.mjs)
|
|
235
248
|
* @param {Record<string, Function | { open: Function, authorize?: Function }>} [opts.endpoints] named virtual endpoints
|
|
236
249
|
* @param {boolean} [opts.tcp=true] false: no TCP or DNS at all (an endpoints-only host such as the memory host)
|
|
237
250
|
* @param {(line: string) => void} [opts.log]
|
|
@@ -264,6 +277,9 @@ export function normalizeGateway(opts) {
|
|
|
264
277
|
maxClientBufferedBytes,
|
|
265
278
|
connectTimeoutMs: opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
|
|
266
279
|
udpIdleMs: opts.udpIdleMs ?? DEFAULT_UDP_IDLE_MS,
|
|
280
|
+
udp: normalizeUdp(opts.udp),
|
|
281
|
+
reverse: normalizeReverse(opts.reverse),
|
|
282
|
+
stats: newGatewayStats(),
|
|
267
283
|
socks: parseSocks(opts.socks),
|
|
268
284
|
tcp: opts.tcp !== false,
|
|
269
285
|
unix,
|
|
@@ -398,11 +414,23 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
|
|
|
398
414
|
}
|
|
399
415
|
}
|
|
400
416
|
|
|
401
|
-
// ── UDP
|
|
402
|
-
//
|
|
403
|
-
//
|
|
404
|
-
//
|
|
405
|
-
//
|
|
417
|
+
// ── UDP ──────────────────────────────────────────────────────────
|
|
418
|
+
// A flow is one connect()ed UDP socket: one destination, fixed at OpenUdp, whose address passed the resolved-address
|
|
419
|
+
// policy; the kernel delivers nothing to it from any other address or port, so the host is no relay to arbitrary peers.
|
|
420
|
+
// Payloads travel as WebTransport datagrams when both ends negotiated "gateway-datagram" (no retransmission, no
|
|
421
|
+
// head-of-line blocking between flows), else one GatewayData per datagram on the reliable control stream. Both
|
|
422
|
+
// directions are rate-limited (token buckets: per flow, per client, and bytes per client) and a datagram over a limit
|
|
423
|
+
// is dropped and counted, as a congested network would. What a client cannot take fast enough is dropped, never buffered.
|
|
424
|
+
|
|
425
|
+
const udpCfg = cfg.udp;
|
|
426
|
+
const stats = cfg.stats.udp;
|
|
427
|
+
const clientPackets = new TokenBucket(udpCfg.packetsPerSecondPerClient, Math.max(udpCfg.packetsPerSecondPerClient / 4, 32));
|
|
428
|
+
const clientBytes = new TokenBucket(udpCfg.bytesPerSecondPerClient, Math.max(udpCfg.bytesPerSecondPerClient / 4, 65536));
|
|
429
|
+
/** gateway_id -> handler for a datagram that arrived for the flow. */
|
|
430
|
+
const udpFlows = new Map();
|
|
431
|
+
const udpPending = new Set();
|
|
432
|
+
let peerDatagrams = false;
|
|
433
|
+
const datagramsOn = () => peerDatagrams && udpCfg.datagrams && !!ctx.datagrams;
|
|
406
434
|
|
|
407
435
|
async function openUdp(m) {
|
|
408
436
|
const id = m.gateway_id;
|
|
@@ -417,7 +445,9 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
|
|
|
417
445
|
log(`gateway: refused udp ${m.host}:${m.port} (not on the allow list)`);
|
|
418
446
|
return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'destination not allowed by the gateway policy');
|
|
419
447
|
}
|
|
448
|
+
if (udpFlows.size + udpPending.size >= udpCfg.maxFlows) return fail(id, GATEWAY_FAIL.QUEUE_FULL, `too many UDP flows (limit ${udpCfg.maxFlows})`);
|
|
420
449
|
if (active() >= cfg.maxConnections) return fail(id, GATEWAY_FAIL.QUEUE_FULL, 'too many gateway connections');
|
|
450
|
+
udpPending.add(id);
|
|
421
451
|
pending.add(id);
|
|
422
452
|
let sock;
|
|
423
453
|
let address;
|
|
@@ -427,34 +457,50 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
|
|
|
427
457
|
sock = dgram.createSocket(address.includes(':') ? 'udp6' : 'udp4');
|
|
428
458
|
await new Promise((resolve, reject) => { sock.once('error', reject); sock.connect(m.port, address, () => { sock.off('error', reject); resolve(); }); });
|
|
429
459
|
} catch (e) {
|
|
430
|
-
pending.delete(id);
|
|
460
|
+
pending.delete(id); udpPending.delete(id);
|
|
431
461
|
try { sock?.close(); } catch { /* not open */ }
|
|
432
462
|
if (e.code === GATEWAY_FAIL.POLICY_DENIED) log(`gateway: refused udp ${m.host}:${m.port} (${e.message})`);
|
|
433
463
|
return fail(id, typeof e.code === 'number' ? e.code : GATEWAY_FAIL.HOST_UNREACHABLE, String(e.message).slice(0, 200));
|
|
434
464
|
}
|
|
435
|
-
pending.delete(id);
|
|
465
|
+
pending.delete(id); udpPending.delete(id);
|
|
436
466
|
if (closed) { sock.close(); return undefined; }
|
|
437
467
|
attachDatagrams(id, sock);
|
|
438
|
-
|
|
468
|
+
stats.flowsOpened++;
|
|
469
|
+
log(`gateway: ${id} -> udp ${m.host}:${m.port}${address !== m.host ? ` (${address})` : ''}${datagramsOn() ? ' (datagrams)' : ''} (local port ${sock.address().port})`);
|
|
439
470
|
return reply(gatewayOk({ gatewayId: id, resolvedAddr: address }));
|
|
440
471
|
}
|
|
441
472
|
|
|
442
473
|
function attachDatagrams(id, sock) {
|
|
443
474
|
let idle = null;
|
|
444
475
|
const touch = () => { clearTimeout(idle); idle = setTimeout(() => channel.destroy('idle timeout'), cfg.udpIdleMs); idle.unref?.(); };
|
|
476
|
+
const flowPackets = new TokenBucket(udpCfg.packetsPerSecondPerFlow, Math.max(udpCfg.packetsPerSecondPerFlow / 4, 16));
|
|
477
|
+
const useDatagrams = datagramsOn();
|
|
478
|
+
/** All three buckets must have room; a datagram over any limit is dropped. */
|
|
479
|
+
const admit = (n) => {
|
|
480
|
+
if (flowPackets.take(1) && clientPackets.take(1) && clientBytes.take(n)) return true;
|
|
481
|
+
stats.rateDropped++;
|
|
482
|
+
return false;
|
|
483
|
+
};
|
|
445
484
|
const outbox = [];
|
|
446
485
|
let outboxBytes = 0;
|
|
447
486
|
let pumping = false;
|
|
448
487
|
const channel = makeChannel(id, {
|
|
449
|
-
onData: (bytes) => {
|
|
488
|
+
onData: (bytes) => { // a payload on the reliable stream (the only path without datagrams; the oversize path with them)
|
|
450
489
|
touch();
|
|
451
|
-
if (bytes.byteLength > MAX_DATAGRAM) { channel.consumed(bytes.byteLength); return; }
|
|
490
|
+
if (bytes.byteLength > MAX_DATAGRAM || !admit(bytes.byteLength)) { channel.consumed(bytes.byteLength); return; }
|
|
491
|
+
stats.reliableFromClient++;
|
|
452
492
|
sock.send(bytes, () => channel.consumed(bytes.byteLength));
|
|
453
493
|
},
|
|
454
494
|
onRemoteClose: () => channel.destroy(), // UDP has no half-close
|
|
455
|
-
onClose: () => { clearTimeout(idle); try { sock.close(); } catch { /* closed */ } },
|
|
495
|
+
onClose: () => { clearTimeout(idle); udpFlows.delete(id); try { sock.close(); } catch { /* closed */ } },
|
|
456
496
|
});
|
|
457
497
|
conns.set(id, { channel, sock: null });
|
|
498
|
+
udpFlows.set(id, (payload) => { // a datagram from the client
|
|
499
|
+
touch();
|
|
500
|
+
if (payload.byteLength > MAX_DATAGRAM || !admit(payload.byteLength)) return;
|
|
501
|
+
stats.datagramsFromClient++;
|
|
502
|
+
sock.send(payload);
|
|
503
|
+
});
|
|
458
504
|
async function pump() {
|
|
459
505
|
if (pumping) return;
|
|
460
506
|
pumping = true;
|
|
@@ -468,7 +514,18 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
|
|
|
468
514
|
}
|
|
469
515
|
sock.on('message', (d) => {
|
|
470
516
|
touch();
|
|
517
|
+
if (!admit(d.length)) return;
|
|
518
|
+
if (useDatagrams) {
|
|
519
|
+
const frame = encodeDatagram(id, d);
|
|
520
|
+
if (frame.length <= ctx.datagrams.maxSize()) {
|
|
521
|
+
if (ctx.datagrams.send(frame)) stats.datagramsToClient++; else stats.backpressureDropped++;
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
if (udpCfg.oversize === 'drop') { stats.oversizeDropped++; log(`gateway ${id}: dropped a ${d.length}-byte reply that does not fit a datagram (${ctx.datagrams.maxSize() - 4} bytes)`); return; }
|
|
525
|
+
stats.oversizeReliable++;
|
|
526
|
+
}
|
|
471
527
|
if (outboxBytes + d.length > UDP_OUTBOX_BYTES) return; // the client is not keeping up: drop, as a network would
|
|
528
|
+
stats.reliableToClient++;
|
|
472
529
|
outbox.push(d); outboxBytes += d.length;
|
|
473
530
|
void pump();
|
|
474
531
|
});
|
|
@@ -561,7 +618,7 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
|
|
|
561
618
|
stat = await unix.statSocket(chk.path);
|
|
562
619
|
}
|
|
563
620
|
if (closed) { server.close(); if (stat) await unix.unlinkIfSocket(chk.path, stat); return undefined; }
|
|
564
|
-
const entry = { server, path: chk.path, abstract: chk.abstract, stat, pendingChannels: new Set() };
|
|
621
|
+
const entry = { server, kind: 'unix', path: chk.path, abstract: chk.abstract, stat, pendingChannels: new Set(), open: 0 };
|
|
565
622
|
listeners.set(id, entry);
|
|
566
623
|
server.on('connection', (sock) => onInbound(id, entry, sock));
|
|
567
624
|
server.on('error', (e) => log(`gateway listener ${id}: ${e.message}`));
|
|
@@ -575,17 +632,58 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
|
|
|
575
632
|
}
|
|
576
633
|
}
|
|
577
634
|
|
|
635
|
+
// ── TCP reverse tunnels ──────────────────────────────────────────
|
|
636
|
+
|
|
637
|
+
async function listenTcp(m) {
|
|
638
|
+
const id = m.listener_id;
|
|
639
|
+
if (!Number.isInteger(id) || !Number.isInteger(m.port) || m.port < 0 || m.port > 65535) return failListen(id, 'malformed ListenRequest');
|
|
640
|
+
if (!cfg.reverse) return failListen(id, 'reverse tunnels are not enabled on this gateway');
|
|
641
|
+
if (listeners.has(id) || pendingListeners.has(id)) return failListen(id, 'listener_id already in use');
|
|
642
|
+
const rev = cfg.reverse;
|
|
643
|
+
if (!reversePortAllowed(rev, m.port)) { log(`gateway: refused reverse listen on port ${m.port} (port policy)`); return failListen(id, reversePortRefusal(rev, m.port)); }
|
|
644
|
+
let tcpCount = pendingListeners.size;
|
|
645
|
+
for (const l of listeners.values()) if (l.kind === 'tcp') tcpCount++;
|
|
646
|
+
if (tcpCount >= rev.maxListeners) return failListen(id, `too many reverse listeners (limit ${rev.maxListeners})`);
|
|
647
|
+
pendingListeners.add(id);
|
|
648
|
+
let server;
|
|
649
|
+
try {
|
|
650
|
+
const net = await loadNet();
|
|
651
|
+
const host = reverseBindAddress(rev, m.bind_addr);
|
|
652
|
+
if (host !== m.bind_addr) log(`gateway: reverse listen: ignoring the client's bind address ${JSON.stringify(String(m.bind_addr).slice(0, 64))}, binding ${host}`);
|
|
653
|
+
server = net.createServer();
|
|
654
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen({ port: m.port, host, backlog: rev.backlog }, () => { server.off('error', reject); resolve(); }); });
|
|
655
|
+
if (closed) { server.close(); return undefined; }
|
|
656
|
+
const addr = server.address();
|
|
657
|
+
const entry = { server, kind: 'tcp', path: '', abstract: false, stat: null, pendingChannels: new Set(), open: 0 };
|
|
658
|
+
listeners.set(id, entry);
|
|
659
|
+
server.on('connection', (sock) => onInbound(id, entry, sock));
|
|
660
|
+
server.on('error', (e) => log(`gateway listener ${id}: ${e.message}`));
|
|
661
|
+
cfg.stats.reverse.listeners++;
|
|
662
|
+
log(`gateway: listening on ${host}:${addr.port} (reverse listener ${id})`);
|
|
663
|
+
return await reply(listenOk({ listenerId: id, actualPort: addr.port }));
|
|
664
|
+
} catch (e) {
|
|
665
|
+
try { server?.close(); } catch { /* not listening */ }
|
|
666
|
+
return failListen(id, e.code === 'EADDRINUSE' ? 'address in use' : e.code === 'EACCES' ? 'permission denied binding that port' : String(e.message).slice(0, 200));
|
|
667
|
+
} finally {
|
|
668
|
+
pendingListeners.delete(id);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
578
672
|
function onInbound(listenerId, entry, sock) {
|
|
579
|
-
|
|
673
|
+
const tcp = entry.kind === 'tcp';
|
|
674
|
+
const refuse = (why) => { if (tcp) cfg.stats.reverse.refusedConnections++; log(`gateway: reverse listener ${listenerId}: dropped a connection (${why})`); sock.destroy(); };
|
|
675
|
+
if (closed || inbound.size >= MAX_PENDING_INBOUND || active() + inbound.size >= cfg.maxConnections) return refuse('too many gateway connections');
|
|
676
|
+
if (tcp && entry.open >= cfg.reverse.maxConnectionsPerListener) return refuse(`listener is at its limit of ${cfg.reverse.maxConnectionsPerListener} connections`);
|
|
580
677
|
sock.pause();
|
|
581
678
|
sock.on('error', () => {});
|
|
582
679
|
const channelId = ++nextInbound;
|
|
583
680
|
const timer = setTimeout(() => { inbound.delete(channelId); entry.pendingChannels.delete(channelId); sock.destroy(); }, INBOUND_ACCEPT_TIMEOUT_MS);
|
|
584
681
|
timer.unref?.();
|
|
682
|
+
if (tcp) { entry.open++; cfg.stats.reverse.accepted++; sock.once('close', () => { entry.open--; }); }
|
|
585
683
|
sock.once('close', () => { if (inbound.get(channelId)?.sock === sock) { clearTimeout(timer); inbound.delete(channelId); entry.pendingChannels.delete(channelId); } });
|
|
586
684
|
inbound.set(channelId, { sock, listenerId, timer });
|
|
587
685
|
entry.pendingChannels.add(channelId);
|
|
588
|
-
void reply(inboundOpen({ listenerId, channelId, peerAddr: 'unix', peerPort: 0 }));
|
|
686
|
+
void reply(inboundOpen({ listenerId, channelId, peerAddr: tcp ? (sock.remoteAddress ?? '') : 'unix', peerPort: tcp ? (sock.remotePort ?? 0) : 0 }));
|
|
589
687
|
}
|
|
590
688
|
|
|
591
689
|
function inboundAccept(m) {
|
|
@@ -597,6 +695,11 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
|
|
|
597
695
|
const id = m.gateway_id;
|
|
598
696
|
if (!Number.isInteger(id) || idInUse(id) || p.sock.destroyed || active() >= cfg.maxConnections) { p.sock.destroy(); return; }
|
|
599
697
|
attachSocket(id, p.sock);
|
|
698
|
+
const rev = listeners.get(p.listenerId)?.kind === 'tcp' ? cfg.reverse : null;
|
|
699
|
+
if (rev && rev.idleMs > 0) {
|
|
700
|
+
// Inactivity in either direction ends the connection (the socket's own timeout counts reads and writes).
|
|
701
|
+
p.sock.setTimeout(rev.idleMs, () => { cfg.stats.reverse.idleClosed++; log(`gateway: reverse connection ${id} idle for ${rev.idleMs} ms, closing`); p.sock.destroy(); });
|
|
702
|
+
}
|
|
600
703
|
p.sock.resume();
|
|
601
704
|
}
|
|
602
705
|
|
|
@@ -618,7 +721,16 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
|
|
|
618
721
|
}
|
|
619
722
|
|
|
620
723
|
return {
|
|
621
|
-
setPeerFeatures: (features) => core.setPeerFeatures(features),
|
|
724
|
+
setPeerFeatures: (features) => { core.setPeerFeatures(features); peerDatagrams = Array.isArray(features) && features.includes(GATEWAY_DATAGRAM_FEATURE); },
|
|
725
|
+
/** A WebTransport datagram arrived from the client: [flow id][payload]. */
|
|
726
|
+
handleDatagram(bytes) {
|
|
727
|
+
if (closed) return;
|
|
728
|
+
const d = decodeDatagram(bytes);
|
|
729
|
+
if (!d) { stats.malformed++; return; }
|
|
730
|
+
const flow = datagramsOn() ? udpFlows.get(d.id) : undefined;
|
|
731
|
+
if (!flow) { stats.unknownFlow++; return; }
|
|
732
|
+
flow(d.payload);
|
|
733
|
+
},
|
|
622
734
|
/** @returns {Promise<boolean>} true when the message was a gateway message this session consumed */
|
|
623
735
|
async handle(m) {
|
|
624
736
|
if (closed) return true;
|
|
@@ -627,7 +739,7 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
|
|
|
627
739
|
case MSG.OPEN_UDP: await openUdp(m); return true;
|
|
628
740
|
case MSG.OPEN_UNIX: await openUnix(m); return true;
|
|
629
741
|
case MSG.RESOLVE_DNS: await resolveDns(m); return true;
|
|
630
|
-
case MSG.LISTEN_REQUEST:
|
|
742
|
+
case MSG.LISTEN_REQUEST: await listenTcp(m); return true;
|
|
631
743
|
case MSG.LISTEN_UNIX: await listenUnix(m); return true;
|
|
632
744
|
case MSG.LISTEN_CLOSE: await closeListener(m.listener_id); return true;
|
|
633
745
|
case MSG.INBOUND_ACCEPT: inboundAccept(m); return true;
|
package/src/server/index.d.ts
CHANGED
|
@@ -158,6 +158,39 @@ export interface WshServerGatewayOptions {
|
|
|
158
158
|
endpoints?: Record<string, WshGatewayEndpointHandler | { open: WshGatewayEndpointHandler; authorize?: (who: WshGatewayWho) => boolean | Promise<boolean> }>;
|
|
159
159
|
/** `false`: no TCP or DNS at all (an endpoints-only gateway). Default true. */
|
|
160
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
|
+
};
|
|
161
194
|
}
|
|
162
195
|
|
|
163
196
|
export interface WshServerPtyOptions {
|
|
@@ -530,6 +563,8 @@ export interface WshServer {
|
|
|
530
563
|
rotateCertificate(options?: { activate?: boolean }): Promise<{ current: WshServerCertificateInfo; next: WshServerCertificateInfo | null }>;
|
|
531
564
|
/** Fingerprints of the peers currently registered with this relay (`[]` when it is not one). */
|
|
532
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;
|
|
533
568
|
/** The advertised host identity; `null` before `listen()` resolves or without a `hostKey`. */
|
|
534
569
|
hostKey(): WshServerHostKey | null;
|
|
535
570
|
}
|
package/src/server/index.mjs
CHANGED
|
@@ -82,7 +82,7 @@ function tlsChannelBinding(socket) {
|
|
|
82
82
|
* @param {{ allow: string[], maxConnections?: number, connectTimeoutMs?: number, socks?: string | { host: string, port: number } }} [options.gateway]
|
|
83
83
|
* Answer the gateway opcodes (OpenTcp, ResolveDns, GatewayData/Close): the client opens TCP connections and resolves
|
|
84
84
|
* names from this host. Default deny: a destination must match `allow` (`"*"`, `"host"`, `"host:port"`). `socks` dials
|
|
85
|
-
* through a SOCKS5 proxy (Tor) with the name unresolved. UDP and reverse tunnels are
|
|
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`.
|
|
86
86
|
* @param {number} [options.bindTimeoutMs=3000]
|
|
87
87
|
* @param {number} [options.connectionTtlMs=0] - End every authenticated connection this long after login (0 = never).
|
|
88
88
|
* Advertised as `AuthOk.ttl` in whole seconds, rounded up; the client reads it as `client.authTtl`.
|
|
@@ -284,6 +284,11 @@ export function createWshServer({
|
|
|
284
284
|
return wt.rotateCertificate(options);
|
|
285
285
|
},
|
|
286
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
|
+
|
|
287
292
|
/** Fingerprints of the peers currently registered with this relay (`[]` when it is not one). */
|
|
288
293
|
peerFingerprints() {
|
|
289
294
|
return hub ? hub.peerFingerprints() : [];
|
package/src/server/relay.mjs
CHANGED
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
import { cborEncode, cborDecode } from '../cbor.mjs';
|
|
29
29
|
import { fingerprint as fingerprintOf, importPublicKeyRaw, verifyPeerRecord } from '../auth.mjs';
|
|
30
30
|
import { MSG, isRelayForwardable, relayForward, reversePeers, reverseReject, reverseClose } from '../messages.gen.mjs';
|
|
31
|
+
import { OPERATOR_PROOF_FEATURE } from '../operator-proof.mjs';
|
|
31
32
|
|
|
32
33
|
export const DEFAULT_MAX_PEERS = 1024;
|
|
33
34
|
export const DEFAULT_CONNECT_TIMEOUT_MS = 8000;
|
|
@@ -253,7 +254,11 @@ export class RelayHub {
|
|
|
253
254
|
from_fingerprint: operator.fingerprint,
|
|
254
255
|
};
|
|
255
256
|
// What the operator says it can do (#117), bounded; it is the operator's own claim and decides nothing here.
|
|
256
|
-
|
|
257
|
+
// Only to a peer that advertised `operator-proof` in its registered record: a released peer (rust-v0.6 to v0.8) rejects
|
|
258
|
+
// the field outright (its generated types deny unknown fields), which the operator would see as a timeout. Stripped,
|
|
259
|
+
// that peer answers as it always did, without a challenge; an operator that insists on proof then fails at once.
|
|
260
|
+
const peerCanProve = (target.meta.capabilities ?? []).includes(OPERATOR_PROOF_FEATURE);
|
|
261
|
+
if (peerCanProve && Array.isArray(msg.features) && msg.features.length <= MAX_OPERATOR_FEATURES && msg.features.every((f) => isStr(f, MAX_FEATURE_LENGTH))) forwarded.features = [...msg.features];
|
|
257
262
|
target.handle.send(forwarded);
|
|
258
263
|
this.log(`relay: ${operator.fingerprint.slice(0, 12)} -> ${target.meta.fingerprint.slice(0, 12)} requested`);
|
|
259
264
|
}
|
|
@@ -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
|
+
}
|
|
@@ -117,7 +117,23 @@ export async function startWebTransport({ options, host, attach, log }) {
|
|
|
117
117
|
|
|
118
118
|
let controlWriter = null;
|
|
119
119
|
const decoder = new FrameDecoder();
|
|
120
|
+
// Datagrams (#124): `createWritable()` is the standard sender (`writable` is the deprecated one); a sender that is
|
|
121
|
+
// not draining drops rather than queues, which is what a datagram is.
|
|
122
|
+
let dgWriter = null;
|
|
123
|
+
try {
|
|
124
|
+
const dg = session.datagrams;
|
|
125
|
+
if (dg && typeof dg.maxDatagramSize === 'number') dgWriter = (typeof dg.createWritable === 'function' ? dg.createWritable() : dg.writable).getWriter();
|
|
126
|
+
} catch { dgWriter = null; }
|
|
127
|
+
const datagrams = dgWriter ? {
|
|
128
|
+
send(bytes) {
|
|
129
|
+
if (closed || (dgWriter.desiredSize !== null && dgWriter.desiredSize <= 0)) return false;
|
|
130
|
+
dgWriter.write(bytes).catch(() => {});
|
|
131
|
+
return true;
|
|
132
|
+
},
|
|
133
|
+
maxSize: () => session.datagrams.maxDatagramSize,
|
|
134
|
+
} : null;
|
|
120
135
|
conn = attach({
|
|
136
|
+
datagrams,
|
|
121
137
|
sendMessage: (msg) => (controlWriter ? controlWriter.write(frameEncode(msg)) : undefined),
|
|
122
138
|
remote: { address: session.peerAddress, headers: session.header ?? {} },
|
|
123
139
|
closeTransport: () => { try { session.close(); } catch { /* already closed */ } },
|
|
@@ -125,6 +141,19 @@ export async function startWebTransport({ options, host, attach, log }) {
|
|
|
125
141
|
channelBinding: current?.hash ? { 'cert-hash': [current.hash] } : null,
|
|
126
142
|
});
|
|
127
143
|
|
|
144
|
+
if (datagrams) {
|
|
145
|
+
(async () => {
|
|
146
|
+
const reader = session.datagrams.readable.getReader();
|
|
147
|
+
try {
|
|
148
|
+
for (;;) {
|
|
149
|
+
const { done, value } = await reader.read();
|
|
150
|
+
if (done) break;
|
|
151
|
+
conn.receiveDatagram(value);
|
|
152
|
+
}
|
|
153
|
+
} catch { /* session went away */ }
|
|
154
|
+
})();
|
|
155
|
+
}
|
|
156
|
+
|
|
128
157
|
const incoming = session.incomingBidirectionalStreams.getReader();
|
|
129
158
|
let first = true;
|
|
130
159
|
try {
|