@torrent-tv/proxy 2.9.20 → 2.9.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,7 @@
1
+ ## 2.9.23
2
+
3
+ - **New**: Symmetric-NAT port prediction for WebRTC (roadmap step 4; `webrtc-manager.js` + `nat-classifier.js` delta + `cli.js` wiring). When the startup NAT classification reports a **symmetric** NAT, for each real IPv4 `srflx` candidate the proxy also offers predicted-port candidates at `base + delta*k` (k = 1..16, `delta` = the per-destination external-port step measured at startup), each with a unique ICE foundation. The browser probes these too; if one matches the external port the NAT assigns for the proxy→browser path, ICE connects — the practical, signalling-only form of the birthday-paradox trick (no node-datachannel changes, no extra sockets). **Scope**: covers sequential/predictable symmetric NATs; a fully-random symmetric NAT (where the true 256-socket birthday would be needed) is not solved by this and is out of reach on the node-datachannel stack. No-op for cone NATs (the fixed-port mapping already suffices) and IPv6 (no NAT). Diagnostics: logs the injected predicted ports per session (`symmetric NAT (delta=D) — injecting N predicted srflx candidates: …`); combined with the existing `selected pair local=[…]` log this shows whether a predicted port won. NOTE: could not be exercised end-to-end — the dev's home NAT is cone; needs a symmetric-NAT vantage to verify in the field (the logging is there to diagnose it when it appears).
4
+
1
5
  ## 2.9.22
2
6
 
