@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.
@@ -1,44 +1,73 @@
1
1
  /**
2
- * Gateway for the Node server: the TCP and DNS half of the wire protocol's
3
- * gateway opcodes (0x70-0x7e), which until now only the Rust `wsh-server`
4
- * answered. It lets an authenticated client (typically a browser tab running
5
- * `GatewayBackend` from `@johnhenry/browsermesh-netway`) open TCP connections
6
- * and resolve names FROM THE HOST, so a page can reach a plain-TCP service
7
- * (an MQTT broker, a database) that a browser cannot.
2
+ * Gateway for the Node server: the TCP and DNS half of the wire protocol's gateway opcodes (0x70-0x7f), which until
3
+ * now only the Rust `wsh-server` answered, plus unix-domain socket forwarding (`OpenUnix`, `ListenUnix`) and named
4
+ * virtual endpoints (`OpenEndpoint`). It lets an authenticated client (typically a browser tab running
5
+ * `GatewayBackend` from `@johnhenry/browsermesh-netway`) open TCP connections and resolve names FROM THE HOST, so a
6
+ * page can reach a plain-TCP service (an MQTT broker, a database) that a browser cannot.
8
7
  *
9
- * Off unless `createWshServer({ gateway })` is given, and then default-deny:
10
- * a destination must match `allow`. Pattern forms (the same as the Rust policy):
11
- * `"*"` any host and port, `"host"` that name on any port, `"host:port"`.
12
- * Matching is on the NAME the client asked for, case-insensitively; with `socks`
13
- * set the name is handed to the proxy unresolved, so the host never looks it up.
8
+ * Off unless `createWshServer({ gateway })` is given, and then default-deny: a destination must match `allow`.
9
+ * Pattern forms (the same as the Rust policy): `"*"` any host and port, `"host"` that name on any port,
10
+ * `"host:port"`. The pattern is matched against the NAME the client asked for, case-insensitively, and then the
11
+ * ADDRESS it resolves to is checked as well: the host resolves the name once, refuses every address that is not
12
+ * globally routable (loopback, private, link-local, CGNAT, ULA, multicast, reserved, and IPv4 wrapped in IPv6 as
13
+ * mapped, NAT64 or 6to4 forms) unless a rule says otherwise, and connects to that same address, so a name that
14
+ * resolves differently a moment later cannot redirect the connection. Rules that say otherwise: `allowPrivate`
15
+ * (CIDR blocks or addresses the host may dial even though they are not public), and an allow entry that is itself
16
+ * an IP literal (`"127.0.0.1:1883"`), which permits exactly that address. `ResolveDns` answers are filtered with
17
+ * the same rule. With `socks` set the name is handed to the proxy unresolved, so the host never looks it up and
18
+ * cannot check what it resolves to (the proxy's network is then the egress); IP literals are still checked.
14
19
  *
15
- * Not implemented, and answered with a clean GatewayFail / ListenFail rather than
16
- * silence: UDP (`OpenUdp`) and reverse tunnels (`ListenRequest`).
20
+ * Flow control: with "gateway-credit" negotiated each direction of each connection is metered (see
21
+ * `src/gateway-channel.mjs`); with an older peer the host bounds its buffering by `maxBufferedBytes` per connection
22
+ * and `maxClientBufferedBytes` per client and closes a connection that exceeds them.
17
23
  *
18
- * `socks`: dial through a SOCKS5 proxy (`'host:port'`, `socks5://host:port` or
19
- * `{ host, port }`), e.g. a local Tor client (`127.0.0.1:9050`). Commands carry the
20
- * destination as a domain name (ATYP 3), so name resolution happens at the proxy
21
- * (no DNS leak) and `.onion` names work. In that mode `ResolveDns` is refused:
22
- * the host would have to resolve the name itself.
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`.
33
+ *
34
+ * `socks`: dial through a SOCKS5 proxy (`'host:port'`, `socks5://host:port` or `{ host, port }`), e.g. a local Tor
35
+ * client (`127.0.0.1:9050`). Commands carry the destination as a domain name (ATYP 3), so name resolution happens at
36
+ * the proxy (no DNS leak) and `.onion` names work. In that mode `ResolveDns` is refused.
37
+ *
38
+ * `unix: { connect, listen, replaceStale }` (Node only): sockets in the host's file system a client may connect to
39
+ * or create. Off unless given. See `unix-policy.mjs`. `endpoints: { name: handler }`: named virtual endpoints.
23
40
  */
24
41
 
25
- import { MSG, gatewayOk, gatewayFail, gatewayClose, gatewayData, dnsResult, listenFail } from '../messages.gen.mjs';
42
+ import { MSG, gatewayOk, dnsResult, listenOk, listenFail, inboundOpen } from '../messages.gen.mjs';
43
+ import {
44
+ GATEWAY_FAIL, HALF_CLOSE_GRACE_MS, gatewayFeatures, createGatewayCore, normalizeGatewayLimits, normalizeEndpoints,
45
+ } from './gateway-core.mjs';
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';
26
53
 
27
54
  // Loaded on first use so that importing the connection handler (which serves the gateway opcodes)
28
55
  // does not pull `node:net` into a browser bundle (see `src/memory-host.mjs`).
29
56
  let netModule = null;
30
57
  let dnsModule = null;
58
+ let unixModule = null;
31
59
  const loadNet = async () => (netModule ??= (await import('node:net')).default);
32
60
  const loadDns = async () => (dnsModule ??= (await import('node:dns/promises')).default);
61
+ const loadUnix = async () => (unixModule ??= await import('./unix-policy.mjs'));
33
62
 
