@johnhenry/wsh 0.37.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.
- package/README.md +140 -17
- package/package.json +1 -1
- package/src/client.mjs +33 -7
- package/src/gateway-client.mjs +64 -9
- package/src/gateway-datagram.mjs +191 -0
- package/src/index.d.ts +30 -2
- 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/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/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() : [];
|
|
@@ -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 {
|
package/src/transport.mjs
CHANGED
|
@@ -136,6 +136,24 @@ export class WshTransport {
|
|
|
136
136
|
return this.#state;
|
|
137
137
|
}
|
|
138
138
|
|
|
139
|
+
/** @type {function(Uint8Array): void} Callback for an unreliable datagram (WebTransport only). */
|
|
140
|
+
onDatagram = null;
|
|
141
|
+
|
|
142
|
+
/** True where this transport can carry unreliable datagrams (WebTransport); false for WebSocket and the rest. */
|
|
143
|
+
get supportsDatagrams() { return false; }
|
|
144
|
+
|
|
145
|
+
/** The largest datagram the connection can carry right now, in bytes (0 = none). Read it again before sending: it can change. */
|
|
146
|
+
get maxDatagramSize() { return 0; }
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Send one datagram. Never waits and never queues without bound.
|
|
150
|
+
* @param {Uint8Array} bytes
|
|
151
|
+
* @returns {boolean} false when it was dropped (no datagram support, closed, or the sender is not draining)
|
|
152
|
+
*/
|
|
153
|
+
sendDatagram(bytes) { // eslint-disable-line no-unused-vars
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
|
|
139
157
|
/**
|
|
140
158
|
* TLS keying material for channel binding (#119): `length` bytes exported with `label` (RFC 5705 / 8446 7.5), or
|
|
141
159
|
* `null` where the platform does not expose it (every browser, and Node's own global `WebSocket`).
|
|
@@ -516,6 +534,16 @@ export class WebTransportTransport extends WshTransport {
|
|
|
516
534
|
const controlStream = await wt.createBidirectionalStream();
|
|
517
535
|
this.#controlWriter = controlStream.writable.getWriter();
|
|
518
536
|
|
|
537
|
+
// Datagrams: `createWritable()` is the standard sender, `writable` the deprecated one older engines have.
|
|
538
|
+
this.#datagramWriter = null;
|
|
539
|
+
try {
|
|
540
|
+
const dg = wt.datagrams;
|
|
541
|
+
if (dg && dg.readable) {
|
|
542
|
+
this.#datagramWriter = (typeof dg.createWritable === 'function' ? dg.createWritable() : dg.writable).getWriter();
|
|
543
|
+
this.#readDatagrams(dg.readable);
|
|
544
|
+
}
|
|
545
|
+
} catch { this.#datagramWriter = null; }
|
|
546
|
+
|
|
519
547
|
// Start reading control messages in the background.
|
|
520
548
|
this.#controlReaderDone = this.#readControlStream(controlStream.readable);
|
|
521
549
|
|
|
@@ -526,8 +554,40 @@ export class WebTransportTransport extends WshTransport {
|
|
|
526
554
|
this.#monitorClosed(wt);
|
|
527
555
|
}
|
|
528
556
|
|
|
557
|
+
/** @type {WritableStreamDefaultWriter|null} */
|
|
558
|
+
#datagramWriter = null;
|
|
559
|
+
|
|
560
|
+
/** @override */
|
|
561
|
+
get supportsDatagrams() { return this.#datagramWriter !== null; }
|
|
562
|
+
|
|
563
|
+
/** @override */
|
|
564
|
+
get maxDatagramSize() {
|
|
565
|
+
try { return this.#datagramWriter ? Number(this.#wt?.datagrams?.maxDatagramSize) || 0 : 0; } catch { return 0; }
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** @override */
|
|
569
|
+
sendDatagram(bytes) {
|
|
570
|
+
const w = this.#datagramWriter;
|
|
571
|
+
if (!w || this.state !== 'connected') return false;
|
|
572
|
+
if (w.desiredSize !== null && w.desiredSize <= 0) return false; // not draining: drop, do not queue
|
|
573
|
+
w.write(bytes).catch(() => {});
|
|
574
|
+
return true;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
async #readDatagrams(readable) {
|
|
578
|
+
const reader = readable.getReader();
|
|
579
|
+
try {
|
|
580
|
+
for (;;) {
|
|
581
|
+
const { done, value } = await reader.read();
|
|
582
|
+
if (done) break;
|
|
583
|
+
try { this.onDatagram?.(value); } catch (err) { console.error('[wsh:transport] onDatagram handler error:', err); }
|
|
584
|
+
}
|
|
585
|
+
} catch { /* session closed */ }
|
|
586
|
+
}
|
|
587
|
+
|
|
529
588
|
/** @override */
|
|
530
589
|
async _doClose() {
|
|
590
|
+
this.#datagramWriter = null;
|
|
531
591
|
this.#abort.abort();
|
|
532
592
|
try {
|
|
533
593
|
this.#controlWriter?.releaseLock?.();
|