onelobby 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +77 -2
  3. package/dist/chat.d.ts +60 -0
  4. package/dist/chat.js +163 -0
  5. package/dist/chat.js.map +1 -0
  6. package/dist/chunking.d.ts +17 -0
  7. package/dist/chunking.js +59 -0
  8. package/dist/chunking.js.map +1 -0
  9. package/dist/clock.d.ts +8 -0
  10. package/dist/clock.js +39 -0
  11. package/dist/clock.js.map +1 -0
  12. package/dist/codec.d.ts +141 -0
  13. package/dist/codec.js +308 -0
  14. package/dist/codec.js.map +1 -0
  15. package/dist/crockford.d.ts +14 -0
  16. package/dist/crockford.js +55 -0
  17. package/dist/crockford.js.map +1 -0
  18. package/dist/deflate.d.ts +4 -0
  19. package/dist/deflate.js +32 -0
  20. package/dist/deflate.js.map +1 -0
  21. package/dist/deprecated.d.ts +18 -0
  22. package/dist/deprecated.js +11 -0
  23. package/dist/deprecated.js.map +1 -0
  24. package/dist/direct/hub-host.d.ts +82 -0
  25. package/dist/direct/hub-host.js +393 -0
  26. package/dist/direct/hub-host.js.map +1 -0
  27. package/dist/direct/hub.d.ts +178 -0
  28. package/dist/direct/hub.js +862 -0
  29. package/dist/direct/hub.js.map +1 -0
  30. package/dist/direct/index.d.ts +57 -0
  31. package/dist/direct/index.js +71 -0
  32. package/dist/direct/index.js.map +1 -0
  33. package/dist/direct/portmap.d.ts +84 -0
  34. package/dist/direct/portmap.js +465 -0
  35. package/dist/direct/portmap.js.map +1 -0
  36. package/dist/direct-address.d.ts +20 -0
  37. package/dist/direct-address.js +61 -0
  38. package/dist/direct-address.js.map +1 -0
  39. package/dist/emitter.d.ts +9 -0
  40. package/dist/emitter.js +36 -0
  41. package/dist/emitter.js.map +1 -0
  42. package/dist/friendly.d.ts +20 -0
  43. package/dist/friendly.js +120 -0
  44. package/dist/friendly.js.map +1 -0
  45. package/dist/global.d.ts +8 -0
  46. package/dist/global.js +9 -0
  47. package/dist/global.js.map +1 -0
  48. package/dist/gridpaint.d.ts +27 -0
  49. package/dist/gridpaint.js +106 -0
  50. package/dist/gridpaint.js.map +1 -0
  51. package/dist/hub.d.ts +25 -0
  52. package/dist/hub.js +2 -0
  53. package/dist/hub.js.map +1 -0
  54. package/dist/index.d.ts +35 -0
  55. package/dist/index.js +25 -0
  56. package/dist/index.js.map +1 -0
  57. package/dist/internals.d.ts +28 -0
  58. package/dist/internals.js +24 -0
  59. package/dist/internals.js.map +1 -0
  60. package/dist/joincode.d.ts +21 -0
  61. package/dist/joincode.js +84 -0
  62. package/dist/joincode.js.map +1 -0
  63. package/dist/lobby.d.ts +203 -0
  64. package/dist/lobby.js +840 -0
  65. package/dist/lobby.js.map +1 -0
  66. package/dist/lockstep.d.ts +132 -0
  67. package/dist/lockstep.js +471 -0
  68. package/dist/lockstep.js.map +1 -0
  69. package/dist/migration.d.ts +17 -0
  70. package/dist/migration.js +34 -0
  71. package/dist/migration.js.map +1 -0
  72. package/dist/onelobby.bundle.mjs +140 -0
  73. package/dist/onelobby.bundle.mjs.map +7 -0
  74. package/dist/onelobby.d.ts +151 -0
  75. package/dist/onelobby.global.js +3897 -0
  76. package/dist/onelobby.global.js.map +7 -0
  77. package/dist/onelobby.global.min.js +140 -0
  78. package/dist/onelobby.global.min.js.map +7 -0
  79. package/dist/onelobby.js +337 -0
  80. package/dist/onelobby.js.map +1 -0
  81. package/dist/signaling.d.ts +94 -0
  82. package/dist/signaling.js +134 -0
  83. package/dist/signaling.js.map +1 -0
  84. package/dist/socket.d.ts +63 -0
  85. package/dist/socket.js +142 -0
  86. package/dist/socket.js.map +1 -0
  87. package/dist/testing.d.ts +135 -0
  88. package/dist/testing.js +438 -0
  89. package/dist/testing.js.map +1 -0
  90. package/dist/transport.d.ts +80 -0
  91. package/dist/transport.js +7 -0
  92. package/dist/transport.js.map +1 -0
  93. package/dist/ui/controller.d.ts +137 -0
  94. package/dist/ui/controller.js +337 -0
  95. package/dist/ui/controller.js.map +1 -0
  96. package/dist/ui/element.d.ts +22 -0
  97. package/dist/ui/element.js +284 -0
  98. package/dist/ui/element.js.map +1 -0
  99. package/dist/ui/index.d.ts +5 -0
  100. package/dist/ui/index.js +9 -0
  101. package/dist/ui/index.js.map +1 -0
  102. package/dist/ui/server-url.d.ts +9 -0
  103. package/dist/ui/server-url.js +39 -0
  104. package/dist/ui/server-url.js.map +1 -0
  105. package/dist/ui/styles.d.ts +2 -0
  106. package/dist/ui/styles.js +70 -0
  107. package/dist/ui/styles.js.map +1 -0
  108. package/dist/voice-browser.d.ts +19 -0
  109. package/dist/voice-browser.js +151 -0
  110. package/dist/voice-browser.js.map +1 -0
  111. package/dist/voice-core.d.ts +98 -0
  112. package/dist/voice-core.js +233 -0
  113. package/dist/voice-core.js.map +1 -0
  114. package/dist/voice-types.d.ts +35 -0
  115. package/dist/voice-types.js +3 -0
  116. package/dist/voice-types.js.map +1 -0
  117. package/dist/voice.d.ts +68 -0
  118. package/dist/voice.js +223 -0
  119. package/dist/voice.js.map +1 -0
  120. package/dist/webrtc.d.ts +29 -0
  121. package/dist/webrtc.js +169 -0
  122. package/dist/webrtc.js.map +1 -0
  123. package/package.json +93 -4