34
- /** Numeric codes of GatewayFail (the same table `@johnhenry/browsermesh-netway` decodes). */
35
- export const GATEWAY_FAIL = Object.freeze({
36
- CONNECTION_REFUSED: 1, HOST_UNREACHABLE: 2, DNS_FAILED: 3, POLICY_DENIED: 4, TIMEOUT: 5, CLOSED: 6, QUEUE_FULL: 7,
37
- });
63
+ export { GATEWAY_FAIL, gatewayFeatures };
38
64
 
39
- const DEFAULT_MAX_CONNECTIONS = 32;
40
65
  const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;
41
- const MAX_DATA_BYTES = 1024 * 1024;
66
+ const MAX_PENDING_INBOUND = 16;
67
+ const INBOUND_ACCEPT_TIMEOUT_MS = 30_000;
68
+ const DEFAULT_UDP_IDLE_MS = 60_000;
69
+ const MAX_DATAGRAM = MAX_UDP_PAYLOAD;
70
+ const UDP_OUTBOX_BYTES = 256 * 1024;
42
71
 
43
72
  /** @param {string|{host:string,port:number}} socks */
44
73
  export function parseSocks(socks) {
@@ -52,7 +81,7 @@ export function parseSocks(socks) {
52
81
  return { host: m[1].replace(/^\[|\]$/g, ''), port: Number(m[2]) };
53
82
  }
54
83
 
55
- /** Does `host:port` match one of the allow patterns? */
84
+ /** Does `host:port` match one of the allow patterns? (The NAME check only; see `addressPermitted` for the address.) */
56
85
  export function destinationAllowed(allow, host, port) {
57
86
  const h = String(host).toLowerCase();
58
87
  for (const raw of allow) {
@@ -62,6 +91,33 @@ export function destinationAllowed(allow, host, port) {
62
91
  return false;
63
92
  }
64
93
 
94
+ /**
95
+ * The name rule: does any allow entry match, and does a matching entry name the requested host as an IP literal
96
+ * (`explicit`: that entry is then allowed to reach exactly that address even if it is not public)?
97
+ */
98
+ function nameDecision(allow, host, port) {
99
+ const h = String(host).toLowerCase();
100
+ let allowed = false;
101
+ let explicit = false;
102
+ for (const raw of allow) {
103
+ const p = String(raw).toLowerCase();
104
+ if (p === '*') allowed = true;
105
+ else if (p === h || p === `${h}:${port}`) { allowed = true; if (parseIp(h)) explicit = true; }
106
+ }
107
+ return { allowed, explicit };
108
+ }
109
+
110
+ /**
111
+ * May the host dial this resolved address? Public addresses, addresses in `allowPrivate`, and the literal address of
112
+ * an explicit IP rule.
113
+ * @param {{ allowPrivate: Array<object> }} cfg
114
+ */
115
+ export function addressPermitted(cfg, address, { explicitLiteral = null } = {}) {
116
+ if (explicitLiteral && sameAddress(address, explicitLiteral)) return true;
117
+ if (isPublicAddress(address)) return true;
118
+ return cfg.allowPrivate.some((c) => addressInCidr(address, c));
119
+ }
120
+
65
121
  /**
66
122
  * SOCKS5 CONNECT (RFC 1928) with no authentication, destination as a domain name.
67
123
  * Resolves with the connected socket, or rejects with an Error carrying `.code`
@@ -114,12 +170,83 @@ export async function socksConnect(proxy, host, port, { timeoutMs = DEFAULT_CONN
114
170
  });
115
171
  }
116
172
 
173
+ const connectError = (e) => {
174
+ const code = e.code === 'ECONNREFUSED' ? GATEWAY_FAIL.CONNECTION_REFUSED : e.code === 'ENOTFOUND' || e.code === 'EAI_AGAIN' ? GATEWAY_FAIL.DNS_FAILED : GATEWAY_FAIL.HOST_UNREACHABLE;
175
+ const err = new Error(e.code === 'ENOTFOUND' ? 'name not found' : e.message);
176
+ err.code = code;
177
+ return err;
178
+ };
179
+
180
+ /**
181
+ * Connect to ONE address (no name lookup happens: the caller already resolved and checked it).
182
+ * @returns {Promise<import('node:net').Socket>}
183
+ */
184
+ async function connectAddress(address, port, timeoutMs) {
185
+ const net = await loadNet();
186
+ return new Promise((resolve, reject) => {
187
+ const s = net.connect({ host: address, port });
188
+ const t = setTimeout(() => { s.destroy(); const e = new Error('connect timed out'); e.code = GATEWAY_FAIL.TIMEOUT; reject(e); }, timeoutMs);
189
+ s.once('connect', () => { clearTimeout(t); s.removeAllListeners('error'); resolve(s); });
190
+ s.once('error', (e) => { clearTimeout(t); reject(connectError(e)); });
191
+ });
192
+ }
193
+
194
+ /**
195
+ * Resolve `host` ONCE and return only the addresses `cfg` permits (an empty answer after filtering is POLICY_DENIED).
196
+ * Everything that then connects does so to one of these addresses, never to the name.
197
+ * @returns {Promise<string[]>}
198
+ */
199
+ export async function resolveChecked(cfg, host, explicitLiteral, timeoutMs = cfg.connectTimeoutMs) {
200
+ const dns = await loadDns();
201
+ let found;
202
+ try {
203
+ found = await Promise.race([
204
+ dns.lookup(host, { all: true, verbatim: true }),
205
+ new Promise((_, rej) => { const t = setTimeout(() => { const e = new Error('name lookup timed out'); e.code = GATEWAY_FAIL.TIMEOUT; rej(e); }, timeoutMs); t.unref?.(); }),
206
+ ]);
207
+ } catch (e) { throw typeof e.code === 'number' ? e : connectError(e); }
208
+ const addresses = found.map((a) => a.address);
209
+ const usable = addresses.filter((a) => addressPermitted(cfg, a, { explicitLiteral }));
210
+ if (usable.length === 0) {
211
+ const e = new Error('the address this name resolves to is not permitted by the gateway policy');
212
+ e.code = GATEWAY_FAIL.POLICY_DENIED;
213
+ e.refusedAddresses = addresses;
214
+ throw e;
215
+ }
216
+ return usable;
217
+ }
218
+
219
+ /**
220
+ * Resolve `host` once, keep only the addresses `cfg` permits, and connect to the first that answers. A refusal of
221
+ * every address is POLICY_DENIED; the connect uses the address that was checked, never the name.
222
+ * @returns {Promise<{ sock: import('node:net').Socket, address: string }>}
223
+ */
224
+ export async function dialChecked(cfg, host, port, explicitLiteral, timeoutMs = cfg.connectTimeoutMs) {
225
+ const deadline = Date.now() + timeoutMs;
226
+ const usable = await resolveChecked(cfg, host, explicitLiteral, timeoutMs);
227
+ let last;
228
+ for (const address of usable) {
229
+ const left = deadline - Date.now();
230
+ if (left <= 0) break;
231
+ try { return { sock: await connectAddress(address, port, left), address }; } catch (e) { last = e; }
232
+ }
233
+ throw last ?? Object.assign(new Error('connect timed out'), { code: GATEWAY_FAIL.TIMEOUT });
234
+ }
235
+
117
236
  /**
118
237
  * @param {object} opts
119
238
  * @param {string[]} [opts.allow=[]] destination patterns; empty = nothing is reachable
239
+ * @param {string[]} [opts.allowPrivate=[]] CIDR blocks or addresses (`"10.0.0.0/8"`, `"127.0.0.1"`, `"fd00::/8"`) the host may dial even though they are not globally routable
120
240
  * @param {number} [opts.maxConnections=32] concurrent gateway sockets per client connection
121
241
  * @param {number} [opts.connectTimeoutMs=15000]
242
+ * @param {number} [opts.maxBufferedBytes=4194304] bytes received from a client for one connection and not yet taken by its origin
243
+ * @param {number} [opts.maxClientBufferedBytes=33554432] the same, summed over one client's connections
122
244
  * @param {string|{host:string,port:number}} [opts.socks] dial through this SOCKS5 proxy (Tor)
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)
248
+ * @param {Record<string, Function | { open: Function, authorize?: Function }>} [opts.endpoints] named virtual endpoints
249
+ * @param {boolean} [opts.tcp=true] false: no TCP or DNS at all (an endpoints-only host such as the memory host)
123
250
  * @param {(line: string) => void} [opts.log]
124
251
  */
125
252
  export function normalizeGateway(opts) {
@@ -127,14 +254,55 @@ export function normalizeGateway(opts) {
127
254
  if (!opts || typeof opts !== 'object') return null;
128
255
  const allow = opts.allow ?? [];
129
256
  if (!Array.isArray(allow) || allow.some((a) => typeof a !== 'string' || !a)) throw new TypeError('gateway.allow must be an array of non-empty strings');
130
- const maxConnections = opts.maxConnections ?? DEFAULT_MAX_CONNECTIONS;
131
- if (!Number.isInteger(maxConnections) || maxConnections < 1) throw new TypeError('gateway.maxConnections must be a positive integer');
257
+ const privateRules = opts.allowPrivate ?? [];
258
+ if (!Array.isArray(privateRules)) throw new TypeError('gateway.allowPrivate must be an array of CIDR blocks or addresses');
259
+ const allowPrivate = privateRules.map((r) => {
260
+ const c = parseCidr(r);
261
+ if (!c) throw new TypeError(`gateway.allowPrivate: ${JSON.stringify(r)} is not an address or CIDR block`);
262
+ return c;
263
+ });
264
+ const { maxConnections, maxBufferedBytes, maxClientBufferedBytes } = normalizeGatewayLimits(opts);
265
+ let unix = null;
266
+ if (opts.unix !== undefined && opts.unix !== null && opts.unix !== false) {
267
+ if (opts.unix === true || typeof opts.unix !== 'object') throw new TypeError('gateway.unix needs explicit paths (default deny): { connect: [...], listen: [...] }');
268
+ // The policy module touches the file system; validate its shape here without loading `node:fs`.
269
+ unix = normalizeUnixShape(opts.unix);
270
+ }
271
+ const endpoints = normalizeEndpoints(opts.endpoints);
132
272
  return {
133
273
  allow: [...allow],
274
+ allowPrivate,
134
275
  maxConnections,
276
+ maxBufferedBytes,
277
+ maxClientBufferedBytes,
135
278
  connectTimeoutMs: opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
279
+ udpIdleMs: opts.udpIdleMs ?? DEFAULT_UDP_IDLE_MS,
280
+ udp: normalizeUdp(opts.udp),
281
+ reverse: normalizeReverse(opts.reverse),
282
+ stats: newGatewayStats(),
136
283
  socks: parseSocks(opts.socks),
284
+ tcp: opts.tcp !== false,
285
+ unix,
286
+ endpoints,
287
+ };
288
+ }
289
+
290
+ /** The shape check of `normalizeUnixPolicy`, without importing it (it needs `node:fs`). */
291
+ function normalizeUnixShape(u) {
292
+ const list = (v, what) => {
293
+ if (v === undefined) return [];
294
+ if (!Array.isArray(v) || v.some((p) => typeof p !== 'string' || !p)) throw new TypeError(`gateway.unix.${what} must be an array of non-empty strings`);
295
+ for (const p of v) {
296
+ if (p.includes('\0') || p.length > 4096) throw new TypeError(`gateway.unix.${what}: bad pattern ${JSON.stringify(p.slice(0, 80))}`);
297
+ if (!p.startsWith('/') && !p.startsWith('@')) throw new TypeError(`gateway.unix.${what}: ${JSON.stringify(p)} must be an absolute path or an abstract name starting with "@"`);
298
+ if (p === '/' || p === '@' || p === '@/') throw new TypeError(`gateway.unix.${what}: ${JSON.stringify(p)} would allow everything; list a specific path or directory`);
299
+ if (p.split('/').includes('..')) throw new TypeError(`gateway.unix.${what}: ${JSON.stringify(p)} must not contain ".."`);
300
+ }
301
+ return [...v];
137
302
  };
303
+ const maxListeners = u.maxListeners ?? 4;
304
+ if (!Number.isInteger(maxListeners) || maxListeners < 0) throw new TypeError('gateway.unix.maxListeners must be a non-negative integer');
305
+ return { connect: list(u.connect, 'connect'), listen: list(u.listen, 'listen'), replaceStale: u.replaceStale === true, maxListeners };
138
306
  }
139
307
 
140
308
  /**
@@ -142,65 +310,90 @@ export function normalizeGateway(opts) {
142
310
  * @param {ReturnType<typeof normalizeGateway>} cfg
143
311
  * @param {(msg: object) => unknown} send
144
312
  * @param {(line: string) => void} log
313
+ * @param {{ who?: () => { username: string | null, fingerprint: string | null } }} [ctx]
145
314
  */
146
- export function createGatewaySession(cfg, send, log = () => {}) {
147
- /** @type {Map<number, net.Socket>} */
148
- const sockets = new Map();
149
- /** gateway_ids whose connect is still in flight (they count against the cap). */
150
- const pending = new Set();
315
+ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
316
+ // The connection table, credit negotiation, the per-client budget and the endpoint opcodes are the browser-safe core.
317
+ const core = createGatewayCore(cfg, send, log, ctx);
318
+ const { conns, pending, reply, fail, active, idInUse, makeChannel } = core;
319
+ /** @type {Map<number, { server: import('node:net').Server, path: string, abstract: boolean, stat: any, pendingChannels: Set<number> }>} */
320
+ const listeners = new Map();
321
+ const pendingListeners = new Set();
322
+ /** Accepted inbound sockets waiting for InboundAccept: channel_id -> { sock, listenerId, timer }. */
323
+ const inbound = new Map();
324
+ let nextInbound = 0;
325
+ let closed = false;
326
+ const failListen = (listenerId, reason) => reply(listenFail({ listenerId, reason }));
151
327
 
152
- const reply = (m) => { try { return send(m); } catch { return undefined; } };
153
- const fail = (gatewayId, code, message) => reply(gatewayFail({ gatewayId, code, message }));
154
- const active = () => sockets.size + pending.size;
328
+ /** Attach a connected socket (TCP or unix) as gateway connection `id`. */
329
+ function attachSocket(id, sock) {
330
+ sock.setNoDelay?.(true);
331
+ let tail = Promise.resolve();
332
+ let graceTimer = null;
333
+ const channel = makeChannel(id, {
334
+ writeAfterRemoteClose: true,
335
+ graceMs: HALF_CLOSE_GRACE_MS,
336
+ onData: (bytes) => { sock.write(bytes, () => channel.consumed(bytes.byteLength)); },
337
+ onRemoteClose: () => { sock.end(); graceTimer = setTimeout(() => sock.destroy(), HALF_CLOSE_GRACE_MS); graceTimer.unref?.(); },
338
+ onClose: () => { clearTimeout(graceTimer); sock.destroy(); },
339
+ });
340
+ conns.set(id, { channel, sock });
341
+ // Origin -> client: one chunk at a time. The socket is paused until the channel has taken the chunk (it waits for
342
+ // credit and for the transport), so a client that stops reading stops the origin instead of filling memory here.
343
+ sock.on('data', (d) => {
344
+ sock.pause();
345
+ tail = channel.write(new Uint8Array(d.buffer, d.byteOffset, d.length)).then(() => { if (!sock.destroyed) sock.resume(); }, () => { sock.destroy(); });
346
+ });
347
+ sock.on('error', (e) => log(`gateway ${id}: ${e.message}`));
348
+ // The origin is gone: say so once everything it sent has gone out, and forget the connection (the client's own
349
+ // GatewayClose, if it sends one, then finds nothing and is ignored).
350
+ sock.on('close', () => { void tail.finally(() => channel.destroy()); });
351
+ return channel;
352
+ }
155
353
 
156
354
  async function openTcp(m) {
157
355
  const id = m.gateway_id;
158
356
  if (!Number.isInteger(id) || typeof m.host !== 'string' || !Number.isInteger(m.port) || m.port < 1 || m.port > 65535) {
159
357
  return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'malformed OpenTcp');
160
358
  }
161
- if (sockets.has(id) || pending.has(id)) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'gateway_id already in use');
162
- if (!destinationAllowed(cfg.allow, m.host, m.port)) {
359
+ if (idInUse(id)) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'gateway_id already in use');
360
+ if (!cfg.tcp) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'TCP is not enabled on this gateway');
361
+ const decision = nameDecision(cfg.allow, m.host, m.port);
362
+ if (!decision.allowed) {
163
363
  log(`gateway: refused ${m.host}:${m.port} (not on the allow list)`);
164
364
  return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'destination not allowed by the gateway policy');
165
365
  }
166
366
  if (active() >= cfg.maxConnections) return fail(id, GATEWAY_FAIL.QUEUE_FULL, 'too many gateway connections');
167
367
  pending.add(id);
168
368
  let sock;
369
+ let resolvedAddr;
169
370
  try {
170
- const net = await loadNet();
171
- if (cfg.socks) sock = await socksConnect(cfg.socks, m.host, m.port, { timeoutMs: cfg.connectTimeoutMs });
172
- else {
173
- sock = await new Promise((resolve, reject) => {
174
- const s = net.connect({ host: m.host, port: m.port });
175
- const t = setTimeout(() => { s.destroy(); const e = new Error('connect timed out'); e.code = GATEWAY_FAIL.TIMEOUT; reject(e); }, cfg.connectTimeoutMs);
176
- s.once('connect', () => { clearTimeout(t); s.removeAllListeners('error'); resolve(s); });
177
- s.once('error', (e) => {
178
- clearTimeout(t);
179
- const code = e.code === 'ECONNREFUSED' ? GATEWAY_FAIL.CONNECTION_REFUSED : e.code === 'ENOTFOUND' || e.code === 'EAI_AGAIN' ? GATEWAY_FAIL.DNS_FAILED : GATEWAY_FAIL.HOST_UNREACHABLE;
180
- const err = new Error(e.code === 'ENOTFOUND' ? 'name not found' : e.message);
181
- err.code = code;
182
- reject(err);
183
- });
184
- });
371
+ if (cfg.socks) {
372
+ const lit = parseIp(m.host);
373
+ if (lit && !addressPermitted(cfg, m.host, { explicitLiteral: decision.explicit ? m.host : null })) {
374
+ const e = new Error('the address is not permitted by the gateway policy');
375
+ e.code = GATEWAY_FAIL.POLICY_DENIED;
376
+ throw e;
377
+ }
378
+ sock = await socksConnect(cfg.socks, m.host, m.port, { timeoutMs: cfg.connectTimeoutMs });
379
+ } else {
380
+ ({ sock, address: resolvedAddr } = await dialChecked(cfg, m.host, m.port, decision.explicit ? m.host : null));
185
381
  }
186
382
  } catch (e) {
187
383
  pending.delete(id);
384
+ if (e.code === GATEWAY_FAIL.POLICY_DENIED) log(`gateway: refused ${m.host}:${m.port} (${e.message})`);
188
385
  return fail(id, typeof e.code === 'number' ? e.code : GATEWAY_FAIL.HOST_UNREACHABLE, String(e.message).slice(0, 200));
189
386
  }
190
387
  pending.delete(id);
191
- sockets.set(id, sock);
192
- sock.setNoDelay(true);
193
- sock.on('data', (d) => { void reply(gatewayData({ gatewayId: id, data: new Uint8Array(d.buffer, d.byteOffset, d.length) })); });
194
- sock.on('error', (e) => log(`gateway ${id}: ${e.message}`));
195
- sock.on('close', () => {
196
- if (sockets.get(id) === sock) { sockets.delete(id); void reply(gatewayClose({ gatewayId: id })); }
197
- });
198
- log(`gateway: ${id} -> ${m.host}:${m.port}${cfg.socks ? ' (via SOCKS5)' : ''}`);
199
- return reply(gatewayOk({ gatewayId: id }));
388
+ if (closed) { sock.destroy(); return undefined; }
389
+ attachSocket(id, sock);
390
+ log(`gateway: ${id} -> ${m.host}:${m.port}${resolvedAddr && resolvedAddr !== m.host ? ` (${resolvedAddr})` : ''}${cfg.socks ? ' (via SOCKS5)' : ''}`);
391
+ return reply(gatewayOk({ gatewayId: id, resolvedAddr }));
200
392
  }
201
393
 
202
394
  async function resolveDns(m) {
203
395
  const id = m.gateway_id;
396
+ if (!cfg.tcp) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'DNS is not enabled on this gateway');
204
397
  if (cfg.socks) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'names are resolved by the SOCKS proxy; this gateway does not look them up');
205
398
  if (typeof m.name !== 'string' || !m.name) return fail(id, GATEWAY_FAIL.DNS_FAILED, 'malformed ResolveDns');
206
399
  // Only names the client could also connect to: the allow list is about hosts, not ports, here.
@@ -209,40 +402,362 @@ export function createGatewaySession(cfg, send, log = () => {}) {
209
402
  try {
210
403
  const family = m.record_type === 'AAAA' ? 6 : m.record_type === 'A' || m.record_type === undefined ? 4 : 0;
211
404
  if (!family) return fail(id, GATEWAY_FAIL.DNS_FAILED, `unsupported record type ${String(m.record_type).slice(0, 8)}`);
212
- const addresses = (await (await loadDns()).lookup(m.name, { family, all: true })).map((a) => a.address);
405
+ const all = (await (await loadDns()).lookup(m.name, { family, all: true, verbatim: true })).map((a) => a.address);
406
+ // An answer a client could not connect to is not handed out either: it would only be a way to learn the
407
+ // host's internal addresses, and a later OpenTcp to it has to pass the same check.
408
+ const lit = parseIp(m.name) ? m.name : null;
409
+ const addresses = all.filter((a) => addressPermitted(cfg, a, { explicitLiteral: lit }));
410
+ if (all.length && !addresses.length) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'the addresses this name resolves to are not permitted by the gateway policy');
213
411
  return reply(dnsResult({ gatewayId: id, addresses }));
214
412
  } catch (e) {
215
413
  return fail(id, GATEWAY_FAIL.DNS_FAILED, String(e.code === 'ENOTFOUND' ? 'name not found' : e.message).slice(0, 200));
216
414
  }
217
415
  }