3
7
  - **Fix**: The proxy no longer crashes on a repeat/remote WebRTC session (regression from 2.9.18). Two causes, both fixed: (1) `webrtc-manager.handleSignal` called `setRemoteDescription`/`addRemoteCandidate` with **no try/catch**, so when node-datachannel threw synchronously (`Failed to gather local ICE candidates`) the whole process died — killing every viewer and the tunnel — and was restarted by s6. It now contains the error per session (logs + closes only that session, never throws out of the handler). (2) Root cause of the gather failure: 2.9.18 set `enableIceUdpMux` per-PeerConnection but with **no persistent mux owner**, so the shared UDP socket was bound/freed with each connection — a session opened while a just-closed one still held the fixed port could not bind it and failed to gather. Fixed by creating ONE persistent `IceUdpMuxListener` on the fixed UDP port once at startup (owned by the WebRTC manager for the proxy's whole lifetime, released on shutdown via `dispose()`); every session keeps `enableIceUdpMux` + the same port and demuxes over the shared socket by ICE ufrag. This keeps the clean single-port model (one UDP port, one UPnP mapping, one reachable endpoint) while surviving session churn. Verified against libdatachannel issue #861 and locally: 5 sequential + 2 concurrent PeerConnections all gather on the one port with no error, and the srflx candidate carries the fixed port.
package/bin/cli.js CHANGED
@@ -129,6 +129,9 @@ let udpPortMapper = null;
129
129
  /** @type {ReturnType<typeof createWebRtcManager> | null} */
130
130
  let webRtcManager = null;
131
131
 
132
+ /** @type {import("../services/nat-classifier.js").NatClassification | null} Latest NAT classification (for WebRTC port prediction). */
133
+ let natInfo = null;
134
+
132
135
 
133
136
  /**
134
137
  * Register this proxy with the registry server.
@@ -291,13 +294,15 @@ try {
291
294
  // never block startup.
292
295
  void classifyNat()
293
296
  .then((nat) => {
297
+ // Stored for WebRTC port prediction (webRtcManager reads it per session).
298
+ natInfo = nat;
294
299
  if (nat.klass === "endpoint-independent") {
295
300
  logger.info(
296
301
  `nat: endpoint-independent (cone) — external UDP port stable across STUN servers (${nat.externalIp}); fixed-port WebRTC mapping is sufficient, no port prediction needed`
297
302
  );
298
303
  } else if (nat.klass === "symmetric") {
299
304
  logger.warn(
300
- `nat: SYMMETRIC — external UDP port varies per destination (delta ${nat.portDelta}); WebRTC will need port prediction to reach remote viewers`
305
+ `nat: SYMMETRIC — external UDP port varies per destination (delta ${nat.portDelta}); WebRTC offers predicted ports (base+delta*k) covers sequential/predictable symmetric NAT, not fully random`
301
306
  );
302
307
  } else {
303
308
  logger.info("nat: classification inconclusive (STUN probes failed); continuing");
@@ -356,6 +361,8 @@ try {
356
361
  // persistent ICE UDP mux listener, so the WebRTC path is reachable from the
357
362
  // internet on one fixed port.
358
363
  udpPort: webrtcUdpPort,
364
+ // Latest NAT classification — enables symmetric-NAT port prediction.
365
+ getNatInfo: () => natInfo,
359
366
  sendSignal(sessionId, signal) {
360
367
  tunnelClient?.sendSignal(sessionId, signal);
361
368
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.9.20",
3
+ "version": "2.9.21",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "publishConfig": {
@@ -15,6 +15,72 @@ import nodeDataChannel from "node-datachannel";
15
15
 
16
16
  const ICE_SERVERS = ["stun:stun.l.google.com:19302"];
17
17
 
18
+ // Symmetric-NAT port prediction window. For each real srflx candidate we offer
19
+ // this many extra candidates at ports base + delta*k (k = 1..N), because the
20
+ // number of NAT mappings the router allocates between STUN gathering and the
21
+ // browser connectivity check is unknown — a small window covers the likely
22
+ // values without bloating the SDP.
23
+ const PORT_PREDICTION_WINDOW = 16;
24
+
25
+ /**
26
+ * Build predicted srflx ICE candidates for a symmetric NAT.
27
+ *
28
+ * A symmetric NAT assigns a different external port per destination, so the
29
+ * STUN-learned srflx port is not the port the NAT will use toward the browser.
30
+ * Given the per-destination port `delta` measured at startup, we offer ports
31
+ * `base + delta*k` (k = 1..window) so the browser also probes them; if one
32
+ * matches the mapping the NAT creates for the proxy→browser path, ICE connects.
33
+ * This is the practical, signalling-only form of the birthday-paradox trick —
34
+ * it works for sequential/predictable symmetric NATs, not fully random ones.
35
+ *
36
+ * Each predicted candidate gets a unique foundation so ICE treats it as a
37
+ * distinct candidate. Returns [] for non-srflx, IPv6, missing/zero delta, or a
38
+ * candidate string we cannot parse.
39
+ *
40
+ * @param {string} candidate - Raw candidate string (with or without `a=`).
41
+ * @param {number} delta - Per-destination external-port delta (from NAT classification).
42
+ * @param {number} [windowSize]
43
+ * @returns {Array<{ candidate: string, port: number }>}
44
+ */
45
+ function buildPredictedSrflxCandidates(candidate, delta, windowSize = PORT_PREDICTION_WINDOW) {
46
+ if (!Number.isInteger(delta) || delta === 0) {
47
+ return [];
48
+ }
49
+ const raw = candidate.replace(/^a=/, "");
50
+ if (!/ typ srflx /.test(raw)) {
51
+ return [];
52
+ }
53
+ // candidate:<foundation> <component> <proto> <priority> <ip> <port> typ srflx ...
54
+ const parts = raw.split(" ");
55
+ if (parts.length < 8 || !parts[0].startsWith("candidate:")) {
56
+ return [];
57
+ }
58
+ const ip = parts[4];
59
+ if (typeof ip !== "string" || ip.includes(":")) {
60
+ // IPv6 has no NAT — port prediction is meaningless.
61
+ return [];
62
+ }
63
+ const basePort = Number(parts[5]);
64
+ if (!Number.isInteger(basePort)) {
65
+ return [];
66
+ }
67
+
68
+ const out = [];
69
+ const seen = new Set([basePort]);
70
+ for (let k = 1; k <= windowSize; k++) {
71
+ const port = basePort + delta * k;
72
+ if (port < 1 || port > 65535 || seen.has(port)) {
73
+ continue;
74
+ }
75
+ seen.add(port);
76
+ const p = parts.slice();
77
+ p[0] = `candidate:pp${k}`;
78
+ p[5] = String(port);
79
+ out.push({ candidate: p.join(" "), port });
80
+ }
81
+ return out;
82
+ }
83
+
18
84
  /**
19
85
  * Return true when the ICE candidate string describes a `typ host` candidate
20
86
  * with a private (RFC 1918 / ULA / loopback) IP address.
@@ -70,6 +136,10 @@ function isPrivateHostCandidate(candidate) {
70
136
  * `node-datachannel` `DataChannel` object; hand it to `createDataChannelHandler`.
71
137
  * @property {(message: string) => void} [onLog]
72
138
  * Optional log sink.
139
+ * @property {() => ({ klass: string, portDelta: number|null } | null)} [getNatInfo]
140
+ * Returns the latest NAT classification (or null if not yet known). When it
141
+ * reports a symmetric NAT with a known port delta, each srflx candidate is
142
+ * accompanied by predicted-port candidates (see {@link buildPredictedSrflxCandidates}).
73
143
  * @property {number} [udpPort]
74
144
  * When set, all WebRTC sessions are multiplexed onto this single UDP port so
75
145
  * it can be statically UPnP-mapped (one mapping, one reachable port). A
@@ -106,7 +176,7 @@ function isPrivateHostCandidate(candidate) {
106
176
  * @param {WebRtcManagerOptions} options
107
177
  * @returns {WebRtcManager}
108
178
  */
109
- export function createWebRtcManager({ sendSignal, onDataChannel, onLog, udpPort }) {
179
+ export function createWebRtcManager({ sendSignal, onDataChannel, onLog, udpPort, getNatInfo }) {
110
180
  /** @type {Map<string, import("node-datachannel").PeerConnection>} */
111
181
  const peers = new Map();
112
182
 
@@ -182,6 +252,28 @@ export function createWebRtcManager({ sendSignal, onDataChannel, onLog, udpPort
182
252
  `[webrtc] Session ${sessionId.slice(0, 8)}: sending ${isPrivate ? "private" : "public"} candidate: ${candidate.replace(/^a=/, "")}`
183
253
  );
184
254
  sendSignal(sessionId, { type: "candidate", candidate, mid });
255
+
256
+ // Symmetric-NAT port prediction: offer extra srflx candidates at the
257
+ // predicted external ports so the browser probes them too. No-op unless
258
+ // the NAT is symmetric with a known delta and this is an IPv4 srflx
259
+ // candidate. Best-effort — never let it break candidate forwarding.
260
+ try {
261
+ const nat = typeof getNatInfo === "function" ? getNatInfo() : null;
262
+ if (nat && nat.klass === "symmetric") {
263
+ const predicted = buildPredictedSrflxCandidates(candidate, nat.portDelta);
264
+ if (predicted.length > 0) {
265
+ log(
266
+ `[webrtc] Session ${sessionId.slice(0, 8)}: symmetric NAT (delta=${nat.portDelta}) — injecting ${predicted.length} predicted srflx candidates: ${predicted.map((p) => p.port).join(",")}`
267
+ );
268
+ for (const p of predicted) {
269
+ sendSignal(sessionId, { type: "candidate", candidate: p.candidate, mid });
270
+ }
271
+ }
272
+ }
273
+ } catch (error) {
274
+ const message = error instanceof Error ? error.message : String(error);
275
+ log(`[webrtc] Session ${sessionId.slice(0, 8)}: port-prediction inject failed: ${message}`);
276
+ }
185
277
  });
186
278
 
187
279
  pc.onGatheringStateChange((state) => {