@@ -0,0 +1,465 @@
1
+ /// <reference types="node" />
2
+ import { createSocket } from "node:dgram";
3
+ import { request as httpRequest } from "node:http";
4
+ import { networkInterfaces } from "node:os";
5
+ import { execFile } from "node:child_process";
6
+ const SEARCH_TARGETS = [
7
+ "urn:schemas-upnp-org:device:InternetGatewayDevice:1",
8
+ "urn:schemas-upnp-org:device:InternetGatewayDevice:2",
9
+ "urn:schemas-upnp-org:service:WANIPConnection:1",
10
+ ];
11
+ const SERVICE_TYPES = [
12
+ "urn:schemas-upnp-org:service:WANIPConnection:2",
13
+ "urn:schemas-upnp-org:service:WANIPConnection:1",
14
+ "urn:schemas-upnp-org:service:WANPPPConnection:1",
15
+ ];
16
+ class UpnpError extends Error {
17
+ code;
18
+ constructor(code, message) {
19
+ super(message);
20
+ this.code = code;
21
+ }
22
+ }
23
+ /**
24
+ * Opens TCP and UDP `port` on the home router for a direct-IP host (docs/direct-ip.md s.2a): UPnP IGD (SSDP, then
25
+ * GetExternalIPAddress + AddPortMapping), then NAT-PMP (RFC 6886). Node twin of C#'s `PortMapper`, same order and rules:
26
+ * same external and internal port or nothing (a join code carries one port), leases renew at half-life, {@link close}
27
+ * deletes the mappings. Windows Firewall drops SSDP replies on a network marked Public; the result is then unmapped.
28
+ */
29
+ export class PortMapper {
30
+ port;
31
+ result = null;
32
+ o;
33
+ control = null;
34
+ service = "";
35
+ lease = 0;
36
+ natPmpAt = null;
37
+ renew = null;
38
+ stopped = false;
39
+ constructor(port, options = {}) {
40
+ this.port = port;
41
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
42
+ throw new RangeError(`bad port ${port}`);
43
+ this.o = {
44
+ ssdp: { address: "239.255.255.250", port: 1900 },
45
+ discoveryTimeoutMs: 2000,
46
+ requestTimeoutMs: 3000,
47
+ leaseSeconds: 7200,
48
+ description: "OneLobby",
49
+ tryUpnp: true,
50
+ tryNatPmp: true,
51
+ ...options,
52
+ };
53
+ }
54
+ /** Finds the router and maps TCP + UDP `port`. Never rejects for network trouble: see `detail`. */
55
+ async open() {
56
+ const notes = [];
57
+ if (this.o.tryUpnp) {
58
+ try {
59
+ const r = await this.tryUpnp();
60
+ if (r)
61
+ return this.done(r);
62
+ notes.push("no UPnP gateway answered");
63
+ }
64
+ catch (e) {
65
+ notes.push(`UPnP: ${e.message}`);
66
+ }
67
+ }
68
+ if (this.o.tryNatPmp) {
69
+ try {
70
+ const r = await this.tryNatPmp();
71
+ if (r)
72
+ return this.done(r);
73
+ notes.push("no NAT-PMP answer");
74
+ }
75
+ catch (e) {
76
+ notes.push(`NAT-PMP: ${e.message}`);
77
+ }
78
+ }
79
+ return (this.result = { mapped: false, method: "none", externalIPv4: null, localIPv4: null, detail: notes.join("; ") });
80
+ }
81
+ done(r) {
82
+ this.result = r;
83
+ if (r.mapped && !this.stopped && (this.lease > 0 || r.method === "natpmp")) {
84
+ const everyMs = Math.max(30, (this.lease > 0 ? this.lease : this.o.leaseSeconds) / 2) * 1000;
85
+ this.renew = setInterval(() => {
86
+ const p = r.method === "upnp" ? this.addUpnpBoth(r.localIPv4, this.lease) : this.natPmpMapBoth(this.o.leaseSeconds);
87
+ p.catch(() => { }); // the next round tries again; the old lease still has half its life
88
+ }, everyMs);
89
+ this.renew.unref?.();
90
+ }
91
+ return r;
92
+ }
93
+ // ------------------------------------------------------------------------------------------------ UPnP IGD
94
+ async tryUpnp() {
95
+ const location = await this.discover();
96
+ if (!location)
97
+ return null;
98
+ const desc = await this.http("GET", location, null, {});
99
+ const baseText = tag(desc.body, "URLBase");
100
+ const base = baseText && /^https?:\/\//i.test(baseText) ? new URL(baseText) : location;
101
+ for (const type of SERVICE_TYPES) {
102
+ for (const svc of desc.body.match(/<service>[\s\S]*?<\/service>/g) ?? []) {
103
+ if ((tag(svc, "serviceType") ?? "").trim() !== type)
104
+ continue;
105
+ const ctl = tag(svc, "controlURL")?.trim();
106
+ if (!ctl)
107
+ continue;
108
+ this.control = new URL(ctl, base);
109
+ this.service = type;
110
+ break;
111
+ }
112
+ if (this.control)
113
+ break;
114
+ }
115
+ if (!this.control)
116
+ return { mapped: false, method: "upnp", externalIPv4: null, localIPv4: null, detail: "UPnP gateway has no WANIPConnection service" };
117
+ const local = await localAddressToward(this.control.hostname, Number(this.control.port) || 80);
118
+ let external = null;
119
+ try {
120
+ external = tag((await this.soap("GetExternalIPAddress", [])).body, "NewExternalIPAddress")?.trim() ?? null;
121
+ }
122
+ catch (e) {
123
+ if (!(e instanceof UpnpError))
124
+ throw e; // some routers refuse this but still map
125
+ }
126
+ this.lease = this.o.leaseSeconds;
127
+ try {
128
+ await this.addUpnpBoth(local, this.lease);
129
+ }
130
+ catch (e) {
131
+ if (!(e instanceof UpnpError))
132
+ throw e;
133
+ if (e.code === 725) {
134
+ // OnlyPermanentLeasesSupported
135
+ this.lease = 0;
136
+ await this.addUpnpBoth(local, 0);
137
+ }
138
+ else
139
+ return { mapped: false, method: "upnp", externalIPv4: external, localIPv4: local, detail: `UPnP ${e.message}` };
140
+ }
141
+ return { mapped: true, method: "upnp", externalIPv4: external, localIPv4: local, detail: "UPnP" };
142
+ }
143
+ async addUpnpBoth(local, lease) {
144
+ for (const proto of ["TCP", "UDP"])
145
+ await this.soap("AddPortMapping", [
146
+ ["NewRemoteHost", ""], ["NewExternalPort", String(this.port)], ["NewProtocol", proto], ["NewInternalPort", String(this.port)],
147
+ ["NewInternalClient", local], ["NewEnabled", "1"], ["NewPortMappingDescription", this.o.description], ["NewLeaseDuration", String(lease)],
148
+ ]);
149
+ }
150
+ /**
151
+ * SSDP search: multicast once per interface that has a gateway (so a Hyper-V, WSL or Docker adapter cannot swallow
152
+ * it), plus a unicast copy to the gateway.
153
+ */
154
+ discover() {
155
+ const multicast = Number(this.o.ssdp.address.split(".")[0]) >= 224;
156
+ const locals = multicast ? gatewayInterfaces() : [];
157
+ if (locals.length === 0)
158
+ locals.push({ local: "0.0.0.0", gateway: null });
159
+ return new Promise((resolve) => {
160
+ const sockets = [];
161
+ let finished = false;
162
+ const finish = (u) => {
163
+ if (finished)
164
+ return;
165
+ finished = true;
166
+ clearTimeout(timer);
167
+ for (const s of sockets)
168
+ s.close();
169
+ resolve(u);
170
+ };
171
+ const timer = setTimeout(() => finish(null), this.o.discoveryTimeoutMs);
172
+ for (const { local, gateway } of locals) {
173
+ const s = createSocket({ type: "udp4", reuseAddr: false });
174
+ sockets.push(s);
175
+ s.on("error", () => { });
176
+ s.on("message", (m) => {
177
+ const u = parseSsdp(m.toString("latin1"));
178
+ if (u)
179
+ finish(u);
180
+ });
181
+ s.bind(0, local === "0.0.0.0" ? undefined : local, () => {
182
+ try {
183
+ s.setMulticastTTL(2);
184
+ if (local !== "0.0.0.0")
185
+ s.setMulticastInterface(local);
186
+ }
187
+ catch {
188
+ /* not fatal: the OS default interface is used */
189
+ }
190
+ for (const st of SEARCH_TARGETS) {
191
+ const b = Buffer.from(`M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: "ssdp:discover"\r\nMX: 1\r\nST: ${st}\r\n\r\n`);
192
+ s.send(b, this.o.ssdp.port, this.o.ssdp.address, () => { });
193
+ if (gateway)
194
+ s.send(b, 1900, gateway, () => { });
195
+ }
196
+ });
197
+ }
198
+ });
199
+ }
200
+ async soap(action, args) {
201
+ const inner = args.map(([k, v]) => `<${k}>${xmlEscape(v)}</${k}>`).join("");
202
+ const body = `<?xml version="1.0"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">` +
203
+ `<s:Body><u:${action} xmlns:u="${this.service}">${inner}</u:${action}></s:Body></s:Envelope>`;
204
+ const res = await this.http("POST", this.control, body, { "Content-Type": 'text/xml; charset="utf-8"', SOAPAction: `"${this.service}#${action}"` });
205
+ if (res.status < 200 || res.status >= 300) {
206
+ const code = tag(res.body, "errorCode");
207
+ const desc = tag(res.body, "errorDescription") ?? "";
208
+ throw new UpnpError(Number(code) || 0, `${action} error ${code ?? res.status} ${desc}`.trim());
209
+ }
210
+ return res;
211
+ }
212
+ /**
213
+ * One connection per request: some routers close after each reply without saying so, and a reused
214
+ * keep-alive socket then fails every second request with "socket hang up".
215
+ */
216
+ http(method, url, body, headers) {
217
+ return new Promise((resolve, reject) => {
218
+ const h = { ...headers, Connection: "close" };
219
+ const req = httpRequest({ method, hostname: url.hostname, port: url.port || 80, path: url.pathname + url.search, timeout: this.o.requestTimeoutMs, agent: false,
220
+ headers: body === null ? h : { ...h, "Content-Length": Buffer.byteLength(body) } }, (res) => {
221
+ let text = "";
222
+ res.setEncoding("utf8");
223
+ res.on("data", (d) => (text += d));
224
+ res.on("end", () => resolve({ status: res.statusCode ?? 0, body: text }));
225
+ });
226
+ req.on("timeout", () => req.destroy(new Error(`${method} ${url.pathname} timed out`)));
227
+ req.on("error", reject);
228
+ if (body !== null)
229
+ req.write(body);
230
+ req.end();
231
+ });
232
+ }
233
+ // ------------------------------------------------------------------------------------------------ NAT-PMP
234
+ async tryNatPmp() {
235
+ // One gateway only: each silent one costs the full retransmission budget.
236
+ let gw0 = this.o.natPmp ?? null;
237
+ if (!gw0) {
238
+ const routed = (await defaultGatewayFallback()) ?? gatewayInterfaces().find((g) => g.gateway)?.gateway ?? null;
239
+ if (routed)
240
+ gw0 = { address: routed, port: 5351 };
241
+ }
242
+ const candidates = gw0 ? [gw0] : [];
243
+ for (const gw of candidates) {
244
+ const ext = await this.natPmpRequest(gw, Buffer.from([0, 0]), 12);
245
+ if (!ext)
246
+ continue;
247
+ this.natPmpAt = gw;
248
+ const local = await localAddressToward(gw.address, gw.port);
249
+ const external = ext.readUInt16BE(2) === 0 ? `${ext[8]}.${ext[9]}.${ext[10]}.${ext[11]}` : null;
250
+ const err = await this.natPmpMapBoth(this.o.leaseSeconds);
251
+ if (err)
252
+ return { mapped: false, method: "natpmp", externalIPv4: external, localIPv4: local, detail: `NAT-PMP ${err}` };
253
+ return { mapped: true, method: "natpmp", externalIPv4: external, localIPv4: local, detail: "NAT-PMP" };
254
+ }
255
+ return null;
256
+ }
257
+ /** Maps UDP then TCP; null on success, else why. A different external port counts as failure (and is undone). */
258
+ async natPmpMapBoth(lifetime) {
259
+ for (const op of [1, 2]) {
260
+ const reply = await this.natPmpRequest(this.natPmpAt, this.mapRequest(op, lifetime), 16);
261
+ if (!reply)
262
+ return "no answer to the mapping request";
263
+ const rc = reply.readUInt16BE(2);
264
+ if (rc !== 0)
265
+ return `result code ${rc}`;
266
+ const mapped = reply.readUInt16BE(10);
267
+ if (lifetime > 0 && mapped !== this.port) {
268
+ await this.natPmpRequest(this.natPmpAt, this.mapRequest(op, 0), 16);
269
+ return `router offered port ${mapped} instead of ${this.port}`;
270
+ }
271
+ }
272
+ return null;
273
+ }
274
+ mapRequest(op, lifetime) {
275
+ const b = Buffer.alloc(12);
276
+ b[1] = op;
277
+ b.writeUInt16BE(this.port, 4);
278
+ b.writeUInt16BE(lifetime > 0 ? this.port : 0, 6);
279
+ b.writeUInt32BE(lifetime, 8);
280
+ return b;
281
+ }
282
+ /** RFC 6886 s.3.1 retransmission: 250 ms, doubling, 3 tries (under 2 s). Null when nobody answers. */
283
+ natPmpRequest(to, req, replyLength) {
284
+ return new Promise((resolve) => {
285
+ const s = createSocket("udp4");
286
+ let wait = 250;
287
+ let tries = 0;
288
+ let timer = null;
289
+ const finish = (b) => {
290
+ if (timer)
291
+ clearTimeout(timer);
292
+ s.close();
293
+ resolve(b);
294
+ };
295
+ s.on("error", () => { }); // ICMP port unreachable on Windows: keep waiting for the timer
296
+ s.on("message", (b) => {
297
+ if (b.length >= replyLength && b[0] === 0 && b[1] === req[1] + 128)
298
+ finish(b);
299
+ });
300
+ const attempt = () => {
301
+ if (tries++ >= 3)
302
+ return finish(null);
303
+ s.send(req, to.port, to.address, () => { });
304
+ timer = setTimeout(attempt, wait);
305
+ wait *= 2;
306
+ };
307
+ s.bind(0, attempt);
308
+ });
309
+ }
310
+ /** Deletes the mappings (best effort, bounded to about 1.5 s) and stops renewing. */
311
+ async close() {
312
+ if (this.stopped)
313
+ return;
314
+ this.stopped = true;
315
+ if (this.renew)
316
+ clearInterval(this.renew);
317
+ const r = this.result;
318
+ if (!r?.mapped)
319
+ return;
320
+ const work = r.method === "upnp"
321
+ ? Promise.all(["TCP", "UDP"].map((p) => this.soap("DeletePortMapping", [["NewRemoteHost", ""], ["NewExternalPort", String(this.port)], ["NewProtocol", p]])))
322
+ : Promise.all([1, 2].map((op) => this.natPmpOnce(this.mapRequest(op, 0))));
323
+ await Promise.race([work.catch(() => { }), new Promise((r2) => setTimeout(r2, 1500).unref?.())]);
324
+ }
325
+ natPmpOnce(req) {
326
+ return new Promise((resolve) => {
327
+ const s = createSocket("udp4");
328
+ s.on("error", () => { });
329
+ s.send(req, this.natPmpAt.port, this.natPmpAt.address, () => {
330
+ s.close();
331
+ resolve();
332
+ });
333
+ });
334
+ }
335
+ }
336
+ // ------------------------------------------------------------------------------------------------ helpers
337
+ /**
338
+ * True for an address the internet can route to: not private (RFC 1918), carrier-grade NAT (100.64/10), loopback,
339
+ * link-local, 0/8, or multicast/reserved (224+). A router that reports a non-public WAN address is itself behind NAT.
340
+ */
341
+ export function isPublicIPv4(address) {
342
+ if (!address)
343
+ return false;
344
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(address);
345
+ if (!m)
346
+ return false;
347
+ const [a, b] = [Number(m[1]), Number(m[2])];
348
+ if (m.slice(1).some((x) => Number(x) > 255))
349
+ return false;
350
+ if (a === 0 || a === 10 || a === 127 || a >= 224)
351
+ return false;
352
+ if (a === 100 && b >= 64 && b < 128)
353
+ return false;
354
+ if (a === 169 && b === 254)
355
+ return false;
356
+ if (a === 172 && b >= 16 && b < 32)
357
+ return false;
358
+ if (a === 192 && b === 168)
359
+ return false;
360
+ return true;
361
+ }
362
+ function tag(xml, name) {
363
+ const m = new RegExp(`<(?:[A-Za-z0-9_]+:)?${name}(?:\\s[^>]*)?>([\\s\\S]*?)</(?:[A-Za-z0-9_]+:)?${name}>`).exec(xml);
364
+ return m ? m[1] : null;
365
+ }
366
+ function xmlEscape(s) {
367
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
368
+ }
369
+ function parseSsdp(text) {
370
+ let location = null;
371
+ let gateway = false;
372
+ for (const line of text.split(/\r?\n/)) {
373
+ const i = line.indexOf(":");
374
+ if (i < 0)
375
+ continue;
376
+ const name = line.slice(0, i).trim().toLowerCase();
377
+ const value = line.slice(i + 1).trim();
378
+ if (name === "location")
379
+ location = value;
380
+ if ((name === "st" || name === "usn") && /InternetGatewayDevice|WANIPConnection/.test(value))
381
+ gateway = true;
382
+ }
383
+ if (!gateway || !location)
384
+ return null;
385
+ try {
386
+ return new URL(location);
387
+ }
388
+ catch {
389
+ return null;
390
+ }
391
+ }
392
+ /**
393
+ * Each IPv4 interface address, with its gateway when one can be guessed. Node's `os` does not report gateways, so the
394
+ * gateway is the interface's .1 (true for nearly every home router); the SSDP multicast does not depend on it.
395
+ */
396
+ function gatewayInterfaces() {
397
+ const out = [];
398
+ for (const addrs of Object.values(networkInterfaces())) {
399
+ for (const a of addrs ?? []) {
400
+ if (a.family !== "IPv4" || a.internal || a.address.startsWith("169.254."))
401
+ continue;
402
+ const ip = a.address.split(".").map(Number);
403
+ const mask = a.netmask.split(".").map(Number);
404
+ const net = ip.map((x, i) => x & mask[i]);
405
+ out.push({ local: a.address, gateway: mask[3] === 255 ? null : `${net[0]}.${net[1]}.${net[2]}.${net[3] + 1}` });
406
+ }
407
+ }
408
+ return out;
409
+ }
410
+ /** The IPv4 default gateway from the OS route table (Windows `route print`, else `ip route`); null if it will not say. */
411
+ function defaultGatewayFallback() {
412
+ return new Promise((resolve) => {
413
+ const win = process.platform === "win32";
414
+ execFile(win ? "route" : "ip", win ? ["print", "0.0.0.0"] : ["route", "show", "default"], { timeout: 2000 }, (err, stdout) => {
415
+ if (err)
416
+ return resolve(null);
417
+ const m = win ? /0\.0\.0\.0\s+0\.0\.0\.0\s+(\d+\.\d+\.\d+\.\d+)/.exec(stdout) : /default via (\d+\.\d+\.\d+\.\d+)/.exec(stdout);
418
+ resolve(m ? m[1] : null);
419
+ });
420
+ });
421
+ }
422
+ /** The local IPv4 the OS would use to reach `host` (a connected UDP socket sends nothing). */
423
+ function localAddressToward(host, port) {
424
+ return new Promise((resolve, reject) => {
425
+ const s = createSocket("udp4");
426
+ s.on("error", (e) => {
427
+ s.close();
428
+ reject(e);
429
+ });
430
+ s.connect(port, host, () => {
431
+ const a = s.address().address;
432
+ s.close();
433
+ resolve(a);
434
+ });
435
+ });
436
+ }
437
+ /** The IPv4 a same-network join code carries when the router was not found (see C#'s DirectAddress.LanIPv4). */
438
+ export async function lanIPv4() {
439
+ try {
440
+ const a = await localAddressToward("192.0.2.1", 9); // TEST-NET-1: routed like the internet, never contacted
441
+ if (a && a !== "0.0.0.0" && !a.startsWith("127."))
442
+ return a;
443
+ }
444
+ catch {
445
+ /* no default route: offline LAN party, look at the interfaces instead */
446
+ }
447
+ return gatewayInterfaces()[0]?.local ?? null;
448
+ }
449
+ /** This machine's addresses with the port, IPv4 first, for an "Advanced" fold-out on the host screen. */
450
+ export function localAddresses(port) {
451
+ const v4 = [];
452
+ const v6 = [];
453
+ for (const addrs of Object.values(networkInterfaces())) {
454
+ for (const a of addrs ?? []) {
455
+ if (a.internal)
456
+ continue;
457
+ if (a.family === "IPv4" && !a.address.startsWith("169.254."))
458
+ v4.push(`${a.address}:${port}`);
459
+ else if (a.family === "IPv6" && !/^fe80:/i.test(a.address) && !/^ff/i.test(a.address))
460
+ v6.push(`[${a.address}]:${port}`);
461
+ }
462
+ }
463
+ return [...v4, ...v6];
464
+ }
465
+ //# sourceMappingURL=portmap.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"portmap.js","sourceRoot":"","sources":["../../src/direct/portmap.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAC9B,OAAO,EAAE,YAAY,EAA4B,MAAM,YAAY,CAAC;AACpE,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AA+B9C,MAAM,cAAc,GAAG;IACrB,qDAAqD;IACrD,qDAAqD;IACrD,gDAAgD;CACjD,CAAC;AACF,MAAM,aAAa,GAAG;IACpB,gDAAgD;IAChD,gDAAgD;IAChD,iDAAiD;CAClD,CAAC;AAEF,MAAM,SAAU,SAAQ,KAAK;IACN;IAArB,YAAqB,IAAY,EAAE,OAAe;QAChD,KAAK,CAAC,OAAO,CAAC,CAAC;QADI,SAAI,GAAJ,IAAI,CAAQ;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BAAiB,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC;AAC/C,CAAC;AAED,yGAAyG;AACzG,MAAM,UAAU,cAAc,CAAC,IAAY;IACzC,MAAM,EAAE,GAAa,EAAE,CAAC;IACxB,MAAM,EAAE,GAAa,EAAE,CAAC;IACxB,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,iBAAiB,EAAE,CAAC,EAAE,CAAC;QACvD,KAAK,MAAM,CAAC,IAAI,KAAK,IAAI,EAAE,EAAE,CAAC;YAC5B,IAAI,CAAC,CAAC,QAAQ;gBAAE,SAAS;YACzB,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC;gBAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,IAAI,IAAI,EAAE,CAAC,CAAC;iBACzF,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC;gBAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,KAAK,IAAI,EAAE,CAAC,CAAC;QAC3H,CAAC;IACH,CAAC;IACD,OAAO,CAAC,GAAG,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC;AACxB,CAAC","sourcesContent":["/// <reference types=\"node\" />\nimport { createSocket, type Socket as UdpSocket } from \"node:dgram\";\nimport { request as httpRequest } from \"node:http\";\nimport { networkInterfaces } from \"node:os\";\nimport { execFile } from \"node:child_process\";\n\nexport type PortMapMethod = \"none\" | \"upnp\" | \"natpmp\";\n\n/** What {@link PortMapper.open} found. `mapped` means TCP and UDP `port` both forward here. */\nexport interface PortMapResult {\n mapped: boolean;\n method: PortMapMethod;\n /** The router's WAN address as it reports it (may itself be private or carrier-grade NAT). */\n externalIPv4: string | null;\n /** This PC's address on the router's network, when the router was found. */\n localIPv4: string | null;\n /** Why nothing was mapped, for logs. */\n detail: string;\n}\n\n/** Seams for tests (a fake gateway on loopback) and the few knobs a game might want. Same as C#'s PortMapperOptions. */\nexport interface PortMapperOptions {\n /** Where the SSDP M-SEARCH goes; default the UPnP multicast group 239.255.255.250:1900. */\n ssdp?: { address: string; port: number };\n /** NAT-PMP server; default this PC's IPv4 default gateway, port 5351. */\n natPmp?: { address: string; port: number };\n discoveryTimeoutMs?: number;\n requestTimeoutMs?: number;\n /** Lease asked for; renewed at half of it while hosting. Routers that only allow permanent leases get 0. */\n leaseSeconds?: number;\n description?: string;\n tryUpnp?: boolean;\n tryNatPmp?: boolean;\n}\n\nconst SEARCH_TARGETS = [\n \"urn:schemas-upnp-org:device:InternetGatewayDevice:1\",\n \"urn:schemas-upnp-org:device:InternetGatewayDevice:2\",\n \"urn:schemas-upnp-org:service:WANIPConnection:1\",\n];\nconst SERVICE_TYPES = [\n \"urn:schemas-upnp-org:service:WANIPConnection:2\",\n \"urn:schemas-upnp-org:service:WANIPConnection:1\",\n \"urn:schemas-upnp-org:service:WANPPPConnection:1\",\n];\n\nclass UpnpError extends Error {\n constructor(readonly code: number, message: string) {\n super(message);\n }\n}\n\n/**\n * Opens TCP and UDP `port` on the home router for a direct-IP host (docs/direct-ip.md s.2a): UPnP IGD (SSDP, then\n * GetExternalIPAddress + AddPortMapping), then NAT-PMP (RFC 6886). Node twin of C#'s `PortMapper`, same order and rules:\n * same external and internal port or nothing (a join code carries one port), leases renew at half-life, {@link close}\n * deletes the mappings. Windows Firewall drops SSDP replies on a network marked Public; the result is then unmapped.\n */\nexport class PortMapper {\n result: PortMapResult | null = null;\n private readonly o: Required<Omit<PortMapperOptions, \"natPmp\">> & { natPmp?: { address: string; port: number } };\n private control: URL | null = null;\n private service = \"\";\n private lease = 0;\n private natPmpAt: { address: string; port: number } | null = null;\n private renew: ReturnType<typeof setInterval> | null = null;\n private stopped = false;\n\n constructor(readonly port: number, options: PortMapperOptions = {}) {\n if (!Number.isInteger(port) || port < 1 || port > 65535) throw new RangeError(`bad port ${port}`);\n this.o = {\n ssdp: { address: \"239.255.255.250\", port: 1900 },\n discoveryTimeoutMs: 2000,\n requestTimeoutMs: 3000,\n leaseSeconds: 7200,\n description: \"OneLobby\",\n tryUpnp: true,\n tryNatPmp: true,\n ...options,\n };\n }\n\n /** Finds the router and maps TCP + UDP `port`. Never rejects for network trouble: see `detail`. */\n async open(): Promise<PortMapResult> {\n const notes: string[] = [];\n if (this.o.tryUpnp) {\n try {\n const r = await this.tryUpnp();\n if (r) return this.done(r);\n notes.push(\"no UPnP gateway answered\");\n } catch (e) {\n notes.push(`UPnP: ${(e as Error).message}`);\n }\n }\n if (this.o.tryNatPmp) {\n try {\n const r = await this.tryNatPmp();\n if (r) return this.done(r);\n notes.push(\"no NAT-PMP answer\");\n } catch (e) {\n notes.push(`NAT-PMP: ${(e as Error).message}`);\n }\n }\n return (this.result = { mapped: false, method: \"none\", externalIPv4: null, localIPv4: null, detail: notes.join(\"; \") });\n }\n\n private done(r: PortMapResult): PortMapResult {\n this.result = r;\n if (r.mapped && !this.stopped && (this.lease > 0 || r.method === \"natpmp\")) {\n const everyMs = Math.max(30, (this.lease > 0 ? this.lease : this.o.leaseSeconds) / 2) * 1000;\n this.renew = setInterval(() => {\n const p = r.method === \"upnp\" ? this.addUpnpBoth(r.localIPv4!, this.lease) : this.natPmpMapBoth(this.o.leaseSeconds);\n p.catch(() => {}); // the next round tries again; the old lease still has half its life\n }, everyMs);\n this.renew.unref?.();\n }\n return r;\n }\n\n // ------------------------------------------------------------------------------------------------ UPnP IGD\n\n private async tryUpnp(): Promise<PortMapResult | null> {\n const location = await this.discover();\n if (!location) return null;\n const desc = await this.http(\"GET\", location, null, {});\n const baseText = tag(desc.body, \"URLBase\");\n const base = baseText && /^https?:\\/\\//i.test(baseText) ? new URL(baseText) : location;\n for (const type of SERVICE_TYPES) {\n for (const svc of desc.body.match(/<service>[\\s\\S]*?<\\/service>/g) ?? []) {\n if ((tag(svc, \"serviceType\") ?? \"\").trim() !== type) continue;\n const ctl = tag(svc, \"controlURL\")?.trim();\n if (!ctl) continue;\n this.control = new URL(ctl, base);\n this.service = type;\n break;\n }\n if (this.control) break;\n }\n if (!this.control) return { mapped: false, method: \"upnp\", externalIPv4: null, localIPv4: null, detail: \"UPnP gateway has no WANIPConnection service\" };\n\n const local = await localAddressToward(this.control.hostname, Number(this.control.port) || 80);\n let external: string | null = null;\n try {\n external = tag((await this.soap(\"GetExternalIPAddress\", [])).body, \"NewExternalIPAddress\")?.trim() ?? null;\n } catch (e) {\n if (!(e instanceof UpnpError)) throw e; // some routers refuse this but still map\n }\n this.lease = this.o.leaseSeconds;\n try {\n await this.addUpnpBoth(local, this.lease);\n } catch (e) {\n if (!(e instanceof UpnpError)) throw e;\n if (e.code === 725) {\n // OnlyPermanentLeasesSupported\n this.lease = 0;\n await this.addUpnpBoth(local, 0);\n } else return { mapped: false, method: \"upnp\", externalIPv4: external, localIPv4: local, detail: `UPnP ${e.message}` };\n }\n return { mapped: true, method: \"upnp\", externalIPv4: external, localIPv4: local, detail: \"UPnP\" };\n }\n\n private async addUpnpBoth(local: string, lease: number): Promise<void> {\n for (const proto of [\"TCP\", \"UDP\"])\n await this.soap(\"AddPortMapping\", [\n [\"NewRemoteHost\", \"\"], [\"NewExternalPort\", String(this.port)], [\"NewProtocol\", proto], [\"NewInternalPort\", String(this.port)],\n [\"NewInternalClient\", local], [\"NewEnabled\", \"1\"], [\"NewPortMappingDescription\", this.o.description], [\"NewLeaseDuration\", String(lease)],\n ]);\n }\n\n /**\n * SSDP search: multicast once per interface that has a gateway (so a Hyper-V, WSL or Docker adapter cannot swallow\n * it), plus a unicast copy to the gateway.\n */\n private discover(): Promise<URL | null> {\n const multicast = Number(this.o.ssdp.address.split(\".\")[0]) >= 224;\n const locals = multicast ? gatewayInterfaces() : [];\n if (locals.length === 0) locals.push({ local: \"0.0.0.0\", gateway: null });\n return new Promise((resolve) => {\n const sockets: UdpSocket[] = [];\n let finished = false;\n const finish = (u: URL | null) => {\n if (finished) return;\n finished = true;\n clearTimeout(timer);\n for (const s of sockets) s.close();\n resolve(u);\n };\n const timer = setTimeout(() => finish(null), this.o.discoveryTimeoutMs);\n for (const { local, gateway } of locals) {\n const s = createSocket({ type: \"udp4\", reuseAddr: false });\n sockets.push(s);\n s.on(\"error\", () => {});\n s.on(\"message\", (m) => {\n const u = parseSsdp(m.toString(\"latin1\"));\n if (u) finish(u);\n });\n s.bind(0, local === \"0.0.0.0\" ? undefined : local, () => {\n try {\n s.setMulticastTTL(2);\n if (local !== \"0.0.0.0\") s.setMulticastInterface(local);\n } catch {\n /* not fatal: the OS default interface is used */\n }\n for (const st of SEARCH_TARGETS) {\n const b = Buffer.from(`M-SEARCH * HTTP/1.1\\r\\nHOST: 239.255.255.250:1900\\r\\nMAN: \"ssdp:discover\"\\r\\nMX: 1\\r\\nST: ${st}\\r\\n\\r\\n`);\n s.send(b, this.o.ssdp.port, this.o.ssdp.address, () => {});\n if (gateway) s.send(b, 1900, gateway, () => {});\n }\n });\n }\n });\n }\n\n private async soap(action: string, args: [string, string][]): Promise<{ status: number; body: string }> {\n const inner = args.map(([k, v]) => `<${k}>${xmlEscape(v)}</${k}>`).join(\"\");\n const body =\n `<?xml version=\"1.0\"?><s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">` +\n `<s:Body><u:${action} xmlns:u=\"${this.service}\">${inner}</u:${action}></s:Body></s:Envelope>`;\n const res = await this.http(\"POST\", this.control!, body, { \"Content-Type\": 'text/xml; charset=\"utf-8\"', SOAPAction: `\"${this.service}#${action}\"` });\n if (res.status < 200 || res.status >= 300) {\n const code = tag(res.body, \"errorCode\");\n const desc = tag(res.body, \"errorDescription\") ?? \"\";\n throw new UpnpError(Number(code) || 0, `${action} error ${code ?? res.status} ${desc}`.trim());\n }\n return res;\n }\n\n /**\n * One connection per request: some routers close after each reply without saying so, and a reused\n * keep-alive socket then fails every second request with \"socket hang up\".\n */\n private http(method: string, url: URL, body: string | null, headers: Record<string, string>): Promise<{ status: number; body: string }> {\n return new Promise((resolve, reject) => {\n const h = { ...headers, Connection: \"close\" };\n const req = httpRequest(\n { method, hostname: url.hostname, port: url.port || 80, path: url.pathname + url.search, timeout: this.o.requestTimeoutMs, agent: false,\n headers: body === null ? h : { ...h, \"Content-Length\": Buffer.byteLength(body) } },\n (res) => {\n let text = \"\";\n res.setEncoding(\"utf8\");\n res.on(\"data\", (d) => (text += d));\n res.on(\"end\", () => resolve({ status: res.statusCode ?? 0, body: text }));\n },\n );\n req.on(\"timeout\", () => req.destroy(new Error(`${method} ${url.pathname} timed out`)));\n req.on(\"error\", reject);\n if (body !== null) req.write(body);\n req.end();\n });\n }\n\n // ------------------------------------------------------------------------------------------------ NAT-PMP\n\n private async tryNatPmp(): Promise<PortMapResult | null> {\n // One gateway only: each silent one costs the full retransmission budget.\n let gw0 = this.o.natPmp ?? null;\n if (!gw0) {\n const routed = (await defaultGatewayFallback()) ?? gatewayInterfaces().find((g) => g.gateway)?.gateway ?? null;\n if (routed) gw0 = { address: routed, port: 5351 };\n }\n const candidates = gw0 ? [gw0] : [];\n for (const gw of candidates) {\n const ext = await this.natPmpRequest(gw, Buffer.from([0, 0]), 12);\n if (!ext) continue;\n this.natPmpAt = gw;\n const local = await localAddressToward(gw.address, gw.port);\n const external = ext.readUInt16BE(2) === 0 ? `${ext[8]}.${ext[9]}.${ext[10]}.${ext[11]}` : null;\n const err = await this.natPmpMapBoth(this.o.leaseSeconds);\n if (err) return { mapped: false, method: \"natpmp\", externalIPv4: external, localIPv4: local, detail: `NAT-PMP ${err}` };\n return { mapped: true, method: \"natpmp\", externalIPv4: external, localIPv4: local, detail: \"NAT-PMP\" };\n }\n return null;\n }\n\n /** Maps UDP then TCP; null on success, else why. A different external port counts as failure (and is undone). */\n private async natPmpMapBoth(lifetime: number): Promise<string | null> {\n for (const op of [1, 2]) {\n const reply = await this.natPmpRequest(this.natPmpAt!, this.mapRequest(op, lifetime), 16);\n if (!reply) return \"no answer to the mapping request\";\n const rc = reply.readUInt16BE(2);\n if (rc !== 0) return `result code ${rc}`;\n const mapped = reply.readUInt16BE(10);\n if (lifetime > 0 && mapped !== this.port) {\n await this.natPmpRequest(this.natPmpAt!, this.mapRequest(op, 0), 16);\n return `router offered port ${mapped} instead of ${this.port}`;\n }\n }\n return null;\n }\n\n private mapRequest(op: number, lifetime: number): Buffer {\n const b = Buffer.alloc(12);\n b[1] = op;\n b.writeUInt16BE(this.port, 4);\n b.writeUInt16BE(lifetime > 0 ? this.port : 0, 6);\n b.writeUInt32BE(lifetime, 8);\n return b;\n }\n\n /** RFC 6886 s.3.1 retransmission: 250 ms, doubling, 3 tries (under 2 s). Null when nobody answers. */\n private natPmpRequest(to: { address: string; port: number }, req: Buffer, replyLength: number): Promise<Buffer | null> {\n return new Promise((resolve) => {\n const s = createSocket(\"udp4\");\n let wait = 250;\n let tries = 0;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const finish = (b: Buffer | null) => {\n if (timer) clearTimeout(timer);\n s.close();\n resolve(b);\n };\n s.on(\"error\", () => {}); // ICMP port unreachable on Windows: keep waiting for the timer\n s.on(\"message\", (b) => {\n if (b.length >= replyLength && b[0] === 0 && b[1] === req[1] + 128) finish(b);\n });\n const attempt = () => {\n if (tries++ >= 3) return finish(null);\n s.send(req, to.port, to.address, () => {});\n timer = setTimeout(attempt, wait);\n wait *= 2;\n };\n s.bind(0, attempt);\n });\n }\n\n /** Deletes the mappings (best effort, bounded to about 1.5 s) and stops renewing. */\n async close(): Promise<void> {\n if (this.stopped) return;\n this.stopped = true;\n if (this.renew) clearInterval(this.renew);\n const r = this.result;\n if (!r?.mapped) return;\n const work =\n r.method === \"upnp\"\n ? Promise.all([\"TCP\", \"UDP\"].map((p) => this.soap(\"DeletePortMapping\", [[\"NewRemoteHost\", \"\"], [\"NewExternalPort\", String(this.port)], [\"NewProtocol\", p]])))\n : Promise.all([1, 2].map((op) => this.natPmpOnce(this.mapRequest(op, 0))));\n await Promise.race([work.catch(() => {}), new Promise((r2) => setTimeout(r2, 1500).unref?.())]);\n }\n\n private natPmpOnce(req: Buffer): Promise<void> {\n return new Promise((resolve) => {\n const s = createSocket(\"udp4\");\n s.on(\"error\", () => {});\n s.send(req, this.natPmpAt!.port, this.natPmpAt!.address, () => {\n s.close();\n resolve();\n });\n });\n }\n}\n\n// ------------------------------------------------------------------------------------------------ helpers\n\n/**\n * True for an address the internet can route to: not private (RFC 1918), carrier-grade NAT (100.64/10), loopback,\n * link-local, 0/8, or multicast/reserved (224+). A router that reports a non-public WAN address is itself behind NAT.\n */\nexport function isPublicIPv4(address: string | null | undefined): boolean {\n if (!address) return false;\n const m = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(address);\n if (!m) return false;\n const [a, b] = [Number(m[1]), Number(m[2])];\n if (m.slice(1).some((x) => Number(x) > 255)) return false;\n if (a === 0 || a === 10 || a === 127 || a >= 224) return false;\n if (a === 100 && b >= 64 && b < 128) return false;\n if (a === 169 && b === 254) return false;\n if (a === 172 && b >= 16 && b < 32) return false;\n if (a === 192 && b === 168) return false;\n return true;\n}\n\nfunction tag(xml: string, name: string): string | null {\n const m = new RegExp(`<(?:[A-Za-z0-9_]+:)?${name}(?:\\\\s[^>]*)?>([\\\\s\\\\S]*?)</(?:[A-Za-z0-9_]+:)?${name}>`).exec(xml);\n return m ? m[1] : null;\n}\n\nfunction xmlEscape(s: string): string {\n return s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\").replace(/'/g, \"&apos;\");\n}\n\nfunction parseSsdp(text: string): URL | null {\n let location: string | null = null;\n let gateway = false;\n for (const line of text.split(/\\r?\\n/)) {\n const i = line.indexOf(\":\");\n if (i < 0) continue;\n const name = line.slice(0, i).trim().toLowerCase();\n const value = line.slice(i + 1).trim();\n if (name === \"location\") location = value;\n if ((name === \"st\" || name === \"usn\") && /InternetGatewayDevice|WANIPConnection/.test(value)) gateway = true;\n }\n if (!gateway || !location) return null;\n try {\n return new URL(location);\n } catch {\n return null;\n }\n}\n\n/**\n * Each IPv4 interface address, with its gateway when one can be guessed. Node's `os` does not report gateways, so the\n * gateway is the interface's .1 (true for nearly every home router); the SSDP multicast does not depend on it.\n */\nfunction gatewayInterfaces(): { local: string; gateway: string | null }[] {\n const out: { local: string; gateway: string | null }[] = [];\n for (const addrs of Object.values(networkInterfaces())) {\n for (const a of addrs ?? []) {\n if (a.family !== \"IPv4\" || a.internal || a.address.startsWith(\"169.254.\")) continue;\n const ip = a.address.split(\".\").map(Number);\n const mask = a.netmask.split(\".\").map(Number);\n const net = ip.map((x, i) => x & mask[i]);\n out.push({ local: a.address, gateway: mask[3] === 255 ? null : `${net[0]}.${net[1]}.${net[2]}.${net[3] + 1}` });\n }\n }\n return out;\n}\n\n/** The IPv4 default gateway from the OS route table (Windows `route print`, else `ip route`); null if it will not say. */\nfunction defaultGatewayFallback(): Promise<string | null> {\n return new Promise((resolve) => {\n const win = process.platform === \"win32\";\n execFile(win ? \"route\" : \"ip\", win ? [\"print\", \"0.0.0.0\"] : [\"route\", \"show\", \"default\"], { timeout: 2000 }, (err, stdout) => {\n if (err) return resolve(null);\n const m = win ? /0\\.0\\.0\\.0\\s+0\\.0\\.0\\.0\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)/.exec(stdout) : /default via (\\d+\\.\\d+\\.\\d+\\.\\d+)/.exec(stdout);\n resolve(m ? m[1] : null);\n });\n });\n}\n\n/** The local IPv4 the OS would use to reach `host` (a connected UDP socket sends nothing). */\nfunction localAddressToward(host: string, port: number): Promise<string> {\n return new Promise((resolve, reject) => {\n const s = createSocket(\"udp4\");\n s.on(\"error\", (e) => {\n s.close();\n reject(e);\n });\n s.connect(port, host, () => {\n const a = s.address().address;\n s.close();\n resolve(a);\n });\n });\n}\n\n/** The IPv4 a same-network join code carries when the router was not found (see C#'s DirectAddress.LanIPv4). */\nexport async function lanIPv4(): Promise<string | null> {\n try {\n const a = await localAddressToward(\"192.0.2.1\", 9); // TEST-NET-1: routed like the internet, never contacted\n if (a && a !== \"0.0.0.0\" && !a.startsWith(\"127.\")) return a;\n } catch {\n /* no default route: offline LAN party, look at the interfaces instead */\n }\n return gatewayInterfaces()[0]?.local ?? null;\n}\n\n/** This machine's addresses with the port, IPv4 first, for an \"Advanced\" fold-out on the host screen. */\nexport function localAddresses(port: number): string[] {\n const v4: string[] = [];\n const v6: string[] = [];\n for (const addrs of Object.values(networkInterfaces())) {\n for (const a of addrs ?? []) {\n if (a.internal) continue;\n if (a.family === \"IPv4\" && !a.address.startsWith(\"169.254.\")) v4.push(`${a.address}:${port}`);\n else if (a.family === \"IPv6\" && !/^fe80:/i.test(a.address) && !/^ff/i.test(a.address)) v6.push(`[${a.address}]:${port}`);\n }\n }\n return [...v4, ...v6];\n}\n"]}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * A direct-IP host address as a player types it (docs/direct-ip.md s.3): `ip`, `ip:port`, `[v6]:port`, a bare IPv6
3
+ * address or a host name (a virtual-LAN name, say). Same rules as OneLobby.Direct's `DirectAddress` in C#.
4
+ */
5
+ export interface DirectAddress {
6
+ host: string;
7
+ port: number;
8
+ isIPv6: boolean;
9
+ /** `host:port`, with brackets for IPv6. */
10
+ display: string;
11
+ /** The joiner's signaling URL: `ws://host:port/`. */
12
+ url: string;
13
+ /**
14
+ * The address as a remote ICE host candidate (UDP, same port number as the TCP listener). Without it a joiner on the
15
+ * internet only learns the host's private LAN addresses (docs/direct-ip.md s.2).
16
+ */
17
+ candidate: string;
18
+ }
19
+ export declare const DEFAULT_DIRECT_PORT = 47810;
20
+ export declare function parseDirectAddress(input: string, defaultPort?: number): DirectAddress | null;
@@ -0,0 +1,61 @@
1
+ export const DEFAULT_DIRECT_PORT = 47810;
2
+ const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
3
+ const HOSTNAME = /^(?=.{1,253}$)([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
4
+ function isIPv4(s) {
5
+ const m = IPV4.exec(s);
6
+ return !!m && m.slice(1).every((x) => Number(x) <= 255);
7
+ }
8
+ function isIPv6(s) {
9
+ if (!/^[0-9A-Fa-f:.]+$/.test(s) || s.split("::").length > 2 || !s.includes(":"))
10
+ return false;
11
+ const tail = s.split(":").pop() ?? "";
12
+ const groups = s.split(":").filter((g, i, a) => g !== "" || (i > 0 && i < a.length - 1));
13
+ if (tail.includes(".") && !isIPv4(tail))
14
+ return false;
15
+ return groups.every((g) => g === "" || g.includes(".") || /^[0-9A-Fa-f]{1,4}$/.test(g));
16
+ }
17
+ export function parseDirectAddress(input, defaultPort = DEFAULT_DIRECT_PORT) {
18
+ let s = input.trim();
19
+ if (/^ws:\/\//i.test(s))
20
+ s = s.slice(5);
21
+ s = s.replace(/\/+$/, "");
22
+ if (!s)
23
+ return null;
24
+ let host;
25
+ let portText = null;
26
+ if (s[0] === "[") {
27
+ const close = s.indexOf("]");
28
+ if (close < 0)
29
+ return null;
30
+ host = s.slice(1, close);
31
+ const rest = s.slice(close + 1);
32
+ if (rest) {
33
+ if (rest[0] !== ":")
34
+ return null;
35
+ portText = rest.slice(1);
36
+ }
37
+ }
38
+ else {
39
+ const first = s.indexOf(":");
40
+ if (first >= 0 && first === s.lastIndexOf(":")) {
41
+ host = s.slice(0, first);
42
+ portText = s.slice(first + 1);
43
+ }
44
+ else
45
+ host = s; // no colon, or several (a bare IPv6 address)
46
+ }
47
+ let port = defaultPort;
48
+ if (portText !== null) {
49
+ if (!/^\d{1,5}$/.test(portText))
50
+ return null;
51
+ port = Number(portText);
52
+ if (port < 1 || port > 65535)
53
+ return null;
54
+ }
55
+ const v6 = isIPv6(host);
56
+ if (!v6 && !isIPv4(host) && !HOSTNAME.test(host))
57
+ return null;
58
+ const display = (v6 ? `[${host}]` : host) + `:${port}`;
59
+ return { host, port, isIPv6: v6, display, url: `ws://${display}/`, candidate: `candidate:1 1 UDP 2122317823 ${host} ${port} typ host` };
60
+ }
61
+ //# sourceMappingURL=direct-address.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"direct-address.js","sourceRoot":"","sources":["../src/direct-address.ts"],"names":[],"mappings":"AAmBA,MAAM,CAAC,MAAM,mBAAmB,GAAG,KAAK,CAAC;AAEzC,MAAM,IAAI,GAAG,8CAA8C,CAAC;AAC5D,MAAM,QAAQ,GAAG,8GAA8G,CAAC;AAEhI,SAAS,MAAM,CAAC,CAAS;IACvB,MAAM,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACvB,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC;AAC1D,CAAC;AAED,SAAS,MAAM,CAAC,CAAS;IACvB,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9F,MAAM,IAAI,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC;IACtC,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,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AAE,CAAC;AAC1I,CAAC","sourcesContent":["/**\n * A direct-IP host address as a player types it (docs/direct-ip.md s.3): `ip`, `ip:port`, `[v6]:port`, a bare IPv6\n * address or a host name (a virtual-LAN name, say). Same rules as OneLobby.Direct's `DirectAddress` in C#.\n */\nexport interface DirectAddress {\n host: string;\n port: number;\n isIPv6: boolean;\n /** `host:port`, with brackets for IPv6. */\n display: string;\n /** The joiner's signaling URL: `ws://host:port/`. */\n url: string;\n /**\n * The address as a remote ICE host candidate (UDP, same port number as the TCP listener). Without it a joiner on the\n * internet only learns the host's private LAN addresses (docs/direct-ip.md s.2).\n */\n candidate: string;\n}\n\nexport const DEFAULT_DIRECT_PORT = 47810;\n\nconst IPV4 = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/;\nconst HOSTNAME = /^(?=.{1,253}$)([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(\\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;\n\nfunction isIPv4(s: string): boolean {\n const m = IPV4.exec(s);\n return !!m && m.slice(1).every((x) => Number(x) <= 255);\n}\n\nfunction isIPv6(s: string): boolean {\n if (!/^[0-9A-Fa-f:.]+$/.test(s) || s.split(\"::\").length > 2 || !s.includes(\":\")) return false;\n const tail = s.split(\":\").pop() ?? \"\";\n const groups = s.split(\":\").filter((g, i, a) => g !== \"\" || (i > 0 && i < a.length - 1));\n if (tail.includes(\".\") && !isIPv4(tail)) return false;\n return groups.every((g) => g === \"\" || g.includes(\".\") || /^[0-9A-Fa-f]{1,4}$/.test(g));\n}\n\nexport function parseDirectAddress(input: string, defaultPort = DEFAULT_DIRECT_PORT): DirectAddress | null {\n let s = input.trim();\n if (/^ws:\\/\\//i.test(s)) s = s.slice(5);\n s = s.replace(/\\/+$/, \"\");\n if (!s) return null;\n let host: string;\n let portText: string | null = null;\n if (s[0] === \"[\") {\n const close = s.indexOf(\"]\");\n if (close < 0) return null;\n host = s.slice(1, close);\n const rest = s.slice(close + 1);\n if (rest) {\n if (rest[0] !== \":\") return null;\n portText = rest.slice(1);\n }\n } else {\n const first = s.indexOf(\":\");\n if (first >= 0 && first === s.lastIndexOf(\":\")) {\n host = s.slice(0, first);\n portText = s.slice(first + 1);\n } else host = s; // no colon, or several (a bare IPv6 address)\n }\n let port = defaultPort;\n if (portText !== null) {\n if (!/^\\d{1,5}$/.test(portText)) return null;\n port = Number(portText);\n if (port < 1 || port > 65535) return null;\n }\n const v6 = isIPv6(host);\n if (!v6 && !isIPv4(host) && !HOSTNAME.test(host)) return null;\n const display = (v6 ? `[${host}]` : host) + `:${port}`;\n return { host, port, isIPv6: v6, display, url: `ws://${display}/`, candidate: `candidate:1 1 UDP 2122317823 ${host} ${port} typ host` };\n}\n"]}