218
416
 
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;
434
+
435
+ async function openUdp(m) {
436
+ const id = m.gateway_id;
437
+ if (!Number.isInteger(id) || typeof m.host !== 'string' || !Number.isInteger(m.port) || m.port < 1 || m.port > 65535) {
438
+ return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'malformed OpenUdp');
439
+ }
440
+ if (idInUse(id)) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'gateway_id already in use');
441
+ if (!cfg.tcp) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'UDP is not enabled on this gateway');
442
+ if (cfg.socks) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'UDP is not available through a SOCKS proxy');
443
+ const decision = nameDecision(cfg.allow, m.host, m.port);
444
+ if (!decision.allowed) {
445
+ log(`gateway: refused udp ${m.host}:${m.port} (not on the allow list)`);
446
+ return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'destination not allowed by the gateway policy');
447
+ }
448
+ if (udpFlows.size + udpPending.size >= udpCfg.maxFlows) return fail(id, GATEWAY_FAIL.QUEUE_FULL, `too many UDP flows (limit ${udpCfg.maxFlows})`);
449
+ if (active() >= cfg.maxConnections) return fail(id, GATEWAY_FAIL.QUEUE_FULL, 'too many gateway connections');
450
+ udpPending.add(id);
451
+ pending.add(id);
452
+ let sock;
453
+ let address;
454
+ try {
455
+ address = (await resolveChecked(cfg, m.host, decision.explicit ? m.host : null))[0];
456
+ const dgram = (await import('node:dgram')).default;
457
+ sock = dgram.createSocket(address.includes(':') ? 'udp6' : 'udp4');
458
+ await new Promise((resolve, reject) => { sock.once('error', reject); sock.connect(m.port, address, () => { sock.off('error', reject); resolve(); }); });
459
+ } catch (e) {
460
+ pending.delete(id); udpPending.delete(id);
461
+ try { sock?.close(); } catch { /* not open */ }
462
+ if (e.code === GATEWAY_FAIL.POLICY_DENIED) log(`gateway: refused udp ${m.host}:${m.port} (${e.message})`);
463
+ return fail(id, typeof e.code === 'number' ? e.code : GATEWAY_FAIL.HOST_UNREACHABLE, String(e.message).slice(0, 200));
464
+ }
465
+ pending.delete(id); udpPending.delete(id);
466
+ if (closed) { sock.close(); return undefined; }
467
+ attachDatagrams(id, sock);
468
+ stats.flowsOpened++;
469
+ log(`gateway: ${id} -> udp ${m.host}:${m.port}${address !== m.host ? ` (${address})` : ''}${datagramsOn() ? ' (datagrams)' : ''} (local port ${sock.address().port})`);
470
+ return reply(gatewayOk({ gatewayId: id, resolvedAddr: address }));
471
+ }
472
+
473
+ function attachDatagrams(id, sock) {
474
+ let idle = null;
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
+ };
484
+ const outbox = [];
485
+ let outboxBytes = 0;
486
+ let pumping = false;
487
+ const channel = makeChannel(id, {
488
+ onData: (bytes) => { // a payload on the reliable stream (the only path without datagrams; the oversize path with them)
489
+ touch();
490
+ if (bytes.byteLength > MAX_DATAGRAM || !admit(bytes.byteLength)) { channel.consumed(bytes.byteLength); return; }
491
+ stats.reliableFromClient++;
492
+ sock.send(bytes, () => channel.consumed(bytes.byteLength));
493
+ },
494
+ onRemoteClose: () => channel.destroy(), // UDP has no half-close
495
+ onClose: () => { clearTimeout(idle); udpFlows.delete(id); try { sock.close(); } catch { /* closed */ } },
496
+ });
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
+ });
504
+ async function pump() {
505
+ if (pumping) return;
506
+ pumping = true;
507
+ try {
508
+ while (outbox.length && !channel.closed) {
509
+ const d = outbox.shift();
510
+ outboxBytes -= d.length;
511
+ await channel.write(new Uint8Array(d.buffer, d.byteOffset, d.length));
512
+ }
513
+ } catch { /* closed while writing */ } finally { pumping = false; }
514
+ }
515
+ sock.on('message', (d) => {
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
+ }
527
+ if (outboxBytes + d.length > UDP_OUTBOX_BYTES) return; // the client is not keeping up: drop, as a network would
528
+ stats.reliableToClient++;
529
+ outbox.push(d); outboxBytes += d.length;
530
+ void pump();
531
+ });
532
+ sock.on('error', (e) => log(`gateway ${id}: ${e.message}`));
533
+ touch();
534
+ }
535
+
536
+ // ── unix sockets ─────────────────────────────────────────────────
537
+
538
+ async function openUnix(m) {
539
+ const id = m.gateway_id;
540
+ if (!Number.isInteger(id) || typeof m.path !== 'string') return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'malformed OpenUnix');
541
+ if (idInUse(id)) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'gateway_id already in use');
542
+ if (!cfg.unix || cfg.unix.connect.length === 0) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'unix sockets are not enabled on this gateway');
543
+ if (active() >= cfg.maxConnections) return fail(id, GATEWAY_FAIL.QUEUE_FULL, 'too many gateway connections');
544
+ pending.add(id);
545
+ let sock;
546
+ try {
547
+ const unix = await loadUnix();
548
+ const chk = await unix.checkUnixPath(m.path, cfg.unix.connect);
549
+ if (!chk.ok) {
550
+ log(`gateway: refused unix ${JSON.stringify(m.path.slice(0, 200))} (${chk.reason})`);
551
+ pending.delete(id);
552
+ return fail(id, GATEWAY_FAIL.POLICY_DENIED, chk.reason);
553
+ }
554
+ if (!chk.abstract) {
555
+ const st = await unix.statSocket(chk.path);
556
+ if (!st) { pending.delete(id); return fail(id, GATEWAY_FAIL.CONNECTION_REFUSED, 'no such socket'); }
557
+ if (!st.socket) { pending.delete(id); log(`gateway: refused unix ${chk.path} (not a socket)`); return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'not a socket'); }
558
+ }
559
+ sock = await new Promise((resolve, reject) => {
560
+ loadNet().then((net) => {
561
+ const s = net.connect({ path: chk.path });
562
+ const t = setTimeout(() => { s.destroy(); const e = new Error('connect timed out'); e.code = GATEWAY_FAIL.TIMEOUT; reject(e); }, cfg.connectTimeoutMs);
563
+ s.once('connect', () => { clearTimeout(t); s.removeAllListeners('error'); resolve(s); });
564
+ s.once('error', (e) => { clearTimeout(t); reject(connectError(e)); });
565
+ }, reject);
566
+ });
567
+ } catch (e) {
568
+ pending.delete(id);
569
+ return fail(id, typeof e.code === 'number' ? e.code : GATEWAY_FAIL.HOST_UNREACHABLE, String(e.message).slice(0, 200));
570
+ }
571
+ pending.delete(id);
572
+ if (closed) { sock.destroy(); return undefined; }
573
+ attachSocket(id, sock);
574
+ log(`gateway: ${id} -> unix ${m.path.slice(0, 200)}`);
575
+ return reply(gatewayOk({ gatewayId: id }));
576
+ }
577
+
578
+ async function listenUnix(m) {
579
+ const id = m.listener_id;
580
+ if (!Number.isInteger(id) || typeof m.path !== 'string') return failListen(id, 'malformed ListenUnix');
581
+ if (listeners.has(id) || pendingListeners.has(id)) return failListen(id, 'listener_id already in use');
582
+ if (!cfg.unix || cfg.unix.listen.length === 0) return failListen(id, 'unix listeners are not enabled on this gateway');
583
+ if (listeners.size + pendingListeners.size >= cfg.unix.maxListeners) return failListen(id, 'too many unix listeners');
584
+ pendingListeners.add(id);
585
+ let server;
586
+ try {
587
+ const unix = await loadUnix();
588
+ const net = await loadNet();
589
+ const chk = await unix.checkUnixPath(m.path, cfg.unix.listen);
590
+ if (!chk.ok) { log(`gateway: refused unix listen ${JSON.stringify(m.path.slice(0, 200))} (${chk.reason})`); return await failListen(id, chk.reason); }
591
+ if (!chk.abstract) {
592
+ const st = await unix.statSocket(chk.path);
593
+ if (st) {
594
+ if (!st.socket) return await failListen(id, 'a file that is not a socket is in the way');
595
+ if (m.replace !== true) return await failListen(id, 'address in use (a socket file exists; ask to replace it)');
596
+ if (!cfg.unix.replaceStale) return await failListen(id, 'replacing an existing socket is not allowed by the gateway policy');
597
+ // Only a stale socket: one nothing accepts connections on.
598
+ const live = await new Promise((resolve) => {
599
+ const probe = net.connect({ path: chk.path });
600
+ probe.once('connect', () => { probe.destroy(); resolve(true); });
601
+ probe.once('error', (e) => resolve(e.code !== 'ECONNREFUSED' && e.code !== 'ENOENT'));
602
+ });
603
+ if (live) return await failListen(id, 'address in use (the existing socket is live)');
604
+ await unix.unlinkIfSocket(chk.path, st);
605
+ }
606
+ }
607
+ if (closed) return undefined;
608
+ server = net.createServer();
609
+ // Created private from the first instant: the mode of a socket is its umask at bind time.
610
+ const oldMask = (() => { try { return process.umask(0o177); } catch { return null; } })();
611
+ try {
612
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen({ path: chk.path }, () => { server.off('error', reject); resolve(); }); });
613
+ } finally { if (oldMask !== null) { try { process.umask(oldMask); } catch { /* gone */ } } }
614
+ let stat = null;
615
+ if (!chk.abstract) {
616
+ const fsp = (await import('node:fs/promises')).default;
617
+ await fsp.chmod(chk.path, 0o600);
618
+ stat = await unix.statSocket(chk.path);
619
+ }
620
+ if (closed) { server.close(); if (stat) await unix.unlinkIfSocket(chk.path, stat); return undefined; }
621
+ const entry = { server, kind: 'unix', path: chk.path, abstract: chk.abstract, stat, pendingChannels: new Set(), open: 0 };
622
+ listeners.set(id, entry);
623
+ server.on('connection', (sock) => onInbound(id, entry, sock));
624
+ server.on('error', (e) => log(`gateway listener ${id}: ${e.message}`));
625
+ log(`gateway: listening on unix ${m.path.slice(0, 200)} (listener ${id})`);
626
+ return await reply(listenOk({ listenerId: id, actualPort: 0 }));
627
+ } catch (e) {
628
+ try { server?.close(); } catch { /* not listening */ }
629
+ return failListen(id, e.code === 'EADDRINUSE' ? 'address in use' : String(e.message).slice(0, 200));
630
+ } finally {
631
+ pendingListeners.delete(id);
632
+ }
633
+ }
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
+
672
+ function onInbound(listenerId, entry, sock) {
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`);
677
+ sock.pause();
678
+ sock.on('error', () => {});
679
+ const channelId = ++nextInbound;
680
+ const timer = setTimeout(() => { inbound.delete(channelId); entry.pendingChannels.delete(channelId); sock.destroy(); }, INBOUND_ACCEPT_TIMEOUT_MS);
681
+ timer.unref?.();
682
+ if (tcp) { entry.open++; cfg.stats.reverse.accepted++; sock.once('close', () => { entry.open--; }); }
683
+ sock.once('close', () => { if (inbound.get(channelId)?.sock === sock) { clearTimeout(timer); inbound.delete(channelId); entry.pendingChannels.delete(channelId); } });
684
+ inbound.set(channelId, { sock, listenerId, timer });
685
+ entry.pendingChannels.add(channelId);
686
+ void reply(inboundOpen({ listenerId, channelId, peerAddr: tcp ? (sock.remoteAddress ?? '') : 'unix', peerPort: tcp ? (sock.remotePort ?? 0) : 0 }));
687
+ }
688
+
689
+ function inboundAccept(m) {
690
+ const p = inbound.get(m.channel_id);
691
+ if (!p) return;
692
+ clearTimeout(p.timer);
693
+ inbound.delete(m.channel_id);
694
+ listeners.get(p.listenerId)?.pendingChannels.delete(m.channel_id);
695
+ const id = m.gateway_id;
696
+ if (!Number.isInteger(id) || idInUse(id) || p.sock.destroyed || active() >= cfg.maxConnections) { p.sock.destroy(); return; }
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
+ }
703
+ p.sock.resume();
704
+ }
705
+
706
+ function inboundReject(m) {
707
+ const p = inbound.get(m.channel_id);
708
+ if (!p) return;
709
+ clearTimeout(p.timer);
710
+ inbound.delete(m.channel_id);
711
+ p.sock.destroy();
712
+ }
713
+
714
+ async function closeListener(id) {
715
+ const l = listeners.get(id);
716
+ if (!l) return;
717
+ listeners.delete(id);
718
+ for (const ch of l.pendingChannels) { const p = inbound.get(ch); if (p) { clearTimeout(p.timer); inbound.delete(ch); p.sock.destroy(); } }
719
+ await new Promise((r) => { l.server.close(() => r()); });
720
+ if (l.stat) await (await loadUnix()).unlinkIfSocket(l.path, l.stat);
721
+ }
722
+
219
723
  return {
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
+ },
220
734
  /** @returns {Promise<boolean>} true when the message was a gateway message this session consumed */
221
735
  async handle(m) {
736
+ if (closed) return true;
222
737
  switch (m.type) {
223
738
  case MSG.OPEN_TCP: await openTcp(m); return true;
224
- case MSG.OPEN_UDP: fail(m.gateway_id, GATEWAY_FAIL.POLICY_DENIED, 'UDP is not supported by this gateway'); return true;
739
+ case MSG.OPEN_UDP: await openUdp(m); return true;
740
+ case MSG.OPEN_UNIX: await openUnix(m); return true;
225
741
  case MSG.RESOLVE_DNS: await resolveDns(m); return true;
226
- case MSG.GATEWAY_DATA: {
227
- const s = sockets.get(m.gateway_id);
228
- const d = m.data;
229
- if (s && d && d.length <= MAX_DATA_BYTES) s.write(Buffer.from(d.buffer, d.byteOffset, d.length));
230
- return true;
231
- }
232
- case MSG.GATEWAY_CLOSE: {
233
- const s = sockets.get(m.gateway_id);
234
- if (s) { s.end(); setTimeout(() => s.destroy(), 1000).unref(); } // its 'close' event deletes it and acknowledges
235
- return true;
236
- }
237
- case MSG.LISTEN_REQUEST: reply(listenFail({ listenerId: m.listener_id, reason: 'reverse tunnels are not supported by this gateway' })); return true;
238
- case MSG.LISTEN_CLOSE: return true;
239
- default: return false;
742
+ case MSG.LISTEN_REQUEST: await listenTcp(m); return true;
743
+ case MSG.LISTEN_UNIX: await listenUnix(m); return true;
744
+ case MSG.LISTEN_CLOSE: await closeListener(m.listener_id); return true;
745
+ case MSG.INBOUND_ACCEPT: inboundAccept(m); return true;
746
+ case MSG.INBOUND_REJECT: inboundReject(m); return true;
747
+ // OpenEndpoint, GatewayData, GatewayCredit, GatewayClose: the core.
748
+ default: return core.handle(m);
240
749
  }
241
750
  },
242
751
  close() {
243
- for (const s of sockets.values()) s.destroy();
244
- sockets.clear();
752
+ closed = true;
753
+ core.close();
754
+ for (const { sock, timer } of inbound.values()) { clearTimeout(timer); sock.destroy(); }
755
+ inbound.clear();
756
+ for (const id of [...listeners.keys()]) void closeListener(id).catch(() => {});
245
757
  },
246
- get size() { return sockets.size; },
758
+ get size() { return conns.size; },
759
+ /** Bytes received from the client for its origins and not yet taken by them (what the caps bound). */
760
+ get bufferedBytes() { return core.bufferedBytes; },
761
+ get listenerCount() { return listeners.size; },
247
762
  };
248
763
  }